Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
chore: remove dead multi-agent code (#9787)
Kian Jonesf25c7f4fef01
diff --git a/letta/functions/function_sets/multi_agent.py b/letta/functions/function_sets/multi_agent.pyindex cc81f69c7..7e9e448f7 100644--- a/letta/functions/function_sets/multi_agent.py+++ b/letta/functions/function_sets/multi_agent.py@@ -1,10 +1,5 @@-import asyncio-from typing import TYPE_CHECKING, Any, Iterable, List+from typing import Any, Iterable, List-if TYPE_CHECKING:- from letta.agents.letta_agent import LettaAgent as Agent--from letta.functions.helpers import _send_message_to_all_agents_in_group_asyncfrom letta.settings import settings@@ -165,22 +160,6 @@ def send_message_to_agents_matching_tags(message: str, match_all: List[str], matreturn results-def send_message_to_all_agents_in_group(self: "Agent", message: str) -> List[str]:- """- Sends a message to all agents within the same multi-agent group.-- Args:- message (str): The content of the message to be sent to each matching agent.-- Returns:- List[str]: A list of responses from the agents that matched the filtering criteria. Each- response corresponds to a single agent. Agents that do not respond will not have an entry- in the returned list.- """-- return asyncio.run(_send_message_to_all_agents_in_group_async(self, message))--def send_message_to_agent_async(message: str, other_agent_id: str) -> str:"""Sends a message to a specific Letta agent within the same organization. The sender's identity is automatically included, so no explicit introduction is required in the message. This function does not expect a response from the target agent, making it suitable for notifications or one-way communication.diff --git a/letta/functions/helpers.py b/letta/functions/helpers.pyindex ce023a4b7..9a6a54818 100644--- a/letta/functions/helpers.py+++ b/letta/functions/helpers.py@@ -1,15 +1,8 @@-import asyncioimport jsonimport logging-import threading-from random import uniformfrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Unionif TYPE_CHECKING:- from letta.agents.letta_agent import LettaAgent as Agent- from letta.schemas.agent import AgentState- from letta.server.server import SyncServer-try:from langchain.tools.base import BaseTool as LangChainBaseToolexcept ImportError:@@ -19,19 +12,7 @@ import humpsfrom pydantic import BaseModel, Field, create_modelfrom letta.constants import DEFAULT_MESSAGE_TOOL, DEFAULT_MESSAGE_TOOL_KWARG-from letta.functions.interface import MultiAgentMessagingInterface-from letta.orm.errors import NoResultFound-from letta.schemas.enums import MessageRole-from letta.schemas.letta_message import AssistantMessage-from letta.schemas.letta_response import LettaResponse-from letta.schemas.letta_stop_reason import LettaStopReason, StopReasonType-from letta.schemas.message import Message, MessageCreate-from letta.schemas.user import User-from letta.server.rest_api.dependencies import get_letta_server-from letta.settings import settings-from letta.utils import safe_create_task--_background_tasks: set[asyncio.Task] = set()+from letta.schemas.message import Message# TODO needed?@@ -220,301 +201,6 @@ def _generate_import_code(module_attr_map: Optional[dict]):return "\n".join(code_lines)-def _parse_letta_response_for_assistant_message(- target_agent_id: str,- letta_response: LettaResponse,-) -> Optional[str]:- messages = []- for m in letta_response.messages:- if isinstance(m, AssistantMessage):- messages.append(m.content)-- if messages:- messages_str = "\n".join(messages)- return f"{target_agent_id} said: '{messages_str}'"- else:- return f"No response from {target_agent_id}"---async def async_execute_send_message_to_agent(- sender_agent: "Agent",- messages: List[MessageCreate],- other_agent_id: str,- log_prefix: str,-) -> Optional[str]:- """- Async helper to:- 1) validate the target agent exists & is in the same org,- 2) send a message via _async_send_message_with_retries.- """- server = get_letta_server()-- # 1. Validate target agent- try:- server.agent_manager.get_agent_by_id(agent_id=other_agent_id, actor=sender_agent.user)- except NoResultFound:- raise ValueError(f"Target agent {other_agent_id} either does not exist or is not in org ({sender_agent.user.organization_id}).")-- # 2. Use your async retry logic- return await _async_send_message_with_retries(- server=server,- sender_agent=sender_agent,- target_agent_id=other_agent_id,- messages=messages,- max_retries=settings.multi_agent_send_message_max_retries,- timeout=settings.multi_agent_send_message_timeout,- logging_prefix=log_prefix,- )---def execute_send_message_to_agent(- sender_agent: "Agent",- messages: List[MessageCreate],- other_agent_id: str,- log_prefix: str,-) -> Optional[str]:- """- Synchronous wrapper that calls `async_execute_send_message_to_agent` using asyncio.run.- This function must be called from a synchronous context (i.e., no running event loop).- """- return asyncio.run(async_execute_send_message_to_agent(sender_agent, messages, other_agent_id, log_prefix))---async def _send_message_to_agent_no_stream(- server: "SyncServer",- agent_id: str,- actor: User,- messages: List[MessageCreate],- metadata: Optional[dict] = None,-) -> LettaResponse:- """- A simpler helper to send messages to a single agent WITHOUT streaming.- Returns a LettaResponse containing the final messages.- """- interface = MultiAgentMessagingInterface()- if metadata:- interface.metadata = metadata-- # Offload the synchronous `send_messages` call- usage_stats = await asyncio.to_thread(- server.send_messages,- actor=actor,- agent_id=agent_id,- input_messages=messages,- interface=interface,- metadata=metadata,- )-- final_messages = interface.get_captured_send_messages()- return LettaResponse(- messages=final_messages,- stop_reason=LettaStopReason(stop_reason=StopReasonType.end_turn.value),- usage=usage_stats,- )---async def _async_send_message_with_retries(- server: "SyncServer",- sender_agent: "Agent",- target_agent_id: str,- messages: List[MessageCreate],- max_retries: int,- timeout: int,- logging_prefix: Optional[str] = None,-) -> str:- logging_prefix = logging_prefix or "[_async_send_message_with_retries]"-- for attempt in range(1, max_retries + 1):- try:- response = await asyncio.wait_for(- _send_message_to_agent_no_stream(- server=server,- agent_id=target_agent_id,- actor=sender_agent.user,- messages=messages,- ),- timeout=timeout,- )-- # Then parse out the assistant message- assistant_message = _parse_letta_response_for_assistant_message(target_agent_id, response)- if assistant_message:- sender_agent.logger.info(f"{logging_prefix} - {assistant_message}")- return assistant_message- else:- msg = f"(No response from agent {target_agent_id})"- sender_agent.logger.info(f"{logging_prefix} - {msg}")- return msg-- except asyncio.TimeoutError:- error_msg = f"(Timeout on attempt {attempt}/{max_retries} for agent {target_agent_id})"- sender_agent.logger.warning(f"{logging_prefix} - {error_msg}")-- except Exception as e:- error_msg = f"(Error on attempt {attempt}/{max_retries} for agent {target_agent_id}: {e})"- sender_agent.logger.warning(f"{logging_prefix} - {error_msg}")-- # Exponential backoff before retrying- if attempt < max_retries:- backoff = uniform(0.5, 2) * (2**attempt)- sender_agent.logger.warning(f"{logging_prefix} - Retrying the agent-to-agent send_message...sleeping for {backoff}")- await asyncio.sleep(backoff)- else:- sender_agent.logger.error(f"{logging_prefix} - Fatal error: {error_msg}")- raise Exception(error_msg)---def fire_and_forget_send_to_agent(- sender_agent: "Agent",- messages: List[MessageCreate],- other_agent_id: str,- log_prefix: str,- use_retries: bool = False,-) -> None:- """- Fire-and-forget send of messages to a specific agent.- Returns immediately in the calling thread, never blocks.-- Args:- sender_agent (Agent): The sender agent object.- server: The Letta server instance- messages (List[MessageCreate]): The messages to send.- other_agent_id (str): The ID of the target agent.- log_prefix (str): Prefix for logging.- use_retries (bool): If True, uses _async_send_message_with_retries;- if False, calls server.send_message_to_agent directly.- """- server = get_letta_server()-- # 1) Validate the target agent (raises ValueError if not in same org)- try:- server.agent_manager.get_agent_by_id(agent_id=other_agent_id, actor=sender_agent.user)- except NoResultFound:- raise ValueError(- f"The passed-in agent_id {other_agent_id} either does not exist, "- f"or does not belong to the same org ({sender_agent.user.organization_id})."- )-- # 2) Define the async coroutine to run- async def background_task():- try:- if use_retries:- result = await _async_send_message_with_retries(- server=server,- sender_agent=sender_agent,- target_agent_id=other_agent_id,- messages=messages,- max_retries=settings.multi_agent_send_message_max_retries,- timeout=settings.multi_agent_send_message_timeout,- logging_prefix=log_prefix,- )- sender_agent.logger.info(f"{log_prefix} fire-and-forget success with retries: {result}")- else:- # Direct call to server.send_message_to_agent, no retry logic- await server.send_message_to_agent(- agent_id=other_agent_id,- actor=sender_agent.user,- input_messages=messages,- stream_steps=False,- stream_tokens=False,- use_assistant_message=True,- assistant_message_tool_name=DEFAULT_MESSAGE_TOOL,- assistant_message_tool_kwarg=DEFAULT_MESSAGE_TOOL_KWARG,- )- sender_agent.logger.info(f"{log_prefix} fire-and-forget success (no retries).")- except Exception as e:- sender_agent.logger.error(f"{log_prefix} fire-and-forget send failed: {e}")-- # 3) Helper to run the coroutine in a brand-new event loop in a separate thread- def run_in_background_thread(coro):- def runner():- loop = asyncio.new_event_loop()- try:- asyncio.set_event_loop(loop)- loop.run_until_complete(coro)- finally:- loop.close()-- thread = threading.Thread(target=runner, daemon=True)- thread.start()-- # 4) Try to schedule the coroutine in an existing loop, else spawn a thread- try:- loop = asyncio.get_running_loop()- task = loop.create_task(background_task())- _background_tasks.add(task)- task.add_done_callback(_background_tasks.discard)- except RuntimeError:- run_in_background_thread(background_task())---async def _send_message_to_agents_matching_tags_async(- sender_agent: "Agent",- server: "SyncServer",- messages: List[MessageCreate],- matching_agents: List["AgentState"],-) -> List[str]:- async def _send_single(agent_state):- return await _async_send_message_with_retries(- server=server,- sender_agent=sender_agent,- target_agent_id=agent_state.id,- messages=messages,- max_retries=3,- timeout=settings.multi_agent_send_message_timeout,- )-- tasks = [safe_create_task(_send_single(agent_state), label=f"send_to_agent_{agent_state.id}") for agent_state in matching_agents]- results = await asyncio.gather(*tasks, return_exceptions=True)- final = []- for r in results:- if isinstance(r, Exception):- final.append(str(r))- else:- final.append(r)-- return final---async def _send_message_to_all_agents_in_group_async(sender_agent: "Agent", message: str) -> List[str]:- server = get_letta_server()-- augmented_message = (- f"[Incoming message from agent with ID '{sender_agent.agent_state.id}' - your response will be delivered to the sender] {message}"- )-- worker_agents_ids = sender_agent.agent_state.multi_agent_group.agent_ids- worker_agents = [server.agent_manager.get_agent_by_id(agent_id=agent_id, actor=sender_agent.user) for agent_id in worker_agents_ids]-- # Create a system message- messages = [MessageCreate(role=MessageRole.system, content=augmented_message, name=sender_agent.agent_state.name)]-- # Possibly limit concurrency to avoid meltdown:- sem = asyncio.Semaphore(settings.multi_agent_concurrent_sends)-- async def _send_single(agent_state):- async with sem:- return await _async_send_message_with_retries(- server=server,- sender_agent=sender_agent,- target_agent_id=agent_state.id,- messages=messages,- max_retries=3,- timeout=settings.multi_agent_send_message_timeout,- )-- tasks = [safe_create_task(_send_single(agent_state), label=f"send_to_worker_{agent_state.id}") for agent_state in worker_agents]- results = await asyncio.gather(*tasks, return_exceptions=True)- final = []- for r in results:- if isinstance(r, Exception):- final.append(str(r))- else:- final.append(r)-- return final--def generate_model_from_args_json_schema(schema: Dict[str, Any]) -> Type[BaseModel]:"""Creates a Pydantic model from a JSON schema.diff --git a/letta/services/tool_executor/multi_agent_tool_executor.py b/letta/services/tool_executor/multi_agent_tool_executor.pydeleted file mode 100644index cdb55116d..000000000--- a/letta/services/tool_executor/multi_agent_tool_executor.py+++ /dev/null@@ -1,150 +0,0 @@-from typing import Any, Dict, List, Optional--from letta.log import get_logger-from letta.schemas.agent import AgentState-from letta.schemas.enums import MessageRole-from letta.schemas.letta_message import AssistantMessage-from letta.schemas.letta_message_content import TextContent-from letta.schemas.message import MessageCreate-from letta.schemas.run import Run-from letta.schemas.sandbox_config import SandboxConfig-from letta.schemas.tool import Tool-from letta.schemas.tool_execution_result import ToolExecutionResult-from letta.schemas.user import User-from letta.services.run_manager import RunManager-from letta.services.tool_executor.tool_executor_base import ToolExecutor-from letta.settings import settings-from letta.utils import safe_create_task--logger = get_logger(__name__)---class LettaMultiAgentToolExecutor(ToolExecutor):- """Executor for LETTA multi-agent core tools."""-- async def execute(- self,- function_name: str,- function_args: dict,- tool: Tool,- actor: User,- agent_state: Optional[AgentState] = None,- sandbox_config: Optional[SandboxConfig] = None,- sandbox_env_vars: Optional[Dict[str, Any]] = None,- ) -> ToolExecutionResult:- assert agent_state is not None, "Agent state is required for multi-agent tools"- function_map = {- "send_message_to_agent_and_wait_for_reply": self.send_message_to_agent_and_wait_for_reply,- "send_message_to_agent_async": self.send_message_to_agent_async,- "send_message_to_agents_matching_tags": self.send_message_to_agents_matching_tags_async,- }-- if function_name not in function_map:- raise ValueError(f"Unknown function: {function_name}")-- # Execute the appropriate function- function_args_copy = function_args.copy() # Make a copy to avoid modifying the original- function_response = await function_map[function_name](agent_state, actor, **function_args_copy)- return ToolExecutionResult(- status="success",- func_return=function_response,- )-- async def send_message_to_agent_and_wait_for_reply(- self, agent_state: AgentState, actor: User, message: str, other_agent_id: str- ) -> str:- augmented_message = (- f"[Incoming message from agent with ID '{agent_state.id}' - to reply to this message, "- f"make sure to use the 'send_message' at the end, and the system will notify the sender of your response] "- f"{message}"- )-- other_agent_state = await self.agent_manager.get_agent_by_id_async(agent_id=other_agent_id, actor=self.actor)- return str(await self._process_agent(agent_state=other_agent_state, message=augmented_message, actor=actor))-- async def send_message_to_agents_matching_tags_async(- self, agent_state: AgentState, actor: User, message: str, match_all: List[str], match_some: List[str]- ) -> str:- # Find matching agents- matching_agents = await self.agent_manager.list_agents_matching_tags_async(- actor=self.actor, match_all=match_all, match_some=match_some- )- if not matching_agents:- return str([])-- augmented_message = (- "[Incoming message from external Letta agent - to reply to this message, "- "make sure to use the 'send_message' at the end, and the system will notify "- "the sender of your response] "- f"{message}"- )-- # Process agents sequentially to avoid exhausting the database connection pool.- # When many agents match the tags, concurrent execution can create too many simultaneous- # database connections, causing pool exhaustion errors.- results = []- for agent_state in matching_agents:- result = await self._process_agent(agent_state=agent_state, message=augmented_message, actor=actor)- results.append(result)- return str(results)-- async def _process_agent(self, agent_state: AgentState, message: str, actor: User) -> Dict[str, Any]:- from letta.agents.letta_agent_v3 import LettaAgentV3-- try:- runs_manager = RunManager()- run = await runs_manager.create_run(- pydantic_run=Run(- agent_id=agent_state.id,- background=False,- metadata={- "run_type": "agent_send_message_to_agent", # TODO: Make this a constant- },- ),- actor=actor,- )-- letta_agent = LettaAgentV3(- agent_state=agent_state,- actor=self.actor,- )-- letta_response = await letta_agent.step(- [MessageCreate(role=MessageRole.system, content=[TextContent(text=message)])], run_id=run.id- )- messages = letta_response.messages-- send_message_content = [message.content for message in messages if isinstance(message, AssistantMessage)]-- return {- "agent_id": agent_state.id,- "response": send_message_content if send_message_content else ["<no response>"],- }-- except Exception as e:- return {- "agent_id": agent_state.id,- "error": str(e),- "type": type(e).__name__,- }-- async def send_message_to_agent_async(self, agent_state: AgentState, actor: User, message: str, other_agent_id: str) -> str:- if settings.environment == "prod":- raise RuntimeError("This tool is not allowed to be run on Letta Cloud.")-- # 1) Build the prefixed system‐message- prefixed = (- f"[Incoming message from agent with ID '{agent_state.id}' - "- f"to reply to this message, make sure to use the "- f"'send_message_to_agent_async' tool, or the agent will not receive your message] "- f"{message}"- )-- other_agent_state = await self.agent_manager.get_agent_by_id_async(agent_id=other_agent_id, actor=self.actor)- task = safe_create_task(- self._process_agent(agent_state=other_agent_state, message=prefixed, actor=actor), label=f"send_message_to_{other_agent_id}"- )-- task.add_done_callback(lambda t: (logger.error(f"Async send_message task failed: {t.exception()}") if t.exception() else None))-- return "Successfully sent message"