A programming framework for agentic AI
Feat/tool call loop (#6651)
Tejas Dharani6f15270cb203
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_assistant_agent.py b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_assistant_agent.pyindex 3e50c0e94..d01cf93ee 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_assistant_agent.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_assistant_agent.py@@ -5,7 +5,20 @@ import jsonimport loggingimport uuidimport warnings-from typing import Any, AsyncGenerator, Awaitable, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Union+from typing import (+ Any,+ AsyncGenerator,+ Awaitable,+ Callable,+ Dict,+ List,+ Mapping,+ Optional,+ Sequence,+ Tuple,+ TypeVar,+ Union,+)from autogen_core import CancellationToken, Component, ComponentModel, FunctionCallfrom autogen_core.memory import Memory@@ -24,7 +37,7 @@ from autogen_core.models import (SystemMessage,)from autogen_core.tools import BaseTool, FunctionTool, StaticStreamWorkbench, ToolResult, Workbench-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom typing_extensions import Selffrom .. import EVENT_LOGGER_NAME@@ -50,6 +63,10 @@ from ._base_chat_agent import BaseChatAgentevent_logger = logging.getLogger(EVENT_LOGGER_NAME)+# Add type variables for more specific typing+T = TypeVar("T", bound=BaseModel)+R = TypeVar("R", bound=BaseModel)+class AssistantAgentConfig(BaseModel):"""The declarative configuration for the assistant agent."""@@ -66,13 +83,13 @@ class AssistantAgentConfig(BaseModel):model_client_stream: bool = Falsereflect_on_tool_use: booltool_call_summary_format: str+ max_tool_iterations: int = Field(default=1, ge=1)metadata: Dict[str, str] | None = Nonestructured_message_factory: ComponentModel | None = Noneclass AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):"""An agent that provides assistance with tool use.-The :meth:`on_messages` returns a :class:`~autogen_agentchat.base.Response`in which :attr:`~autogen_agentchat.base.Response.chat_message` is the finalresponse message.@@ -120,13 +137,14 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):**Tool call behavior:**- * If the model returns no tool call, then the response is immediately returned as a :class:`~autogen_agentchat.messages.TextMessage` or a :class:`~autogen_agentchat.messages.StructuredMessage` (when using structured output) in :attr:`~autogen_agentchat.base.Response.chat_message`.+ * If the model returns no tool call, then the response is immediately returned as a :class:`~autogen_agentchat.messages.TextMessage` or a :class:`~autogen_agentchat.messages.StructuredMessage` (when using structured output) in :attr:`~autogen_agentchat.base.Response.chat_message`. This ends the tool call iteration loop regardless of the `max_tool_iterations` setting.* When the model returns tool calls, they will be executed right away:- When `reflect_on_tool_use` is False, the tool call results are returned as a :class:`~autogen_agentchat.messages.ToolCallSummaryMessage` in :attr:`~autogen_agentchat.base.Response.chat_message`. You can customise the summary with either a static format string (`tool_call_summary_format`) **or** a callable (`tool_call_summary_formatter`); the callable is evaluated once per tool call.- When `reflect_on_tool_use` is True, the another model inference is made using the tool calls and results, and final response is returned as a :class:`~autogen_agentchat.messages.TextMessage` or a :class:`~autogen_agentchat.messages.StructuredMessage` (when using structured output) in :attr:`~autogen_agentchat.base.Response.chat_message`.- `reflect_on_tool_use` is set to `True` by default when `output_content_type` is set.- `reflect_on_tool_use` is set to `False` by default when `output_content_type` is not set.* If the model returns multiple tool calls, they will be executed concurrently. To disable parallel tool calls you need to configure the model client. For example, set `parallel_tool_calls=False` for :class:`~autogen_ext.models.openai.OpenAIChatCompletionClient` and :class:`~autogen_ext.models.openai.AzureOpenAIChatCompletionClient`.+ * The `max_tool_iterations` parameter controls how many sequential tool call iterations the agent can perform in a single run. When set to 1 (default), the agent executes tool calls once and returns the result. When set higher, the agent can make additional model calls to execute more tool calls if the model continues to request them, enabling multi-step tool-based workflows. The agent stops when either the model returns a text response (instead of tool calls) or the maximum number of iterations is reached... tip::@@ -174,7 +192,6 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):messages as the model client produces chunks of response.The chunk messages will not be included in the final response's inner messages.-Args:name (str): The name of the agent.model_client (ChatCompletionClient): The model client to use for inference.@@ -199,6 +216,12 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):If this is set, the agent will respond with a :class:`~autogen_agentchat.messages.StructuredMessage` instead of a :class:`~autogen_agentchat.messages.TextMessage`in the final response, unless `reflect_on_tool_use` is `False` and a tool call is made.output_content_type_format (str | None, optional): (Experimental) The format string used for the content of a :class:`~autogen_agentchat.messages.StructuredMessage` response.+ max_tool_iterations (int, optional): The maximum number of tool iterations to perform until the model stops making tool calls. Defaults to `1`, which means the agent will+ only execute the tool calls made by the model once, and return the result as a :class:`~autogen_agentchat.messages.ToolCallSummaryMessage`,+ or a :class:`~autogen_agentchat.messages.TextMessage` or a :class:`~autogen_agentchat.messages.StructuredMessage` (when using structured output)+ in :attr:`~autogen_agentchat.base.Response.chat_message` as the final response.+ As soon as the model stops making tool calls, the agent will stop executing tool calls and return the result as the final response.+ The value must be greater than or equal to 1.tool_call_summary_format (str, optional): Static format string applied to each tool call result when composing the :class:`~autogen_agentchat.messages.ToolCallSummaryMessage`.Defaults to ``"{result}"``. Ignored if `tool_call_summary_formatter` is provided. When `reflect_on_tool_use` is ``False``, the summaries for all toolcalls are concatenated with a newline ('\\n') and returned as the response. Placeholders available in the template:@@ -337,7 +360,59 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):asyncio.run(main())- **Example 4: agent with Model-Context Protocol (MCP) workbench**+ **Example 4: agent with max_tool_iterations**++ The following example demonstrates how to use the `max_tool_iterations` parameter+ to control how many times the agent can execute tool calls in a single run.+ This is useful when you want the agent to perform multiple sequential tool+ operations to reach a goal.++ .. code-block:: python++ import asyncio+ from autogen_ext.models.openai import OpenAIChatCompletionClient+ from autogen_agentchat.agents import AssistantAgent+ from autogen_agentchat.ui import Console+++ # Global counter state+ counter = 0+++ def increment_counter() -> str:+ \"\"\"Increment the counter by 1 and return the current value.\"\"\"+ global counter+ counter += 1+ return f"Counter incremented to: {counter}"+++ def get_counter() -> str:+ \"\"\"Get the current counter value.\"\"\"+ global counter+ return f"Current counter value: {counter}"+++ async def main() -> None:+ model_client = OpenAIChatCompletionClient(+ model="gpt-4o",+ # api_key = "your_openai_api_key"+ )++ # Create agent with max_tool_iterations=5 to allow multiple tool calls+ agent = AssistantAgent(+ name="assistant",+ model_client=model_client,+ tools=[increment_counter, get_counter],+ max_tool_iterations=5, # Allow up to 5 tool call iterations+ reflect_on_tool_use=True, # Get a final summary after tool calls+ )++ await Console(agent.run_stream(task="Increment the counter 3 times and then tell me the final value."))+++ asyncio.run(main())++ **Example 5: agent with Model-Context Protocol (MCP) workbench**The following example demonstrates how to create an assistant agent witha model client and an :class:`~autogen_ext.tools.mcp.McpWorkbench` for@@ -375,7 +450,7 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):asyncio.run(main())- **Example 5: agent with structured output and tool**+ **Example 6: agent with structured output and tool**The following example demonstrates how to create an assistant agent witha model client configured to use structured output and a tool.@@ -443,7 +518,7 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):---------- assistant ----------{"thoughts":"The user expresses a clear positive emotion by stating they are happy today, suggesting an upbeat mood.","response":"happy"}- **Example 6: agent with bounded model context**+ **Example 7: agent with bounded model context**The following example shows how to use a:class:`~autogen_core.model_context.BufferedChatCompletionContext`@@ -496,7 +571,7 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):That's great! Blue is often associated with calmness and serenity. Do you have a specific shade of blue that you like, or any particular reason why it's your favorite?No, you didn't ask a question. I apologize for any misunderstanding. If you have something specific you'd like to discuss or ask, feel free to let me know!- **Example 7: agent with memory**+ **Example 8: agent with memory**The following example shows how to use a list-based memory with the assistant agent.The memory is preloaded with some initial content.@@ -552,7 +627,7 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):Serve it with a side salad or some garlic bread to complete the meal! Enjoy your dinner!- **Example 8: agent with `o1-mini`**+ **Example 9: agent with `o1-mini`**The following example shows how to use `o1-mini` model with the assistant agent.@@ -584,7 +659,7 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):See `o1 beta limitations <https://platform.openai.com/docs/guides/reasoning#beta-limitations>`_ for more details.- **Example 9: agent using reasoning model with custom model context.**+ **Example 10: agent using reasoning model with custom model context.**The following example shows how to use a reasoning model (DeepSeek R1) with the assistant agent.The model context is used to filter out the thought field from the assistant message.@@ -640,6 +715,7 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):asyncio.run(run_reasoning_agent())+ For detailed examples and usage, see the Examples section below."""component_version = 2@@ -661,6 +737,7 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):) = "You are a helpful AI assistant. Solve tasks using your tools. Reply with TERMINATE when the task has been completed.",model_client_stream: bool = False,reflect_on_tool_use: bool | None = None,+ max_tool_iterations: int = 1,tool_call_summary_format: str = "{result}",tool_call_summary_formatter: Callable[[FunctionCall, FunctionExecutionResult], str] | None = None,output_content_type: type[BaseModel] | None = None,@@ -730,12 +807,23 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):handoff_tool_names = [tool.name for tool in self._handoff_tools]if len(handoff_tool_names) != len(set(handoff_tool_names)):raise ValueError(f"Handoff names must be unique: {handoff_tool_names}")- # Check if handoff tool names not in tool names.- if any(name in tool_names for name in handoff_tool_names):- raise ValueError(- f"Handoff names must be unique from tool names. "- f"Handoff names: {handoff_tool_names}; tool names: {tool_names}"- )+ # Create sets for faster lookup+ tool_names_set = set(tool_names)+ handoff_tool_names_set = set(handoff_tool_names)++ # Check if there's any overlap between handoff tool names and tool names+ overlap = tool_names_set.intersection(handoff_tool_names_set)++ # Also check if any handoff target name matches a tool name+ # This handles the case where a handoff is specified directly with a string that matches a tool name+ for handoff in handoffs or []:+ if isinstance(handoff, str) and handoff in tool_names_set:+ raise ValueError("Handoff names must be unique from tool names")+ elif isinstance(handoff, HandoffBase) and handoff.target in tool_names_set:+ raise ValueError("Handoff names must be unique from tool names")++ if overlap:+ raise ValueError("Handoff names must be unique from tool names")if workbench is not None:if self._tools:@@ -769,41 +857,71 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):UserWarning,stacklevel=2,)++ # Tool call loop+ self._max_tool_iterations = max_tool_iterations+ if self._max_tool_iterations < 1:+ raise ValueError(+ f"Maximum number of tool iterations must be greater than or equal to 1, got {max_tool_iterations}"+ )+self._tool_call_summary_format = tool_call_summary_formatself._tool_call_summary_formatter = tool_call_summary_formatterself._is_running = False@propertydef produced_message_types(self) -> Sequence[type[BaseChatMessage]]:- message_types: List[type[BaseChatMessage]] = []- if self._handoffs:- message_types.append(HandoffMessage)- if self._tools:- message_types.append(ToolCallSummaryMessage)- if self._output_content_type:- message_types.append(StructuredMessage[self._output_content_type]) # type: ignore[name-defined]- else:- message_types.append(TextMessage)- return tuple(message_types)+ """Get the types of messages this agent can produce.++ Returns:+ Sequence of message types this agent can generate+ """+ types: List[type[BaseChatMessage]] = [TextMessage, ToolCallSummaryMessage, HandoffMessage]+ if self._structured_message_factory is not None:+ types.append(StructuredMessage)+ return types@propertydef model_context(self) -> ChatCompletionContext:- """- The model context in use by the agent.+ """Get the model context used by this agent.++ Returns:+ The chat completion context for this agent"""return self._model_context- async def on_messages(self, messages: Sequence[BaseChatMessage], cancellation_token: CancellationToken) -> Response:+ async def on_messages(+ self,+ messages: Sequence[BaseChatMessage],+ cancellation_token: CancellationToken,+ ) -> Response:+ """Process incoming messages and generate a response.++ Args:+ messages: Sequence of messages to process+ cancellation_token: Token for cancelling operation++ Returns:+ Response containing the agent's reply+ """async for message in self.on_messages_stream(messages, cancellation_token):if isinstance(message, Response):return messageraise AssertionError("The stream should have returned the final result.")async def on_messages_stream(- self, messages: Sequence[BaseChatMessage], cancellation_token: CancellationToken- ) -> AsyncGenerator[BaseAgentEvent | BaseChatMessage | Response, None]:- """- Process the incoming messages with the assistant agent and yield events/responses as they happen.+ self,+ messages: Sequence[BaseChatMessage],+ cancellation_token: CancellationToken,+ ) -> AsyncGenerator[Union[BaseAgentEvent, BaseChatMessage, Response], None]:+ """Process messages and stream the response.++ Args:+ messages: Sequence of messages to process+ cancellation_token: Token for cancelling operation++ Yields:+ Events, messages and final response during processing"""# Gather all relevant state here@@ -817,10 +935,10 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):model_client = self._model_clientmodel_client_stream = self._model_client_streamreflect_on_tool_use = self._reflect_on_tool_use+ max_tool_iterations = self._max_tool_iterationstool_call_summary_format = self._tool_call_summary_formattool_call_summary_formatter = self._tool_call_summary_formatteroutput_content_type = self._output_content_type- format_string = self._output_content_type_format# STEP 1: Add new user/handoff messages to the model contextawait self._add_messages_to_context(@@ -892,11 +1010,12 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):model_client=model_client,model_client_stream=model_client_stream,reflect_on_tool_use=reflect_on_tool_use,+ max_tool_iterations=max_tool_iterations,tool_call_summary_format=tool_call_summary_format,tool_call_summary_formatter=tool_call_summary_formatter,output_content_type=output_content_type,message_id=message_id,- format_string=format_string,+ format_string=self._output_content_type_format,):yield output_event@@ -920,8 +1039,15 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):model_context: ChatCompletionContext,agent_name: str,) -> List[MemoryQueryEvent]:- """- If memory modules are present, update the model context and return the events produced.+ """Update model context with memory content.++ Args:+ memory: Optional sequence of memory stores to query+ model_context: Context to update with memory content+ agent_name: Name of the agent for event tracking++ Returns:+ List of memory query events generated during update"""events: List[MemoryQueryEvent] = []if memory:@@ -949,8 +1075,21 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):output_content_type: type[BaseModel] | None,message_id: str,) -> AsyncGenerator[Union[CreateResult, ModelClientStreamingChunkEvent], None]:- """- Perform a model inference and yield either streaming chunk events or the final CreateResult.+ """Call the language model with given context and configuration.++ Args:+ model_client: Client for model inference+ model_client_stream: Whether to stream responses+ system_messages: System messages to include+ model_context: Context containing message history+ workbench: Available workbenches+ handoff_tools: Tools for handling handoffs+ agent_name: Name of the agent+ cancellation_token: Token for cancelling operation+ output_content_type: Optional type for structured output++ Returns:+ Generator yielding model results or streaming chunks"""all_messages = await model_context.get_messages()llm_messages = cls._get_compatible_context(model_client=model_client, messages=system_messages + all_messages)@@ -1001,130 +1140,184 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):reflect_on_tool_use: bool,tool_call_summary_format: str,tool_call_summary_formatter: Callable[[FunctionCall, FunctionExecutionResult], str] | None,+ max_tool_iterations: int,output_content_type: type[BaseModel] | None,message_id: str,format_string: str | None = None,) -> AsyncGenerator[BaseAgentEvent | BaseChatMessage | Response, None]:"""Handle final or partial responses from model_result, including tool calls, handoffs,- and reflection if needed.+ and reflection if needed. Supports tool call loops when enabled."""- # If direct text response (string)- if isinstance(model_result.content, str):- # Use the passed message ID for the final message- if output_content_type:- content = output_content_type.model_validate_json(model_result.content)- yield Response(- chat_message=StructuredMessage[output_content_type]( # type: ignore[valid-type]- content=content,- source=agent_name,- models_usage=model_result.usage,- format_string=format_string,- id=message_id,- ),- inner_messages=inner_messages,- )- else:- yield Response(- chat_message=TextMessage(- content=model_result.content,- source=agent_name,- models_usage=model_result.usage,- id=message_id,- ),- inner_messages=inner_messages,- )- return-- # Otherwise, we have function calls- assert isinstance(model_result.content, list) and all(- isinstance(item, FunctionCall) for item in model_result.content- )-- # STEP 4A: Yield ToolCallRequestEvent- tool_call_msg = ToolCallRequestEvent(- content=model_result.content,- source=agent_name,- models_usage=model_result.usage,- )- event_logger.debug(tool_call_msg)- inner_messages.append(tool_call_msg)- yield tool_call_msg-- # STEP 4B: Execute tool calls- # Use a queue to handle streaming results from tool calls.- stream = asyncio.Queue[BaseAgentEvent | BaseChatMessage | None]()-- async def _execute_tool_calls(- function_calls: List[FunctionCall],- ) -> List[Tuple[FunctionCall, FunctionExecutionResult]]:- results = await asyncio.gather(- *[- cls._execute_tool_call(- tool_call=call,- workbench=workbench,- handoff_tools=handoff_tools,- agent_name=agent_name,- cancellation_token=cancellation_token,- stream=stream,+ # Tool call loop implementation with streaming support+ current_model_result = model_result+ # This variable is needed for the final summary/reflection step+ executed_calls_and_results: List[Tuple[FunctionCall, FunctionExecutionResult]] = []++ for loop_iteration in range(max_tool_iterations):+ # If direct text response (string), we're done+ if isinstance(current_model_result.content, str):+ # Use the passed message ID for the final message+ if output_content_type:+ content = output_content_type.model_validate_json(current_model_result.content)+ yield Response(+ chat_message=StructuredMessage[output_content_type]( # type: ignore[valid-type]+ content=content,+ source=agent_name,+ models_usage=current_model_result.usage,+ format_string=format_string,+ id=message_id,+ ),+ inner_messages=inner_messages,+ )+ else:+ yield Response(+ chat_message=TextMessage(+ content=current_model_result.content,+ source=agent_name,+ models_usage=current_model_result.usage,+ id=message_id,+ ),+ inner_messages=inner_messages,)- for call in function_calls- ]+ return++ # Otherwise, we have function calls+ assert isinstance(current_model_result.content, list) and all(+ isinstance(item, FunctionCall) for item in current_model_result.content)- # Signal the end of streaming by putting None in the queue.- stream.put_nowait(None)- return results- task = asyncio.create_task(_execute_tool_calls(model_result.content))+ # STEP 4A: Yield ToolCallRequestEvent+ tool_call_msg = ToolCallRequestEvent(+ content=current_model_result.content,+ source=agent_name,+ models_usage=current_model_result.usage,+ )+ event_logger.debug(tool_call_msg)+ inner_messages.append(tool_call_msg)+ yield tool_call_msg++ # STEP 4B: Execute tool calls with streaming support+ # Use a queue to handle streaming results from tool calls.+ stream = asyncio.Queue[BaseAgentEvent | BaseChatMessage | None]()++ async def _execute_tool_calls(+ function_calls: List[FunctionCall],+ stream_queue: asyncio.Queue[BaseAgentEvent | BaseChatMessage | None],+ ) -> List[Tuple[FunctionCall, FunctionExecutionResult]]:+ results = await asyncio.gather(+ *[+ cls._execute_tool_call(+ tool_call=call,+ workbench=workbench,+ handoff_tools=handoff_tools,+ agent_name=agent_name,+ cancellation_token=cancellation_token,+ stream=stream_queue,+ )+ for call in function_calls+ ]+ )+ # Signal the end of streaming by putting None in the queue.+ stream_queue.put_nowait(None)+ return results++ task = asyncio.create_task(_execute_tool_calls(current_model_result.content, stream))++ while True:+ event = await stream.get()+ if event is None:+ # End of streaming, break the loop.+ break+ if isinstance(event, BaseAgentEvent) or isinstance(event, BaseChatMessage):+ yield event+ inner_messages.append(event)+ else:+ raise RuntimeError(f"Unexpected event type: {type(event)}")- while True:- event = await stream.get()- if event is None:- # End of streaming, break the loop.- break- if isinstance(event, BaseAgentEvent) or isinstance(event, BaseChatMessage):- yield event- inner_messages.append(event)- else:- raise RuntimeError(f"Unexpected event type: {type(event)}")+ # Wait for all tool calls to complete.+ executed_calls_and_results = await task+ exec_results = [result for _, result in executed_calls_and_results]- # Wait for all tool calls to complete.- executed_calls_and_results = await task- exec_results = [result for _, result in executed_calls_and_results]+ # Yield ToolCallExecutionEvent+ tool_call_result_msg = ToolCallExecutionEvent(+ content=exec_results,+ source=agent_name,+ )+ event_logger.debug(tool_call_result_msg)+ await model_context.add_message(FunctionExecutionResultMessage(content=exec_results))+ inner_messages.append(tool_call_result_msg)+ yield tool_call_result_msg++ # STEP 4C: Check for handoff+ handoff_output = cls._check_and_handle_handoff(+ model_result=current_model_result,+ executed_calls_and_results=executed_calls_and_results,+ inner_messages=inner_messages,+ handoffs=handoffs,+ agent_name=agent_name,+ )+ if handoff_output:+ yield handoff_output+ return- # Yield ToolCallExecutionEvent- tool_call_result_msg = ToolCallExecutionEvent(- content=exec_results,- source=agent_name,- )- event_logger.debug(tool_call_result_msg)- await model_context.add_message(FunctionExecutionResultMessage(content=exec_results))- inner_messages.append(tool_call_result_msg)- yield tool_call_result_msg+ # STEP 4D: Check if we should continue the loop.+ # If we are on the last iteration, break to the summary/reflection step.+ if loop_iteration == max_tool_iterations - 1:+ break- # STEP 4C: Check for handoff- handoff_output = cls._check_and_handle_handoff(- model_result=model_result,- executed_calls_and_results=executed_calls_and_results,- inner_messages=inner_messages,- handoffs=handoffs,- agent_name=agent_name,- )- if handoff_output:- yield handoff_output- return+ # Continue the loop: make another model call using _call_llm+ next_model_result: Optional[CreateResult] = None+ async for llm_output in cls._call_llm(+ model_client=model_client,+ model_client_stream=model_client_stream,+ system_messages=system_messages,+ model_context=model_context,+ workbench=workbench,+ handoff_tools=handoff_tools,+ agent_name=agent_name,+ cancellation_token=cancellation_token,+ output_content_type=output_content_type,+ message_id=message_id, # Use same message ID for consistency+ ):+ if isinstance(llm_output, CreateResult):+ next_model_result = llm_output+ else:+ # Streaming chunk event+ yield llm_output++ assert next_model_result is not None, "No model result was produced in tool call loop."+ current_model_result = next_model_result++ # Yield thought event if present+ if current_model_result.thought:+ thought_event = ThoughtEvent(content=current_model_result.thought, source=agent_name)+ yield thought_event+ inner_messages.append(thought_event)++ # Add the assistant message to the model context (including thought if present)+ await model_context.add_message(+ AssistantMessage(+ content=current_model_result.content,+ source=agent_name,+ thought=getattr(current_model_result, "thought", None),+ )+ )- # STEP 4D: Reflect or summarize tool results+ # After the loop, reflect or summarize tool resultsif reflect_on_tool_use:async for reflection_response in cls._reflect_on_tool_use_flow(system_messages=system_messages,model_client=model_client,model_client_stream=model_client_stream,model_context=model_context,+ workbench=workbench,+ handoff_tools=handoff_tools,agent_name=agent_name,inner_messages=inner_messages,output_content_type=output_content_type,+ cancellation_token=cancellation_token,):yield reflection_responseelse:@@ -1136,6 +1329,7 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):tool_call_summary_formatter=tool_call_summary_formatter,agent_name=agent_name,)+ return@staticmethoddef _check_and_handle_handoff(@@ -1145,9 +1339,17 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):handoffs: Dict[str, HandoffBase],agent_name: str,) -> Optional[Response]:- """- Detect handoff calls, generate the HandoffMessage if needed, and return a Response.- If multiple handoffs exist, only the first is used.+ """Check for and handle any handoff requests in the model result.++ Args:+ model_result: Result from model inference+ executed_calls_and_results: List of executed tool calls and their results+ inner_messages: List of messages generated during processing+ handoffs: Dictionary of available handoff configurations+ agent_name: Name of the agent++ Returns:+ Optional response containing handoff message if handoff detected"""handoff_reqs = [call for call in model_result.content if isinstance(call, FunctionCall) and call.name in handoffs@@ -1217,9 +1419,12 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):model_client: ChatCompletionClient,model_client_stream: bool,model_context: ChatCompletionContext,+ workbench: Sequence[Workbench],+ handoff_tools: List[BaseTool[Any, Any]],agent_name: str,inner_messages: List[BaseAgentEvent | BaseChatMessage],output_content_type: type[BaseModel] | None,+ cancellation_token: CancellationToken,) -> AsyncGenerator[Response | ModelClientStreamingChunkEvent | ThoughtEvent, None]:"""If reflect_on_tool_use=True, we do another inference based on tool results@@ -1237,6 +1442,7 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):async for chunk in model_client.create_stream(llm_messages,json_output=output_content_type,+ cancellation_token=cancellation_token,):if isinstance(chunk, CreateResult):reflection_result = chunk@@ -1247,7 +1453,9 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):else:raise RuntimeError(f"Invalid chunk type: {type(chunk)}")else:- reflection_result = await model_client.create(llm_messages, json_output=output_content_type)+ reflection_result = await model_client.create(+ llm_messages, json_output=output_content_type, cancellation_token=cancellation_token+ )if not reflection_result or not isinstance(reflection_result.content, str):raise RuntimeError("Reflect on tool use produced no valid text response.")@@ -1305,19 +1513,16 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):normal_tool_calls = [(call, result) for call, result in executed_calls_and_results if call.name not in handoffs]def default_tool_call_summary_formatter(call: FunctionCall, result: FunctionExecutionResult) -> str:- return tool_call_summary_format-- summary_formatter = tool_call_summary_formatter or default_tool_call_summary_formatter-- tool_call_summaries = [- summary_formatter(call, result).format(+ return tool_call_summary_format.format(tool_name=call.name,arguments=call.arguments,result=result.content,is_error=result.is_error,)- for call, result in normal_tool_calls- ]++ summary_formatter = tool_call_summary_formatter or default_tool_call_summary_formatter++ tool_call_summaries = [summary_formatter(call, result) for call, result in normal_tool_calls]tool_call_summary = "\n".join(tool_call_summaries)return Response(@@ -1461,6 +1666,7 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):else None,model_client_stream=self._model_client_stream,reflect_on_tool_use=self._reflect_on_tool_use,+ max_tool_iterations=self._max_tool_iterations,tool_call_summary_format=self._tool_call_summary_format,structured_message_factory=self._structured_message_factory.dump_component()if self._structured_message_factory@@ -1492,6 +1698,7 @@ class AssistantAgent(BaseChatAgent, Component[AssistantAgentConfig]):system_message=config.system_message,model_client_stream=config.model_client_stream,reflect_on_tool_use=config.reflect_on_tool_use,+ max_tool_iterations=config.max_tool_iterations,tool_call_summary_format=config.tool_call_summary_format,output_content_type=output_content_type,output_content_type_format=format_string,diff --git a/python/packages/autogen-agentchat/tests/test_assistant_agent.py b/python/packages/autogen-agentchat/tests/test_assistant_agent.pyindex 5ffb731c1..5f9f3cf47 100644--- a/python/packages/autogen-agentchat/tests/test_assistant_agent.py+++ b/python/packages/autogen-agentchat/tests/test_assistant_agent.py@@ -1,17 +1,23 @@+"""Comprehensive tests for AssistantAgent functionality."""++# Standard library imports+import asyncioimport json-import logging-from typing import Dict, List+from typing import Any, List, Optional, Union, cast+from unittest.mock import AsyncMock, MagicMock, patch+# Third-party importsimport pytest-from autogen_agentchat import EVENT_LOGGER_NAME++# First-party importsfrom autogen_agentchat.agents import AssistantAgent-from autogen_agentchat.base import Handoff, TaskResult+from autogen_agentchat.agents._assistant_agent import AssistantAgentConfig+from autogen_agentchat.base import Handoff, Response, TaskResultfrom autogen_agentchat.messages import (BaseChatMessage,HandoffMessage,MemoryQueryEvent,ModelClientStreamingChunkEvent,- MultiModalMessage,StructuredMessage,TextMessage,ThoughtEvent,@@ -19,1616 +25,3383 @@ from autogen_agentchat.messages import (ToolCallRequestEvent,ToolCallSummaryMessage,)-from autogen_core import ComponentModel, FunctionCall, Image-from autogen_core.memory import ListMemory, Memory, MemoryContent, MemoryMimeType, MemoryQueryResult+from autogen_core import CancellationToken, ComponentModel, FunctionCall+from autogen_core.memory import Memory, MemoryContent, UpdateContextResult+from autogen_core.memory import MemoryQueryResult as MemoryQueryResultSetfrom autogen_core.model_context import BufferedChatCompletionContextfrom autogen_core.models import (AssistantMessage,CreateResult,FunctionExecutionResult,- FunctionExecutionResultMessage,- LLMMessage,+ ModelFamily,RequestUsage,SystemMessage,UserMessage,)-from autogen_core.models._model_client import ModelFamily, ModelInfo-from autogen_core.tools import BaseTool, FunctionTool, StaticWorkbenchfrom autogen_ext.models.openai import OpenAIChatCompletionClientfrom autogen_ext.models.replay import ReplayChatCompletionClient-from autogen_ext.tools.mcp import (- McpWorkbench,- SseServerParams,-)+from autogen_ext.tools.mcp import McpWorkbench, SseServerParamsfrom pydantic import BaseModel, ValidationError-from utils import FileLogHandler, compare_messages, compare_task_results-logger = logging.getLogger(EVENT_LOGGER_NAME)-logger.setLevel(logging.DEBUG)-logger.addHandler(FileLogHandler("test_assistant_agent.log"))++def mock_tool_function(param: str) -> str:+ """Mock tool function for testing.++ Args:+ param: Input parameter to process++ Returns:+ Formatted string with the input parameter+ """+ return f"Tool executed with: {param}"+++async def async_mock_tool_function(param: str) -> str:+ """Async mock tool function for testing.++ Args:+ param: Input parameter to process++ Returns:+ Formatted string with the input parameter+ """+ return f"Async tool executed with: {param}"def _pass_function(input: str) -> str:- return "pass"+ """Pass through function for testing.+ Args:+ input: Input to pass through-async def _fail_function(input: str) -> str:- return "fail"+ Returns:+ The string "pass"+ """+ return "pass"-async def _throw_function(input: str) -> str:- raise ValueError("Helpful debugging information what went wrong.")+def _echo_function(input: str) -> str:+ """Echo function for testing.+ Args:+ input: Input to echo-async def _echo_function(input: str) -> str:+ Returns:+ The input string+ """return input-def model_info_all_capabilities() -> ModelInfo:- return {- "function_calling": True,- "vision": True,- "json_output": True,- "family": ModelFamily.GPT_4O,- "structured_output": True,- }+class MockMemory(Memory):+ """Mock memory implementation for testing.+ A simple memory implementation that stores strings and provides basic memory operations+ for testing purposes.-async def test_run_with_tool_call_summary_format_function(model_info_all_capabilities: ModelInfo) -> None:- model_client = ReplayChatCompletionClient(- [- CreateResult(- finish_reason="function_calls",- content=[- FunctionCall(id="1", arguments=json.dumps({"input": "task"}), name="_pass_function"),- FunctionCall(id="2", arguments=json.dumps({"input": "task"}), name="_throw_function"),- ],- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),- thought="Calling pass and fail function",- cached=False,- ),- ],- model_info=model_info_all_capabilities,- )+ Args:+ contents: Optional list of initial memory contents+ """- def conditional_string_templates(function_call: FunctionCall, function_call_result: FunctionExecutionResult) -> str:- if not function_call_result.is_error:- return "SUCCESS: {tool_name} with {arguments}"+ def __init__(self, contents: Optional[List[str]] = None) -> None:+ """Initialize mock memory.++ Args:+ contents: Optional list of initial memory contents+ """+ self._contents: List[str] = contents or []++ async def add(self, content: MemoryContent, cancellation_token: Optional[CancellationToken] = None) -> None:+ """Add content to memory.++ Args:+ content: Content to add to memory+ cancellation_token: Optional token for cancelling operation+ """+ self._contents.append(str(content))++ async def query(+ self, query: Union[str, MemoryContent], cancellation_token: Optional[CancellationToken] = None, **kwargs: Any+ ) -> MemoryQueryResultSet:+ """Query memory contents.++ Args:+ query: Search query+ cancellation_token: Optional token for cancelling operation+ kwargs: Additional query parameters++ Returns:+ Query results containing all memory contents+ """+ results = [MemoryContent(content=content, mime_type="text/plain") for content in self._contents]+ return MemoryQueryResultSet(results=results)++ async def clear(self, cancellation_token: Optional[CancellationToken] = None) -> None:+ """Clear all memory contents.++ Args:+ cancellation_token: Optional token for cancelling operation+ """+ self._contents.clear()++ async def close(self) -> None:+ """Close memory resources."""+ pass- else:- return "FAILURE: {result}"+ async def update_context(self, model_context: Any) -> UpdateContextResult:+ """Update model context with memory contents.- agent = AssistantAgent(- "tool_use_agent",- model_client=model_client,- tools=[_pass_function, _throw_function],- tool_call_summary_formatter=conditional_string_templates,- )- result = await agent.run(task="task")+ Args:+ model_context: Context to update- first_tool_call_summary = next((x for x in result.messages if isinstance(x, ToolCallSummaryMessage)), None)- if first_tool_call_summary is None:- raise AssertionError("Expected a ToolCallSummaryMessage but found none")+ Returns:+ Update result containing memory contents+ """+ if self._contents:+ results = [MemoryContent(content=content, mime_type="text/plain") for content in self._contents]+ return UpdateContextResult(memories=MemoryQueryResultSet(results=results))+ return UpdateContextResult(memories=MemoryQueryResultSet(results=[]))- assert (- first_tool_call_summary.content- == 'SUCCESS: _pass_function with {"input": "task"}\nFAILURE: Helpful debugging information what went wrong.'- )+ def dump_component(self) -> ComponentModel:+ """Dump memory state as component model.+ Returns:+ Component model representing memory state+ """+ return ComponentModel(provider="test", config={"type": "mock_memory"})-async def test_run_with_tools(monkeypatch: pytest.MonkeyPatch) -> None:- model_client = ReplayChatCompletionClient(- [- CreateResult(- finish_reason="function_calls",- content=[FunctionCall(id="1", arguments=json.dumps({"input": "task"}), name="_pass_function")],- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),- thought="Calling pass function",- cached=False,- ),- "pass",- "TERMINATE",- ],- model_info={- "function_calling": True,- "vision": True,- "json_output": True,- "family": ModelFamily.GPT_4O,- "structured_output": True,- },- )- agent = AssistantAgent(- "tool_use_agent",- model_client=model_client,- tools=[- _pass_function,- _fail_function,- FunctionTool(_echo_function, description="Echo"),- ],- )- result = await agent.run(task="task")-- # Make sure the create call was made with the correct parameters.- assert len(model_client.create_calls) == 1- llm_messages = model_client.create_calls[0]["messages"]- assert len(llm_messages) == 2- assert isinstance(llm_messages[0], SystemMessage)- assert llm_messages[0].content == agent._system_messages[0].content # type: ignore- assert isinstance(llm_messages[1], UserMessage)- assert llm_messages[1].content == "task"-- assert len(result.messages) == 5- assert isinstance(result.messages[0], TextMessage)- assert result.messages[0].models_usage is None- assert isinstance(result.messages[1], ThoughtEvent)- assert result.messages[1].content == "Calling pass function"- assert isinstance(result.messages[2], ToolCallRequestEvent)- assert result.messages[2].models_usage is not None- assert result.messages[2].models_usage.completion_tokens == 5- assert result.messages[2].models_usage.prompt_tokens == 10- assert isinstance(result.messages[3], ToolCallExecutionEvent)- assert result.messages[3].models_usage is None- assert isinstance(result.messages[4], ToolCallSummaryMessage)- assert result.messages[4].content == "pass"- assert result.messages[4].models_usage is None-- # Test streaming.- model_client.reset()- index = 0- async for message in agent.run_stream(task="task"):- if isinstance(message, TaskResult):- assert compare_task_results(message, result)- else:- assert compare_messages(message, result.messages[index])- index += 1-- # Test state saving and loading.- state = await agent.save_state()- agent2 = AssistantAgent(- "tool_use_agent",- model_client=model_client,- tools=[_pass_function, _fail_function, FunctionTool(_echo_function, description="Echo")],- )- await agent2.load_state(state)- state2 = await agent2.save_state()- assert state == state2+class StructuredOutput(BaseModel):+ """Test structured output model.-async def test_run_with_tools_and_reflection() -> None:- model_client = ReplayChatCompletionClient(- [- CreateResult(- finish_reason="function_calls",- content=[FunctionCall(id="1", arguments=json.dumps({"input": "task"}), name="_pass_function")],- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),- cached=False,- ),- CreateResult(- finish_reason="stop",- content="Hello",- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),- cached=False,- ),- CreateResult(- finish_reason="stop",- content="TERMINATE",- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),- cached=False,- ),- ],- model_info={- "function_calling": True,- "vision": True,- "json_output": True,- "family": ModelFamily.GPT_4O,- "structured_output": True,- },- )- agent = AssistantAgent(- "tool_use_agent",- model_client=model_client,- tools=[_pass_function, _fail_function, FunctionTool(_echo_function, description="Echo")],- reflect_on_tool_use=True,- )- result = await agent.run(task="task")-- # Make sure the create call was made with the correct parameters.- assert len(model_client.create_calls) == 2- llm_messages = model_client.create_calls[0]["messages"]- assert len(llm_messages) == 2- assert isinstance(llm_messages[0], SystemMessage)- assert llm_messages[0].content == agent._system_messages[0].content # type: ignore- assert isinstance(llm_messages[1], UserMessage)- assert llm_messages[1].content == "task"- llm_messages = model_client.create_calls[1]["messages"]- assert len(llm_messages) == 4- assert isinstance(llm_messages[0], SystemMessage)- assert llm_messages[0].content == agent._system_messages[0].content # type: ignore- assert isinstance(llm_messages[1], UserMessage)- assert llm_messages[1].content == "task"- assert isinstance(llm_messages[2], AssistantMessage)- assert isinstance(llm_messages[3], FunctionExecutionResultMessage)-- assert len(result.messages) == 4- assert isinstance(result.messages[0], TextMessage)- assert result.messages[0].models_usage is None- assert isinstance(result.messages[1], ToolCallRequestEvent)- assert result.messages[1].models_usage is not None- assert result.messages[1].models_usage.completion_tokens == 5- assert result.messages[1].models_usage.prompt_tokens == 10- assert isinstance(result.messages[2], ToolCallExecutionEvent)- assert result.messages[2].models_usage is None- assert isinstance(result.messages[3], TextMessage)- assert result.messages[3].content == "Hello"- assert result.messages[3].models_usage is not None- assert result.messages[3].models_usage.completion_tokens == 5- assert result.messages[3].models_usage.prompt_tokens == 10-- # Test streaming.- model_client.reset()- index = 0- async for message in agent.run_stream(task="task"):- if isinstance(message, TaskResult):- assert compare_task_results(message, result)- else:- assert compare_messages(message, result.messages[index])- index += 1-- # Test state saving and loading.- state = await agent.save_state()- agent2 = AssistantAgent(- "tool_use_agent",- model_client=model_client,- tools=[- _pass_function,- _fail_function,- FunctionTool(_echo_function, description="Echo"),- ],- )- await agent2.load_state(state)- state2 = await agent2.save_state()- assert state == state2+ Attributes:+ content: Main content string+ confidence: Confidence score between 0 and 1+ """++ content: str+ confidence: float@pytest.mark.asyncio-async def test_run_with_parallel_tools() -> None:- model_client = ReplayChatCompletionClient(+async def test_model_client_stream() -> None:+ mock_client = ReplayChatCompletionClient([- CreateResult(- finish_reason="function_calls",- content=[- FunctionCall(id="1", arguments=json.dumps({"input": "task1"}), name="_pass_function"),- FunctionCall(id="2", arguments=json.dumps({"input": "task2"}), name="_pass_function"),- FunctionCall(id="3", arguments=json.dumps({"input": "task3"}), name="_echo_function"),- ],- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),- thought="Calling pass and echo functions",- cached=False,- ),- "pass",- "TERMINATE",- ],- model_info={- "function_calling": True,- "vision": True,- "json_output": True,- "family": ModelFamily.GPT_4O,- "structured_output": True,- },+ "Response to message 3",+ ])agent = AssistantAgent(- "tool_use_agent",- model_client=model_client,- tools=[- _pass_function,- _fail_function,- FunctionTool(_echo_function, description="Echo"),- ],+ "test_agent",+ model_client=mock_client,+ model_client_stream=True,)- result = await agent.run(task="task")-- assert len(result.messages) == 5- assert isinstance(result.messages[0], TextMessage)- assert result.messages[0].models_usage is None- assert isinstance(result.messages[1], ThoughtEvent)- assert result.messages[1].content == "Calling pass and echo functions"- assert isinstance(result.messages[2], ToolCallRequestEvent)- assert result.messages[2].content == [- FunctionCall(id="1", arguments=r'{"input": "task1"}', name="_pass_function"),- FunctionCall(id="2", arguments=r'{"input": "task2"}', name="_pass_function"),- FunctionCall(id="3", arguments=r'{"input": "task3"}', name="_echo_function"),- ]- assert result.messages[2].models_usage is not None- assert result.messages[2].models_usage.completion_tokens == 5- assert result.messages[2].models_usage.prompt_tokens == 10- assert isinstance(result.messages[3], ToolCallExecutionEvent)- expected_content = [- FunctionExecutionResult(call_id="1", content="pass", is_error=False, name="_pass_function"),- FunctionExecutionResult(call_id="2", content="pass", is_error=False, name="_pass_function"),- FunctionExecutionResult(call_id="3", content="task3", is_error=False, name="_echo_function"),- ]- for expected in expected_content:- assert expected in result.messages[3].content- assert result.messages[3].models_usage is None- assert isinstance(result.messages[4], ToolCallSummaryMessage)- assert result.messages[4].content == "pass\npass\ntask3"- assert result.messages[4].models_usage is None-- # Test streaming.- model_client.reset()- index = 0+ chunks: List[str] = []async for message in agent.run_stream(task="task"):if isinstance(message, TaskResult):- assert compare_task_results(message, result)- else:- assert compare_messages(message, result.messages[index])- index += 1-- # Test state saving and loading.- state = await agent.save_state()- agent2 = AssistantAgent(- "tool_use_agent",- model_client=model_client,- tools=[_pass_function, _fail_function, FunctionTool(_echo_function, description="Echo")],- )- await agent2.load_state(state)- state2 = await agent2.save_state()- assert state == state2+ assert isinstance(message.messages[-1], TextMessage)+ assert message.messages[-1].content == "Response to message 3"+ elif isinstance(message, ModelClientStreamingChunkEvent):+ chunks.append(message.content)+ assert "".join(chunks) == "Response to message 3"@pytest.mark.asyncio-async def test_run_with_parallel_tools_with_empty_call_ids() -> None:- model_client = ReplayChatCompletionClient(+async def test_model_client_stream_with_tool_calls() -> None:+ mock_client = ReplayChatCompletionClient([CreateResult(- finish_reason="function_calls",content=[- FunctionCall(id="", arguments=json.dumps({"input": "task1"}), name="_pass_function"),- FunctionCall(id="", arguments=json.dumps({"input": "task2"}), name="_pass_function"),- FunctionCall(id="", arguments=json.dumps({"input": "task3"}), name="_echo_function"),+ FunctionCall(id="1", name="_pass_function", arguments=r'{"input": "task"}'),+ FunctionCall(id="3", name="_echo_function", arguments=r'{"input": "task"}'),],+ finish_reason="function_calls",usage=RequestUsage(prompt_tokens=10, completion_tokens=5),cached=False,),- "pass",- "TERMINATE",- ],- model_info={- "function_calling": True,- "vision": True,- "json_output": True,- "family": ModelFamily.GPT_4O,- "structured_output": True,- },+ "Example response 2 to task",+ ])+ mock_client._model_info["function_calling"] = True # pyright: ignoreagent = AssistantAgent(- "tool_use_agent",- model_client=model_client,- tools=[- _pass_function,- _fail_function,- FunctionTool(_echo_function, description="Echo"),- ],+ "test_agent",+ model_client=mock_client,+ model_client_stream=True,+ reflect_on_tool_use=True,+ tools=[_pass_function, _echo_function],)- result = await agent.run(task="task")-- assert len(result.messages) == 4- assert isinstance(result.messages[0], TextMessage)- assert result.messages[0].models_usage is None- assert isinstance(result.messages[1], ToolCallRequestEvent)- assert result.messages[1].content == [- FunctionCall(id="", arguments=r'{"input": "task1"}', name="_pass_function"),- FunctionCall(id="", arguments=r'{"input": "task2"}', name="_pass_function"),- FunctionCall(id="", arguments=r'{"input": "task3"}', name="_echo_function"),- ]- assert result.messages[1].models_usage is not None- assert result.messages[1].models_usage.completion_tokens == 5- assert result.messages[1].models_usage.prompt_tokens == 10- assert isinstance(result.messages[2], ToolCallExecutionEvent)- expected_content = [- FunctionExecutionResult(call_id="", content="pass", is_error=False, name="_pass_function"),- FunctionExecutionResult(call_id="", content="pass", is_error=False, name="_pass_function"),- FunctionExecutionResult(call_id="", content="task3", is_error=False, name="_echo_function"),- ]- for expected in expected_content:- assert expected in result.messages[2].content- assert result.messages[2].models_usage is None- assert isinstance(result.messages[3], ToolCallSummaryMessage)- assert result.messages[3].content == "pass\npass\ntask3"- assert result.messages[3].models_usage is None-- # Test streaming.- model_client.reset()- index = 0+ chunks: List[str] = []async for message in agent.run_stream(task="task"):if isinstance(message, TaskResult):- assert compare_task_results(message, result)- else:- assert compare_messages(message, result.messages[index])- index += 1-- # Test state saving and loading.- state = await agent.save_state()- agent2 = AssistantAgent(- "tool_use_agent",- model_client=model_client,- tools=[_pass_function, _fail_function, FunctionTool(_echo_function, description="Echo")],- )- await agent2.load_state(state)- state2 = await agent2.save_state()- assert state == state2+ assert isinstance(message.messages[-1], TextMessage)+ assert isinstance(message.messages[1], ToolCallRequestEvent)+ assert message.messages[-1].content == "Example response 2 to task"+ assert message.messages[1].content == [+ FunctionCall(id="1", name="_pass_function", arguments=r'{"input": "task"}'),+ FunctionCall(id="3", name="_echo_function", arguments=r'{"input": "task"}'),+ ]+ assert isinstance(message.messages[2], ToolCallExecutionEvent)+ assert message.messages[2].content == [+ FunctionExecutionResult(call_id="1", content="pass", is_error=False, name="_pass_function"),+ FunctionExecutionResult(call_id="3", content="task", is_error=False, name="_echo_function"),+ ]+ elif isinstance(message, ModelClientStreamingChunkEvent):+ chunks.append(message.content)+ assert "".join(chunks) == "Example response 2 to task"@pytest.mark.asyncio-async def test_run_with_workbench() -> None:+async def test_invalid_structured_output_format() -> None:+ class AgentResponse(BaseModel):+ response: str+ status: str+model_client = ReplayChatCompletionClient([- CreateResult(- finish_reason="function_calls",- content=[FunctionCall(id="1", arguments=json.dumps({"input": "task"}), name="_pass_function")],- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),- cached=False,- ),- CreateResult(- finish_reason="stop",- content="Hello",- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),- cached=False,- ),CreateResult(finish_reason="stop",- content="TERMINATE",+ content='{"response": "Hello"}',usage=RequestUsage(prompt_tokens=10, completion_tokens=5),cached=False,),- ],- model_info={- "function_calling": True,- "vision": True,- "json_output": True,- "family": ModelFamily.GPT_4O,- "structured_output": True,- },- )- workbench = StaticWorkbench(- [- FunctionTool(_pass_function, description="Pass"),- FunctionTool(_fail_function, description="Fail"),- FunctionTool(_echo_function, description="Echo"),])- # Test raise error when both workbench and tools are provided.- with pytest.raises(ValueError):- AssistantAgent(- "tool_use_agent",- model_client=model_client,- tools=[- _pass_function,- _fail_function,- FunctionTool(_echo_function, description="Echo"),- ],- workbench=workbench,- )-agent = AssistantAgent(- "tool_use_agent",- model_client=model_client,- workbench=workbench,- reflect_on_tool_use=True,- )- result = await agent.run(task="task")-- # Make sure the create call was made with the correct parameters.- assert len(model_client.create_calls) == 2- llm_messages = model_client.create_calls[0]["messages"]- assert len(llm_messages) == 2- assert isinstance(llm_messages[0], SystemMessage)- assert llm_messages[0].content == agent._system_messages[0].content # type: ignore- assert isinstance(llm_messages[1], UserMessage)- assert llm_messages[1].content == "task"- llm_messages = model_client.create_calls[1]["messages"]- assert len(llm_messages) == 4- assert isinstance(llm_messages[0], SystemMessage)- assert llm_messages[0].content == agent._system_messages[0].content # type: ignore- assert isinstance(llm_messages[1], UserMessage)- assert llm_messages[1].content == "task"- assert isinstance(llm_messages[2], AssistantMessage)- assert isinstance(llm_messages[3], FunctionExecutionResultMessage)-- assert len(result.messages) == 4- assert isinstance(result.messages[0], TextMessage)- assert result.messages[0].models_usage is None- assert isinstance(result.messages[1], ToolCallRequestEvent)- assert result.messages[1].models_usage is not None- assert result.messages[1].models_usage.completion_tokens == 5- assert result.messages[1].models_usage.prompt_tokens == 10- assert isinstance(result.messages[2], ToolCallExecutionEvent)- assert result.messages[2].models_usage is None- assert isinstance(result.messages[3], TextMessage)- assert result.messages[3].content == "Hello"- assert result.messages[3].models_usage is not None- assert result.messages[3].models_usage.completion_tokens == 5- assert result.messages[3].models_usage.prompt_tokens == 10-- # Test streaming.- model_client.reset()- index = 0- async for message in agent.run_stream(task="task"):- if isinstance(message, TaskResult):- assert compare_task_results(message, result)- else:- assert compare_messages(message, result.messages[index])- index += 1-- # Test state saving and loading.- state = await agent.save_state()- agent2 = AssistantAgent(- "tool_use_agent",+ name="assistant",model_client=model_client,- tools=[- _pass_function,- _fail_function,- FunctionTool(_echo_function, description="Echo"),- ],+ output_content_type=AgentResponse,)- await agent2.load_state(state)- state2 = await agent2.save_state()- assert state == state2++ with pytest.raises(ValidationError):+ await agent.run()@pytest.mark.asyncio-async def test_output_format() -> None:+async def test_structured_message_factory_serialization() -> None:class AgentResponse(BaseModel):- response: str+ result: strstatus: strmodel_client = ReplayChatCompletionClient([CreateResult(finish_reason="stop",- content=AgentResponse(response="Hello", status="success").model_dump_json(),+ content=AgentResponse(result="All good", status="ok").model_dump_json(),usage=RequestUsage(prompt_tokens=10, completion_tokens=5),cached=False,- ),+ )])+agent = AssistantAgent(- "test_agent",+ name="structured_agent",model_client=model_client,output_content_type=AgentResponse,+ output_content_type_format="{result} - {status}",)- assert StructuredMessage[AgentResponse] in agent.produced_message_types- assert TextMessage not in agent.produced_message_types- result = await agent.run()- assert len(result.messages) == 1- assert isinstance(result.messages[0], StructuredMessage)- assert isinstance(result.messages[0].content, AgentResponse) # type: ignore[reportUnknownMemberType]- assert result.messages[0].content.response == "Hello"- assert result.messages[0].content.status == "success"+ dumped = agent.dump_component()+ restored_agent = AssistantAgent.load_component(dumped)+ result = await restored_agent.run()- # Test streaming.- agent = AssistantAgent(- "test_agent",- model_client=model_client,- model_client_stream=True,- output_content_type=AgentResponse,- )- model_client.reset()- stream = agent.run_stream()- stream_result: TaskResult | None = None- async for message in stream:- if isinstance(message, TaskResult):- stream_result = message- assert stream_result is not None- assert len(stream_result.messages) == 1- assert isinstance(stream_result.messages[0], StructuredMessage)- assert isinstance(stream_result.messages[0].content, AgentResponse) # type: ignore[reportUnknownMemberType]- assert stream_result.messages[0].content.response == "Hello"- assert stream_result.messages[0].content.status == "success"+ assert isinstance(result.messages[0], StructuredMessage)+ assert result.messages[0].content.result == "All good" # type: ignore+ assert result.messages[0].content.status == "ok" # type: ignore@pytest.mark.asyncio-async def test_reflection_output_format() -> None:+async def test_structured_message_format_string() -> None:class AgentResponse(BaseModel):- response: str- status: str+ field1: str+ field2: str++ expected = AgentResponse(field1="foo", field2="bar")model_client = ReplayChatCompletionClient([CreateResult(- finish_reason="function_calls",- content=[FunctionCall(id="1", arguments=json.dumps({"input": "task"}), name="_pass_function")],+ finish_reason="stop",+ content=expected.model_dump_json(),usage=RequestUsage(prompt_tokens=10, completion_tokens=5),cached=False,- ),- AgentResponse(response="Hello", status="success").model_dump_json(),- ],- model_info={- "function_calling": True,- "vision": True,- "json_output": True,- "family": ModelFamily.GPT_4O,- "structured_output": True,- },- )- agent = AssistantAgent(- "test_agent",- model_client=model_client,- output_content_type=AgentResponse,- # reflect_on_tool_use=True,- tools=[- _pass_function,- _fail_function,- ],- )- result = await agent.run()- assert len(result.messages) == 3- assert isinstance(result.messages[0], ToolCallRequestEvent)- assert isinstance(result.messages[1], ToolCallExecutionEvent)- assert isinstance(result.messages[2], StructuredMessage)- assert isinstance(result.messages[2].content, AgentResponse) # type: ignore[reportUnknownMemberType]- assert result.messages[2].content.response == "Hello"- assert result.messages[2].content.status == "success"-- # Test streaming.- agent = AssistantAgent(- "test_agent",- model_client=model_client,- model_client_stream=True,- output_content_type=AgentResponse,- # reflect_on_tool_use=True,- tools=[- _pass_function,- _fail_function,- ],+ )+ ])- model_client.reset()- stream = agent.run_stream()- stream_result: TaskResult | None = None- async for message in stream:- if isinstance(message, TaskResult):- stream_result = message- assert stream_result is not None- assert len(stream_result.messages) == 3- assert isinstance(stream_result.messages[0], ToolCallRequestEvent)- assert isinstance(stream_result.messages[1], ToolCallExecutionEvent)- assert isinstance(stream_result.messages[2], StructuredMessage)- assert isinstance(stream_result.messages[2].content, AgentResponse) # type: ignore[reportUnknownMemberType]- assert stream_result.messages[2].content.response == "Hello"- assert stream_result.messages[2].content.status == "success"-- # Test when reflect_on_tool_use is False- model_client.reset()+agent = AssistantAgent(- "test_agent",+ name="formatted_agent",model_client=model_client,output_content_type=AgentResponse,- reflect_on_tool_use=False,- tools=[- _pass_function,- _fail_function,- ],+ output_content_type_format="{field1} - {field2}",)+result = await agent.run()- assert len(result.messages) == 3- assert isinstance(result.messages[0], ToolCallRequestEvent)- assert isinstance(result.messages[1], ToolCallExecutionEvent)- assert isinstance(result.messages[2], ToolCallSummaryMessage)+ assert len(result.messages) == 1+ message = result.messages[0]-async def test_handoffs() -> None:- handoff = Handoff(target="agent2")- model_client = ReplayChatCompletionClient(- [- CreateResult(- finish_reason="function_calls",- content=[- FunctionCall(id="1", arguments=json.dumps({}), name=handoff.name),- ],- usage=RequestUsage(prompt_tokens=42, completion_tokens=43),- cached=False,- thought="Calling handoff function",- )- ],- model_info={- "function_calling": True,- "vision": True,- "json_output": True,- "family": ModelFamily.GPT_4O,- "structured_output": True,- },- )- tool_use_agent = AssistantAgent(- "tool_use_agent",- model_client=model_client,- tools=[- _pass_function,- _fail_function,- FunctionTool(_echo_function, description="Echo"),- ],- handoffs=[handoff],- )- assert HandoffMessage in tool_use_agent.produced_message_types- result = await tool_use_agent.run(task="task")- assert len(result.messages) == 5- assert isinstance(result.messages[0], TextMessage)- assert result.messages[0].models_usage is None- assert isinstance(result.messages[1], ThoughtEvent)- assert result.messages[1].content == "Calling handoff function"- assert isinstance(result.messages[2], ToolCallRequestEvent)- assert result.messages[2].models_usage is not None- assert result.messages[2].models_usage.completion_tokens == 43- assert result.messages[2].models_usage.prompt_tokens == 42- assert isinstance(result.messages[3], ToolCallExecutionEvent)- assert result.messages[3].models_usage is None- assert isinstance(result.messages[4], HandoffMessage)- assert result.messages[4].content == handoff.message- assert result.messages[4].target == handoff.target- assert result.messages[4].models_usage is None- assert result.messages[4].context == [AssistantMessage(content="Calling handoff function", source="tool_use_agent")]-- # Test streaming.- model_client.reset()- index = 0- async for message in tool_use_agent.run_stream(task="task"):- if isinstance(message, TaskResult):- assert compare_task_results(message, result)- else:- assert compare_messages(message, result.messages[index])- index += 1+ # Check that it's a StructuredMessage with the correct content model+ assert isinstance(message, StructuredMessage)+ assert isinstance(message.content, AgentResponse) # type: ignore[reportUnknownMemberType]+ assert message.content == expected++ # Check that the format_string was applied correctly+ assert message.to_model_text() == "foo - bar"@pytest.mark.asyncio-async def test_handoff_with_tool_call_context() -> None:- handoff = Handoff(target="agent2")- model_client = ReplayChatCompletionClient(- [- CreateResult(- finish_reason="function_calls",- content=[- FunctionCall(id="1", arguments=json.dumps({}), name=handoff.name),- FunctionCall(id="2", arguments=json.dumps({"input": "task"}), name="_pass_function"),- ],- usage=RequestUsage(prompt_tokens=42, completion_tokens=43),- cached=False,- thought="Calling handoff function",- )- ],- model_info={- "function_calling": True,- "vision": True,- "json_output": True,- "family": ModelFamily.GPT_4O,- "structured_output": True,- },+async def test_tools_serialize_and_deserialize() -> None:+ def test() -> str:+ return "hello world"++ client = OpenAIChatCompletionClient(+ model="gpt-4o",+ api_key="API_KEY",)- tool_use_agent = AssistantAgent(- "tool_use_agent",- model_client=model_client,- tools=[- _pass_function,- _fail_function,- FunctionTool(_echo_function, description="Echo"),- ],- handoffs=[handoff],++ agent = AssistantAgent(+ name="test",+ model_client=client,+ tools=[test],)- assert HandoffMessage in tool_use_agent.produced_message_types- result = await tool_use_agent.run(task="task")- assert len(result.messages) == 5- assert isinstance(result.messages[0], TextMessage)- assert result.messages[0].models_usage is None- assert isinstance(result.messages[1], ThoughtEvent)- assert result.messages[1].content == "Calling handoff function"- assert isinstance(result.messages[2], ToolCallRequestEvent)- assert result.messages[2].models_usage is not None- assert result.messages[2].models_usage.completion_tokens == 43- assert result.messages[2].models_usage.prompt_tokens == 42- assert isinstance(result.messages[3], ToolCallExecutionEvent)- assert result.messages[3].models_usage is None- assert isinstance(result.messages[4], HandoffMessage)- assert result.messages[4].content == handoff.message- assert result.messages[4].target == handoff.target- assert result.messages[4].models_usage is None- assert result.messages[4].context == [- AssistantMessage(- content=[FunctionCall(id="2", arguments=r'{"input": "task"}', name="_pass_function")],- source="tool_use_agent",- thought="Calling handoff function",- ),- FunctionExecutionResultMessage(- content=[FunctionExecutionResult(call_id="2", content="pass", is_error=False, name="_pass_function")]- ),- ]- # Test streaming.- model_client.reset()- index = 0- async for message in tool_use_agent.run_stream(task="task"):- if isinstance(message, TaskResult):- assert compare_task_results(message, result)- else:- assert compare_messages(message, result.messages[index])- index += 1+ serialize = agent.dump_component()+ deserialize = AssistantAgent.load_component(serialize)++ assert deserialize.name == agent.name+ for original, restored in zip(agent._workbench, deserialize._workbench, strict=True): # type: ignore+ assert await original.list_tools() == await restored.list_tools() # type: ignore+ assert agent.component_version == deserialize.component_version@pytest.mark.asyncio-async def test_custom_handoffs() -> None:- name = "transfer_to_agent2"- description = "Handoff to agent2."- next_action = "next_action"+async def test_workbench_serialize_and_deserialize() -> None:+ workbench = McpWorkbench(server_params=SseServerParams(url="http://test-url"))- class TextCommandHandOff(Handoff):- @property- def handoff_tool(self) -> BaseTool[BaseModel, BaseModel]:- """Create a handoff tool from this handoff configuration."""+ client = OpenAIChatCompletionClient(+ model="gpt-4o",+ api_key="API_KEY",+ )- def _next_action(action: str) -> str:- """Returns the action you want the user to perform"""- return action+ agent = AssistantAgent(+ name="test",+ model_client=client,+ workbench=workbench,+ )- return FunctionTool(_next_action, name=self.name, description=self.description, strict=True)+ serialize = agent.dump_component()+ deserialize = AssistantAgent.load_component(serialize)- handoff = TextCommandHandOff(name=name, description=description, target="agent2")- model_client = ReplayChatCompletionClient(- [- CreateResult(- finish_reason="function_calls",- content=[- FunctionCall(id="1", arguments=json.dumps({"action": next_action}), name=handoff.name),- ],- usage=RequestUsage(prompt_tokens=42, completion_tokens=43),- cached=False,- )- ],- model_info={- "function_calling": True,- "vision": True,- "json_output": True,- "family": ModelFamily.GPT_4O,- "structured_output": True,- },- )- tool_use_agent = AssistantAgent(- "tool_use_agent",- model_client=model_client,- tools=[- _pass_function,- _fail_function,- FunctionTool(_echo_function, description="Echo"),- ],- handoffs=[handoff],- )- assert HandoffMessage in tool_use_agent.produced_message_types- result = await tool_use_agent.run(task="task")- assert len(result.messages) == 4- assert isinstance(result.messages[0], TextMessage)- assert result.messages[0].models_usage is None- assert isinstance(result.messages[1], ToolCallRequestEvent)- assert result.messages[1].models_usage is not None- assert result.messages[1].models_usage.completion_tokens == 43- assert result.messages[1].models_usage.prompt_tokens == 42- assert isinstance(result.messages[2], ToolCallExecutionEvent)- assert result.messages[2].models_usage is None- assert isinstance(result.messages[3], HandoffMessage)- assert result.messages[3].content == next_action- assert result.messages[3].target == handoff.target-- assert result.messages[3].models_usage is None-- # Test streaming.- model_client.reset()- index = 0- async for message in tool_use_agent.run_stream(task="task"):- if isinstance(message, TaskResult):- assert compare_task_results(message, result)- else:- assert compare_messages(message, result.messages[index])- index += 1+ assert deserialize.name == agent.name+ for original, restored in zip(agent._workbench, deserialize._workbench, strict=True): # type: ignore+ assert isinstance(original, McpWorkbench)+ assert isinstance(restored, McpWorkbench)+ assert original._to_config() == restored._to_config() # type: ignore@pytest.mark.asyncio-async def test_custom_object_handoffs() -> None:- """test handoff tool return a object"""- name = "transfer_to_agent2"- description = "Handoff to agent2."- next_action = {"action": "next_action"} # using a map, not a str+async def test_multiple_workbenches_serialize_and_deserialize() -> None:+ workbenches: List[McpWorkbench] = [+ McpWorkbench(server_params=SseServerParams(url="http://test-url-1")),+ McpWorkbench(server_params=SseServerParams(url="http://test-url-2")),+ ]++ client = OpenAIChatCompletionClient(+ model="gpt-4o",+ api_key="API_KEY",+ )- class DictCommandHandOff(Handoff):- @property- def handoff_tool(self) -> BaseTool[BaseModel, BaseModel]:- """Create a handoff tool from this handoff configuration."""+ agent = AssistantAgent(+ name="test_multi",+ model_client=client,+ workbench=workbenches,+ )- def _next_action(action: str) -> Dict[str, str]:- """Returns the action you want the user to perform"""- return {"action": action}+ serialize = agent.dump_component()+ deserialized_agent: AssistantAgent = AssistantAgent.load_component(serialize)- return FunctionTool(_next_action, name=self.name, description=self.description, strict=True)+ assert deserialized_agent.name == agent.name+ assert isinstance(deserialized_agent._workbench, list) # type: ignore+ assert len(deserialized_agent._workbench) == len(workbenches) # type: ignore- handoff = DictCommandHandOff(name=name, description=description, target="agent2")- model_client = ReplayChatCompletionClient(- [- CreateResult(- finish_reason="function_calls",- content=[- FunctionCall(id="1", arguments=json.dumps({"action": "next_action"}), name=handoff.name),- ],- usage=RequestUsage(prompt_tokens=42, completion_tokens=43),- cached=False,- )- ],- model_info={- "function_calling": True,- "vision": True,- "json_output": True,- "family": ModelFamily.GPT_4O,- "structured_output": True,- },- )- tool_use_agent = AssistantAgent(- "tool_use_agent",- model_client=model_client,- tools=[- _pass_function,- _fail_function,- FunctionTool(_echo_function, description="Echo"),- ],- handoffs=[handoff],- )- assert HandoffMessage in tool_use_agent.produced_message_types- result = await tool_use_agent.run(task="task")- assert len(result.messages) == 4- assert isinstance(result.messages[0], TextMessage)- assert result.messages[0].models_usage is None- assert isinstance(result.messages[1], ToolCallRequestEvent)- assert result.messages[1].models_usage is not None- assert result.messages[1].models_usage.completion_tokens == 43- assert result.messages[1].models_usage.prompt_tokens == 42- assert isinstance(result.messages[2], ToolCallExecutionEvent)- assert result.messages[2].models_usage is None- assert isinstance(result.messages[3], HandoffMessage)- # the content will return as a string, because the function call will convert to string- assert result.messages[3].content == str(next_action)- assert result.messages[3].target == handoff.target-- assert result.messages[3].models_usage is None-- # Test streaming.- model_client.reset()- index = 0- async for message in tool_use_agent.run_stream(task="task"):- if isinstance(message, TaskResult):- assert compare_task_results(message, result)- else:- assert compare_messages(message, result.messages[index])- index += 1+ for original, restored in zip(agent._workbench, deserialized_agent._workbench, strict=True): # type: ignore+ assert isinstance(original, McpWorkbench)+ assert isinstance(restored, McpWorkbench)+ assert original._to_config() == restored._to_config() # type: ignore@pytest.mark.asyncio-async def test_multi_modal_task(monkeypatch: pytest.MonkeyPatch) -> None:- model_client = ReplayChatCompletionClient(["Hello"])- agent = AssistantAgent(- name="assistant",- model_client=model_client,- )- # Generate a random base64 image.- img_base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4//8/AAX+Av4N70a4AAAAAElFTkSuQmCC"- result = await agent.run(task=MultiModalMessage(source="user", content=["Test", Image.from_base64(img_base64)]))- assert len(result.messages) == 2+async def test_tools_deserialize_aware() -> None:+ dump = """+ {+ "provider": "autogen_agentchat.agents.AssistantAgent",+ "component_type": "agent",+ "version": 1,+ "component_version": 2,+ "description": "An agent that provides assistance with tool use.",+ "label": "AssistantAgent",+ "config": {+ "name": "TestAgent",+ "model_client":{+ "provider": "autogen_ext.models.replay.ReplayChatCompletionClient",+ "component_type": "replay_chat_completion_client",+ "version": 1,+ "component_version": 1,+ "description": "A mock chat completion client that replays predefined responses using an index-based approach.",+ "label": "ReplayChatCompletionClient",+ "config": {+ "chat_completions": [+ {+ "finish_reason": "function_calls",+ "content": [+ {+ "id": "hello",+ "arguments": "{}",+ "name": "hello"+ }+ ],+ "usage": {+ "prompt_tokens": 0,+ "completion_tokens": 0+ },+ "cached": false+ }+ ],+ "model_info": {+ "vision": false,+ "function_calling": true,+ "json_output": false,+ "family": "unknown",+ "structured_output": false+ }+ }+ },+ "tools": [+ {+ "provider": "autogen_core.tools.FunctionTool",+ "component_type": "tool",+ "version": 1,+ "component_version": 1,+ "description": "Create custom tools by wrapping standard Python functions.",+ "label": "FunctionTool",+ "config": {+ "source_code": "def hello():\\n return 'Hello, World!'\\n",+ "name": "hello",+ "description": "",+ "global_imports": [],+ "has_cancellation_support": false+ }+ }+ ],+ "model_context": {+ "provider": "autogen_core.model_context.UnboundedChatCompletionContext",+ "component_type": "chat_completion_context",+ "version": 1,+ "component_version": 1,+ "description": "An unbounded chat completion context that keeps a view of the all the messages.",+ "label": "UnboundedChatCompletionContext",+ "config": {}+ },+ "description": "An agent that provides assistance with ability to use tools.",+ "system_message": "You are a helpful assistant.",+ "model_client_stream": false,+ "reflect_on_tool_use": false,+ "tool_call_summary_format": "{result}",+ "metadata": {}+ }+ }+ """-async def test_run_with_structured_task() -> None:- class InputTask(BaseModel):- input: str- data: List[str]+ # Test that agent can be deserialized from configuration+ config = json.loads(dump)+ agent = AssistantAgent.load_component(config)- model_client = ReplayChatCompletionClient(["Hello"])- agent = AssistantAgent(- name="assistant",- model_client=model_client,- )+ # Verify the agent was loaded correctly+ assert agent.name == "TestAgent"+ assert agent.description == "An agent that provides assistance with ability to use tools."- task = StructuredMessage[InputTask](content=InputTask(input="Test", data=["Test1", "Test2"]), source="user")- result = await agent.run(task=task)- assert len(result.messages) == 2+class TestAssistantAgentToolCallLoop:+ """Test suite for tool call loop functionality.-async def test_invalid_model_capabilities() -> None:- model = "random-model"- model_client = OpenAIChatCompletionClient(- model=model,- api_key="",- model_info={- "vision": False,- "function_calling": False,- "json_output": False,- "family": ModelFamily.UNKNOWN,- "structured_output": False,- },- )+ Tests the behavior of AssistantAgent's tool call loop feature, which allows+ multiple sequential tool calls before producing a final response.+ """++ @pytest.mark.asyncio+ async def test_tool_call_loop_enabled(self) -> None:+ """Test that tool call loop works when enabled.++ Verifies that:+ 1. Multiple tool calls are executed in sequence+ 2. Loop continues until non-tool response+ 3. Final response is correct type+ """+ # Create mock client with multiple tool calls followed by text response+ model_client = ReplayChatCompletionClient(+ [+ # First tool call+ CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments=json.dumps({"param": "first"}), name="mock_tool_function")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ # Second tool call (loop continues)+ CreateResult(+ finish_reason="function_calls",+ content=[+ FunctionCall(id="2", arguments=json.dumps({"param": "second"}), name="mock_tool_function")+ ],+ usage=RequestUsage(prompt_tokens=12, completion_tokens=5),+ cached=False,+ ),+ # Final text response (loop ends)+ CreateResult(+ finish_reason="stop",+ content="Task completed successfully!",+ usage=RequestUsage(prompt_tokens=15, completion_tokens=10),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )- with pytest.raises(ValueError):agent = AssistantAgent(- name="assistant",+ name="test_agent",model_client=model_client,- tools=[- _pass_function,- _fail_function,- FunctionTool(_echo_function, description="Echo"),- ],+ tools=[mock_tool_function],+ max_tool_iterations=3,)- await agent.run(task=TextMessage(source="user", content="Test"))- with pytest.raises(ValueError):- agent = AssistantAgent(name="assistant", model_client=model_client, handoffs=["agent2"])- await agent.run(task=TextMessage(source="user", content="Test"))+ result = await agent.run(task="Execute multiple tool calls")++ # Verify multiple model calls were made+ assert len(model_client.create_calls) == 3, f"Expected 3 calls, got {len(model_client.create_calls)}"++ # Verify final response is text+ final_message = result.messages[-1]+ assert isinstance(final_message, TextMessage)+ assert final_message.content == "Task completed successfully!"++ @pytest.mark.asyncio+ async def test_tool_call_loop_disabled_default(self) -> None:+ """Test that tool call loop is disabled by default.++ Verifies that:+ 1. Only one tool call is made when loop is disabled+ 2. Agent returns after first tool call+ """+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="mock_tool_function")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ )+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ max_tool_iterations=1,+ )-async def test_remove_images() -> None:- model = "random-model"- model_client_1 = OpenAIChatCompletionClient(- model=model,- api_key="",- model_info={- "vision": False,- "function_calling": False,- "json_output": False,- "family": ModelFamily.UNKNOWN,- "structured_output": False,- },- )- model_client_2 = OpenAIChatCompletionClient(- model=model,- api_key="",- model_info={- "vision": True,- "function_calling": False,- "json_output": False,- "family": ModelFamily.UNKNOWN,- "structured_output": False,- },- )+ result = await agent.run(task="Execute single tool call")++ # Should only make one model call+ assert len(model_client.create_calls) == 1, f"Expected 1 call, got {len(model_client.create_calls)}"+ assert result is not None++ @pytest.mark.asyncio+ async def test_tool_call_loop_max_iterations(self) -> None:+ """Test that tool call loop respects max_iterations limit."""+ # Create responses that would continue forever without max_iterations+ responses: List[CreateResult] = []+ for i in range(15): # More than default max_iterations (10)+ responses.append(+ CreateResult(+ finish_reason="function_calls",+ content=[+ FunctionCall(id=str(i), arguments=json.dumps({"param": f"call_{i}"}), name="mock_tool_function")+ ],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ )+ )- img_base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4//8/AAX+Av4N70a4AAAAAElFTkSuQmCC"- messages: List[LLMMessage] = [- SystemMessage(content="System.1"),- UserMessage(content=["User.1", Image.from_base64(img_base64)], source="user.1"),- AssistantMessage(content="Assistant.1", source="assistant.1"),- UserMessage(content="User.2", source="assistant.2"),- ]+ model_client = ReplayChatCompletionClient(+ responses,+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )- agent_1 = AssistantAgent(name="assistant_1", model_client=model_client_1)- result = agent_1._get_compatible_context(model_client_1, messages) # type: ignore- assert len(result) == 4- assert isinstance(result[1].content, str)+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ max_tool_iterations=5, # Set max iterations to 5+ )- agent_2 = AssistantAgent(name="assistant_2", model_client=model_client_2)- result = agent_2._get_compatible_context(model_client_2, messages) # type: ignore- assert len(result) == 4- assert isinstance(result[1].content, list)+ result = await agent.run(task="Test max iterations")++ # Should stop at max_iterations+ assert len(model_client.create_calls) == 5, f"Expected 5 calls, got {len(model_client.create_calls)}"+ # Verify result is not None+ assert result is not None++ @pytest.mark.asyncio+ async def test_tool_call_loop_with_handoff(self) -> None:+ """Test that tool call loop stops on handoff."""+ model_client = ReplayChatCompletionClient(+ [+ # Tool call followed by handoff+ CreateResult(+ finish_reason="function_calls",+ content=[+ FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="mock_tool_function"),+ FunctionCall(+ id="2", arguments=json.dumps({"target": "other_agent"}), name="transfer_to_other_agent"+ ),+ ],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ handoffs=["other_agent"],+ max_tool_iterations=1,+ )-async def test_list_chat_messages(monkeypatch: pytest.MonkeyPatch) -> None:- model_client = ReplayChatCompletionClient(- [- CreateResult(- finish_reason="stop",- content="Response to message 1",- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),- cached=False,+ result = await agent.run(task="Test handoff in loop")++ # Should stop at handoff+ assert len(model_client.create_calls) == 1, f"Expected 1 call, got {len(model_client.create_calls)}"++ # Should return HandoffMessage+ assert isinstance(result.messages[-1], HandoffMessage)++ @pytest.mark.asyncio+ async def test_tool_call_config_validation(self) -> None:+ """Test that ToolCallConfig validation works correctly."""+ # Test that max_iterations must be >= 1+ with pytest.raises(+ ValueError, match="Maximum number of tool iterations must be greater than or equal to 1, got 0"+ ):+ AssistantAgent(+ name="test_agent",+ model_client=MagicMock(),+ max_tool_iterations=0, # Should raise error)- ]- )- agent = AssistantAgent(- "test_agent",- model_client=model_client,- )- # Create a list of chat messages- messages: List[BaseChatMessage] = [- TextMessage(content="Message 1", source="user"),- TextMessage(content="Message 2", source="user"),- ]- # Test run method with list of messages- result = await agent.run(task=messages)- assert len(result.messages) == 3 # 2 input messages + 1 response message- assert isinstance(result.messages[0], TextMessage)- assert result.messages[0].content == "Message 1"- assert result.messages[0].source == "user"- assert isinstance(result.messages[1], TextMessage)- assert result.messages[1].content == "Message 2"- assert result.messages[1].source == "user"- assert isinstance(result.messages[2], TextMessage)- assert result.messages[2].content == "Response to message 1"- assert result.messages[2].source == "test_agent"- assert result.messages[2].models_usage is not None- assert result.messages[2].models_usage.completion_tokens == 5- assert result.messages[2].models_usage.prompt_tokens == 10-- # Test run_stream method with list of messages- model_client.reset() # Reset the mock client- index = 0- async for message in agent.run_stream(task=messages):- if isinstance(message, TaskResult):- assert compare_task_results(message, result)- else:- assert compare_messages(message, result.messages[index])- index += 1+class TestAssistantAgentInitialization:+ """Test suite for AssistantAgent initialization.+ Tests various initialization scenarios and configurations of the AssistantAgent class.+ """-async def test_model_context(monkeypatch: pytest.MonkeyPatch) -> None:- model_client = ReplayChatCompletionClient(["Response to message 3"])- model_context = BufferedChatCompletionContext(buffer_size=2)- agent = AssistantAgent(- "test_agent",- model_client=model_client,- model_context=model_context,- )+ @pytest.mark.asyncio+ async def test_basic_initialization(self) -> None:+ """Test basic agent initialization with minimal parameters.++ Verifies that:+ 1. Agent initializes with required parameters+ 2. Default values are set correctly+ 3. Basic functionality works+ """+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="stop",+ content="Hello!",+ usage=RequestUsage(prompt_tokens=5, completion_tokens=2),+ cached=False,+ )+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )- messages = [- TextMessage(content="Message 1", source="user"),- TextMessage(content="Message 2", source="user"),- TextMessage(content="Message 3", source="user"),- ]- await agent.run(task=messages)+ agent = AssistantAgent(name="test_agent", model_client=model_client)+ result = await agent.run(task="Say hello")++ assert isinstance(result.messages[-1], TextMessage)+ assert result.messages[-1].content == "Hello!"++ @pytest.mark.asyncio+ async def test_initialization_with_tools(self) -> None:+ """Test agent initialization with tools.++ Verifies that:+ 1. Agent accepts tool configurations+ 2. Tools are properly registered+ 3. Tool calls work correctly+ """+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="mock_tool_function")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ )+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )- # Check that the model_context property returns the correct internal context- assert agent.model_context == model_context- # Check if the mock client is called with only the last two messages.- assert len(model_client.create_calls) == 1- # 2 message from the context + 1 system message- assert len(model_client.create_calls[0]["messages"]) == 3+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ )+ result = await agent.run(task="Use the tool")+ assert isinstance(result.messages[-1], ToolCallSummaryMessage)+ assert "Tool executed with: test" in result.messages[-1].content++ @pytest.mark.asyncio+ async def test_initialization_with_memory(self) -> None:+ """Test agent initialization with memory.++ Verifies that:+ 1. Memory is properly integrated+ 2. Memory contents affect responses+ 3. Memory updates work correctly+ """+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="stop",+ content="Using memory content",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ )+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )-async def test_run_with_memory(monkeypatch: pytest.MonkeyPatch) -> None:- model_client = ReplayChatCompletionClient(["Hello"])- b64_image_str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4//8/AAX+Av4N70a4AAAAAElFTkSuQmCC"-- # Test basic memory properties and empty context- memory = ListMemory(name="test_memory")- assert memory.name == "test_memory"-- empty_context = BufferedChatCompletionContext(buffer_size=2)- empty_results = await memory.update_context(empty_context)- assert len(empty_results.memories.results) == 0-- # Test various content types- memory = ListMemory()- await memory.add(MemoryContent(content="text content", mime_type=MemoryMimeType.TEXT))- await memory.add(MemoryContent(content={"key": "value"}, mime_type=MemoryMimeType.JSON))- await memory.add(MemoryContent(content=Image.from_base64(b64_image_str), mime_type=MemoryMimeType.IMAGE))-- # Test query functionality- query_result = await memory.query(MemoryContent(content="", mime_type=MemoryMimeType.TEXT))- assert isinstance(query_result, MemoryQueryResult)- # Should have all three memories we added- assert len(query_result.results) == 3-- # Test clear and cleanup- await memory.clear()- empty_query = await memory.query(MemoryContent(content="", mime_type=MemoryMimeType.TEXT))- assert len(empty_query.results) == 0- await memory.close() # Should not raise-- # Test invalid memory type- with pytest.raises(TypeError):- AssistantAgent(- "test_agent",+ memory = MockMemory(contents=["Test memory content"])+ agent = AssistantAgent(+ name="test_agent",model_client=model_client,- memory="invalid", # type: ignore+ memory=[memory],)- # Test with agent- memory2 = ListMemory()- await memory2.add(MemoryContent(content="test instruction", mime_type=MemoryMimeType.TEXT))+ result = await agent.run(task="Use memory")+ assert isinstance(result.messages[-1], TextMessage)+ assert result.messages[-1].content == "Using memory content"- agent = AssistantAgent("test_agent", model_client=model_client, memory=[memory2])+ @pytest.mark.asyncio+ async def test_initialization_with_handoffs(self) -> None:+ """Test agent initialization with handoffs."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": True, "vision": False, "family": ModelFamily.GPT_4O}- # Test dump and load component with memory- agent_config: ComponentModel = agent.dump_component()- assert agent_config.provider == "autogen_agentchat.agents.AssistantAgent"- agent2 = AssistantAgent.load_component(agent_config)+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ handoffs=["agent1", Handoff(target="agent2")],+ )- result = await agent2.run(task="test task")- assert len(result.messages) > 0- memory_event = next((msg for msg in result.messages if isinstance(msg, MemoryQueryEvent)), None)- assert memory_event is not None- assert len(memory_event.content) > 0- assert isinstance(memory_event.content[0], MemoryContent)+ assert len(agent._handoffs) == 2 # type: ignore[reportPrivateUsage]+ assert "transfer_to_agent1" in agent._handoffs # type: ignore[reportPrivateUsage]+ assert "transfer_to_agent2" in agent._handoffs # type: ignore[reportPrivateUsage]- # Test memory protocol- class BadMemory:- pass+ @pytest.mark.asyncio+ async def test_initialization_with_custom_model_context(self) -> None:+ """Test agent initialization with custom model context."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}- assert not isinstance(BadMemory(), Memory)- assert isinstance(ListMemory(), Memory)+ model_context = BufferedChatCompletionContext(buffer_size=5)+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ model_context=model_context,+ )+ assert agent._model_context == model_context # type: ignore[reportPrivateUsage]-async def test_assistant_agent_declarative() -> None:- model_client = ReplayChatCompletionClient(- ["Response to message 3"],- model_info={- "function_calling": True,- "vision": True,- "json_output": True,- "family": ModelFamily.GPT_4O,- "structured_output": True,- },- )- model_context = BufferedChatCompletionContext(buffer_size=2)- agent = AssistantAgent(- "test_agent",- model_client=model_client,- model_context=model_context,- memory=[ListMemory(name="test_memory")],- )+ @pytest.mark.asyncio+ async def test_initialization_with_structured_output(self) -> None:+ """Test agent initialization with structured output."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}- agent_config: ComponentModel = agent.dump_component()- assert agent_config.provider == "autogen_agentchat.agents.AssistantAgent"+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ output_content_type=StructuredOutput,+ )- agent2 = AssistantAgent.load_component(agent_config)- assert agent2.name == agent.name+ assert agent._output_content_type == StructuredOutput # type: ignore[reportPrivateUsage]+ assert agent._reflect_on_tool_use is True # type: ignore[reportPrivateUsage] # Should be True by default with structured output- agent3 = AssistantAgent(- "test_agent",- model_client=model_client,- model_context=model_context,- tools=[- _pass_function,- _fail_function,- FunctionTool(_echo_function, description="Echo"),- ],- )- agent3_config = agent3.dump_component()- assert agent3_config.provider == "autogen_agentchat.agents.AssistantAgent"+ @pytest.mark.asyncio+ async def test_initialization_with_metadata(self) -> None:+ """Test agent initialization with metadata."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}+ metadata = {"key1": "value1", "key2": "value2"}+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ metadata=metadata,+ )-async def test_model_client_stream() -> None:- mock_client = ReplayChatCompletionClient(- [- "Response to message 3",- ]- )- agent = AssistantAgent(- "test_agent",- model_client=mock_client,- model_client_stream=True,- )- chunks: List[str] = []- async for message in agent.run_stream(task="task"):- if isinstance(message, TaskResult):- assert isinstance(message.messages[-1], TextMessage)- assert message.messages[-1].content == "Response to message 3"- elif isinstance(message, ModelClientStreamingChunkEvent):- chunks.append(message.content)- assert "".join(chunks) == "Response to message 3"+ assert agent._metadata == metadata # type: ignore[reportPrivateUsage]-async def test_model_client_stream_with_tool_calls() -> None:- mock_client = ReplayChatCompletionClient(- [- CreateResult(- content=[- FunctionCall(id="1", name="_pass_function", arguments=r'{"input": "task"}'),- FunctionCall(id="3", name="_echo_function", arguments=r'{"input": "task"}'),- ],- finish_reason="function_calls",- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),- cached=False,- ),- "Example response 2 to task",- ]- )- mock_client._model_info["function_calling"] = True # pyright: ignore- agent = AssistantAgent(- "test_agent",- model_client=mock_client,- model_client_stream=True,- reflect_on_tool_use=True,- tools=[_pass_function, _echo_function],- )- chunks: List[str] = []- async for message in agent.run_stream(task="task"):- if isinstance(message, TaskResult):- assert isinstance(message.messages[-1], TextMessage)- assert isinstance(message.messages[1], ToolCallRequestEvent)- assert message.messages[-1].content == "Example response 2 to task"- assert message.messages[1].content == [- FunctionCall(id="1", name="_pass_function", arguments=r'{"input": "task"}'),- FunctionCall(id="3", name="_echo_function", arguments=r'{"input": "task"}'),- ]- assert isinstance(message.messages[2], ToolCallExecutionEvent)- assert message.messages[2].content == [- FunctionExecutionResult(call_id="1", content="pass", is_error=False, name="_pass_function"),- FunctionExecutionResult(call_id="3", content="task", is_error=False, name="_echo_function"),- ]- elif isinstance(message, ModelClientStreamingChunkEvent):- chunks.append(message.content)- assert "".join(chunks) == "Example response 2 to task"+class TestAssistantAgentValidation:+ """Test suite for AssistantAgent validation.+ Tests various validation scenarios to ensure proper error handling and input validation.+ """-async def test_invalid_structured_output_format() -> None:- class AgentResponse(BaseModel):- response: str- status: str+ @pytest.mark.asyncio+ async def test_tool_names_must_be_unique(self) -> None:+ """Test validation of unique tool names.++ Verifies that:+ 1. Duplicate tool names are detected+ 2. Appropriate error is raised+ """++ def duplicate_tool(param: str) -> str:+ """Test tool with duplicate name.++ Args:+ param: Input parameter++ Returns:+ Formatted string with parameter+ """+ return f"Duplicate tool: {param}"++ model_client = ReplayChatCompletionClient(+ [],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )- model_client = ReplayChatCompletionClient(- [- CreateResult(- finish_reason="stop",- content='{"response": "Hello"}',- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),- cached=False,- ),- ]- )+ with pytest.raises(ValueError, match="Tool names must be unique"):+ AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function, duplicate_tool, mock_tool_function],+ )- agent = AssistantAgent(- name="assistant",- model_client=model_client,- output_content_type=AgentResponse,- )+ @pytest.mark.asyncio+ async def test_handoff_names_must_be_unique(self) -> None:+ """Test validation of unique handoff names.++ Verifies that:+ 1. Duplicate handoff names are detected+ 2. Appropriate error is raised+ """+ model_client = ReplayChatCompletionClient(+ [],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )- with pytest.raises(ValidationError):- await agent.run()+ with pytest.raises(ValueError, match="Handoff names must be unique"):+ AssistantAgent(+ name="test_agent",+ model_client=model_client,+ handoffs=["agent1", "agent2", "agent1"],+ )+ @pytest.mark.asyncio+ async def test_handoff_names_must_be_unique_from_tool_names(self) -> None:+ """Test validation of handoff names against tool names.++ Verifies that:+ 1. Handoff names cannot conflict with tool names+ 2. Appropriate error is raised+ """++ def test_tool() -> str:+ """Test tool with name that conflicts with handoff.++ Returns:+ Static test string+ """+ return "test"++ model_client = ReplayChatCompletionClient(+ [],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )-async def test_structured_message_factory_serialization() -> None:- class AgentResponse(BaseModel):- result: str- status: str+ with pytest.raises(ValueError, match="Handoff names must be unique from tool names"):+ AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[test_tool],+ handoffs=["test_tool"],+ )- model_client = ReplayChatCompletionClient(- [- CreateResult(- finish_reason="stop",- content=AgentResponse(result="All good", status="ok").model_dump_json(),- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),- cached=False,+ @pytest.mark.asyncio+ async def test_function_calling_required_for_tools(self) -> None:+ """Test that function calling is required for tools."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}++ with pytest.raises(ValueError, match="The model does not support function calling"):+ AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],)- ]- )- agent = AssistantAgent(- name="structured_agent",- model_client=model_client,- output_content_type=AgentResponse,- output_content_type_format="{result} - {status}",- )+ @pytest.mark.asyncio+ async def test_function_calling_required_for_handoffs(self) -> None:+ """Test that function calling is required for handoffs."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}++ with pytest.raises(+ ValueError, match="The model does not support function calling, which is needed for handoffs"+ ):+ AssistantAgent(+ name="test_agent",+ model_client=model_client,+ handoffs=["agent1"],+ )- dumped = agent.dump_component()- restored_agent = AssistantAgent.load_component(dumped)- result = await restored_agent.run()+ @pytest.mark.asyncio+ async def test_memory_type_validation(self) -> None:+ """Test memory type validation."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}++ with pytest.raises(TypeError, match="Expected Memory, List\\[Memory\\], or None"):+ AssistantAgent(+ name="test_agent",+ model_client=model_client,+ memory="invalid_memory", # type: ignore+ )- assert isinstance(result.messages[0], StructuredMessage)- assert result.messages[0].content.result == "All good" # type: ignore- assert result.messages[0].content.status == "ok" # type: ignore+ @pytest.mark.asyncio+ async def test_tools_and_workbench_mutually_exclusive(self) -> None:+ """Test that tools and workbench are mutually exclusive."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": True, "vision": False, "family": ModelFamily.GPT_4O}+ workbench = MagicMock()-async def test_structured_message_format_string() -> None:- class AgentResponse(BaseModel):- field1: str- field2: str+ with pytest.raises(ValueError, match="Tools cannot be used with a workbench"):+ AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ workbench=workbench,+ )- expected = AgentResponse(field1="foo", field2="bar")+ @pytest.mark.asyncio+ async def test_unsupported_tool_type(self) -> None:+ """Test error handling for unsupported tool types."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": True, "vision": False, "family": ModelFamily.GPT_4O}++ with pytest.raises(ValueError, match="Unsupported tool type"):+ AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=["invalid_tool"], # type: ignore+ )- model_client = ReplayChatCompletionClient(- [- CreateResult(- finish_reason="stop",- content=expected.model_dump_json(),- usage=RequestUsage(prompt_tokens=10, completion_tokens=5),- cached=False,+ @pytest.mark.asyncio+ async def test_unsupported_handoff_type(self) -> None:+ """Test error handling for unsupported handoff types."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": True, "vision": False, "family": ModelFamily.GPT_4O}++ with pytest.raises(ValueError, match="Unsupported handoff type"):+ AssistantAgent(+ name="test_agent",+ model_client=model_client,+ handoffs=[123], # type: ignore)- ]- )- agent = AssistantAgent(- name="formatted_agent",- model_client=model_client,- output_content_type=AgentResponse,- output_content_type_format="{field1} - {field2}",- )- result = await agent.run()+class TestAssistantAgentStateManagement:+ """Test suite for AssistantAgent state management."""- assert len(result.messages) == 1- message = result.messages[0]+ @pytest.mark.asyncio+ async def test_save_and_load_state(self) -> None:+ """Test saving and loading agent state."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}- # Check that it's a StructuredMessage with the correct content model- assert isinstance(message, StructuredMessage)- assert isinstance(message.content, AgentResponse) # type: ignore[reportUnknownMemberType]- assert message.content == expected+ # Mock model context state+ mock_context = MagicMock()+ mock_context.save_state = AsyncMock(return_value={"context": "state"})+ mock_context.load_state = AsyncMock()- # Check that the format_string was applied correctly- assert message.to_model_text() == "foo - bar"+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ model_context=mock_context,+ )+ # Test save state+ state = await agent.save_state()+ assert "llm_context" in state-async def test_tools_serialize_and_deserialize() -> None:- def test() -> str:- return "hello world"+ # Test load state+ await agent.load_state(state)+ mock_context.load_state.assert_called_once()- client = OpenAIChatCompletionClient(- model="gpt-4o",- api_key="API_KEY",- )+ @pytest.mark.asyncio+ async def test_on_reset(self) -> None:+ """Test agent reset functionality."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}- agent = AssistantAgent(- name="test",- model_client=client,- tools=[test],- )+ mock_context = MagicMock()+ mock_context.clear = AsyncMock()- serialize = agent.dump_component()- deserialize = AssistantAgent.load_component(serialize)+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ model_context=mock_context,+ )- assert deserialize.name == agent.name- for original, restored in zip(agent._workbench, deserialize._workbench, strict=True): # type: ignore- assert await original.list_tools() == await restored.list_tools() # type: ignore- assert agent.component_version == deserialize.component_version+ cancellation_token = CancellationToken()+ await agent.on_reset(cancellation_token)+ mock_context.clear.assert_called_once()-async def test_workbenchs_serialize_and_deserialize() -> None:- workbench = McpWorkbench(server_params=SseServerParams(url="http://test-url"))- client = OpenAIChatCompletionClient(- model="gpt-4o",- api_key="API_KEY",- )+class TestAssistantAgentProperties:+ """Test suite for AssistantAgent properties."""- agent = AssistantAgent(- name="test",- model_client=client,- workbench=workbench,- )+ @pytest.mark.asyncio+ async def test_produced_message_types_text_only(self) -> None:+ """Test produced message types for text-only agent."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}- serialize = agent.dump_component()- deserialize = AssistantAgent.load_component(serialize)+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ )- assert deserialize.name == agent.name- for original, restored in zip(agent._workbench, deserialize._workbench, strict=True): # type: ignore- assert isinstance(original, McpWorkbench)- assert isinstance(restored, McpWorkbench)- assert original._to_config() == restored._to_config() # type: ignore+ message_types = agent.produced_message_types+ assert TextMessage in message_types+ @pytest.mark.asyncio+ async def test_produced_message_types_with_tools(self) -> None:+ """Test produced message types for agent with tools."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": True, "vision": False, "family": ModelFamily.GPT_4O}-async def test_multiple_workbenchs_serialize_and_deserialize() -> None:- workbenches: List[McpWorkbench] = [- McpWorkbench(server_params=SseServerParams(url="http://test-url-1")),- McpWorkbench(server_params=SseServerParams(url="http://test-url-2")),- ]+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ )- client = OpenAIChatCompletionClient(- model="gpt-4o",- api_key="API_KEY",- )+ message_types = agent.produced_message_types+ assert ToolCallSummaryMessage in message_types- agent = AssistantAgent(- name="test_multi",- model_client=client,- workbench=workbenches,- )+ @pytest.mark.asyncio+ async def test_produced_message_types_with_handoffs(self) -> None:+ """Test produced message types for agent with handoffs."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": True, "vision": False, "family": ModelFamily.GPT_4O}- serialize = agent.dump_component()- deserialized_agent: AssistantAgent = AssistantAgent.load_component(serialize)+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ handoffs=["agent1"],+ )- assert deserialized_agent.name == agent.name- assert isinstance(deserialized_agent._workbench, list) # type: ignore- assert len(deserialized_agent._workbench) == len(workbenches) # type: ignore+ message_types = agent.produced_message_types+ assert HandoffMessage in message_types- for original, restored in zip(agent._workbench, deserialized_agent._workbench, strict=True): # type: ignore- assert isinstance(original, McpWorkbench)- assert isinstance(restored, McpWorkbench)- assert original._to_config() == restored._to_config() # type: ignore+ @pytest.mark.asyncio+ async def test_model_context_property(self) -> None:+ """Test model_context property access."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}+ custom_context = BufferedChatCompletionContext(buffer_size=3)+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ model_context=custom_context,+ )-async def test_tools_deserialize_aware() -> None:- dump = """- {- "provider": "autogen_agentchat.agents.AssistantAgent",- "component_type": "agent",- "version": 1,- "component_version": 2,- "description": "An agent that provides assistance with tool use.",- "label": "AssistantAgent",- "config": {- "name": "TestAgent",- "model_client":{- "provider": "autogen_ext.models.replay.ReplayChatCompletionClient",- "component_type": "replay_chat_completion_client",- "version": 1,- "component_version": 1,- "description": "A mock chat completion client that replays predefined responses using an index-based approach.",- "label": "ReplayChatCompletionClient",- "config": {- "chat_completions": [- {- "finish_reason": "function_calls",- "content": [- {- "id": "hello",- "arguments": "{}",- "name": "hello"- }- ],- "usage": {- "prompt_tokens": 0,- "completion_tokens": 0- },- "cached": false- }+ assert agent.model_context == custom_context+++class TestAssistantAgentErrorHandling:+ """Test suite for error handling scenarios."""++ @pytest.mark.asyncio+ async def test_invalid_json_in_tool_arguments(self) -> None:+ """Test handling of invalid JSON in tool arguments."""+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments="invalid json", name="mock_tool_function")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ )++ result = await agent.run(task="Execute tool with invalid JSON")++ # Should handle JSON parsing error+ assert isinstance(result.messages[-1], ToolCallSummaryMessage)+++class TestAssistantAgentMemoryIntegration:+ """Test suite for AssistantAgent memory integration.++ Tests the integration between AssistantAgent and memory components, including:+ - Memory initialization+ - Context updates+ - Query operations+ - Memory persistence+ """++ @pytest.mark.asyncio+ async def test_memory_updates_context(self) -> None:+ """Test that memory properly updates model context.++ Verifies that:+ 1. Memory contents are added to context+ 2. Context updates trigger appropriate events+ 3. Memory query results are properly handled+ """+ # Setup test memory with initial content+ memory = MockMemory(contents=["Previous conversation about topic A"])++ # Configure model client with expected response+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="stop",+ content="Response incorporating memory content",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ )+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ # Create agent with memory+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ memory=[memory],+ description="Agent with memory integration",+ )++ # Track memory events during execution+ memory_events: List[MemoryQueryEvent] = []++ async def event_handler(event: MemoryQueryEvent) -> None:+ """Handle memory query events.++ Args:+ event: Memory query event to process+ """+ memory_events.append(event)++ # Create a handler function to capture memory events+ async def handle_memory_events(result: Any) -> None:+ messages: List[BaseChatMessage] = result.messages if hasattr(result, "messages") else []+ for msg in messages:+ if isinstance(msg, MemoryQueryEvent):+ await event_handler(msg)++ # Run agent+ result = await agent.run(task="Respond using memory context")++ # Process the events+ await handle_memory_events(result)++ # Verify memory integration+ assert len(memory_events) > 0, "No memory events were generated"+ assert isinstance(result.messages[-1], TextMessage)+ assert "Response incorporating memory content" in result.messages[-1].content++ @pytest.mark.asyncio+ async def test_memory_persistence(self) -> None:+ """Test memory persistence across multiple sessions.++ Verifies:+ 1. Memory content persists between sessions+ 2. Memory updates are preserved+ 3. Context is properly restored+ 4. Memory query events are generated correctly+ """+ # Create memory with initial content+ memory = MockMemory(contents=["Initial memory"])++ # Create model client+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="stop",+ content="Response using memory",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ CreateResult(+ finish_reason="stop",+ content="Response with updated memory",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": False,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ # Create agent with memory+ agent = AssistantAgent(name="memory_test_agent", model_client=model_client, memory=[memory])++ # First session+ result1 = await agent.run(task="First task")+ state = await agent.save_state()++ # Add new memory content+ await memory.add(MemoryContent(content="New memory", mime_type="text/plain"))++ # Create new agent and restore state+ new_agent = AssistantAgent(name="memory_test_agent", model_client=model_client, memory=[memory])+ await new_agent.load_state(state)++ # Second session+ result2 = await new_agent.run(task="Second task")++ # Verify memory persistence+ assert isinstance(result1.messages[-1], TextMessage)+ assert isinstance(result2.messages[-1], TextMessage)+ assert result1.messages[-1].content == "Response using memory"+ assert result2.messages[-1].content == "Response with updated memory"++ # Verify memory events+ memory_events = [msg for msg in result2.messages if isinstance(msg, MemoryQueryEvent)]+ assert len(memory_events) > 0+ assert any("New memory" in str(event.content) for event in memory_events)+++class TestAssistantAgentSystemMessage:+ """Test suite for system message functionality."""++ @pytest.mark.asyncio+ async def test_system_message_none(self) -> None:+ """Test agent with system_message=None."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ system_message=None,+ )++ assert agent._system_messages == [] # type: ignore[reportPrivateUsage]++ @pytest.mark.asyncio+ async def test_custom_system_message(self) -> None:+ """Test agent with custom system message."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}++ custom_message = "You are a specialized assistant."+ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ system_message=custom_message,+ )++ assert len(agent._system_messages) == 1 # type: ignore[reportPrivateUsage]+ assert agent._system_messages[0].content == custom_message # type: ignore[reportPrivateUsage]+++class TestAssistantAgentModelCompatibility:+ """Test suite for model compatibility functionality."""++ @pytest.mark.asyncio+ async def test_claude_model_warning(self) -> None:+ """Test warning for Claude models with reflection."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": True, "vision": False, "family": ModelFamily.CLAUDE_3_5_SONNET}++ with pytest.warns(UserWarning, match="Claude models may not work with reflection"):+ AssistantAgent(+ name="test_agent",+ model_client=model_client,+ reflect_on_tool_use=True,+ )++ @pytest.mark.asyncio+ async def test_vision_compatibility(self) -> None:+ """Test vision model compatibility."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": True, "family": ModelFamily.GPT_4O}++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ )++ # Test _get_compatible_context with vision model+ from autogen_core.models import LLMMessage++ messages: List[LLMMessage] = [SystemMessage(content="Test")]+ compatible_messages = agent._get_compatible_context(model_client, messages) # type: ignore[reportPrivateUsage]++ # Should return original messages for vision models+ assert compatible_messages == messages+++class TestAssistantAgentComponentSerialization:+ """Test suite for component serialization functionality."""++ @pytest.mark.asyncio+ async def test_to_config_basic_agent(self) -> None:+ """Test _to_config method with basic agent configuration."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}+ model_client.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_client"})+ )++ mock_context = MagicMock()+ mock_context.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_context"})+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ description="Test description",+ system_message="Test system message",+ model_context=mock_context,+ metadata={"key": "value"},+ )++ config = agent._to_config() # type: ignore[reportPrivateUsage]++ assert config.name == "test_agent"+ assert config.description == "Test description"+ assert config.system_message == "Test system message"+ assert config.model_client_stream is False+ assert config.reflect_on_tool_use is False+ assert config.max_tool_iterations == 1+ assert config.metadata == {"key": "value"}+ model_client.dump_component.assert_called_once()+ mock_context.dump_component.assert_called_once()++ @pytest.mark.asyncio+ async def test_to_config_agent_with_handoffs(self) -> None:+ """Test _to_config method with agent having handoffs."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": True, "vision": False, "family": ModelFamily.GPT_4O}+ model_client.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_client"})+ )++ mock_context = MagicMock()+ mock_context.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_context"})+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ handoffs=["agent1", Handoff(target="agent2")],+ model_context=mock_context,+ )++ config = agent._to_config() # type: ignore[reportPrivateUsage]++ assert config.handoffs is not None+ assert len(config.handoffs) == 2+ handoff_targets: List[str] = [h.target if hasattr(h, "target") else str(h) for h in config.handoffs] # type: ignore[reportUnknownMemberType, reportAttributeAccessIssue]+ assert "agent1" in handoff_targets+ assert "agent2" in handoff_targets++ @pytest.mark.asyncio+ async def test_to_config_agent_with_memory(self) -> None:+ """Test _to_config method with agent having memory modules."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}+ model_client.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_client"})+ )++ mock_context = MagicMock()+ mock_context.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_context"})+ )++ mock_memory = MockMemory()++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ memory=[mock_memory],+ model_context=mock_context,+ )++ config = agent._to_config() # type: ignore[reportPrivateUsage]++ assert config.memory is not None+ assert len(config.memory) == 1+ assert config.memory[0].provider == "test"+ assert config.memory[0].config == {"type": "mock_memory"}++ @pytest.mark.asyncio+ async def test_to_config_agent_with_workbench(self) -> None:+ """Test _to_config method with agent having workbench."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": True, "vision": False, "family": ModelFamily.GPT_4O}+ model_client.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_client"})+ )++ mock_context = MagicMock()+ mock_context.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_context"})+ )++ mock_workbench = MagicMock()+ mock_workbench.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_workbench"})+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ model_context=mock_context,+ )++ # Replace the workbench with our mock+ agent._workbench = [mock_workbench] # type: ignore[reportPrivateUsage]++ config = agent._to_config() # type: ignore[reportPrivateUsage]++ assert config.workbench is not None+ assert len(config.workbench) == 1+ mock_workbench.dump_component.assert_called_once()++ @pytest.mark.asyncio+ async def test_to_config_agent_with_structured_output(self) -> None:+ """Test _to_config method with agent having structured output."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}+ model_client.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_client"})+ )++ mock_context = MagicMock()+ mock_context.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_context"})+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ output_content_type=StructuredOutput,+ model_context=mock_context,+ )++ config = agent._to_config() # type: ignore[reportPrivateUsage]++ assert config.structured_message_factory is not None+ assert config.reflect_on_tool_use is True # Should be True with structured output++ @pytest.mark.asyncio+ async def test_to_config_system_message_none(self) -> None:+ """Test _to_config method with system_message=None."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}+ model_client.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_client"})+ )++ mock_context = MagicMock()+ mock_context.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_context"})+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ system_message=None,+ model_context=mock_context,+ )++ config = agent._to_config() # type: ignore[reportPrivateUsage]++ assert config.system_message is None++ @pytest.mark.asyncio+ async def test_from_config_basic_agent(self) -> None:+ """Test _from_config method with basic agent configuration."""+ mock_model_client = MagicMock()+ mock_model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}++ with patch("autogen_core.models.ChatCompletionClient.load_component", return_value=mock_model_client):+ config = AssistantAgentConfig(+ name="test_agent",+ model_client=ComponentModel(provider="test", config={"type": "mock_client"}),+ description="Test description",+ system_message="Test system",+ model_client_stream=True,+ reflect_on_tool_use=False,+ tool_call_summary_format="{tool_name}: {result}",+ metadata={"test": "value"},+ )++ agent = AssistantAgent._from_config(config) # type: ignore[reportPrivateUsage]++ assert agent.name == "test_agent"+ assert agent.description == "Test description"+ assert agent._model_client_stream is True # type: ignore[reportPrivateUsage]+ assert agent._reflect_on_tool_use is False # type: ignore[reportPrivateUsage]+ assert agent._tool_call_summary_format == "{tool_name}: {result}" # type: ignore[reportPrivateUsage]+ assert agent._metadata == {"test": "value"} # type: ignore[reportPrivateUsage]++ @pytest.mark.asyncio+ async def test_from_config_with_structured_output(self) -> None:+ """Test _from_config method with structured output configuration."""+ mock_model_client = MagicMock()+ mock_model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}++ mock_structured_factory = MagicMock()+ mock_structured_factory.format_string = "Test format"+ mock_structured_factory.ContentModel = StructuredOutput++ with (+ patch("autogen_core.models.ChatCompletionClient.load_component", return_value=mock_model_client),+ patch(+ "autogen_agentchat.messages.StructuredMessageFactory.load_component",+ return_value=mock_structured_factory,+ ),+ ):+ config = AssistantAgentConfig(+ name="test_agent",+ model_client=ComponentModel(provider="test", config={"type": "mock_client"}),+ description="Test description",+ reflect_on_tool_use=True,+ tool_call_summary_format="{result}",+ structured_message_factory=ComponentModel(provider="test", config={"type": "mock_factory"}),+ )++ agent = AssistantAgent._from_config(config) # type: ignore[reportPrivateUsage]++ assert agent._reflect_on_tool_use is True # type: ignore[reportPrivateUsage]+ assert agent._output_content_type == StructuredOutput # type: ignore[reportPrivateUsage]+ assert agent._output_content_type_format == "Test format" # type: ignore[reportPrivateUsage]++ @pytest.mark.asyncio+ async def test_from_config_with_workbench_and_memory(self) -> None:+ """Test _from_config method with workbench and memory."""+ mock_model_client = MagicMock()+ mock_model_client.model_info = {"function_calling": True, "vision": False, "family": ModelFamily.GPT_4O}++ mock_workbench = MagicMock()+ mock_memory = MockMemory()+ mock_context = MagicMock()++ with (+ patch("autogen_core.models.ChatCompletionClient.load_component", return_value=mock_model_client),+ patch("autogen_core.tools.Workbench.load_component", return_value=mock_workbench),+ patch("autogen_core.memory.Memory.load_component", return_value=mock_memory),+ patch("autogen_core.model_context.ChatCompletionContext.load_component", return_value=mock_context),+ ):+ config = AssistantAgentConfig(+ name="test_agent",+ model_client=ComponentModel(provider="test", config={"type": "mock_client"}),+ description="Test description",+ workbench=[ComponentModel(provider="test", config={"type": "mock_workbench"})],+ memory=[ComponentModel(provider="test", config={"type": "mock_memory"})],+ model_context=ComponentModel(provider="test", config={"type": "mock_context"}),+ reflect_on_tool_use=True,+ tool_call_summary_format="{result}",+ )++ agent = AssistantAgent._from_config(config) # type: ignore[reportPrivateUsage]++ assert len(agent._workbench) == 1 # type: ignore[reportPrivateUsage]+ assert agent._memory is not None # type: ignore[reportPrivateUsage]+ assert len(agent._memory) == 1 # type: ignore[reportPrivateUsage]+ assert agent._model_context == mock_context # type: ignore[reportPrivateUsage]++ @pytest.mark.asyncio+ async def test_config_roundtrip_consistency(self) -> None:+ """Test that converting to config and back preserves agent properties."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": True, "vision": False, "family": ModelFamily.GPT_4O}+ model_client.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_client"})+ )++ mock_context = MagicMock()+ mock_context.dump_component = MagicMock(+ return_value=ComponentModel(provider="test", config={"type": "mock_context"})+ )++ original_agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ description="Test description",+ system_message="Test system message",+ model_client_stream=True,+ reflect_on_tool_use=True,+ max_tool_iterations=5,+ tool_call_summary_format="{tool_name}: {result}",+ handoffs=["agent1"],+ model_context=mock_context,+ metadata={"test": "value"},+ )++ # Convert to config+ config = original_agent._to_config() # type: ignore[reportPrivateUsage]++ # Verify config properties+ assert config.name == "test_agent"+ assert config.description == "Test description"+ assert config.system_message == "Test system message"+ assert config.model_client_stream is True+ assert config.reflect_on_tool_use is True+ assert config.max_tool_iterations == 5+ assert config.tool_call_summary_format == "{tool_name}: {result}"+ assert config.metadata == {"test": "value"}+++class TestAssistantAgentThoughtHandling:+ """Test suite for thought handling functionality."""++ @pytest.mark.asyncio+ async def test_thought_event_yielded_from_model_result(self) -> None:+ """Test that thought events are yielded when model result contains thoughts."""+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="stop",+ content="Final response",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ thought="This is my internal thought process",+ ),+ ],+ model_info={+ "function_calling": False,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ )++ messages: List[Any] = []+ async for message in agent.on_messages_stream(+ [TextMessage(content="Test", source="user")], CancellationToken()+ ):+ messages.append(message)++ # Should have ThoughtEvent in the stream+ thought_events = [msg for msg in messages if isinstance(msg, ThoughtEvent)]+ assert len(thought_events) == 1+ assert thought_events[0].content == "This is my internal thought process"+ assert thought_events[0].source == "test_agent"++ @pytest.mark.asyncio+ async def test_thought_event_with_tool_calls(self) -> None:+ """Test that thought events are yielded when tool calls have thoughts."""+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="mock_tool_function")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ thought="I need to use this tool to help the user",+ ),+ CreateResult(+ finish_reason="stop",+ content="Tool execution completed",+ usage=RequestUsage(prompt_tokens=15, completion_tokens=10),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ max_tool_iterations=1,+ )++ messages: List[Any] = []+ async for message in agent.on_messages_stream(+ [TextMessage(content="Test", source="user")], CancellationToken()+ ):+ messages.append(message)++ # Should have ThoughtEvent in the stream+ thought_events = [msg for msg in messages if isinstance(msg, ThoughtEvent)]+ assert len(thought_events) == 1+ assert thought_events[0].content == "I need to use this tool to help the user"+ assert thought_events[0].source == "test_agent"++ @pytest.mark.asyncio+ async def test_thought_event_with_reflection(self) -> None:+ """Test that thought events are yielded during reflection."""+ model_client = ReplayChatCompletionClient(+ [+ # Initial tool call with thought+ CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="mock_tool_function")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ thought="Initial thought before tool call",+ ),+ # Reflection with thought+ CreateResult(+ finish_reason="stop",+ content="Based on the tool result, here's my response",+ usage=RequestUsage(prompt_tokens=15, completion_tokens=10),+ cached=False,+ thought="Reflection thought after tool execution",+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ reflect_on_tool_use=True,+ model_client_stream=True, # Enable streaming+ )++ messages: List[Any] = []+ async for message in agent.on_messages_stream(+ [TextMessage(content="Test", source="user")], CancellationToken()+ ):+ messages.append(message)++ # Should have two ThoughtEvents - one for initial call, one for reflection+ thought_events = [msg for msg in messages if isinstance(msg, ThoughtEvent)]+ assert len(thought_events) == 2++ thought_contents = [event.content for event in thought_events]+ assert "Initial thought before tool call" in thought_contents+ assert "Reflection thought after tool execution" in thought_contents++ @pytest.mark.asyncio+ async def test_thought_event_with_tool_call_loop(self) -> None:+ """Test that thought events are yielded in tool call loops."""+ model_client = ReplayChatCompletionClient(+ [+ # First tool call with thought+ CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments=json.dumps({"param": "first"}), name="mock_tool_function")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ thought="First iteration thought",+ ),+ # Second tool call with thought+ CreateResult(+ finish_reason="function_calls",+ content=[+ FunctionCall(id="2", arguments=json.dumps({"param": "second"}), name="mock_tool_function")+ ],+ usage=RequestUsage(prompt_tokens=12, completion_tokens=5),+ cached=False,+ thought="Second iteration thought",+ ),+ # Final response with thought+ CreateResult(+ finish_reason="stop",+ content="Loop completed",+ usage=RequestUsage(prompt_tokens=15, completion_tokens=10),+ cached=False,+ thought="Final completion thought",+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ max_tool_iterations=3,+ )++ messages: List[Any] = []+ async for message in agent.on_messages_stream(+ [TextMessage(content="Test", source="user")], CancellationToken()+ ):+ messages.append(message)++ # Should have three ThoughtEvents - one for each iteration+ thought_events = [msg for msg in messages if isinstance(msg, ThoughtEvent)]+ assert len(thought_events) == 3++ thought_contents = [event.content for event in thought_events]+ assert "First iteration thought" in thought_contents+ assert "Second iteration thought" in thought_contents+ assert "Final completion thought" in thought_contents++ @pytest.mark.asyncio+ async def test_thought_event_with_handoff(self) -> None:+ """Test that thought events are included in handoff context."""+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[+ FunctionCall(+ id="1", arguments=json.dumps({"target": "other_agent"}), name="transfer_to_other_agent"+ )+ ],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ thought="I need to hand this off to another agent",+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ handoffs=["other_agent"],+ max_tool_iterations=1,+ )++ result = await agent.run(task="Test handoff with thought")++ # Should have ThoughtEvent in inner messages+ thought_events = [msg for msg in result.messages if isinstance(msg, ThoughtEvent)]+ assert len(thought_events) == 1+ assert thought_events[0].content == "I need to hand this off to another agent"++ # Should have handoff message with thought in context+ handoff_message = result.messages[-1]+ assert isinstance(handoff_message, HandoffMessage)+ assert len(handoff_message.context) == 1+ assert isinstance(handoff_message.context[0], AssistantMessage)+ assert handoff_message.context[0].content == "I need to hand this off to another agent"++ @pytest.mark.asyncio+ async def test_no_thought_event_when_no_thought(self) -> None:+ """Test that no thought events are yielded when model result has no thoughts."""+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="stop",+ content="Simple response without thought",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ # No thought field+ ),+ ],+ model_info={+ "function_calling": False,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ )++ messages: List[Any] = []+ async for message in agent.on_messages_stream(+ [TextMessage(content="Test", source="user")], CancellationToken()+ ):+ messages.append(message)++ # Should have no ThoughtEvents+ thought_events = [msg for msg in messages if isinstance(msg, ThoughtEvent)]+ assert len(thought_events) == 0++ @pytest.mark.asyncio+ async def test_thought_event_context_preservation(self) -> None:+ """Test that thoughts are properly preserved in model context."""+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="stop",+ content="Response with thought",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ thought="Internal reasoning",+ ),+ ],+ model_info={+ "function_calling": False,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ )++ await agent.run(task="Test thought preservation")++ # Check that the model context contains the thought+ messages = await agent.model_context.get_messages()+ assistant_messages = [msg for msg in messages if isinstance(msg, AssistantMessage)]+ assert len(assistant_messages) > 0++ # The last assistant message should have the thought+ last_assistant_msg = assistant_messages[-1]+ # Fix line 2727 - properly check for thought attribute with type checking+ if hasattr(last_assistant_msg, "thought"):+ thought_content = cast(str, last_assistant_msg.thought)+ assert thought_content == "Internal reasoning"+++class TestAssistantAgentAdvancedScenarios:+ """Test suite for advanced usage scenarios."""++ @pytest.mark.asyncio+ async def test_handoff_without_tool_calls(self) -> None:+ """Test handoff without any tool calls."""+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[+ FunctionCall(id="1", arguments=json.dumps({"target": "agent2"}), name="transfer_to_agent2")+ ],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ handoffs=["agent2"],+ )++ result = await agent.run(task="Handoff to agent2")++ # Should return HandoffMessage+ assert isinstance(result.messages[-1], HandoffMessage)+ assert result.messages[-1].target == "agent2"++ @pytest.mark.asyncio+ async def test_multiple_handoff_warning(self) -> None:+ """Test warning for multiple handoffs."""+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[+ FunctionCall(id="1", arguments=json.dumps({"target": "agent2"}), name="transfer_to_agent2"),+ FunctionCall(id="2", arguments=json.dumps({"target": "agent3"}), name="transfer_to_agent3"),+ ],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ handoffs=["agent2", "agent3"],+ )++ with pytest.warns(UserWarning, match="Multiple handoffs detected"):+ result = await agent.run(task="Multiple handoffs")++ # Should only execute first handoff+ assert isinstance(result.messages[-1], HandoffMessage)+ assert result.messages[-1].target == "agent2"++ @pytest.mark.asyncio+ async def test_structured_output_with_reflection(self) -> None:+ """Test structured output with reflection enabled."""+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="mock_tool_function")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ CreateResult(+ finish_reason="stop",+ content='{"content": "Structured response", "confidence": 0.95}',+ usage=RequestUsage(prompt_tokens=15, completion_tokens=10),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ output_content_type=StructuredOutput,+ reflect_on_tool_use=True,+ )++ result = await agent.run(task="Test structured output with reflection")++ # Should return StructuredMessage+ from autogen_agentchat.messages import StructuredMessage++ final_message = result.messages[-1]+ assert isinstance(final_message, StructuredMessage)+ # Fix line 1710 - properly access structured content with explicit type annotation+ structured_message: StructuredMessage[StructuredOutput] = cast(+ StructuredMessage[StructuredOutput], final_message+ )+ assert structured_message.content.content == "Structured response"+ assert structured_message.content.confidence == 0.95+++class TestAssistantAgentAdvancedToolFeatures:+ """Test suite for advanced tool features including custom formatters."""++ @pytest.mark.asyncio+ async def test_custom_tool_call_summary_formatter(self) -> None:+ """Test custom tool call summary formatter functionality."""+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[+ FunctionCall(id="1", arguments=json.dumps({"param": "success"}), name="mock_tool_function"),+ FunctionCall(id="2", arguments=json.dumps({"param": "error"}), name="mock_tool_function"),+ ],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ def custom_formatter(call: FunctionCall, result: FunctionExecutionResult) -> str:+ if result.is_error:+ return f"ERROR in {call.name}: {result.content} (args: {call.arguments})"+ else:+ return f"SUCCESS: {call.name} completed"++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ tool_call_summary_formatter=custom_formatter,+ reflect_on_tool_use=False,+ )++ result = await agent.run(task="Test custom formatter")++ # Should return ToolCallSummaryMessage with custom formatting+ final_message = result.messages[-1]+ assert isinstance(final_message, ToolCallSummaryMessage)+ # Fix line 1875 - properly access content with type checking+ assert hasattr(final_message, "content"), "ToolCallSummaryMessage should have content attribute"+ content = final_message.content+ assert "SUCCESS: mock_tool_function completed" in content+ assert "SUCCESS: mock_tool_function completed" in content # Both calls should be successful++ @pytest.mark.asyncio+ async def test_custom_tool_call_summary_format_string(self) -> None:+ """Test custom tool call summary format string."""+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="mock_tool_function")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ tool_call_summary_format="Tool {tool_name} called with {arguments} -> {result}",+ reflect_on_tool_use=False,+ )++ result = await agent.run(task="Test custom format string")++ # Should return ToolCallSummaryMessage with custom format+ final_message = result.messages[-1]+ assert isinstance(final_message, ToolCallSummaryMessage)+ content = final_message.content+ assert "Tool mock_tool_function called with" in content+ assert "Tool executed with: test" in content++ @pytest.mark.asyncio+ async def test_tool_call_summary_formatter_overrides_format_string(self) -> None:+ """Test that tool_call_summary_formatter overrides format string."""+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="mock_tool_function")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ def custom_formatter(call: FunctionCall, result: FunctionExecutionResult) -> str:+ return f"CUSTOM: {call.name} -> {result.content}"++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ tool_call_summary_format="This should be ignored: {result}",+ tool_call_summary_formatter=custom_formatter,+ reflect_on_tool_use=False,+ )++ result = await agent.run(task="Test formatter override")++ # Should use custom formatter, not format string+ final_message = result.messages[-1]+ assert isinstance(final_message, ToolCallSummaryMessage)+ content = final_message.content+ assert "CUSTOM: mock_tool_function" in content+ assert "This should be ignored" not in content++ @pytest.mark.asyncio+ async def test_output_content_type_format_string(self) -> None:+ """Test structured output with custom format string."""+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="stop",+ content='{"content": "Test response", "confidence": 0.8}',+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": False,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ output_content_type=StructuredOutput,+ output_content_type_format="Response: {content} (Confidence: {confidence})",+ )++ result = await agent.run(task="Test structured output format")++ # Should return StructuredMessage with custom format+ final_message = result.messages[-1]+ assert isinstance(final_message, StructuredMessage)+ # Fix line 1880 - properly access structured content with explicit type annotation+ structured_message: StructuredMessage[StructuredOutput] = cast(+ StructuredMessage[StructuredOutput], final_message+ )+ assert structured_message.content.content == "Test response"+ assert structured_message.content.confidence == 0.8+ # The format string should be stored in the agent+ assert hasattr(agent, "_output_content_type_format")+ output_format = getattr(agent, "_output_content_type_format", None)+ assert output_format == "Response: {content} (Confidence: {confidence})"++ @pytest.mark.asyncio+ async def test_tool_call_error_handling_with_custom_formatter(self) -> None:+ """Test error handling in tool calls with custom formatter."""++ def error_tool(param: str) -> str:+ raise ValueError(f"Tool error with param: {param}")++ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="error_tool")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ def error_formatter(call: FunctionCall, result: FunctionExecutionResult) -> str:+ if result.is_error:+ return f"ERROR in {call.name}: {result.content}"+ else:+ return f"SUCCESS: {result.content}"++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[error_tool],+ tool_call_summary_formatter=error_formatter,+ reflect_on_tool_use=False,+ )++ result = await agent.run(task="Test error handling")++ # Should return ToolCallSummaryMessage with error formatting+ assert isinstance(result.messages[-1], ToolCallSummaryMessage)+ content = result.messages[-1].content+ assert "ERROR in error_tool" in content++ @pytest.mark.asyncio+ async def test_multiple_tools_with_different_formats(self) -> None:+ """Test multiple tool calls with different return formats."""++ def json_tool(data: str) -> str:+ return json.dumps({"result": data, "status": "success"})++ def simple_tool(text: str) -> str:+ return f"Processed: {text}"++ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[+ FunctionCall(id="1", arguments=json.dumps({"data": "json_data"}), name="json_tool"),+ FunctionCall(id="2", arguments=json.dumps({"text": "simple_text"}), name="simple_tool"),],- "model_info": {- "vision": false,- "function_calling": true,- "json_output": false,- "family": "unknown",- "structured_output": false- }- }+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,},- "tools": [- {- "provider": "autogen_core.tools.FunctionTool",- "component_type": "tool",- "version": 1,- "component_version": 1,- "description": "Create custom tools by wrapping standard Python functions.",- "label": "FunctionTool",- "config": {- "source_code": "def hello():\\n return 'Hello, World!'\\n",- "name": "hello",- "description": "",- "global_imports": [],- "has_cancellation_support": false- }- }+ )++ def smart_formatter(call: FunctionCall, result: FunctionExecutionResult) -> str:+ try:+ # Try to parse as JSON+ parsed = json.loads(result.content)+ return f"{call.name}: {parsed}"+ except json.JSONDecodeError:+ # Plain text+ return f"{call.name}: {result.content}"++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[json_tool, simple_tool],+ tool_call_summary_formatter=smart_formatter,+ reflect_on_tool_use=False,+ )++ result = await agent.run(task="Test multiple tool formats")++ # Should handle both JSON and plain text tools+ assert isinstance(result.messages[-1], ToolCallSummaryMessage)+ content = result.messages[-1].content+ assert "json_tool:" in content+ assert "simple_tool:" in content+ assert "Processed: simple_text" in content+++class TestAssistantAgentCancellationToken:+ """Test suite for cancellation token handling."""++ @pytest.mark.asyncio+ async def test_cancellation_during_model_inference(self) -> None:+ """Test cancellation token during model inference."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}++ # Mock create method to check cancellation token+ model_client.create = AsyncMock()+ model_client.create.return_value = CreateResult(+ finish_reason="stop",+ content="Response",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ )++ cancellation_token = CancellationToken()+ result = await agent.on_messages([TextMessage(content="Test", source="user")], cancellation_token)++ # Verify cancellation token was passed to model client+ model_client.create.assert_called_once()+ call_args = model_client.create.call_args+ assert call_args.kwargs["cancellation_token"] == cancellation_token+ # Verify result is not None+ assert result is not None++ @pytest.mark.asyncio+ async def test_cancellation_during_streaming_inference(self) -> None:+ """Test cancellation token during streaming model inference."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}++ # Mock create_stream method+ async def mock_create_stream(*args: Any, **kwargs: Any) -> Any:+ yield "chunk1" # First chunk+ yield "chunk2" # Second chunk+ yield CreateResult(+ finish_reason="stop",+ content="chunk1chunk2",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ )++ model_client.create_stream = mock_create_stream++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ model_client_stream=True,+ )++ cancellation_token = CancellationToken()+ messages: List[Any] = []+ async for message in agent.on_messages_stream([TextMessage(content="Test", source="user")], cancellation_token):+ messages.append(message)++ # Should have received streaming chunks and final response+ chunk_events = [msg for msg in messages if isinstance(msg, ModelClientStreamingChunkEvent)]+ assert len(chunk_events) == 2+ assert chunk_events[0].content == "chunk1"+ assert chunk_events[1].content == "chunk2"++ @pytest.mark.asyncio+ async def test_cancellation_during_tool_execution(self) -> None:+ """Test cancellation token during tool execution."""++ async def slow_tool(param: str) -> str:+ await asyncio.sleep(0.1) # Simulate slow operation+ return f"Slow result: {param}"++ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="slow_tool")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),],- "model_context": {- "provider": "autogen_core.model_context.UnboundedChatCompletionContext",- "component_type": "chat_completion_context",- "version": 1,- "component_version": 1,- "description": "An unbounded chat completion context that keeps a view of the all the messages.",- "label": "UnboundedChatCompletionContext",- "config": {}+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,},- "description": "An agent that provides assistance with ability to use tools.",- "system_message": "You are a helpful assistant.",- "model_client_stream": false,- "reflect_on_tool_use": false,- "tool_call_summary_format": "{result}",- "metadata": {}- }- }+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[slow_tool],+ )++ cancellation_token = CancellationToken()+ result = await agent.on_messages([TextMessage(content="Test", source="user")], cancellation_token)++ # Tool should execute successfully with cancellation token+ assert isinstance(result.chat_message, ToolCallSummaryMessage)+ assert "Slow result: test" in result.chat_message.content++ @pytest.mark.asyncio+ async def test_cancellation_during_workbench_tool_execution(self) -> None:+ """Test cancellation token during workbench tool execution."""+ mock_workbench = MagicMock()+ mock_workbench.list_tools = AsyncMock(return_value=[{"name": "test_tool", "description": "Test tool"}])++ # Mock tool execution result+ mock_result = MagicMock()+ mock_result.to_text.return_value = "Workbench tool result"+ mock_result.is_error = False+ mock_workbench.call_tool = AsyncMock(return_value=mock_result)++ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="test_tool")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ workbench=[mock_workbench],+ )++ cancellation_token = CancellationToken()+ result = await agent.on_messages([TextMessage(content="Test", source="user")], cancellation_token)++ # Verify cancellation token was passed to workbench+ mock_workbench.call_tool.assert_called_once()+ call_args = mock_workbench.call_tool.call_args+ assert call_args.kwargs["cancellation_token"] == cancellation_token+ # Verify result is not None+ assert result is not None++ @pytest.mark.asyncio+ async def test_cancellation_during_memory_operations(self) -> None:+ """Test cancellation token during memory operations."""+ mock_memory = MagicMock()+ mock_memory.update_context = AsyncMock(return_value=None)++ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}+ model_client.create = AsyncMock(+ return_value=CreateResult(+ finish_reason="stop",+ content="Response",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ )+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ memory=[mock_memory],+ )++ cancellation_token = CancellationToken()+ await agent.on_messages([TextMessage(content="Test", source="user")], cancellation_token)++ # Memory update_context should be called+ mock_memory.update_context.assert_called_once()++ @pytest.mark.asyncio+ async def test_reset_with_cancellation_token(self) -> None:+ """Test agent reset with cancellation token."""+ mock_context = MagicMock()+ mock_context.clear = AsyncMock()++ agent = AssistantAgent(+ name="test_agent",+ model_client=MagicMock(),+ model_context=mock_context,+ )++ cancellation_token = CancellationToken()+ await agent.on_reset(cancellation_token)++ # Context clear should be called+ mock_context.clear.assert_called_once()+++class TestAssistantAgentStreamingEdgeCases:+ """Test suite for streaming edge cases and error scenarios."""++ @pytest.mark.asyncio+ async def test_streaming_with_empty_chunks(self) -> None:+ """Test streaming with empty chunks."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}++ async def mock_create_stream(*args: Any, **kwargs: Any) -> Any:+ yield "" # Empty chunk+ yield "content"+ yield "" # Another empty chunk+ yield CreateResult(+ finish_reason="stop",+ content="content",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ )++ model_client.create_stream = mock_create_stream++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ model_client_stream=True,+ )++ messages: List[Any] = []+ async for message in agent.on_messages_stream(+ [TextMessage(content="Test", source="user")], CancellationToken()+ ):+ messages.append(message)++ # Should handle empty chunks gracefully+ chunk_events = [msg for msg in messages if isinstance(msg, ModelClientStreamingChunkEvent)]+ assert len(chunk_events) == 3 # Including empty chunks+ assert chunk_events[0].content == ""+ assert chunk_events[1].content == "content"+ assert chunk_events[2].content == ""++ @pytest.mark.asyncio+ async def test_streaming_with_invalid_chunk_type(self) -> None:+ """Test streaming with invalid chunk type raises error."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}++ async def mock_create_stream(*args: Any, **kwargs: Any) -> Any:+ yield "valid_chunk"+ yield 123 # Invalid chunk type+ yield CreateResult(+ finish_reason="stop",+ content="content",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ )++ model_client.create_stream = mock_create_stream++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ model_client_stream=True,+ )++ with pytest.raises(RuntimeError, match="Invalid chunk type"):+ async for _ in agent.on_messages_stream([TextMessage(content="Test", source="user")], CancellationToken()):+ pass++ @pytest.mark.asyncio+ async def test_streaming_without_final_result(self) -> None:+ """Test streaming without final CreateResult raises error."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}++ async def mock_create_stream(*args: Any, **kwargs: Any) -> Any:+ yield "chunk1"+ yield "chunk2"+ # No final CreateResult++ model_client.create_stream = mock_create_stream++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ model_client_stream=True,+ )++ with pytest.raises(RuntimeError, match="No final model result in streaming mode"):+ async for _ in agent.on_messages_stream([TextMessage(content="Test", source="user")], CancellationToken()):+ pass++ @pytest.mark.asyncio+ async def test_streaming_with_tool_calls_and_reflection(self) -> None:+ """Test streaming with tool calls followed by reflection."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": True, "vision": False, "family": ModelFamily.GPT_4O}++ call_count = 0++ async def mock_create_stream(*args: Any, **kwargs: Any) -> Any:+ nonlocal call_count+ call_count += 1++ if call_count == 1:+ # First call: tool call+ yield CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="mock_tool_function")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ )+ else:+ # Second call: reflection streaming+ yield "Reflection "+ yield "response "+ yield "complete"+ yield CreateResult(+ finish_reason="stop",+ content="Reflection response complete",+ usage=RequestUsage(prompt_tokens=15, completion_tokens=10),+ cached=False,+ )++ model_client.create_stream = mock_create_stream++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ reflect_on_tool_use=True,+ model_client_stream=True,+ )++ messages: List[Any] = []+ async for message in agent.on_messages_stream(+ [TextMessage(content="Test", source="user")], CancellationToken()+ ):+ messages.append(message)++ # Should have tool call events, execution events, and streaming chunks for reflection+ tool_call_events = [msg for msg in messages if isinstance(msg, ToolCallRequestEvent)]+ tool_exec_events = [msg for msg in messages if isinstance(msg, ToolCallExecutionEvent)]+ chunk_events = [msg for msg in messages if isinstance(msg, ModelClientStreamingChunkEvent)]++ assert len(tool_call_events) == 1+ assert len(tool_exec_events) == 1+ assert len(chunk_events) == 3 # Three reflection chunks+ assert chunk_events[0].content == "Reflection "+ assert chunk_events[1].content == "response "+ assert chunk_events[2].content == "complete"++ @pytest.mark.asyncio+ async def test_streaming_with_large_chunks(self) -> None:+ """Test streaming with large chunks."""+ model_client = MagicMock()+ model_client.model_info = {"function_calling": False, "vision": False, "family": ModelFamily.GPT_4O}++ large_chunk = "x" * 10000 # 10KB chunk++ async def mock_create_stream(*args: Any, **kwargs: Any) -> Any:+ yield large_chunk+ yield CreateResult(+ finish_reason="stop",+ content=large_chunk,+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ )++ model_client.create_stream = mock_create_stream++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ model_client_stream=True,+ )++ messages: List[Any] = []+ async for message in agent.on_messages_stream(+ [TextMessage(content="Test", source="user")], CancellationToken()+ ):+ messages.append(message)++ # Should handle large chunks+ chunk_events = [msg for msg in messages if isinstance(msg, ModelClientStreamingChunkEvent)]+ assert len(chunk_events) == 1+ assert len(chunk_events[0].content) == 10000+++class TestAssistantAgentWorkbenchIntegration:+ """Test suite for comprehensive workbench testing."""++ @pytest.mark.asyncio+ async def test_multiple_workbenches(self) -> None:+ """Test agent with multiple workbenches."""+ mock_workbench1 = MagicMock()+ mock_workbench1.list_tools = AsyncMock(return_value=[{"name": "tool1", "description": "Tool from workbench 1"}])+ mock_result1 = MagicMock()+ mock_result1.to_text.return_value = "Result from workbench 1"+ mock_result1.is_error = False+ mock_workbench1.call_tool = AsyncMock(return_value=mock_result1)++ mock_workbench2 = MagicMock()+ mock_workbench2.list_tools = AsyncMock(return_value=[{"name": "tool2", "description": "Tool from workbench 2"}])+ mock_result2 = MagicMock()+ mock_result2.to_text.return_value = "Result from workbench 2"+ mock_result2.is_error = False+ mock_workbench2.call_tool = AsyncMock(return_value=mock_result2)++ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[+ FunctionCall(id="1", arguments=json.dumps({"param": "test1"}), name="tool1"),+ FunctionCall(id="2", arguments=json.dumps({"param": "test2"}), name="tool2"),+ ],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ workbench=[mock_workbench1, mock_workbench2],+ )++ result = await agent.run(task="Test multiple workbenches")++ # Both workbenches should be called+ mock_workbench1.call_tool.assert_called_once()+ mock_workbench2.call_tool.assert_called_once()++ # Should return summary with both results+ assert isinstance(result.messages[-1], ToolCallSummaryMessage)+ content = result.messages[-1].content+ assert "Result from workbench 1" in content+ assert "Result from workbench 2" in content++ @pytest.mark.asyncio+ async def test_workbench_tool_not_found(self) -> None:+ """Test handling when tool is not found in any workbench."""+ mock_workbench = MagicMock()+ mock_workbench.list_tools = AsyncMock(+ return_value=[{"name": "available_tool", "description": "Available tool"}]+ )++ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[FunctionCall(id="1", arguments=json.dumps({"param": "test"}), name="missing_tool")],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ workbench=[mock_workbench],+ )++ result = await agent.run(task="Test missing tool")++ # Should return error message for missing tool+ assert isinstance(result.messages[-1], ToolCallSummaryMessage)+ content = result.messages[-1].content+ assert "tool 'missing_tool' not found" in content++ @pytest.mark.asyncio+ async def test_workbench_concurrent_tool_execution(self) -> None:+ """Test concurrent execution of multiple workbench tools."""+ mock_workbench = MagicMock()+ mock_workbench.list_tools = AsyncMock(+ return_value=[+ {"name": "concurrent_tool1", "description": "Concurrent tool 1"},+ {"name": "concurrent_tool2", "description": "Concurrent tool 2"},+ ]+ )++ call_order: List[str] = []++ async def mock_call_tool(name: str, **kwargs: Any) -> Any:+ call_order.append(f"start_{name}")+ await asyncio.sleep(0.01) # Simulate work+ call_order.append(f"end_{name}")++ mock_result = MagicMock()+ mock_result.to_text.return_value = f"Result from {name}"+ mock_result.is_error = False+ return mock_result++ mock_workbench.call_tool = mock_call_tool++ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="function_calls",+ content=[+ FunctionCall(id="1", arguments=json.dumps({"param": "test1"}), name="concurrent_tool1"),+ FunctionCall(id="2", arguments=json.dumps({"param": "test2"}), name="concurrent_tool2"),+ ],+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="test_agent",+ model_client=model_client,+ workbench=[mock_workbench],+ )++ result = await agent.run(task="Test concurrent execution")++ # Should execute both tools concurrently (both start before either ends)+ assert "start_concurrent_tool1" in call_order+ assert "start_concurrent_tool2" in call_order++ # Both results should be present+ assert isinstance(result.messages[-1], ToolCallSummaryMessage)+ content = result.messages[-1].content+ assert "Result from concurrent_tool1" in content+ assert "Result from concurrent_tool2" in content+++class TestAssistantAgentComplexIntegration:+ """Test suite for complex integration scenarios."""++ @pytest.mark.asyncio+ async def test_complete_workflow_with_all_features(self) -> None:+ """Test agent with tools, handoffs, memory, streaming, and reflection."""+ # Setup memory+ memory = MockMemory(["User prefers detailed explanations"])++ # Setup model client with complex workflow+ model_client = ReplayChatCompletionClient(+ [+ # Initial tool call+ CreateResult(+ finish_reason="function_calls",+ content=[+ FunctionCall(id="1", arguments=json.dumps({"param": "analysis"}), name="mock_tool_function")+ ],+ usage=RequestUsage(prompt_tokens=20, completion_tokens=10),+ cached=False,+ thought="I need to analyze this first",+ ),+ # Reflection result+ CreateResult(+ finish_reason="stop",+ content="Based on the analysis, I can provide a detailed response. The user prefers comprehensive explanations.",+ usage=RequestUsage(prompt_tokens=30, completion_tokens=15),+ cached=False,+ thought="I should be thorough based on user preference",+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="comprehensive_agent",+ model_client=model_client,+ tools=[mock_tool_function],+ handoffs=["specialist_agent"],+ memory=[memory],+ reflect_on_tool_use=True,+ model_client_stream=True,+ tool_call_summary_format="Analysis: {result}",+ metadata={"test": "comprehensive"},+ )++ messages: List[Any] = []+ async for message in agent.on_messages_stream(+ [TextMessage(content="Analyze this complex scenario", source="user")], CancellationToken()+ ):+ messages.append(message)++ # Should have all types of events+ memory_events = [msg for msg in messages if isinstance(msg, MemoryQueryEvent)]+ thought_events = [msg for msg in messages if isinstance(msg, ThoughtEvent)]+ tool_events = [msg for msg in messages if isinstance(msg, ToolCallRequestEvent)]+ execution_events = [msg for msg in messages if isinstance(msg, ToolCallExecutionEvent)]+ chunk_events = [msg for msg in messages if isinstance(msg, ModelClientStreamingChunkEvent)]++ assert len(memory_events) > 0+ assert len(thought_events) == 2 # Initial and reflection thoughts+ assert len(tool_events) == 1+ assert len(execution_events) == 1+ assert len(chunk_events) == 0 # No streaming chunks since we removed the string responses++ # Final response should be TextMessage from reflection+ final_response = None+ for msg in reversed(messages):+ if isinstance(msg, Response):+ final_response = msg+ break++ assert final_response is not None+ assert isinstance(final_response.chat_message, TextMessage)+ assert "comprehensive explanations" in final_response.chat_message.content++ @pytest.mark.asyncio+ async def test_error_recovery_in_complex_workflow(self) -> None:+ """Test error recovery in complex workflow with multiple failures."""++ def failing_tool(param: str) -> str:+ if param == "fail":+ raise ValueError("Tool failure")+ return f"Success: {param}"++ model_client = ReplayChatCompletionClient(+ [+ # Multiple tool calls, some failing+ CreateResult(+ finish_reason="function_calls",+ content=[+ FunctionCall(id="1", arguments=json.dumps({"param": "success"}), name="failing_tool"),+ FunctionCall(id="2", arguments=json.dumps({"param": "fail"}), name="failing_tool"),+ FunctionCall(id="3", arguments=json.dumps({"param": "success2"}), name="failing_tool"),+ ],+ usage=RequestUsage(prompt_tokens=20, completion_tokens=10),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": True,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ def error_aware_formatter(call: FunctionCall, result: FunctionExecutionResult) -> str:+ if result.is_error:+ return f"⚠️ {call.name} failed: {result.content}"+ else:+ return f"✅ {call.name}: {result.content}"++ agent = AssistantAgent(+ name="error_recovery_agent",+ model_client=model_client,+ tools=[failing_tool],+ tool_call_summary_formatter=error_aware_formatter,+ reflect_on_tool_use=False,+ )++ result = await agent.run(task="Test error recovery")++ # Should handle mixed success/failure gracefully+ assert isinstance(result.messages[-1], ToolCallSummaryMessage)+ content = result.messages[-1].content+ assert "✅ failing_tool: Success: success" in content+ assert "⚠️ failing_tool failed:" in content+ assert "✅ failing_tool: Success: success2" in content++ @pytest.mark.asyncio+ async def test_state_persistence_across_interactions(self) -> None:+ """Test that agent state persists correctly across multiple interactions."""+ model_client = ReplayChatCompletionClient(+ [+ # First interaction+ CreateResult(+ finish_reason="stop",+ content="First response",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ # Second interaction+ CreateResult(+ finish_reason="stop",+ content="Second response, remembering context",+ usage=RequestUsage(prompt_tokens=15, completion_tokens=8),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": False,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ agent = AssistantAgent(+ name="stateful_agent",+ model_client=model_client,+ system_message="Remember previous conversations",+ )++ # First interaction+ result1 = await agent.run(task="First task")+ final_message_1 = result1.messages[-1]+ assert isinstance(final_message_1, TextMessage)+ assert final_message_1.content == "First response"++ # Save state+ state = await agent.save_state()+ assert "llm_context" in state++ # Second interaction+ result2 = await agent.run(task="Second task, referring to first")+ # Fix line 2730 - properly access content on TextMessage+ final_message_2 = result2.messages[-1]+ assert isinstance(final_message_2, TextMessage)+ assert final_message_2.content == "Second response, remembering context"++ # Verify context contains both interactions+ context_messages = await agent.model_context.get_messages()+ user_messages = [+ msg for msg in context_messages if hasattr(msg, "source") and getattr(msg, "source", None) == "user"+ ]+ assert len(user_messages) == 2+++class TestAssistantAgentMessageContext:+ """Test suite for message context handling in AssistantAgent.++ Tests various scenarios of message handling, context updates, and state management."""- agent = AssistantAgent.load_component(json.loads(dump))- result = await agent.run(task="hello")- assert len(result.messages) == 4- assert result.messages[-1].content == "Hello, World!" # type: ignore- assert result.messages[-1].type == "ToolCallSummaryMessage" # type: ignore- assert isinstance(result.messages[-1], ToolCallSummaryMessage) # type: ignore+ @pytest.mark.asyncio+ async def test_add_messages_to_context(self) -> None:+ """Test adding different message types to context.++ Verifies:+ 1. Regular messages are added correctly+ 2. Handoff messages with context are handled properly+ 3. Message order is preserved+ 4. Model messages are converted correctly+ """+ # Setup test context+ model_context = BufferedChatCompletionContext(buffer_size=10)++ # Create test messages+ regular_msg = TextMessage(content="Regular message", source="user")+ handoff_msg = HandoffMessage(content="Handoff message", source="agent1", target="agent2")++ # Add messages to context+ await AssistantAgent._add_messages_to_context(model_context=model_context, messages=[regular_msg, handoff_msg]) # type: ignore[reportPrivateUsage]++ # Verify context contents+ context_messages = await model_context.get_messages()++ # Should have: regular + handoff = 2 messages (now that handoff doesn't have context)+ assert len(context_messages) == 2++ # Verify message order and content - only the added messages should be present+ assert isinstance(context_messages[0], UserMessage)+ assert context_messages[0].content == "Regular message"++ assert isinstance(context_messages[1], UserMessage)+ assert context_messages[1].content == "Handoff message"++ # No more assertions needed for context_messages since we already verified both++ @pytest.mark.asyncio+ async def test_complex_model_context(self) -> None:+ """Test complex model context management scenarios.++ Verifies:+ 1. Large context handling+ 2. Mixed message type handling+ 3. Context size limits+ 4. Message filtering+ """+ # Setup test context with limited size+ model_context = BufferedChatCompletionContext(buffer_size=5)++ # Create a mix of message types+ messages: List[BaseChatMessage] = [+ TextMessage(content="First message", source="user"),+ StructuredMessage[StructuredOutput](+ content=StructuredOutput(content="Structured data", confidence=0.9), source="agent"+ ),+ ToolCallSummaryMessage(content="Tool result", source="agent", tool_calls=[], results=[]),+ HandoffMessage(content="Handoff", source="agent1", target="agent2"),+ ]++ # Add messages to context+ await AssistantAgent._add_messages_to_context(model_context=model_context, messages=messages) # type: ignore[reportPrivateUsage]++ # Verify context management+ context_messages = await model_context.get_messages()++ # Should respect buffer size limit+ assert len(context_messages) <= 5++ # Verify message conversion+ for msg in context_messages:+ assert isinstance(msg, (SystemMessage, UserMessage, AssistantMessage))++ @pytest.mark.asyncio+ async def test_memory_persistence(self) -> None:+ """Test memory persistence across multiple sessions.++ Verifies:+ 1. Memory content persists between sessions+ 2. Memory updates are preserved+ 3. Context is properly restored+ 4. Memory query events are generated correctly+ """+ # Create memory with initial content+ memory = MockMemory(contents=["Initial memory"])++ # Create model client+ model_client = ReplayChatCompletionClient(+ [+ CreateResult(+ finish_reason="stop",+ content="Response using memory",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ CreateResult(+ finish_reason="stop",+ content="Response with updated memory",+ usage=RequestUsage(prompt_tokens=10, completion_tokens=5),+ cached=False,+ ),+ ],+ model_info={+ "function_calling": False,+ "vision": False,+ "json_output": False,+ "family": ModelFamily.GPT_4O,+ "structured_output": False,+ },+ )++ # Create agent with memory+ agent = AssistantAgent(name="memory_test_agent", model_client=model_client, memory=[memory])++ # First session+ result1 = await agent.run(task="First task")+ state = await agent.save_state()++ # Add new memory content+ await memory.add(MemoryContent(content="New memory", mime_type="text/plain"))++ # Create new agent and restore state+ new_agent = AssistantAgent(name="memory_test_agent", model_client=model_client, memory=[memory])+ await new_agent.load_state(state)++ # Second session+ result2 = await new_agent.run(task="Second task")++ # Verify memory persistence+ assert isinstance(result1.messages[-1], TextMessage)+ assert isinstance(result2.messages[-1], TextMessage)+ assert result1.messages[-1].content == "Response using memory"+ assert result2.messages[-1].content == "Response with updated memory"++ # Verify memory events+ memory_events = [msg for msg in result2.messages if isinstance(msg, MemoryQueryEvent)]+ assert len(memory_events) > 0+ assert any("New memory" in str(event.content) for event in memory_events)diff --git a/python/packages/autogen-core/docs/drawio/assistant-agent.drawio b/python/packages/autogen-core/docs/drawio/assistant-agent.drawioindex 709bb3727..377bfbdf6 100644--- a/python/packages/autogen-core/docs/drawio/assistant-agent.drawio+++ b/python/packages/autogen-core/docs/drawio/assistant-agent.drawio@@ -1,202 +1,222 @@-<mxfile host="app.diagrams.net" agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0" version="25.0.3">+<mxfile host="app.diagrams.net" agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0" version="26.0.6"><diagram name="Page-1" id="bkX10E6zblEP7POKMJXw">- <mxGraphModel dx="1768" dy="1089" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">+ <mxGraphModel dx="775" dy="621" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0"><root><mxCell id="0" /><mxCell id="1" parent="0" />- <mxCell id="NpWbz43RdM9-YawIMZhB-93" value="" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;fontColor=#333333;" vertex="1" parent="1">- <mxGeometry x="180" y="220" width="490" height="800" as="geometry" />+ <mxCell id="NpWbz43RdM9-YawIMZhB-93" value="" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#666666;fontColor=#333333;" parent="1" vertex="1">+ <mxGeometry x="180" y="220" width="500" height="890" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-90" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=none;dashed=1;" vertex="1" parent="1">- <mxGeometry x="210" y="856" width="430" height="143" as="geometry" />+ <mxCell id="NpWbz43RdM9-YawIMZhB-90" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=none;dashed=1;" parent="1" vertex="1">+ <mxGeometry x="210" y="951" width="430" height="143" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-100" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-83" target="NpWbz43RdM9-YawIMZhB-84">+ <mxCell id="NpWbz43RdM9-YawIMZhB-100" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-83" target="NpWbz43RdM9-YawIMZhB-84" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-83" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=none;dashed=1;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-83" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=none;dashed=1;" parent="1" vertex="1"><mxGeometry x="210" y="248" width="430" height="61" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-118" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-84" target="NpWbz43RdM9-YawIMZhB-85">+ <mxCell id="NpWbz43RdM9-YawIMZhB-118" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-84" target="NpWbz43RdM9-YawIMZhB-85" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-84" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=none;dashed=1;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-84" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=none;dashed=1;" parent="1" vertex="1"><mxGeometry x="210" y="329" width="430" height="90" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-122" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-85" target="NpWbz43RdM9-YawIMZhB-70">+ <mxCell id="NpWbz43RdM9-YawIMZhB-122" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;" parent="1" source="NpWbz43RdM9-YawIMZhB-85" target="NpWbz43RdM9-YawIMZhB-70" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-85" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=none;dashed=1;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-85" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=none;dashed=1;" parent="1" vertex="1"><mxGeometry x="210" y="438" width="430" height="110" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-123" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-87" target="NpWbz43RdM9-YawIMZhB-111">+ <mxCell id="NpWbz43RdM9-YawIMZhB-123" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;" parent="1" source="NpWbz43RdM9-YawIMZhB-87" target="NpWbz43RdM9-YawIMZhB-111" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-87" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=none;dashed=1;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-87" value="" style="rounded=1;whiteSpace=wrap;html=1;fillColor=none;dashed=1;" parent="1" vertex="1"><mxGeometry x="210" y="616" width="430" height="114" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-78" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-90" target="NpWbz43RdM9-YawIMZhB-51">+ <mxCell id="NpWbz43RdM9-YawIMZhB-78" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-90" target="NpWbz43RdM9-YawIMZhB-51" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-50" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">- <mxGeometry x="230" y="910" width="120" height="80" as="geometry" />+ <mxCell id="NpWbz43RdM9-YawIMZhB-50" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1">+ <mxGeometry x="230" y="1005" width="120" height="80" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-35" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-35" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1"><mxGeometry x="230" y="646" width="120" height="80" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-16" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-3" target="NpWbz43RdM9-YawIMZhB-12">+ <mxCell id="NpWbz43RdM9-YawIMZhB-16" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-3" target="NpWbz43RdM9-YawIMZhB-12" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-3" value="New Messages" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-3" value="New Messages" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"><mxGeometry x="245" y="170" width="90" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-68" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=1;exitDx=0;exitDy=-15;exitPerimeter=0;entryX=1;entryY=0.75;entryDx=0;entryDy=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-6" target="NpWbz43RdM9-YawIMZhB-19">+ <mxCell id="NpWbz43RdM9-YawIMZhB-68" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=1;exitDx=0;exitDy=-15;exitPerimeter=0;entryX=1;entryY=0.75;entryDx=0;entryDy=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-6" target="NpWbz43RdM9-YawIMZhB-19" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-6" value="Memory" style="shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;size=15;fillColor=#e1d5e7;strokeColor=#9673a6;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-6" value="Memory" style="shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;size=15;fillColor=#e1d5e7;strokeColor=#9673a6;" parent="1" vertex="1"><mxGeometry x="520" y="340" width="90" height="69" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-30" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.13;exitY=0.77;exitDx=0;exitDy=0;exitPerimeter=0;entryX=1;entryY=0.75;entryDx=0;entryDy=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-10" target="NpWbz43RdM9-YawIMZhB-29">+ <mxCell id="NpWbz43RdM9-YawIMZhB-30" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.13;exitY=0.77;exitDx=0;exitDy=0;exitPerimeter=0;entryX=1;entryY=0.75;entryDx=0;entryDy=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-10" target="NpWbz43RdM9-YawIMZhB-29" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-10" value="Model Client" style="ellipse;shape=cloud;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-10" value="Model Client" style="ellipse;shape=cloud;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;" parent="1" vertex="1"><mxGeometry x="490" y="438" width="150" height="100" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-89" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0;exitDx=0;exitDy=60;exitPerimeter=0;entryX=1;entryY=0.75;entryDx=0;entryDy=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-11" target="NpWbz43RdM9-YawIMZhB-35">+ <mxCell id="NpWbz43RdM9-YawIMZhB-89" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0;exitDx=0;exitDy=60;exitPerimeter=0;entryX=1;entryY=0.75;entryDx=0;entryDy=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-11" target="NpWbz43RdM9-YawIMZhB-35" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-11" value="Tools" style="shape=cube;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;darkOpacity=0.05;darkOpacity2=0.1;fillColor=#ffe6cc;strokeColor=#d79b00;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-11" value="Tools" style="shape=cube;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;darkOpacity=0.05;darkOpacity2=0.1;fillColor=#ffe6cc;strokeColor=#d79b00;" parent="1" vertex="1"><mxGeometry x="505" y="636" width="120" height="80" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-12" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-12" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1"><mxGeometry x="230" y="259" width="120" height="40" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-17" value="1. Add New Messages to Context" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-17" value="1. Add New Messages to Context" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"><mxGeometry x="370" y="263.5" width="190" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-19" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-19" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1"><mxGeometry x="230" y="349" width="120" height="60" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-22" value="2. Update Context" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-22" value="2. Update Context" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"><mxGeometry x="370" y="359" width="110" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-24" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-24" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1"><mxGeometry x="230" y="349" width="120" height="40" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-28" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.25;entryY=0.25;entryDx=0;entryDy=0;entryPerimeter=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-27" target="NpWbz43RdM9-YawIMZhB-10">+ <mxCell id="NpWbz43RdM9-YawIMZhB-28" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.25;entryY=0.25;entryDx=0;entryDy=0;entryPerimeter=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-27" target="NpWbz43RdM9-YawIMZhB-10" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-31" value="3. Chat Completion" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-31" value="3. Chat Completion" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"><mxGeometry x="370" y="475" width="110" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-32" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-32" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1"><mxGeometry x="230" y="626" width="120" height="80" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-33" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-33" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1"><mxGeometry x="230" y="626" width="120" height="60" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-34" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-34" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1"><mxGeometry x="230" y="626" width="120" height="40" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-38" value="4. Tool Execution" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-38" value="4. Tool Execution" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"><mxGeometry x="370" y="666" width="110" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-40" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.13;exitY=0.77;exitDx=0;exitDy=0;exitPerimeter=0;entryX=1;entryY=0.75;entryDx=0;entryDy=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-41" target="NpWbz43RdM9-YawIMZhB-50">+ <mxCell id="NpWbz43RdM9-YawIMZhB-40" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.13;exitY=0.77;exitDx=0;exitDy=0;exitPerimeter=0;entryX=1;entryY=0.75;entryDx=0;entryDy=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-41" target="NpWbz43RdM9-YawIMZhB-50" edge="1"><mxGeometry relative="1" as="geometry">- <mxPoint x="370" y="950" as="targetPoint" />+ <mxPoint x="370" y="1045" as="targetPoint" /></mxGeometry></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-41" value="Model Client" style="ellipse;shape=cloud;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;" vertex="1" parent="1">- <mxGeometry x="490" y="870" width="150" height="100" as="geometry" />+ <mxCell id="NpWbz43RdM9-YawIMZhB-41" value="Model Client" style="ellipse;shape=cloud;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;" parent="1" vertex="1">+ <mxGeometry x="490" y="965" width="150" height="100" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-44" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.25;entryY=0.25;entryDx=0;entryDy=0;entryPerimeter=0;exitX=1;exitY=0.25;exitDx=0;exitDy=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-49" target="NpWbz43RdM9-YawIMZhB-41">+ <mxCell id="NpWbz43RdM9-YawIMZhB-44" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.25;entryY=0.25;entryDx=0;entryDy=0;entryPerimeter=0;exitX=1;exitY=0.25;exitDx=0;exitDy=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-49" target="NpWbz43RdM9-YawIMZhB-41" edge="1"><mxGeometry relative="1" as="geometry">- <mxPoint x="370" y="910" as="sourcePoint" />+ <mxPoint x="370" y="1005" as="sourcePoint" /></mxGeometry></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-45" value="5. Chat Completion (Reflect on Tool Use)" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">- <mxGeometry x="355" y="905" width="130" height="30" as="geometry" />+ <mxCell id="NpWbz43RdM9-YawIMZhB-45" value="5. Chat Completion (Reflect on Tool Use)" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1">+ <mxGeometry x="355" y="1000" width="130" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-46" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">- <mxGeometry x="230" y="890" width="120" height="80" as="geometry" />+ <mxCell id="NpWbz43RdM9-YawIMZhB-46" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1">+ <mxGeometry x="230" y="985" width="120" height="80" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-47" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">- <mxGeometry x="230" y="870" width="120" height="80" as="geometry" />+ <mxCell id="NpWbz43RdM9-YawIMZhB-47" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1">+ <mxGeometry x="230" y="965" width="120" height="80" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-48" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">- <mxGeometry x="230" y="870" width="120" height="60" as="geometry" />+ <mxCell id="NpWbz43RdM9-YawIMZhB-48" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1">+ <mxGeometry x="230" y="965" width="120" height="60" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-49" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">- <mxGeometry x="230" y="870" width="120" height="40" as="geometry" />+ <mxCell id="NpWbz43RdM9-YawIMZhB-49" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1">+ <mxGeometry x="230" y="965" width="120" height="40" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-51" value="Response<div>(Text)</div>" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">- <mxGeometry x="395" y="1040" width="60" height="30" as="geometry" />+ <mxCell id="NpWbz43RdM9-YawIMZhB-51" value="Response<div>(Text)</div>" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1">+ <mxGeometry x="395" y="1135" width="60" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-53" value="Response&nbsp;<div>(Tool Result Summary)</div>" style="text;html=1;align=right;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">- <mxGeometry x="10" y="806" width="140" height="30" as="geometry" />+ <mxCell id="NpWbz43RdM9-YawIMZhB-53" value="Response&nbsp;<div>(Tool Result Summary)</div>" style="text;html=1;align=right;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1">+ <mxGeometry x="10" y="888" width="140" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-58" value="Response&nbsp;<div><span style="background-color: initial;">(Text Message)</span></div>" style="text;html=1;align=right;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-58" value="Response&nbsp;<div><span style="background-color: initial;">(Text Message)</span></div>" style="text;html=1;align=right;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"><mxGeometry x="10" y="569" width="140" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-67" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.25;exitDx=0;exitDy=0;entryX=0;entryY=0;entryDx=0;entryDy=15;entryPerimeter=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-24" target="NpWbz43RdM9-YawIMZhB-6">+ <mxCell id="NpWbz43RdM9-YawIMZhB-67" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.25;exitDx=0;exitDy=0;entryX=0;entryY=0;entryDx=0;entryDy=15;entryPerimeter=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-24" target="NpWbz43RdM9-YawIMZhB-6" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-29" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-29" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1"><mxGeometry x="230" y="455" width="120" height="80" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-26" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-26" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1"><mxGeometry x="230" y="455" width="120" height="60" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-27" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-27" value="Model Context" style="shape=document;whiteSpace=wrap;html=1;boundedLbl=1;fillColor=#dae8fc;strokeColor=#6c8ebf;" parent="1" vertex="1"><mxGeometry x="230" y="455" width="120" height="40" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-71" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-70" target="NpWbz43RdM9-YawIMZhB-58">+ <mxCell id="NpWbz43RdM9-YawIMZhB-71" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;" parent="1" source="NpWbz43RdM9-YawIMZhB-70" target="NpWbz43RdM9-YawIMZhB-58" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-126" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-126" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" parent="1" edge="1"><mxGeometry relative="1" as="geometry"><mxPoint x="422.75" y="599" as="sourcePoint" /><mxPoint x="424" y="616" as="targetPoint" /></mxGeometry></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-70" value="Tool Call Detected?" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-70" value="Tool Call Detected?" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"><mxGeometry x="367.5" y="569" width="112.5" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-77" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=1;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-74" target="NpWbz43RdM9-YawIMZhB-53">+ <mxCell id="NpWbz43RdM9-YawIMZhB-77" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=1;entryY=0.5;entryDx=0;entryDy=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-74" target="NpWbz43RdM9-YawIMZhB-53" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-124" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-74" target="NpWbz43RdM9-YawIMZhB-90">+ <mxCell id="NpWbz43RdM9-YawIMZhB-124" value="" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-74" target="NpWbz43RdM9-YawIMZhB-90" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-74" value="Reflect on Tool Use?" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">- <mxGeometry x="365.5" y="806" width="120" height="30" as="geometry" />+ <mxCell id="NpWbz43RdM9-YawIMZhB-74" value="Reflect on Tool Use?" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1">+ <mxGeometry x="365.5" y="888" width="120" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-106" value="No" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-106" value="No" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"><mxGeometry x="230" y="560" width="60" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-107" value="No" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">- <mxGeometry x="230" y="790" width="60" height="30" as="geometry" />+ <mxCell id="NpWbz43RdM9-YawIMZhB-107" value="No" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1">+ <mxGeometry x="230" y="877" width="60" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-110" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0;entryDx=0;entryDy=30;entryPerimeter=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-34" target="NpWbz43RdM9-YawIMZhB-11">+ <mxCell id="NpWbz43RdM9-YawIMZhB-110" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0;entryDx=0;entryDy=30;entryPerimeter=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-34" target="NpWbz43RdM9-YawIMZhB-11" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-113" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=1;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-111" target="NpWbz43RdM9-YawIMZhB-112">+ <mxCell id="NpWbz43RdM9-YawIMZhB-113" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=1;entryY=0.5;entryDx=0;entryDy=0;" parent="1" source="NpWbz43RdM9-YawIMZhB-111" target="NpWbz43RdM9-YawIMZhB-112" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-117" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-111" target="NpWbz43RdM9-YawIMZhB-74">+ <mxCell id="NpWbz43RdM9-YawIMZhB-117" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" parent="1" source="ajhwLJHiypqY-D0M9j8j-1" target="NpWbz43RdM9-YawIMZhB-74" edge="1"><mxGeometry relative="1" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-111" value="Handoff Detected?" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;shadow=1;" vertex="1" parent="1">+ <mxCell id="ajhwLJHiypqY-D0M9j8j-2" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="NpWbz43RdM9-YawIMZhB-111" target="ajhwLJHiypqY-D0M9j8j-1">+ <mxGeometry relative="1" as="geometry" />+ </mxCell>+ <mxCell id="NpWbz43RdM9-YawIMZhB-111" value="Handoff Detected?" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;shadow=1;" parent="1" vertex="1"><mxGeometry x="370.75" y="754" width="110" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-112" value="Response<div>(Handoff)</div>" style="text;html=1;align=right;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-112" value="Response<div>(Handoff)</div>" style="text;html=1;align=right;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"><mxGeometry x="90" y="754" width="60" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-115" value="Yes" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-115" value="Yes" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"><mxGeometry x="230" y="744" width="60" height="30" as="geometry" /></mxCell>- <mxCell id="NpWbz43RdM9-YawIMZhB-127" value="Assistant Agent" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">+ <mxCell id="NpWbz43RdM9-YawIMZhB-127" value="Assistant Agent" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" parent="1" vertex="1"><mxGeometry x="700" y="218" width="109.25" height="30" as="geometry" /></mxCell>+ <mxCell id="ajhwLJHiypqY-D0M9j8j-7" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=1;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="ajhwLJHiypqY-D0M9j8j-1" target="NpWbz43RdM9-YawIMZhB-85">+ <mxGeometry relative="1" as="geometry">+ <Array as="points">+ <mxPoint x="660" y="835" />+ <mxPoint x="660" y="493" />+ </Array>+ </mxGeometry>+ </mxCell>+ <mxCell id="ajhwLJHiypqY-D0M9j8j-1" value="Maximum Tool Iterations Reached?" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">+ <mxGeometry x="325" y="820" width="201" height="30" as="geometry" />+ </mxCell>+ <mxCell id="ajhwLJHiypqY-D0M9j8j-3" value="Yes" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">+ <mxGeometry x="420.75" y="850" width="60" height="30" as="geometry" />+ </mxCell>+ <mxCell id="ajhwLJHiypqY-D0M9j8j-5" value="No" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">+ <mxGeometry x="550" y="808" width="60" height="30" as="geometry" />+ </mxCell></root></mxGraphModel></diagram>diff --git a/python/packages/autogen-core/docs/src/images/assistant-agent.svg b/python/packages/autogen-core/docs/src/images/assistant-agent.svgindex fc1ce4ba1..dd16f6902 100644--- a/python/packages/autogen-core/docs/src/images/assistant-agent.svg+++ b/python/packages/autogen-core/docs/src/images/assistant-agent.svg@@ -1,3 +1,3 @@<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">-<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="800px" height="900px" viewBox="-0.5 -0.5 800 900" class="ge-export-svg-auto" style="background-color: rgb(255, 255, 255);"><defs><style type="text/css">@media (prefers-color-scheme: dark) {
svg.ge-export-svg-auto:not(mjx-container > svg) { filter: invert(100%) hue-rotate(180deg); }
svg.ge-export-svg-auto foreignObject img,
svg.ge-export-svg-auto image:not(svg.ge-export-svg-auto switch image),
svg.ge-export-svg-auto svg:not(mjx-container > svg)
{ filter: invert(100%) hue-rotate(180deg) }
svg.ge-export-svg-auto { background-color: #000000 !important; }
}</style></defs><rect fill="#ffffff" width="100%" height="100%" x="0" y="0"/><g><g data-cell-id="0"><g data-cell-id="1"><g data-cell-id="NpWbz43RdM9-YawIMZhB-93"><g><rect x="170" y="50" width="490" height="800" fill="#f5f5f5" stroke="#666666" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-90"><g><rect x="200" y="686" width="430" height="143" rx="21.45" ry="21.45" fill="none" stroke="rgb(0, 0, 0)" stroke-dasharray="3 3" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-100"><g><path d="M 415 139 L 415 152.63" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 415 157.88 L 411.5 150.88 L 415 152.63 L 418.5 150.88 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-83"><g><rect x="200" y="78" width="430" height="61" rx="9.15" ry="9.15" fill="none" stroke="rgb(0, 0, 0)" stroke-dasharray="3 3" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-118"><g><path d="M 415 249 L 415 261.63" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 415 266.88 L 411.5 259.88 L 415 261.63 L 418.5 259.88 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-84"><g><rect x="200" y="159" width="430" height="90" rx="13.5" ry="13.5" fill="none" stroke="rgb(0, 0, 0)" stroke-dasharray="3 3" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-122"><g><path d="M 415 378 L 415 398 L 413.8 398 L 413.8 392.63" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 413.8 397.88 L 410.3 390.88 L 413.8 392.63 L 417.3 390.88 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-85"><g><rect x="200" y="268" width="430" height="110" rx="16.5" ry="16.5" fill="none" stroke="rgb(0, 0, 0)" stroke-dasharray="3 3" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-123"><g><path d="M 415 560 L 415 580 L 414.55 577.76" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 415.58 582.9 L 410.78 576.73 L 414.55 577.76 L 417.64 575.35 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-87"><g><rect x="200" y="446" width="430" height="114" rx="17.1" ry="17.1" fill="none" stroke="rgb(0, 0, 0)" stroke-dasharray="3 3" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-78"><g><path d="M 415 829 L 415 863.63" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 415 868.88 L 411.5 861.88 L 415 863.63 L 418.5 861.88 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-50"><g><path d="M 220 740 L 340 740 L 340 808 Q 310 786.4 280 808 Q 250 829.6 220 808 L 220 752 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 768px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="772" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-35"><g><path d="M 220 476 L 340 476 L 340 544 Q 310 522.4 280 544 Q 250 565.6 220 544 L 220 488 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 504px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="508" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-16"><g><path d="M 280 30 L 280 82.63" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 280 87.88 L 276.5 80.88 L 280 82.63 L 283.5 80.88 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-3"><g><rect x="235" y="0" width="90" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 88px; height: 1px; padding-top: 15px; margin-left: 236px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">New Messages</div></div></div></foreignObject><text x="280" y="19" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">New Messages</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-68"><g><path d="M 510 224 L 346.37 224" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 341.12 224 L 348.12 220.5 L 346.37 224 L 348.12 227.5 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-6"><g><path d="M 510 185 C 510 176.72 530.15 170 555 170 C 566.93 170 578.38 171.58 586.82 174.39 C 595.26 177.21 600 181.02 600 185 L 600 224 C 600 232.28 579.85 239 555 239 C 530.15 239 510 232.28 510 224 Z" fill="#e1d5e7" stroke="#9673a6" stroke-miterlimit="10" pointer-events="all"/><path d="M 600 185 C 600 193.28 579.85 200 555 200 C 530.15 200 510 193.28 510 185" fill="none" stroke="#9673a6" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 88px; height: 1px; padding-top: 217px; margin-left: 511px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Memory</div></div></div></foreignObject><text x="555" y="221" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Memory</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-30"><g><path d="M 499.5 345 L 346.37 345" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 341.12 345 L 348.12 341.5 L 346.37 345 L 348.12 348.5 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-10"><g><path d="M 517.5 293 C 487.5 293 480 318 504 323 C 480 334 507 358 526.5 348 C 540 368 585 368 600 348 C 630 348 630 328 611.25 318 C 630 298 600 278 573.75 288 C 555 273 525 273 517.5 293 Z" fill="#f8cecc" stroke="#b85450" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 148px; height: 1px; padding-top: 318px; margin-left: 481px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Client</div></div></div></foreignObject><text x="555" y="322" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Client</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-89"><g><path d="M 495 526 L 417.5 526 L 417.5 536 L 346.37 536" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 341.12 536 L 348.12 532.5 L 346.37 536 L 348.12 539.5 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-11"><g><path d="M 495 466 L 595 466 L 615 486 L 615 546 L 515 546 L 495 526 L 495 466 Z" fill="#ffe6cc" stroke="#d79b00" stroke-miterlimit="10" pointer-events="all"/><path d="M 495 466 L 595 466 L 615 486 L 515 486 Z" fill-opacity="0.05" fill="#000000" stroke="none" pointer-events="all"/><path d="M 495 466 L 515 486 L 515 546 L 495 526 Z" fill-opacity="0.1" fill="#000000" stroke="none" pointer-events="all"/><path d="M 515 546 L 515 486 L 495 466 M 515 486 L 615 486" fill="none" stroke="#d79b00" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 98px; height: 1px; padding-top: 516px; margin-left: 516px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Tools</div></div></div></foreignObject><text x="565" y="520" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Tools</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-12"><g><path d="M 220 89 L 340 89 L 340 123 Q 310 112.2 280 123 Q 250 133.8 220 123 L 220 95 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 103px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="107" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-17"><g><rect x="360" y="93.5" width="190" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 188px; height: 1px; padding-top: 109px; margin-left: 361px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">1. Add New Messages to Context</div></div></div></foreignObject><text x="455" y="112" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">1. Add New Messages to Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-19"><g><path d="M 220 179 L 340 179 L 340 230 Q 310 213.8 280 230 Q 250 246.2 220 230 L 220 188 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 200px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="204" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-22"><g><rect x="360" y="189" width="110" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 108px; height: 1px; padding-top: 204px; margin-left: 361px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">2. Update Context</div></div></div></foreignObject><text x="415" y="208" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">2. Update Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-24"><g><path d="M 220 179 L 340 179 L 340 213 Q 310 202.2 280 213 Q 250 223.8 220 213 L 220 185 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 193px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="197" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-28"><g><path d="M 340 305 L 410 305 L 410 293 L 511.13 293" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 516.38 293 L 509.38 296.5 L 511.13 293 L 509.38 289.5 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-31"><g><rect x="360" y="305" width="110" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 108px; height: 1px; padding-top: 320px; margin-left: 361px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">3. Chat Completion</div></div></div></foreignObject><text x="415" y="324" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">3. Chat Completion</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-32"><g><path d="M 220 456 L 340 456 L 340 524 Q 310 502.4 280 524 Q 250 545.6 220 524 L 220 468 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 484px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="488" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-33"><g><path d="M 220 456 L 340 456 L 340 507 Q 310 490.8 280 507 Q 250 523.2 220 507 L 220 465 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 477px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="481" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-34"><g><path d="M 220 456 L 340 456 L 340 490 Q 310 479.2 280 490 Q 250 500.8 220 490 L 220 462 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 470px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="474" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-38"><g><rect x="360" y="496" width="110" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 108px; height: 1px; padding-top: 511px; margin-left: 361px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">4. Tool Execution</div></div></div></foreignObject><text x="415" y="515" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">4. Tool Execution</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-40"><g><path d="M 499.5 777 L 410 777 L 410 800 L 346.37 800" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 341.12 800 L 348.12 796.5 L 346.37 800 L 348.12 803.5 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-41"><g><path d="M 517.5 725 C 487.5 725 480 750 504 755 C 480 766 507 790 526.5 780 C 540 800 585 800 600 780 C 630 780 630 760 611.25 750 C 630 730 600 710 573.75 720 C 555 705 525 705 517.5 725 Z" fill="#f8cecc" stroke="#b85450" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 148px; height: 1px; padding-top: 750px; margin-left: 481px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Client</div></div></div></foreignObject><text x="555" y="754" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Client</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-44"><g><path d="M 340 710 L 410 710 L 410 725 L 511.13 725" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 516.38 725 L 509.38 728.5 L 511.13 725 L 509.38 721.5 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-45"><g><rect x="345" y="735" width="130" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 128px; height: 1px; padding-top: 750px; margin-left: 346px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">5. Chat Completion (Reflect on Tool Use)</div></div></div></foreignObject><text x="410" y="754" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">5. Chat Completion (R...</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-46"><g><path d="M 220 720 L 340 720 L 340 788 Q 310 766.4 280 788 Q 250 809.6 220 788 L 220 732 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 748px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="752" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-47"><g><path d="M 220 700 L 340 700 L 340 768 Q 310 746.4 280 768 Q 250 789.6 220 768 L 220 712 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 728px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="732" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-48"><g><path d="M 220 700 L 340 700 L 340 751 Q 310 734.8 280 751 Q 250 767.2 220 751 L 220 709 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 721px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="725" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-49"><g><path d="M 220 700 L 340 700 L 340 734 Q 310 723.2 280 734 Q 250 744.8 220 734 L 220 706 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 714px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="718" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-51"><g><rect x="385" y="870" width="60" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 58px; height: 1px; padding-top: 885px; margin-left: 386px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Response<div>(Text)</div></div></div></div></foreignObject><text x="415" y="889" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Response...</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-53"><g><rect x="0" y="636" width="140" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe flex-end; width: 138px; height: 1px; padding-top: 651px; margin-left: 0px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: right;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Response <div>(Tool Result Summary)</div></div></div></div></foreignObject><text x="138" y="655" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="end">Response...</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-58"><g><rect x="0" y="399" width="140" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe flex-end; width: 138px; height: 1px; padding-top: 414px; margin-left: 0px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: right;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Response <div><span style="background-color: initial;">(Text Message)</span></div></div></div></div></foreignObject><text x="138" y="418" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="end">Response...</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-67"><g><path d="M 340 189 L 425 189 L 425 185 L 503.63 185" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 508.88 185 L 501.88 188.5 L 503.63 185 L 501.88 181.5 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-29"><g><path d="M 220 285 L 340 285 L 340 353 Q 310 331.4 280 353 Q 250 374.6 220 353 L 220 297 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 313px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="317" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-26"><g><path d="M 220 285 L 340 285 L 340 336 Q 310 319.8 280 336 Q 250 352.2 220 336 L 220 294 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 306px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="310" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-27"><g><path d="M 220 285 L 340 285 L 340 319 Q 310 308.2 280 319 Q 250 329.8 220 319 L 220 291 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 299px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Model Context</div></div></div></foreignObject><text x="280" y="303" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-71"><g><path d="M 357.5 414 L 146.37 414" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 141.12 414 L 148.12 410.5 L 146.37 414 L 148.12 417.5 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-126"><g><path d="M 412.75 429 L 414 429 L 414 439.63" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 414 444.88 L 410.5 437.88 L 414 439.63 L 417.5 437.88 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-70"><g><rect x="357.5" y="399" width="112.5" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 111px; height: 1px; padding-top: 414px; margin-left: 359px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Tool Call Detected?</div></div></div></foreignObject><text x="414" y="418" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Tool Call Detected?</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-77"><g><path d="M 355.5 651 L 146.37 651" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 141.12 651 L 148.12 647.5 L 146.37 651 L 148.12 654.5 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-124"><g><path d="M 415.5 666 L 415.5 679.63" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 415.5 684.88 L 412 677.88 L 415.5 679.63 L 419 677.88 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-74"><g><rect x="355.5" y="636" width="120" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 651px; margin-left: 357px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Reflect on Tool Use?</div></div></div></foreignObject><text x="416" y="655" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Reflect on Tool Use?</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-106"><g><rect x="220" y="390" width="60" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 58px; height: 1px; padding-top: 405px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">No</div></div></div></foreignObject><text x="250" y="409" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">No</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-107"><g><rect x="220" y="620" width="60" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 58px; height: 1px; padding-top: 635px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">No</div></div></div></foreignObject><text x="250" y="639" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">No</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-110"><g><path d="M 340 476 L 417.5 476 L 417.5 496 L 488.63 496" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 493.88 496 L 486.88 499.5 L 488.63 496 L 486.88 492.5 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-113"><g><path d="M 360.75 599 L 146.37 599" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 141.12 599 L 148.12 595.5 L 146.37 599 L 148.12 602.5 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-117"><g><path d="M 415.75 614 L 415.57 629.63" fill="none" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 415.51 634.88 L 412.09 627.84 L 415.57 629.63 L 419.09 627.92 Z" fill="rgb(0, 0, 0)" stroke="rgb(0, 0, 0)" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-111"><g style="filter: drop-shadow(rgba(0, 0, 0, 0.25) 2px 3px 2px);"><rect x="360.75" y="584" width="110" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 108px; height: 1px; padding-top: 599px; margin-left: 362px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Handoff Detected?</div></div></div></foreignObject><text x="416" y="603" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Handoff Detected?</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-112"><g><rect x="80" y="584" width="60" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe flex-end; width: 58px; height: 1px; padding-top: 599px; margin-left: 80px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: right;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Response<div>(Handoff)</div></div></div></div></foreignObject><text x="138" y="603" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="end">Response...</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-115"><g><rect x="220" y="574" width="60" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 58px; height: 1px; padding-top: 589px; margin-left: 221px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Yes</div></div></div></foreignObject><text x="250" y="593" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Yes</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-127"><g><rect x="690" y="48" width="109.25" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" style="overflow: visible; text-align: left;"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 107px; height: 1px; padding-top: 63px; margin-left: 691px;"><div data-drawio-colors="color: rgb(0, 0, 0); " style="box-sizing: border-box; font-size: 0px; text-align: center;"><div style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; pointer-events: all; white-space: normal; overflow-wrap: normal;">Assistant Agent</div></div></div></foreignObject><text x="745" y="67" fill="rgb(0, 0, 0)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Assistant Agent</text></switch></g></g></g></g></g></g></svg>\ No newline at end of file+<svg xmlns="http://www.w3.org/2000/svg" style="background: #ffffff; background-color: light-dark(#ffffff, var(--ge-dark-color, #121212)); color-scheme: light dark;" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="800px" height="995px" viewBox="-0.5 -0.5 800 995"><defs/><rect fill="#ffffff" width="100%" height="100%" x="0" y="0" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212));"/><g><g data-cell-id="0"><g data-cell-id="1"><g data-cell-id="NpWbz43RdM9-YawIMZhB-93"><g><rect x="170" y="50" width="500" height="890" fill="#f5f5f5" stroke="#666666" pointer-events="all" style="fill: light-dark(rgb(245, 245, 245), rgb(26, 26, 26)); stroke: light-dark(rgb(102, 102, 102), rgb(149, 149, 149));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-90"><g><rect x="200" y="781" width="430" height="143" rx="21.45" ry="21.45" fill="none" stroke="#000000" stroke-dasharray="3 3" pointer-events="all" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-100"><g><path d="M 415 139 L 415 152.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 415 157.88 L 411.5 150.88 L 415 152.63 L 418.5 150.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-83"><g><rect x="200" y="78" width="430" height="61" rx="9.15" ry="9.15" fill="none" stroke="#000000" stroke-dasharray="3 3" pointer-events="all" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-118"><g><path d="M 415 249 L 415 261.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 415 266.88 L 411.5 259.88 L 415 261.63 L 418.5 259.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-84"><g><rect x="200" y="159" width="430" height="90" rx="13.5" ry="13.5" fill="none" stroke="#000000" stroke-dasharray="3 3" pointer-events="all" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-122"><g><path d="M 415 378 L 415 398 L 413.8 398 L 413.8 392.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 413.8 397.88 L 410.3 390.88 L 413.8 392.63 L 417.3 390.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-85"><g><rect x="200" y="268" width="430" height="110" rx="16.5" ry="16.5" fill="none" stroke="#000000" stroke-dasharray="3 3" pointer-events="all" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-123"><g><path d="M 415 560 L 415 580 L 414.55 577.76" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 415.58 582.9 L 410.78 576.73 L 414.55 577.76 L 417.64 575.35 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-87"><g><rect x="200" y="446" width="430" height="114" rx="17.1" ry="17.1" fill="none" stroke="#000000" stroke-dasharray="3 3" pointer-events="all" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-78"><g><path d="M 415 924 L 415 958.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 415 963.88 L 411.5 956.88 L 415 958.63 L 418.5 956.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-50"><g><path d="M 220 835 L 340 835 L 340 903 Q 310 881.4 280 903 Q 250 924.6 220 903 L 220 847 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 863px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="867" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-35"><g><path d="M 220 476 L 340 476 L 340 544 Q 310 522.4 280 544 Q 250 565.6 220 544 L 220 488 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 504px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="508" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-16"><g><path d="M 280 30 L 280 82.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 280 87.88 L 276.5 80.88 L 280 82.63 L 283.5 80.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-3"><g><rect x="235" y="0" width="90" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 88px; height: 1px; padding-top: 15px; margin-left: 236px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">New Messages</div></div></div></foreignObject><text x="280" y="19" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">New Messages</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-68"><g><path d="M 510 224 L 346.37 224" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 341.12 224 L 348.12 220.5 L 346.37 224 L 348.12 227.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-6"><g><path d="M 510 185 C 510 176.72 530.15 170 555 170 C 566.93 170 578.38 171.58 586.82 174.39 C 595.26 177.21 600 181.02 600 185 L 600 224 C 600 232.28 579.85 239 555 239 C 530.15 239 510 232.28 510 224 Z" fill="#e1d5e7" stroke="#9673a6" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(225, 213, 231), rgb(57, 47, 63)); stroke: light-dark(rgb(150, 115, 166), rgb(149, 119, 163));"/><path d="M 600 185 C 600 193.28 579.85 200 555 200 C 530.15 200 510 193.28 510 185" fill="none" stroke="#9673a6" stroke-miterlimit="10" pointer-events="all" style="stroke: light-dark(rgb(150, 115, 166), rgb(149, 119, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 88px; height: 1px; padding-top: 217px; margin-left: 511px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Memory</div></div></div></foreignObject><text x="555" y="221" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Memory</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-30"><g><path d="M 499.5 345 L 346.37 345" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 341.12 345 L 348.12 341.5 L 346.37 345 L 348.12 348.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-10"><g><path d="M 517.5 293 C 487.5 293 480 318 504 323 C 480 334 507 358 526.5 348 C 540 368 585 368 600 348 C 630 348 630 328 611.25 318 C 630 298 600 278 573.75 288 C 555 273 525 273 517.5 293 Z" fill="#f8cecc" stroke="#b85450" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(248, 206, 204), rgb(81, 45, 43)); stroke: light-dark(rgb(184, 84, 80), rgb(215, 129, 126));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 148px; height: 1px; padding-top: 318px; margin-left: 481px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Client</div></div></div></foreignObject><text x="555" y="322" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Client</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-89"><g><path d="M 495 526 L 417.5 526 L 417.5 536 L 346.37 536" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 341.12 536 L 348.12 532.5 L 346.37 536 L 348.12 539.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-11"><g><path d="M 495 466 L 595 466 L 615 486 L 615 546 L 515 546 L 495 526 L 495 466 Z" fill="#ffe6cc" stroke="#d79b00" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(255, 230, 204), rgb(54, 33, 10)); stroke: light-dark(rgb(215, 155, 0), rgb(153, 101, 0));"/><path d="M 495 466 L 595 466 L 615 486 L 515 486 Z" fill-opacity="0.05" fill="#000000" stroke="none" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(237, 237, 237));"/><path d="M 495 466 L 515 486 L 515 546 L 495 526 Z" fill-opacity="0.1" fill="#000000" stroke="none" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(237, 237, 237));"/><path d="M 515 546 L 515 486 L 495 466 M 515 486 L 615 486" fill="none" stroke="#d79b00" stroke-miterlimit="10" pointer-events="all" style="stroke: light-dark(rgb(215, 155, 0), rgb(153, 101, 0));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 98px; height: 1px; padding-top: 516px; margin-left: 516px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Tools</div></div></div></foreignObject><text x="565" y="520" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Tools</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-12"><g><path d="M 220 89 L 340 89 L 340 123 Q 310 112.2 280 123 Q 250 133.8 220 123 L 220 95 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 103px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="107" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-17"><g><rect x="360" y="93.5" width="190" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 188px; height: 1px; padding-top: 109px; margin-left: 361px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">1. Add New Messages to Context</div></div></div></foreignObject><text x="455" y="112" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">1. Add New Messages to Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-19"><g><path d="M 220 179 L 340 179 L 340 230 Q 310 213.8 280 230 Q 250 246.2 220 230 L 220 188 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 200px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="204" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-22"><g><rect x="360" y="189" width="110" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 108px; height: 1px; padding-top: 204px; margin-left: 361px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">2. Update Context</div></div></div></foreignObject><text x="415" y="208" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">2. Update Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-24"><g><path d="M 220 179 L 340 179 L 340 213 Q 310 202.2 280 213 Q 250 223.8 220 213 L 220 185 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 193px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="197" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-28"><g><path d="M 340 305 L 410 305 L 410 293 L 511.13 293" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 516.38 293 L 509.38 296.5 L 511.13 293 L 509.38 289.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-31"><g><rect x="360" y="305" width="110" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 108px; height: 1px; padding-top: 320px; margin-left: 361px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">3. Chat Completion</div></div></div></foreignObject><text x="415" y="324" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">3. Chat Completion</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-32"><g><path d="M 220 456 L 340 456 L 340 524 Q 310 502.4 280 524 Q 250 545.6 220 524 L 220 468 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 484px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="488" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-33"><g><path d="M 220 456 L 340 456 L 340 507 Q 310 490.8 280 507 Q 250 523.2 220 507 L 220 465 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 477px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="481" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-34"><g><path d="M 220 456 L 340 456 L 340 490 Q 310 479.2 280 490 Q 250 500.8 220 490 L 220 462 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 470px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="474" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-38"><g><rect x="360" y="496" width="110" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 108px; height: 1px; padding-top: 511px; margin-left: 361px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">4. Tool Execution</div></div></div></foreignObject><text x="415" y="515" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">4. Tool Execution</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-40"><g><path d="M 499.5 872 L 410 872 L 410 895 L 346.37 895" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 341.12 895 L 348.12 891.5 L 346.37 895 L 348.12 898.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-41"><g><path d="M 517.5 820 C 487.5 820 480 845 504 850 C 480 861 507 885 526.5 875 C 540 895 585 895 600 875 C 630 875 630 855 611.25 845 C 630 825 600 805 573.75 815 C 555 800 525 800 517.5 820 Z" fill="#f8cecc" stroke="#b85450" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(248, 206, 204), rgb(81, 45, 43)); stroke: light-dark(rgb(184, 84, 80), rgb(215, 129, 126));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 148px; height: 1px; padding-top: 845px; margin-left: 481px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Client</div></div></div></foreignObject><text x="555" y="849" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Client</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-44"><g><path d="M 340 805 L 410 805 L 410 820 L 511.13 820" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 516.38 820 L 509.38 823.5 L 511.13 820 L 509.38 816.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-45"><g><rect x="345" y="830" width="130" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 128px; height: 1px; padding-top: 845px; margin-left: 346px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">5. Chat Completion (Reflect on Tool Use)</div></div></div></foreignObject><text x="410" y="849" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">5. Chat Completion (R...</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-46"><g><path d="M 220 815 L 340 815 L 340 883 Q 310 861.4 280 883 Q 250 904.6 220 883 L 220 827 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 843px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="847" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-47"><g><path d="M 220 795 L 340 795 L 340 863 Q 310 841.4 280 863 Q 250 884.6 220 863 L 220 807 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 823px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="827" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-48"><g><path d="M 220 795 L 340 795 L 340 846 Q 310 829.8 280 846 Q 250 862.2 220 846 L 220 804 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 816px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="820" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-49"><g><path d="M 220 795 L 340 795 L 340 829 Q 310 818.2 280 829 Q 250 839.8 220 829 L 220 801 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 809px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="813" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-51"><g><rect x="385" y="965" width="60" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 58px; height: 1px; padding-top: 980px; margin-left: 386px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Response<div>(Text)</div></div></div></div></foreignObject><text x="415" y="984" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Response...</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-53"><g><rect x="0" y="718" width="140" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe flex-end; width: 138px; height: 1px; padding-top: 733px; margin-left: 0px;"><div style="box-sizing: border-box; font-size: 0; text-align: right; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Response <div>(Tool Result Summary)</div></div></div></div></foreignObject><text x="138" y="737" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="end">Response...</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-58"><g><rect x="0" y="399" width="140" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe flex-end; width: 138px; height: 1px; padding-top: 414px; margin-left: 0px;"><div style="box-sizing: border-box; font-size: 0; text-align: right; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Response <div><span style="background-color: initial;">(Text Message)</span></div></div></div></div></foreignObject><text x="138" y="418" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="end">Response...</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-67"><g><path d="M 340 189 L 425 189 L 425 185 L 503.63 185" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 508.88 185 L 501.88 188.5 L 503.63 185 L 501.88 181.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-29"><g><path d="M 220 285 L 340 285 L 340 353 Q 310 331.4 280 353 Q 250 374.6 220 353 L 220 297 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 313px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="317" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-26"><g><path d="M 220 285 L 340 285 L 340 336 Q 310 319.8 280 336 Q 250 352.2 220 336 L 220 294 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 306px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="310" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-27"><g><path d="M 220 285 L 340 285 L 340 319 Q 310 308.2 280 319 Q 250 329.8 220 319 L 220 291 Z" fill="#dae8fc" stroke="#6c8ebf" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(218, 232, 252), rgb(29, 41, 59)); stroke: light-dark(rgb(108, 142, 191), rgb(92, 121, 163));"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 299px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Model Context</div></div></div></foreignObject><text x="280" y="303" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Model Context</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-71"><g><path d="M 357.5 414 L 146.37 414" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 141.12 414 L 148.12 410.5 L 146.37 414 L 148.12 417.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-126"><g><path d="M 412.75 429 L 414 429 L 414 439.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 414 444.88 L 410.5 437.88 L 414 439.63 L 417.5 437.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-70"><g><rect x="357.5" y="399" width="112.5" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 111px; height: 1px; padding-top: 414px; margin-left: 359px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Tool Call Detected?</div></div></div></foreignObject><text x="414" y="418" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Tool Call Detected?</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-77"><g><path d="M 355.5 733 L 146.37 733" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 141.12 733 L 148.12 729.5 L 146.37 733 L 148.12 736.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-124"><g><path d="M 415.5 748 L 415.5 768 L 415.24 774.64" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 415.04 779.88 L 411.81 772.75 L 415.24 774.64 L 418.81 773.02 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-74"><g><rect x="355.5" y="718" width="120" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 733px; margin-left: 357px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Reflect on Tool Use?</div></div></div></foreignObject><text x="416" y="737" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Reflect on Tool Use?</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-106"><g><rect x="220" y="390" width="60" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 58px; height: 1px; padding-top: 405px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">No</div></div></div></foreignObject><text x="250" y="409" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">No</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-107"><g><rect x="220" y="707" width="60" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 58px; height: 1px; padding-top: 722px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">No</div></div></div></foreignObject><text x="250" y="726" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">No</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-110"><g><path d="M 340 476 L 417.5 476 L 417.5 496 L 488.63 496" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 493.88 496 L 486.88 499.5 L 488.63 496 L 486.88 492.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-113"><g><path d="M 360.75 599 L 146.37 599" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 141.12 599 L 148.12 595.5 L 146.37 599 L 148.12 602.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-117"><g><path d="M 415.5 680 L 415.5 711.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 415.5 716.88 L 412 709.88 L 415.5 711.63 L 419 709.88 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="ajhwLJHiypqY-D0M9j8j-2"><g><path d="M 415.75 614 L 415.54 643.63" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 415.51 648.88 L 412.06 641.86 L 415.54 643.63 L 419.06 641.91 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-111"><g style="filter: drop-shadow(light-dark(rgba(0, 0, 0, 0.25), rgba(237, 237, 237, 0.25)) 2px 3px 2px);"><rect x="360.75" y="584" width="110" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 108px; height: 1px; padding-top: 599px; margin-left: 362px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Handoff Detected?</div></div></div></foreignObject><text x="416" y="603" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Handoff Detected?</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-112"><g><rect x="80" y="584" width="60" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe flex-end; width: 58px; height: 1px; padding-top: 599px; margin-left: 80px;"><div style="box-sizing: border-box; font-size: 0; text-align: right; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Response<div>(Handoff)</div></div></div></div></foreignObject><text x="138" y="603" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="end">Response...</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-115"><g><rect x="220" y="574" width="60" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 58px; height: 1px; padding-top: 589px; margin-left: 221px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Yes</div></div></div></foreignObject><text x="250" y="593" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Yes</text></switch></g></g></g><g data-cell-id="NpWbz43RdM9-YawIMZhB-127"><g><rect x="690" y="48" width="109.25" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 107px; height: 1px; padding-top: 63px; margin-left: 691px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Assistant Agent</div></div></div></foreignObject><text x="745" y="67" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Assistant Agent</text></switch></g></g></g><g data-cell-id="ajhwLJHiypqY-D0M9j8j-7"><g><path d="M 516 665 L 650 665 L 650 323 L 636.37 323" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="stroke" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/><path d="M 631.12 323 L 638.12 319.5 L 636.37 323 L 638.12 326.5 Z" fill="#000000" stroke="#000000" stroke-miterlimit="10" pointer-events="all" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));"/></g></g><g data-cell-id="ajhwLJHiypqY-D0M9j8j-1"><g><rect x="315" y="650" width="201" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 199px; height: 1px; padding-top: 665px; margin-left: 316px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Maximum Tool Iterations Reached?</div></div></div></foreignObject><text x="416" y="669" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Maximum Tool Iterations Reached?</text></switch></g></g></g><g data-cell-id="ajhwLJHiypqY-D0M9j8j-3"><g><rect x="410.75" y="680" width="60" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 58px; height: 1px; padding-top: 695px; margin-left: 412px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">Yes</div></div></div></foreignObject><text x="441" y="699" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">Yes</text></switch></g></g></g><g data-cell-id="ajhwLJHiypqY-D0M9j8j-5"><g><rect x="540" y="638" width="60" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 58px; height: 1px; padding-top: 653px; margin-left: 541px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 12px; font-family: "Helvetica"; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">No</div></div></div></foreignObject><text x="570" y="657" fill="light-dark(#000000, #ffffff)" font-family=""Helvetica"" font-size="12px" text-anchor="middle">No</text></switch></g></g></g></g></g></g></svg>\ No newline at end of file