Elffuss BraidHub

kikocis/llama-stack public

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