| 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 | |
| 7 | import asyncio |
| 8 | import copy |
| 9 | import os |
| 10 | import re |
| 11 | import secrets |
| 12 | import shutil |
| 13 | import string |
| 14 | import tempfile |
| 15 | import uuid |
| 16 | from datetime import datetime |
| 17 | from typing import AsyncGenerator, List, Tuple |
| 18 | from urllib.parse import urlparse |
| 19 | |
| 20 | import httpx |
| 21 | |
| 22 | from termcolor import cprint |
| 23 | |
| 24 | from llama_stack.apis.agents import * # noqa: F403 |
| 25 | from llama_stack.apis.inference import * # noqa: F403 |
| 26 | from llama_stack.apis.memory import * # noqa: F403 |
| 27 | from llama_stack.apis.safety import * # noqa: F403 |
| 28 | |
| 29 | from llama_stack.providers.utils.kvstore import KVStore |
| 30 | from llama_stack.providers.utils.telemetry import tracing |
| 31 | |
| 32 | from .persistence import AgentPersistence |
| 33 | from .rag.context_retriever import generate_rag_query |
| 34 | from .safety import SafetyException, ShieldRunnerMixin |
| 35 | from .tools.base import BaseTool |
| 36 | from .tools.builtin import ( |
| 37 | CodeInterpreterTool, |
| 38 | interpret_content_as_attachment, |
| 39 | PhotogenTool, |
| 40 | SearchTool, |
| 41 | WolframAlphaTool, |
| 42 | ) |
| 43 | from .tools.safety import SafeTool |
| 44 | |
| 45 | |
| 46 | def make_random_string(length: int = 8): |
| 47 | return "".join( |
| 48 | secrets.choice(string.ascii_letters + string.digits) for _ in range(length) |
| 49 | ) |
| 50 | |
| 51 | |
| 52 | class 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 | cprint(f"{str(msg)}", color=color) |
| 402 | |
| 403 | step_id = str(uuid.uuid4()) |
| 404 | yield AgentTurnResponseStreamChunk( |
| 405 | event=AgentTurnResponseEvent( |
| 406 | payload=AgentTurnResponseStepStartPayload( |
| 407 | step_type=StepType.inference.value, |
| 408 | step_id=step_id, |
| 409 | ) |
| 410 | ) |
| 411 | ) |
| 412 | |
| 413 | tool_calls = [] |
| 414 | content = "" |
| 415 | stop_reason = None |
| 416 | |
| 417 | with tracing.span("inference"): |
| 418 | async for chunk in self.inference_api.chat_completion( |
| 419 | self.agent_config.model, |
| 420 | input_messages, |
| 421 | tools=self._get_tools(), |
| 422 | tool_prompt_format=self.agent_config.tool_prompt_format, |
| 423 | stream=True, |
| 424 | sampling_params=sampling_params, |
| 425 | ): |
| 426 | event = chunk.event |
| 427 | if event.event_type == ChatCompletionResponseEventType.start: |
| 428 | continue |
| 429 | elif event.event_type == ChatCompletionResponseEventType.complete: |
| 430 | stop_reason = StopReason.end_of_turn |
| 431 | continue |
| 432 | |
| 433 | delta = event.delta |
| 434 | if isinstance(delta, ToolCallDelta): |
| 435 | if delta.parse_status == ToolCallParseStatus.success: |
| 436 | tool_calls.append(delta.content) |
| 437 | |
| 438 | if stream: |
| 439 | yield AgentTurnResponseStreamChunk( |
| 440 | event=AgentTurnResponseEvent( |
| 441 | payload=AgentTurnResponseStepProgressPayload( |
| 442 | step_type=StepType.inference.value, |
| 443 | step_id=step_id, |
| 444 | model_response_text_delta="", |
| 445 | tool_call_delta=delta, |
| 446 | ) |
| 447 | ) |
| 448 | ) |
| 449 | |
| 450 | elif isinstance(delta, str): |
| 451 | content += delta |
| 452 | if stream and event.stop_reason is None: |
| 453 | yield AgentTurnResponseStreamChunk( |
| 454 | event=AgentTurnResponseEvent( |
| 455 | payload=AgentTurnResponseStepProgressPayload( |
| 456 | step_type=StepType.inference.value, |
| 457 | step_id=step_id, |
| 458 | model_response_text_delta=event.delta, |
| 459 | ) |
| 460 | ) |
| 461 | ) |
| 462 | else: |
| 463 | raise ValueError(f"Unexpected delta type {type(delta)}") |
| 464 | |
| 465 | if event.stop_reason is not None: |
| 466 | stop_reason = event.stop_reason |
| 467 | |
| 468 | stop_reason = stop_reason or StopReason.out_of_tokens |
| 469 | message = CompletionMessage( |
| 470 | content=content, |
| 471 | stop_reason=stop_reason, |
| 472 | tool_calls=tool_calls, |
| 473 | ) |
| 474 | |
| 475 | yield AgentTurnResponseStreamChunk( |
| 476 | event=AgentTurnResponseEvent( |
| 477 | payload=AgentTurnResponseStepCompletePayload( |
| 478 | step_type=StepType.inference.value, |
| 479 | step_id=step_id, |
| 480 | step_details=InferenceStep( |
| 481 | # somewhere deep, we are re-assigning message or closing over some |
| 482 | # variable which causes message to mutate later on. fix with a |
| 483 | # `deepcopy` for now, but this is symptomatic of a deeper issue. |
| 484 | step_id=step_id, |
| 485 | turn_id=turn_id, |
| 486 | model_response=copy.deepcopy(message), |
| 487 | ), |
| 488 | ) |
| 489 | ) |
| 490 | ) |
| 491 | |
| 492 | if n_iter >= self.agent_config.max_infer_iters: |
| 493 | cprint("Done with MAX iterations, exiting.") |
| 494 | yield message |
| 495 | break |
| 496 | |
| 497 | if stop_reason == StopReason.out_of_tokens: |
| 498 | cprint("Out of token budget, exiting.") |
| 499 | yield message |
| 500 | break |
| 501 | |
| 502 | if len(message.tool_calls) == 0: |
| 503 | if stop_reason == StopReason.end_of_turn: |
| 504 | # TODO: UPDATE RETURN TYPE TO SEND A TUPLE OF (MESSAGE, ATTACHMENTS) |
| 505 | if len(output_attachments) > 0: |
| 506 | if isinstance(message.content, list): |
| 507 | message.content += attachments |
| 508 | else: |
| 509 | message.content = [message.content] + attachments |
| 510 | yield message |
| 511 | else: |
| 512 | cprint(f"Partial message: {str(message)}", color="green") |
| 513 | input_messages = input_messages + [message] |
| 514 | else: |
| 515 | cprint(f"{str(message)}", color="green") |
| 516 | try: |
| 517 | tool_call = message.tool_calls[0] |
| 518 | |
| 519 | name = tool_call.tool_name |
| 520 | if not isinstance(name, BuiltinTool): |
| 521 | yield message |
| 522 | return |
| 523 | |
| 524 | step_id = str(uuid.uuid4()) |
| 525 | yield AgentTurnResponseStreamChunk( |
| 526 | event=AgentTurnResponseEvent( |
| 527 | payload=AgentTurnResponseStepStartPayload( |
| 528 | step_type=StepType.tool_execution.value, |
| 529 | step_id=step_id, |
| 530 | ) |
| 531 | ) |
| 532 | ) |
| 533 | yield AgentTurnResponseStreamChunk( |
| 534 | event=AgentTurnResponseEvent( |
| 535 | payload=AgentTurnResponseStepProgressPayload( |
| 536 | step_type=StepType.tool_execution.value, |
| 537 | step_id=step_id, |
| 538 | tool_call=tool_call, |
| 539 | ) |
| 540 | ) |
| 541 | ) |
| 542 | |
| 543 | with tracing.span("tool_execution"): |
| 544 | result_messages = await execute_tool_call_maybe( |
| 545 | self.tools_dict, |
| 546 | [message], |
| 547 | ) |
| 548 | assert ( |
| 549 | len(result_messages) == 1 |
| 550 | ), "Currently not supporting multiple messages" |
| 551 | result_message = result_messages[0] |
| 552 | |
| 553 | yield AgentTurnResponseStreamChunk( |
| 554 | event=AgentTurnResponseEvent( |
| 555 | payload=AgentTurnResponseStepCompletePayload( |
| 556 | step_type=StepType.tool_execution.value, |
| 557 | step_details=ToolExecutionStep( |
| 558 | step_id=step_id, |
| 559 | turn_id=turn_id, |
| 560 | tool_calls=[tool_call], |
| 561 | tool_responses=[ |
| 562 | ToolResponse( |
| 563 | call_id=result_message.call_id, |
| 564 | tool_name=result_message.tool_name, |
| 565 | content=result_message.content, |
| 566 | ) |
| 567 | ], |
| 568 | ), |
| 569 | ) |
| 570 | ) |
| 571 | ) |
| 572 | |
| 573 | # TODO: add tool-input touchpoint and a "start" event for this step also |
| 574 | # but that needs a lot more refactoring of Tool code potentially |
| 575 | yield AgentTurnResponseStreamChunk( |
| 576 | event=AgentTurnResponseEvent( |
| 577 | payload=AgentTurnResponseStepCompletePayload( |
| 578 | step_type=StepType.shield_call.value, |
| 579 | step_details=ShieldCallStep( |
| 580 | step_id=str(uuid.uuid4()), |
| 581 | turn_id=turn_id, |
| 582 | violation=None, |
| 583 | ), |
| 584 | ) |
| 585 | ) |
| 586 | ) |
| 587 | |
| 588 | except SafetyException as e: |
| 589 | yield AgentTurnResponseStreamChunk( |
| 590 | event=AgentTurnResponseEvent( |
| 591 | payload=AgentTurnResponseStepCompletePayload( |
| 592 | step_type=StepType.shield_call.value, |
| 593 | step_details=ShieldCallStep( |
| 594 | step_id=str(uuid.uuid4()), |
| 595 | turn_id=turn_id, |
| 596 | violation=e.violation, |
| 597 | ), |
| 598 | ) |
| 599 | ) |
| 600 | ) |
| 601 | |
| 602 | yield CompletionMessage( |
| 603 | content=str(e), |
| 604 | stop_reason=StopReason.end_of_turn, |
| 605 | ) |
| 606 | yield False |
| 607 | return |
| 608 | |
| 609 | if out_attachment := interpret_content_as_attachment( |
| 610 | result_message.content |
| 611 | ): |
| 612 | # NOTE: when we push this message back to the model, the model may ignore the |
| 613 | # attached file path etc. since the model is trained to only provide a user message |
| 614 | # with the summary. We keep all generated attachments and then attach them to final message |
| 615 | output_attachments.append(out_attachment) |
| 616 | |
| 617 | input_messages = input_messages + [message, result_message] |
| 618 | |
| 619 | n_iter += 1 |
| 620 | |
| 621 | async def _ensure_memory_bank(self, session_id: str) -> str: |
| 622 | session_info = await self.storage.get_session_info(session_id) |
| 623 | if session_info is None: |
| 624 | raise ValueError(f"Session {session_id} not found") |
| 625 | |
| 626 | if session_info.memory_bank_id is None: |
| 627 | memory_bank = await self.memory_api.create_memory_bank( |
| 628 | name=f"memory_bank_{session_id}", |
| 629 | config=VectorMemoryBankConfig( |
| 630 | embedding_model="all-MiniLM-L6-v2", |
| 631 | chunk_size_in_tokens=512, |
| 632 | ), |
| 633 | ) |
| 634 | bank_id = memory_bank.bank_id |
| 635 | await self.storage.add_memory_bank_to_session(session_id, bank_id) |
| 636 | else: |
| 637 | bank_id = session_info.memory_bank_id |
| 638 | |
| 639 | return bank_id |
| 640 | |
| 641 | async def _should_retrieve_context( |
| 642 | self, messages: List[Message], attachments: List[Attachment] |
| 643 | ) -> bool: |
| 644 | enabled_tools = set(t.type for t in self.agent_config.tools) |
| 645 | if attachments: |
| 646 | if ( |
| 647 | AgentTool.code_interpreter.value in enabled_tools |
| 648 | and self.agent_config.tool_choice == ToolChoice.required |
| 649 | ): |
| 650 | return False |
| 651 | else: |
| 652 | return True |
| 653 | |
| 654 | return AgentTool.memory.value in enabled_tools |
| 655 | |
| 656 | def _memory_tool_definition(self) -> Optional[MemoryToolDefinition]: |
| 657 | for t in self.agent_config.tools: |
| 658 | if t.type == AgentTool.memory.value: |
| 659 | return t |
| 660 | |
| 661 | return None |
| 662 | |
| 663 | async def _retrieve_context( |
| 664 | self, session_id: str, messages: List[Message], attachments: List[Attachment] |
| 665 | ) -> Tuple[List[str], List[int]]: # (rag_context, bank_ids) |
| 666 | bank_ids = [] |
| 667 | |
| 668 | memory = self._memory_tool_definition() |
| 669 | assert memory is not None, "Memory tool not configured" |
| 670 | bank_ids.extend(c.bank_id for c in memory.memory_bank_configs) |
| 671 | |
| 672 | if attachments: |
| 673 | bank_id = await self._ensure_memory_bank(session_id) |
| 674 | bank_ids.append(bank_id) |
| 675 | |
| 676 | documents = [ |
| 677 | MemoryBankDocument( |
| 678 | document_id=str(uuid.uuid4()), |
| 679 | content=a.content, |
| 680 | mime_type=a.mime_type, |
| 681 | metadata={}, |
| 682 | ) |
| 683 | for a in attachments |
| 684 | ] |
| 685 | with tracing.span("insert_documents"): |
| 686 | await self.memory_api.insert_documents(bank_id, documents) |
| 687 | else: |
| 688 | session_info = await self.storage.get_session_info(session_id) |
| 689 | if session_info.memory_bank_id: |
| 690 | bank_ids.append(session_info.memory_bank_id) |
| 691 | |
| 692 | if not bank_ids: |
| 693 | # this can happen if the per-session memory bank is not yet populated |
| 694 | # (i.e., no prior turns uploaded an Attachment) |
| 695 | return None, [] |
| 696 | |
| 697 | query = await generate_rag_query( |
| 698 | memory.query_generator_config, messages, inference_api=self.inference_api |
| 699 | ) |
| 700 | tasks = [ |
| 701 | self.memory_api.query_documents( |
| 702 | bank_id=bank_id, |
| 703 | query=query, |
| 704 | params={ |
| 705 | "max_chunks": 5, |
| 706 | }, |
| 707 | ) |
| 708 | for bank_id in bank_ids |
| 709 | ] |
| 710 | results: List[QueryDocumentsResponse] = await asyncio.gather(*tasks) |
| 711 | chunks = [c for r in results for c in r.chunks] |
| 712 | scores = [s for r in results for s in r.scores] |
| 713 | |
| 714 | # sort by score |
| 715 | chunks, scores = zip( |
| 716 | *sorted(zip(chunks, scores), key=lambda x: x[1], reverse=True) |
| 717 | ) |
| 718 | if not chunks: |
| 719 | return None, bank_ids |
| 720 | |
| 721 | tokens = 0 |
| 722 | picked = [] |
| 723 | for c in chunks[: memory.max_chunks]: |
| 724 | tokens += c.token_count |
| 725 | if tokens > memory.max_tokens_in_context: |
| 726 | cprint( |
| 727 | f"Using {len(picked)} chunks; reached max tokens in context: {tokens}", |
| 728 | "red", |
| 729 | ) |
| 730 | break |
| 731 | picked.append(f"id:{c.document_id}; content:{c.content}") |
| 732 | |
| 733 | return [ |
| 734 | "Here are the retrieved documents for relevant context:\n=== START-RETRIEVED-CONTEXT ===\n", |
| 735 | *picked, |
| 736 | "\n=== END-RETRIEVED-CONTEXT ===\n", |
| 737 | ], bank_ids |
| 738 | |
| 739 | def _get_tools(self) -> List[ToolDefinition]: |
| 740 | ret = [] |
| 741 | for t in self.agent_config.tools: |
| 742 | if isinstance(t, SearchToolDefinition): |
| 743 | ret.append(ToolDefinition(tool_name=BuiltinTool.brave_search)) |
| 744 | elif isinstance(t, WolframAlphaToolDefinition): |
| 745 | ret.append(ToolDefinition(tool_name=BuiltinTool.wolfram_alpha)) |
| 746 | elif isinstance(t, PhotogenToolDefinition): |
| 747 | ret.append(ToolDefinition(tool_name=BuiltinTool.photogen)) |
| 748 | elif isinstance(t, CodeInterpreterToolDefinition): |
| 749 | ret.append(ToolDefinition(tool_name=BuiltinTool.code_interpreter)) |
| 750 | elif isinstance(t, FunctionCallToolDefinition): |
| 751 | ret.append( |
| 752 | ToolDefinition( |
| 753 | tool_name=t.function_name, |
| 754 | description=t.description, |
| 755 | parameters=t.parameters, |
| 756 | ) |
| 757 | ) |
| 758 | return ret |
| 759 | |
| 760 | |
| 761 | async def attachment_message(tempdir: str, urls: List[URL]) -> ToolResponseMessage: |
| 762 | content = [] |
| 763 | |
| 764 | for url in urls: |
| 765 | uri = url.uri |
| 766 | if uri.startswith("file://"): |
| 767 | filepath = uri[len("file://") :] |
| 768 | elif uri.startswith("http"): |
| 769 | path = urlparse(uri).path |
| 770 | basename = os.path.basename(path) |
| 771 | filepath = f"{tempdir}/{make_random_string() + basename}" |
| 772 | print(f"Downloading {url} -> {filepath}") |
| 773 | |
| 774 | async with httpx.AsyncClient() as client: |
| 775 | r = await client.get(uri) |
| 776 | resp = r.text |
| 777 | with open(filepath, "w") as fp: |
| 778 | fp.write(resp) |
| 779 | else: |
| 780 | raise ValueError(f"Unsupported URL {url}") |
| 781 | |
| 782 | content.append(f'# There is a file accessible to you at "{filepath}"\n') |
| 783 | |
| 784 | return ToolResponseMessage( |
| 785 | call_id="", |
| 786 | tool_name=BuiltinTool.code_interpreter, |
| 787 | content=content, |
| 788 | ) |
| 789 | |
| 790 | |
| 791 | async def execute_tool_call_maybe( |
| 792 | tools_dict: Dict[str, BaseTool], messages: List[CompletionMessage] |
| 793 | ) -> List[ToolResponseMessage]: |
| 794 | # While Tools.run interface takes a list of messages, |
| 795 | # All tools currently only run on a single message |
| 796 | # When this changes, we can drop this assert |
| 797 | # Whether to call tools on each message and aggregate |
| 798 | # or aggregate and call tool once, reamins to be seen. |
| 799 | assert len(messages) == 1, "Expected single message" |
| 800 | message = messages[0] |
| 801 | |
| 802 | tool_call = message.tool_calls[0] |
| 803 | name = tool_call.tool_name |
| 804 | assert isinstance(name, BuiltinTool) |
| 805 | |
| 806 | name = name.value |
| 807 | |
| 808 | assert name in tools_dict, f"Tool {name} not found" |
| 809 | tool = tools_dict[name] |
| 810 | result_messages = await tool.run(messages) |
| 811 | return result_messages |
| 812 | |
| 813 | |
| 814 | def print_dialog(messages: List[Message]): |
| 815 | for i, m in enumerate(messages): |
| 816 | if m.role == Role.user.value: |
| 817 | color = "red" |
| 818 | elif m.role == Role.assistant.value: |
| 819 | color = "white" |
| 820 | elif m.role == Role.ipython.value: |
| 821 | color = "yellow" |
| 822 | elif m.role == Role.system.value: |
| 823 | color = "green" |
| 824 | else: |
| 825 | color = "white" |
| 826 | |
| 827 | s = str(m) |
| 828 | cprint(f"{i} ::: {s[:100]}...", color=color) |