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