Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
chore: Move `send_message_to_agent` (#665)
Matthew Zhou15a31da0a341
diff --git a/letta/server/rest_api/routers/openai/chat_completions/chat_completions.py b/letta/server/rest_api/routers/openai/chat_completions/chat_completions.pyindex 4809fa19d..f1485da3c 100644--- a/letta/server/rest_api/routers/openai/chat_completions/chat_completions.py+++ b/letta/server/rest_api/routers/openai/chat_completions/chat_completions.py@@ -3,13 +3,11 @@ from typing import TYPE_CHECKING, Optionalfrom fastapi import APIRouter, Body, Depends, Header, HTTPException-from letta.schemas.enums import MessageRolefrom letta.schemas.letta_message import LettaMessage, ToolCallfrom letta.schemas.openai.chat_completion_request import ChatCompletionRequestfrom letta.schemas.openai.chat_completion_response import ChatCompletionResponse, Choice, Message, UsageStatistics# TODO this belongs in a controller!-from letta.server.rest_api.routers.v1.agents import send_message_to_agentfrom letta.server.rest_api.utils import get_letta_serverif TYPE_CHECKING:@@ -52,12 +50,10 @@ async def create_chat_completion(# TODO(charles) support multimodal partsassert isinstance(input_message.content, str)- return await send_message_to_agent(- server=server,+ return await server.send_message_to_agent(agent_id=agent_id,- user_id=actor.id,- role=MessageRole(input_message.role),- message=input_message.content,+ actor=actor,+ message=input_message.content, # TODO: This is broken# Turn streaming ONstream_steps=True,stream_tokens=True,@@ -71,12 +67,10 @@ async def create_chat_completion(# TODO(charles) support multimodal partsassert isinstance(input_message.content, str)- response_messages = await send_message_to_agent(- server=server,+ response_messages = await server.send_message_to_agent(agent_id=agent_id,- user_id=actor.id,- role=MessageRole(input_message.role),- message=input_message.content,+ actor=actor,+ message=input_message.content, # TODO: This is broken# Turn streaming OFFstream_steps=False,stream_tokens=False,diff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.pyindex 558f59fc4..23a971020 100644--- a/letta/server/rest_api/routers/v1/agents.py+++ b/letta/server/rest_api/routers/v1/agents.py@@ -1,10 +1,8 @@-import asyncio-import warningsfrom datetime import datetimefrom typing import List, Optional, Unionfrom fastapi import APIRouter, BackgroundTasks, Body, Depends, Header, HTTPException, Query, status-from fastapi.responses import JSONResponse, StreamingResponse+from fastapi.responses import JSONResponsefrom pydantic import Fieldfrom letta.constants import DEFAULT_MESSAGE_TOOL, DEFAULT_MESSAGE_TOOL_KWARG@@ -12,20 +10,18 @@ from letta.log import get_loggerfrom letta.orm.errors import NoResultFoundfrom letta.schemas.agent import AgentState, CreateAgent, UpdateAgentfrom letta.schemas.block import Block, BlockUpdate, CreateBlock # , BlockLabelUpdate, BlockLimitUpdate-from letta.schemas.enums import MessageStreamStatusfrom letta.schemas.job import JobStatus, JobUpdate-from letta.schemas.letta_message import LegacyLettaMessage, LettaMessage, LettaMessageUnion+from letta.schemas.letta_message import LettaMessageUnionfrom letta.schemas.letta_request import LettaRequest, LettaStreamingRequestfrom letta.schemas.letta_response import LettaResponsefrom letta.schemas.memory import ArchivalMemorySummary, ContextWindowOverview, CreateArchivalMemory, Memory, RecallMemorySummary-from letta.schemas.message import Message, MessageCreate, MessageUpdate+from letta.schemas.message import Message, MessageUpdatefrom letta.schemas.passage import Passagefrom letta.schemas.run import Runfrom letta.schemas.source import Sourcefrom letta.schemas.tool import Toolfrom letta.schemas.user import User-from letta.server.rest_api.interface import StreamingServerInterface-from letta.server.rest_api.utils import get_letta_server, sse_async_generator+from letta.server.rest_api.utils import get_letta_serverfrom letta.server.server import SyncServer# These can be forward refs, but because Fastapi needs them at runtime the must be imported normally@@ -499,8 +495,7 @@ async def send_message(This endpoint accepts a message from a user and processes it through the agent."""actor = server.user_manager.get_user_or_default(user_id=user_id)- result = await send_message_to_agent(- server=server,+ result = await server.send_message_to_agent(agent_id=agent_id,actor=actor,messages=request.messages,@@ -540,8 +535,7 @@ async def send_message_streaming("""actor = server.user_manager.get_user_or_default(user_id=user_id)- result = await send_message_to_agent(- server=server,+ result = await server.send_message_to_agent(agent_id=agent_id,actor=actor,messages=request.messages,@@ -568,8 +562,7 @@ async def process_message_background("""Background task to process the message and update job status."""try:# TODO(matt) we should probably make this stream_steps and log each step as it progresses, so the job update GET can see the total steps so far + partial usage?- result = await send_message_to_agent(- server=server,+ result = await server.send_message_to_agent(agent_id=agent_id,actor=actor,messages=messages,@@ -646,125 +639,3 @@ async def send_message_async()return run---# TODO: move this into server.py?-async def send_message_to_agent(- server: SyncServer,- agent_id: str,- actor: User,- # role: MessageRole,- messages: Union[List[Message], List[MessageCreate]],- stream_steps: bool,- stream_tokens: bool,- # related to whether or not we return `LettaMessage`s or `Message`s- chat_completion_mode: bool = False,- timestamp: Optional[datetime] = None,- # Support for AssistantMessage- use_assistant_message: bool = True,- assistant_message_tool_name: str = DEFAULT_MESSAGE_TOOL,- assistant_message_tool_kwarg: str = DEFAULT_MESSAGE_TOOL_KWARG,- metadata: Optional[dict] = None,-) -> Union[StreamingResponse, LettaResponse]:- """Split off into a separate function so that it can be imported in the /chat/completion proxy."""-- # TODO: @charles is this the correct way to handle?- include_final_message = True-- if not stream_steps and stream_tokens:- raise HTTPException(status_code=400, detail="stream_steps must be 'true' if stream_tokens is 'true'")-- # For streaming response- try:-- # TODO: move this logic into server.py-- # Get the generator object off of the agent's streaming interface- # This will be attached to the POST SSE request used under-the-hood- letta_agent = server.load_agent(agent_id=agent_id, actor=actor)-- # Disable token streaming if not OpenAI- # TODO: cleanup this logic- llm_config = letta_agent.agent_state.llm_config- if stream_tokens and (llm_config.model_endpoint_type != "openai" or "inference.memgpt.ai" in llm_config.model_endpoint):- warnings.warn(- "Token streaming is only supported for models with type 'openai' or `inference.memgpt.ai` in the model_endpoint: agent has endpoint type {llm_config.model_endpoint_type} and {llm_config.model_endpoint}. Setting stream_tokens to False."- )- stream_tokens = False-- # Create a new interface per request- letta_agent.interface = StreamingServerInterface(use_assistant_message)- streaming_interface = letta_agent.interface- if not isinstance(streaming_interface, StreamingServerInterface):- raise ValueError(f"Agent has wrong type of interface: {type(streaming_interface)}")-- # Enable token-streaming within the request if desired- streaming_interface.streaming_mode = stream_tokens- # "chatcompletion mode" does some remapping and ignores inner thoughts- streaming_interface.streaming_chat_completion_mode = chat_completion_mode-- # streaming_interface.allow_assistant_message = stream- # streaming_interface.function_call_legacy_mode = stream-- # Allow AssistantMessage is desired by client- streaming_interface.assistant_message_tool_name = assistant_message_tool_name- streaming_interface.assistant_message_tool_kwarg = assistant_message_tool_kwarg-- # Related to JSON buffer reader- streaming_interface.inner_thoughts_in_kwargs = (- llm_config.put_inner_thoughts_in_kwargs if llm_config.put_inner_thoughts_in_kwargs is not None else False- )-- # Offload the synchronous message_func to a separate thread- streaming_interface.stream_start()- task = asyncio.create_task(- asyncio.to_thread(- server.send_messages,- actor=actor,- agent_id=agent_id,- messages=messages,- interface=streaming_interface,- metadata=metadata,- )- )-- if stream_steps:- # return a stream- return StreamingResponse(- sse_async_generator(- streaming_interface.get_generator(),- usage_task=task,- finish_message=include_final_message,- ),- media_type="text/event-stream",- )-- else:- # buffer the stream, then return the list- generated_stream = []- async for message in streaming_interface.get_generator():- assert (- isinstance(message, LettaMessage) or isinstance(message, LegacyLettaMessage) or isinstance(message, MessageStreamStatus)- ), type(message)- generated_stream.append(message)- if message == MessageStreamStatus.done:- break-- # Get rid of the stream status messages- filtered_stream = [d for d in generated_stream if not isinstance(d, MessageStreamStatus)]- usage = await task-- # By default the stream will be messages of type LettaMessage or LettaLegacyMessage- # If we want to convert these to Message, we can use the attached IDs- # NOTE: we will need to de-duplicate the Messsage IDs though (since Assistant->Inner+Func_Call)- # TODO: eventually update the interface to use `Message` and `MessageChunk` (new) inside the deque instead- return LettaResponse(messages=filtered_stream, usage=usage)-- except HTTPException:- raise- except Exception as e:- print(e)- import traceback-- traceback.print_exc()- raise HTTPException(status_code=500, detail=f"{e}")diff --git a/letta/server/rest_api/utils.py b/letta/server/rest_api/utils.pyindex bb5dc0340..d355d9e2d 100644--- a/letta/server/rest_api/utils.py+++ b/letta/server/rest_api/utils.py@@ -3,7 +3,7 @@ import jsonimport osimport warningsfrom enum import Enum-from typing import AsyncGenerator, Optional, Union+from typing import TYPE_CHECKING, AsyncGenerator, Optional, Unionfrom fastapi import Headerfrom pydantic import BaseModel@@ -11,7 +11,9 @@ from pydantic import BaseModelfrom letta.errors import ContextWindowExceededError, RateLimitExceededErrorfrom letta.schemas.usage import LettaUsageStatisticsfrom letta.server.rest_api.interface import StreamingServerInterface-from letta.server.server import SyncServer++if TYPE_CHECKING:+ from letta.server.server import SyncServer# from letta.orm.user import User# from letta.orm.utilities import get_db_session@@ -86,7 +88,7 @@ async def sse_async_generator(# TODO: why does this double up the interface?-def get_letta_server() -> SyncServer:+def get_letta_server() -> "SyncServer":# Check if a global server is already instantiatedfrom letta.server.rest_api.app import serverdiff --git a/letta/server/server.py b/letta/server/server.pyindex 1a9b880e0..28d62ec8a 100644--- a/letta/server/server.py+++ b/letta/server/server.py@@ -1,4 +1,5 @@# inspecting tools+import asyncioimport osimport tracebackimport warnings@@ -9,6 +10,7 @@ from typing import Callable, Dict, List, Optional, Tuple, Unionfrom composio.client import Composiofrom composio.client.collections import ActionModel, AppModelfrom fastapi import HTTPException+from fastapi.responses import StreamingResponseimport letta.constants as constantsimport letta.server.utils as server_utils@@ -30,10 +32,11 @@ from letta.schemas.block import BlockUpdatefrom letta.schemas.embedding_config import EmbeddingConfig# openai schemas-from letta.schemas.enums import JobStatus+from letta.schemas.enums import JobStatus, MessageStreamStatusfrom letta.schemas.environment_variables import SandboxEnvironmentVariableCreatefrom letta.schemas.job import Job, JobUpdate-from letta.schemas.letta_message import LettaMessage, ToolReturnMessage+from letta.schemas.letta_message import LegacyLettaMessage, LettaMessage, ToolReturnMessage+from letta.schemas.letta_response import LettaResponsefrom letta.schemas.llm_config import LLMConfigfrom letta.schemas.memory import ArchivalMemorySummary, ContextWindowOverview, Memory, RecallMemorySummaryfrom letta.schemas.message import Message, MessageCreate, MessageRole, MessageUpdate@@ -57,6 +60,8 @@ from letta.schemas.source import Sourcefrom letta.schemas.tool import Toolfrom letta.schemas.usage import LettaUsageStatisticsfrom letta.schemas.user import User+from letta.server.rest_api.interface import StreamingServerInterface+from letta.server.rest_api.utils import sse_async_generatorfrom letta.services.agent_manager import AgentManagerfrom letta.services.block_manager import BlockManagerfrom letta.services.job_manager import JobManager@@ -1193,3 +1198,125 @@ class SyncServer(Server):def get_composio_actions_from_app_name(self, composio_app_name: str, api_key: Optional[str] = None) -> List["ActionModel"]:actions = self.get_composio_client(api_key=api_key).actions.get(apps=[composio_app_name])return actions++ async def send_message_to_agent(+ self,+ agent_id: str,+ actor: User,+ # role: MessageRole,+ messages: Union[List[Message], List[MessageCreate]],+ stream_steps: bool,+ stream_tokens: bool,+ # related to whether or not we return `LettaMessage`s or `Message`s+ chat_completion_mode: bool = False,+ timestamp: Optional[datetime] = None,+ # Support for AssistantMessage+ use_assistant_message: bool = True,+ assistant_message_tool_name: str = constants.DEFAULT_MESSAGE_TOOL,+ assistant_message_tool_kwarg: str = constants.DEFAULT_MESSAGE_TOOL_KWARG,+ metadata: Optional[dict] = None,+ ) -> Union[StreamingResponse, LettaResponse]:+ """Split off into a separate function so that it can be imported in the /chat/completion proxy."""++ # TODO: @charles is this the correct way to handle?+ include_final_message = True++ if not stream_steps and stream_tokens:+ raise HTTPException(status_code=400, detail="stream_steps must be 'true' if stream_tokens is 'true'")++ # For streaming response+ try:++ # TODO: move this logic into server.py++ # Get the generator object off of the agent's streaming interface+ # This will be attached to the POST SSE request used under-the-hood+ letta_agent = self.load_agent(agent_id=agent_id, actor=actor)++ # Disable token streaming if not OpenAI+ # TODO: cleanup this logic+ llm_config = letta_agent.agent_state.llm_config+ if stream_tokens and (llm_config.model_endpoint_type != "openai" or "inference.memgpt.ai" in llm_config.model_endpoint):+ warnings.warn(+ "Token streaming is only supported for models with type 'openai' or `inference.memgpt.ai` in the model_endpoint: agent has endpoint type {llm_config.model_endpoint_type} and {llm_config.model_endpoint}. Setting stream_tokens to False."+ )+ stream_tokens = False++ # Create a new interface per request+ letta_agent.interface = StreamingServerInterface(use_assistant_message)+ streaming_interface = letta_agent.interface+ if not isinstance(streaming_interface, StreamingServerInterface):+ raise ValueError(f"Agent has wrong type of interface: {type(streaming_interface)}")++ # Enable token-streaming within the request if desired+ streaming_interface.streaming_mode = stream_tokens+ # "chatcompletion mode" does some remapping and ignores inner thoughts+ streaming_interface.streaming_chat_completion_mode = chat_completion_mode++ # streaming_interface.allow_assistant_message = stream+ # streaming_interface.function_call_legacy_mode = stream++ # Allow AssistantMessage is desired by client+ streaming_interface.assistant_message_tool_name = assistant_message_tool_name+ streaming_interface.assistant_message_tool_kwarg = assistant_message_tool_kwarg++ # Related to JSON buffer reader+ streaming_interface.inner_thoughts_in_kwargs = (+ llm_config.put_inner_thoughts_in_kwargs if llm_config.put_inner_thoughts_in_kwargs is not None else False+ )++ # Offload the synchronous message_func to a separate thread+ streaming_interface.stream_start()+ task = asyncio.create_task(+ asyncio.to_thread(+ self.send_messages,+ actor=actor,+ agent_id=agent_id,+ messages=messages,+ interface=streaming_interface,+ metadata=metadata,+ )+ )++ if stream_steps:+ # return a stream+ return StreamingResponse(+ sse_async_generator(+ streaming_interface.get_generator(),+ usage_task=task,+ finish_message=include_final_message,+ ),+ media_type="text/event-stream",+ )++ else:+ # buffer the stream, then return the list+ generated_stream = []+ async for message in streaming_interface.get_generator():+ assert (+ isinstance(message, LettaMessage)+ or isinstance(message, LegacyLettaMessage)+ or isinstance(message, MessageStreamStatus)+ ), type(message)+ generated_stream.append(message)+ if message == MessageStreamStatus.done:+ break++ # Get rid of the stream status messages+ filtered_stream = [d for d in generated_stream if not isinstance(d, MessageStreamStatus)]+ usage = await task++ # By default the stream will be messages of type LettaMessage or LettaLegacyMessage+ # If we want to convert these to Message, we can use the attached IDs+ # NOTE: we will need to de-duplicate the Messsage IDs though (since Assistant->Inner+Func_Call)+ # TODO: eventually update the interface to use `Message` and `MessageChunk` (new) inside the deque instead+ return LettaResponse(messages=filtered_stream, usage=usage)++ except HTTPException:+ raise+ except Exception as e:+ print(e)+ import traceback++ traceback.print_exc()+ raise HTTPException(status_code=500, detail=f"{e}")