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