Elffuss BraidHub

kikocis/llama-stack public

329cf2dbbb63 · 30.4 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7import asyncio
8import copy
9import os
10import secrets
11import shutil
12import string
13import tempfile
14import uuid
15from datetime import datetime
16from typing import AsyncGenerator, List, Tuple
17from urllib.parse import urlparse
18
19import httpx
20
21from termcolor import cprint
22
23from llama_stack.apis.agents import * # noqa: F403
24from llama_stack.apis.inference import * # noqa: F403
25from llama_stack.apis.memory import * # noqa: F403
26from llama_stack.apis.safety import * # noqa: F403
27
28from llama_stack.providers.utils.kvstore import KVStore
29from llama_stack.providers.utils.telemetry import tracing
30
31from .persistence import AgentPersistence
32from .rag.context_retriever import generate_rag_query
33from .safety import SafetyException, ShieldRunnerMixin
34from .tools.base import BaseTool
35from .tools.builtin import (
36 CodeInterpreterTool,
37 interpret_content_as_attachment,
38 PhotogenTool,
39 SearchTool,
40 WolframAlphaTool,
41)
42from .tools.safety import SafeTool
43
44
45def make_random_string(length: int = 8):
46 return "".join(
47 secrets.choice(string.ascii_letters + string.digits) for _ in range(length)
48 )
49
50
51class ChatAgent(ShieldRunnerMixin):
52 def __init__(
53 self,
54 agent_id: str,
55 agent_config: AgentConfig,
56 inference_api: Inference,
57 memory_api: Memory,
58 safety_api: Safety,
59 persistence_store: KVStore,
60 ):
61 self.agent_id = agent_id
62 self.agent_config = agent_config
63 self.inference_api = inference_api
64 self.memory_api = memory_api
65 self.safety_api = safety_api
66 self.storage = AgentPersistence(agent_id, persistence_store)
67
68 self.tempdir = tempfile.mkdtemp()
69
70 builtin_tools = []
71 for tool_defn in agent_config.tools:
72 if isinstance(tool_defn, WolframAlphaToolDefinition):
73 tool = WolframAlphaTool(tool_defn.api_key)
74 elif isinstance(tool_defn, SearchToolDefinition):
75 tool = SearchTool(tool_defn.engine, tool_defn.api_key)
76 elif isinstance(tool_defn, CodeInterpreterToolDefinition):
77 tool = CodeInterpreterTool()
78 elif isinstance(tool_defn, PhotogenToolDefinition):
79 tool = PhotogenTool(dump_dir=self.tempdir)
80 else:
81 continue
82
83 builtin_tools.append(
84 SafeTool(
85 tool,
86 safety_api,
87 tool_defn.input_shields,
88 tool_defn.output_shields,
89 )
90 )
91 self.tools_dict = {t.get_name(): t for t in builtin_tools}
92
93 ShieldRunnerMixin.__init__(
94 self,
95 safety_api,
96 input_shields=agent_config.input_shields,
97 output_shields=agent_config.output_shields,
98 )
99
100 def __del__(self):
101 shutil.rmtree(self.tempdir)
102
103 def turn_to_messages(self, turn: Turn) -> List[Message]:
104 messages = []
105
106 # We do not want to keep adding RAG context to the input messages
107 # May be this should be a parameter of the agentic instance
108 # that can define its behavior in a custom way
109 for m in turn.input_messages:
110 msg = m.copy()
111 if isinstance(msg, UserMessage):
112 msg.context = None
113 messages.append(msg)
114
115 for step in turn.steps:
116 if step.step_type == StepType.inference.value:
117 messages.append(step.model_response)
118 elif step.step_type == StepType.tool_execution.value:
119 for response in step.tool_responses:
120 messages.append(
121 ToolResponseMessage(
122 call_id=response.call_id,
123 tool_name=response.tool_name,
124 content=response.content,
125 )
126 )
127 elif step.step_type == StepType.shield_call.value:
128 if step.violation:
129 # CompletionMessage itself in the ShieldResponse
130 messages.append(
131 CompletionMessage(
132 content=violation.user_message,
133 stop_reason=StopReason.end_of_turn,
134 )
135 )
136 # print_dialog(messages)
137 return messages
138
139 async def create_session(self, name: str) -> str:
140 return await self.storage.create_session(name)
141
142 @tracing.span("create_and_execute_turn")
143 async def create_and_execute_turn(
144 self, request: AgentTurnCreateRequest
145 ) -> AsyncGenerator:
146 session_info = await self.storage.get_session_info(request.session_id)
147 if session_info is None:
148 raise ValueError(f"Session {request.session_id} not found")
149
150 turns = await self.storage.get_session_turns(request.session_id)
151
152 messages = []
153 if len(turns) == 0 and self.agent_config.instructions != "":
154 messages.append(SystemMessage(content=self.agent_config.instructions))
155
156 for i, turn in enumerate(turns):
157 messages.extend(self.turn_to_messages(turn))
158
159 messages.extend(request.messages)
160
161 turn_id = str(uuid.uuid4())
162 start_time = datetime.now()
163 yield AgentTurnResponseStreamChunk(
164 event=AgentTurnResponseEvent(
165 payload=AgentTurnResponseTurnStartPayload(
166 turn_id=turn_id,
167 )
168 )
169 )
170
171 steps = []
172 output_message = None
173 async for chunk in self.run(
174 session_id=request.session_id,
175 turn_id=turn_id,
176 input_messages=messages,
177 attachments=request.attachments or [],
178 sampling_params=self.agent_config.sampling_params,
179 stream=request.stream,
180 ):
181 if isinstance(chunk, CompletionMessage):
182 cprint(
183 f"{chunk.role.capitalize()}: {chunk.content}",
184 "white",
185 attrs=["bold"],
186 )
187 output_message = chunk
188 continue
189
190 assert isinstance(
191 chunk, AgentTurnResponseStreamChunk
192 ), f"Unexpected type {type(chunk)}"
193 event = chunk.event
194 if (
195 event.payload.event_type
196 == AgentTurnResponseEventType.step_complete.value
197 ):
198 steps.append(event.payload.step_details)
199
200 yield chunk
201
202 assert output_message is not None
203
204 turn = Turn(
205 turn_id=turn_id,
206 session_id=request.session_id,
207 input_messages=request.messages,
208 output_message=output_message,
209 started_at=start_time,
210 completed_at=datetime.now(),
211 steps=steps,
212 )
213 await self.storage.add_turn_to_session(request.session_id, turn)
214
215 chunk = AgentTurnResponseStreamChunk(
216 event=AgentTurnResponseEvent(
217 payload=AgentTurnResponseTurnCompletePayload(
218 turn=turn,
219 )
220 )
221 )
222 yield chunk
223
224 async def run(
225 self,
226 session_id: str,
227 turn_id: str,
228 input_messages: List[Message],
229 attachments: List[Attachment],
230 sampling_params: SamplingParams,
231 stream: bool = False,
232 ) -> AsyncGenerator:
233 # Doing async generators makes downstream code much simpler and everything amenable to
234 # streaming. However, it also makes things complicated here because AsyncGenerators cannot
235 # return a "final value" for the `yield from` statement. we simulate that by yielding a
236 # final boolean (to see whether an exception happened) and then explicitly testing for it.
237
238 async for res in self.run_multiple_shields_wrapper(
239 turn_id, input_messages, self.input_shields, "user-input"
240 ):
241 if isinstance(res, bool):
242 return
243 else:
244 yield res
245
246 async for res in self._run(
247 session_id, turn_id, input_messages, attachments, sampling_params, stream
248 ):
249 if isinstance(res, bool):
250 return
251 elif isinstance(res, CompletionMessage):
252 final_response = res
253 break
254 else:
255 yield res
256
257 assert final_response is not None
258 # for output shields run on the full input and output combination
259 messages = input_messages + [final_response]
260
261 async for res in self.run_multiple_shields_wrapper(
262 turn_id, messages, self.output_shields, "assistant-output"
263 ):
264 if isinstance(res, bool):
265 return
266 else:
267 yield res
268
269 yield final_response
270
271 @tracing.span("run_shields")
272 async def run_multiple_shields_wrapper(
273 self,
274 turn_id: str,
275 messages: List[Message],
276 shields: List[str],
277 touchpoint: str,
278 ) -> AsyncGenerator:
279 if len(shields) == 0:
280 return
281
282 step_id = str(uuid.uuid4())
283 try:
284 yield AgentTurnResponseStreamChunk(
285 event=AgentTurnResponseEvent(
286 payload=AgentTurnResponseStepStartPayload(
287 step_type=StepType.shield_call.value,
288 step_id=step_id,
289 metadata=dict(touchpoint=touchpoint),
290 )
291 )
292 )
293 await self.run_multiple_shields(messages, shields)
294
295 except SafetyException as e:
296 yield AgentTurnResponseStreamChunk(
297 event=AgentTurnResponseEvent(
298 payload=AgentTurnResponseStepCompletePayload(
299 step_type=StepType.shield_call.value,
300 step_details=ShieldCallStep(
301 step_id=step_id,
302 turn_id=turn_id,
303 violation=e.violation,
304 ),
305 )
306 )
307 )
308
309 yield CompletionMessage(
310 content=str(e),
311 stop_reason=StopReason.end_of_turn,
312 )
313 yield False
314
315 yield AgentTurnResponseStreamChunk(
316 event=AgentTurnResponseEvent(
317 payload=AgentTurnResponseStepCompletePayload(
318 step_type=StepType.shield_call.value,
319 step_details=ShieldCallStep(
320 step_id=step_id,
321 turn_id=turn_id,
322 violation=None,
323 ),
324 )
325 )
326 )
327
328 async def _run(
329 self,
330 session_id: str,
331 turn_id: str,
332 input_messages: List[Message],
333 attachments: List[Attachment],
334 sampling_params: SamplingParams,
335 stream: bool = False,
336 ) -> AsyncGenerator:
337 enabled_tools = set(t.type for t in self.agent_config.tools)
338 need_rag_context = await self._should_retrieve_context(
339 input_messages, attachments
340 )
341 if need_rag_context:
342 step_id = str(uuid.uuid4())
343 yield AgentTurnResponseStreamChunk(
344 event=AgentTurnResponseEvent(
345 payload=AgentTurnResponseStepStartPayload(
346 step_type=StepType.memory_retrieval.value,
347 step_id=step_id,
348 )
349 )
350 )
351
352 # TODO: find older context from the session and either replace it
353 # or append with a sliding window. this is really a very simplistic implementation
354 with tracing.span("retrieve_rag_context"):
355 rag_context, bank_ids = await self._retrieve_context(
356 session_id, input_messages, attachments
357 )
358
359 step_id = str(uuid.uuid4())
360 yield AgentTurnResponseStreamChunk(
361 event=AgentTurnResponseEvent(
362 payload=AgentTurnResponseStepCompletePayload(
363 step_type=StepType.memory_retrieval.value,
364 step_id=step_id,
365 step_details=MemoryRetrievalStep(
366 turn_id=turn_id,
367 step_id=step_id,
368 memory_bank_ids=bank_ids,
369 inserted_context=rag_context or "",
370 ),
371 )
372 )
373 )
374
375 if rag_context:
376 last_message = input_messages[-1]
377 last_message.context = "\n".join(rag_context)
378
379 elif attachments and AgentTool.code_interpreter.value in enabled_tools:
380 urls = [a.content for a in attachments if isinstance(a.content, URL)]
381 msg = await attachment_message(self.tempdir, urls)
382 input_messages.append(msg)
383
384 output_attachments = []
385
386 n_iter = 0
387 while True:
388 msg = input_messages[-1]
389 if msg.role == Role.user.value:
390 color = "blue"
391 elif msg.role == Role.ipython.value:
392 color = "yellow"
393 else:
394 color = None
395 cprint(f"{str(msg)}", color=color)
396
397 step_id = str(uuid.uuid4())
398 yield AgentTurnResponseStreamChunk(
399 event=AgentTurnResponseEvent(
400 payload=AgentTurnResponseStepStartPayload(
401 step_type=StepType.inference.value,
402 step_id=step_id,
403 )
404 )
405 )
406
407 tool_calls = []
408 content = ""
409 stop_reason = None
410
411 with tracing.span("inference"):
412 async for chunk in self.inference_api.chat_completion(
413 self.agent_config.model,
414 input_messages,
415 tools=self._get_tools(),
416 tool_prompt_format=self.agent_config.tool_prompt_format,
417 stream=True,
418 sampling_params=sampling_params,
419 ):
420 event = chunk.event
421 if event.event_type == ChatCompletionResponseEventType.start:
422 continue
423 elif event.event_type == ChatCompletionResponseEventType.complete:
424 stop_reason = StopReason.end_of_turn
425 continue
426
427 delta = event.delta
428 if isinstance(delta, ToolCallDelta):
429 if delta.parse_status == ToolCallParseStatus.success:
430 tool_calls.append(delta.content)
431
432 if stream:
433 yield AgentTurnResponseStreamChunk(
434 event=AgentTurnResponseEvent(
435 payload=AgentTurnResponseStepProgressPayload(
436 step_type=StepType.inference.value,
437 step_id=step_id,
438 model_response_text_delta="",
439 tool_call_delta=delta,
440 )
441 )
442 )
443
444 elif isinstance(delta, str):
445 content += delta
446 if stream and event.stop_reason is None:
447 yield AgentTurnResponseStreamChunk(
448 event=AgentTurnResponseEvent(
449 payload=AgentTurnResponseStepProgressPayload(
450 step_type=StepType.inference.value,
451 step_id=step_id,
452 model_response_text_delta=event.delta,
453 )
454 )
455 )
456 else:
457 raise ValueError(f"Unexpected delta type {type(delta)}")
458
459 if event.stop_reason is not None:
460 stop_reason = event.stop_reason
461
462 stop_reason = stop_reason or StopReason.out_of_tokens
463 message = CompletionMessage(
464 content=content,
465 stop_reason=stop_reason,
466 tool_calls=tool_calls,
467 )
468
469 yield AgentTurnResponseStreamChunk(
470 event=AgentTurnResponseEvent(
471 payload=AgentTurnResponseStepCompletePayload(
472 step_type=StepType.inference.value,
473 step_id=step_id,
474 step_details=InferenceStep(
475 # somewhere deep, we are re-assigning message or closing over some
476 # variable which causes message to mutate later on. fix with a
477 # `deepcopy` for now, but this is symptomatic of a deeper issue.
478 step_id=step_id,
479 turn_id=turn_id,
480 model_response=copy.deepcopy(message),
481 ),
482 )
483 )
484 )
485
486 if n_iter >= self.agent_config.max_infer_iters:
487 cprint("Done with MAX iterations, exiting.")
488 yield message
489 break
490
491 if stop_reason == StopReason.out_of_tokens:
492 cprint("Out of token budget, exiting.")
493 yield message
494 break
495
496 if len(message.tool_calls) == 0:
497 if stop_reason == StopReason.end_of_turn:
498 # TODO: UPDATE RETURN TYPE TO SEND A TUPLE OF (MESSAGE, ATTACHMENTS)
499 if len(output_attachments) > 0:
500 if isinstance(message.content, list):
501 message.content += attachments
502 else:
503 message.content = [message.content] + attachments
504 yield message
505 else:
506 cprint(f"Partial message: {str(message)}", color="green")
507 input_messages = input_messages + [message]
508 else:
509 cprint(f"{str(message)}", color="green")
510 try:
511 tool_call = message.tool_calls[0]
512
513 name = tool_call.tool_name
514 if not isinstance(name, BuiltinTool):
515 yield message
516 return
517
518 step_id = str(uuid.uuid4())
519 yield AgentTurnResponseStreamChunk(
520 event=AgentTurnResponseEvent(
521 payload=AgentTurnResponseStepStartPayload(
522 step_type=StepType.tool_execution.value,
523 step_id=step_id,
524 )
525 )
526 )
527 yield AgentTurnResponseStreamChunk(
528 event=AgentTurnResponseEvent(
529 payload=AgentTurnResponseStepProgressPayload(
530 step_type=StepType.tool_execution.value,
531 step_id=step_id,
532 tool_call=tool_call,
533 )
534 )
535 )
536
537 with tracing.span("tool_execution"):
538 result_messages = await execute_tool_call_maybe(
539 self.tools_dict,
540 [message],
541 )
542 assert (
543 len(result_messages) == 1
544 ), "Currently not supporting multiple messages"
545 result_message = result_messages[0]
546
547 yield AgentTurnResponseStreamChunk(
548 event=AgentTurnResponseEvent(
549 payload=AgentTurnResponseStepCompletePayload(
550 step_type=StepType.tool_execution.value,
551 step_details=ToolExecutionStep(
552 step_id=step_id,
553 turn_id=turn_id,
554 tool_calls=[tool_call],
555 tool_responses=[
556 ToolResponse(
557 call_id=result_message.call_id,
558 tool_name=result_message.tool_name,
559 content=result_message.content,
560 )
561 ],
562 ),
563 )
564 )
565 )
566
567 # TODO: add tool-input touchpoint and a "start" event for this step also
568 # but that needs a lot more refactoring of Tool code potentially
569 yield AgentTurnResponseStreamChunk(
570 event=AgentTurnResponseEvent(
571 payload=AgentTurnResponseStepCompletePayload(
572 step_type=StepType.shield_call.value,
573 step_details=ShieldCallStep(
574 step_id=str(uuid.uuid4()),
575 turn_id=turn_id,
576 violation=None,
577 ),
578 )
579 )
580 )
581
582 except SafetyException as e:
583 yield AgentTurnResponseStreamChunk(
584 event=AgentTurnResponseEvent(
585 payload=AgentTurnResponseStepCompletePayload(
586 step_type=StepType.shield_call.value,
587 step_details=ShieldCallStep(
588 step_id=str(uuid.uuid4()),
589 turn_id=turn_id,
590 violation=e.violation,
591 ),
592 )
593 )
594 )
595
596 yield CompletionMessage(
597 content=str(e),
598 stop_reason=StopReason.end_of_turn,
599 )
600 yield False
601 return
602
603 if out_attachment := interpret_content_as_attachment(
604 result_message.content
605 ):
606 # NOTE: when we push this message back to the model, the model may ignore the
607 # attached file path etc. since the model is trained to only provide a user message
608 # with the summary. We keep all generated attachments and then attach them to final message
609 output_attachments.append(out_attachment)
610
611 input_messages = input_messages + [message, result_message]
612
613 n_iter += 1
614
615 async def _ensure_memory_bank(self, session_id: str) -> str:
616 session_info = await self.storage.get_session_info(session_id)
617 if session_info is None:
618 raise ValueError(f"Session {session_id} not found")
619
620 if session_info.memory_bank_id is None:
621 memory_bank = await self.memory_api.create_memory_bank(
622 name=f"memory_bank_{session_id}",
623 config=VectorMemoryBankConfig(
624 embedding_model="sentence-transformer/all-MiniLM-L6-v2",
625 chunk_size_in_tokens=512,
626 ),
627 )
628 bank_id = memory_bank.bank_id
629 await self.storage.add_memory_bank_to_session(session_id, bank_id)
630 else:
631 bank_id = session_info.memory_bank_id
632
633 return bank_id
634
635 async def _should_retrieve_context(
636 self, messages: List[Message], attachments: List[Attachment]
637 ) -> bool:
638 enabled_tools = set(t.type for t in self.agent_config.tools)
639 if attachments:
640 if (
641 AgentTool.code_interpreter.value in enabled_tools
642 and self.agent_config.tool_choice == ToolChoice.required
643 ):
644 return False
645 else:
646 return True
647
648 return AgentTool.memory.value in enabled_tools
649
650 def _memory_tool_definition(self) -> Optional[MemoryToolDefinition]:
651 for t in self.agent_config.tools:
652 if t.type == AgentTool.memory.value:
653 return t
654
655 return None
656
657 async def _retrieve_context(
658 self, session_id: str, messages: List[Message], attachments: List[Attachment]
659 ) -> Tuple[List[str], List[int]]: # (rag_context, bank_ids)
660 bank_ids = []
661
662 memory = self._memory_tool_definition()
663 assert memory is not None, "Memory tool not configured"
664 bank_ids.extend(c.bank_id for c in memory.memory_bank_configs)
665
666 if attachments:
667 bank_id = await self._ensure_memory_bank(session_id)
668 bank_ids.append(bank_id)
669
670 documents = [
671 MemoryBankDocument(
672 document_id=str(uuid.uuid4()),
673 content=a.content,
674 mime_type=a.mime_type,
675 metadata={},
676 )
677 for a in attachments
678 ]
679 with tracing.span("insert_documents"):
680 await self.memory_api.insert_documents(bank_id, documents)
681 else:
682 session_info = await self.storage.get_session_info(session_id)
683 if session_info.memory_bank_id:
684 bank_ids.append(session_info.memory_bank_id)
685
686 if not bank_ids:
687 # this can happen if the per-session memory bank is not yet populated
688 # (i.e., no prior turns uploaded an Attachment)
689 return None, []
690
691 query = await generate_rag_query(
692 memory.query_generator_config, messages, inference_api=self.inference_api
693 )
694 tasks = [
695 self.memory_api.query_documents(
696 bank_id=bank_id,
697 query=query,
698 params={
699 "max_chunks": 5,
700 },
701 )
702 for bank_id in bank_ids
703 ]
704 results: List[QueryDocumentsResponse] = await asyncio.gather(*tasks)
705 chunks = [c for r in results for c in r.chunks]
706 scores = [s for r in results for s in r.scores]
707
708 # sort by score
709 chunks, scores = zip(
710 *sorted(zip(chunks, scores), key=lambda x: x[1], reverse=True)
711 )
712 if not chunks:
713 return None, bank_ids
714
715 tokens = 0
716 picked = []
717 for c in chunks[: memory.max_chunks]:
718 tokens += c.token_count
719 if tokens > memory.max_tokens_in_context:
720 cprint(
721 f"Using {len(picked)} chunks; reached max tokens in context: {tokens}",
722 "red",
723 )
724 break
725 picked.append(f"id:{c.document_id}; content:{c.content}")
726
727 return [
728 "Here are the retrieved documents for relevant context:\n=== START-RETRIEVED-CONTEXT ===\n",
729 *picked,
730 "\n=== END-RETRIEVED-CONTEXT ===\n",
731 ], bank_ids
732
733 def _get_tools(self) -> List[ToolDefinition]:
734 ret = []
735 for t in self.agent_config.tools:
736 if isinstance(t, SearchToolDefinition):
737 ret.append(ToolDefinition(tool_name=BuiltinTool.brave_search))
738 elif isinstance(t, WolframAlphaToolDefinition):
739 ret.append(ToolDefinition(tool_name=BuiltinTool.wolfram_alpha))
740 elif isinstance(t, PhotogenToolDefinition):
741 ret.append(ToolDefinition(tool_name=BuiltinTool.photogen))
742 elif isinstance(t, CodeInterpreterToolDefinition):
743 ret.append(ToolDefinition(tool_name=BuiltinTool.code_interpreter))
744 elif isinstance(t, FunctionCallToolDefinition):
745 ret.append(
746 ToolDefinition(
747 tool_name=t.function_name,
748 description=t.description,
749 parameters=t.parameters,
750 )
751 )
752 return ret
753
754
755async def attachment_message(tempdir: str, urls: List[URL]) -> ToolResponseMessage:
756 content = []
757
758 for url in urls:
759 uri = url.uri
760 if uri.startswith("file://"):
761 filepath = uri[len("file://") :]
762 elif uri.startswith("http"):
763 path = urlparse(uri).path
764 basename = os.path.basename(path)
765 filepath = f"{tempdir}/{make_random_string() + basename}"
766 print(f"Downloading {url} -> {filepath}")
767
768 async with httpx.AsyncClient() as client:
769 r = await client.get(uri)
770 resp = r.text
771 with open(filepath, "w") as fp:
772 fp.write(resp)
773 else:
774 raise ValueError(f"Unsupported URL {url}")
775
776 content.append(f'# There is a file accessible to you at "{filepath}"\n')
777
778 return ToolResponseMessage(
779 call_id="",
780 tool_name=BuiltinTool.code_interpreter,
781 content=content,
782 )
783
784
785async def execute_tool_call_maybe(
786 tools_dict: Dict[str, BaseTool], messages: List[CompletionMessage]
787) -> List[ToolResponseMessage]:
788 # While Tools.run interface takes a list of messages,
789 # All tools currently only run on a single message
790 # When this changes, we can drop this assert
791 # Whether to call tools on each message and aggregate
792 # or aggregate and call tool once, reamins to be seen.
793 assert len(messages) == 1, "Expected single message"
794 message = messages[0]
795
796 tool_call = message.tool_calls[0]
797 name = tool_call.tool_name
798 assert isinstance(name, BuiltinTool)
799
800 name = name.value
801
802 assert name in tools_dict, f"Tool {name} not found"
803 tool = tools_dict[name]
804 result_messages = await tool.run(messages)
805 return result_messages
806
807
808def print_dialog(messages: List[Message]):
809 for i, m in enumerate(messages):
810 if m.role == Role.user.value:
811 color = "red"
812 elif m.role == Role.assistant.value:
813 color = "white"
814 elif m.role == Role.ipython.value:
815 color = "yellow"
816 elif m.role == Role.system.value:
817 color = "green"
818 else:
819 color = "white"
820
821 s = str(m)
822 cprint(f"{i} ::: {s[:100]}...", color=color)