Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
chore: remove old OpenAI routers (#717)
Sarah Wooders2204d92f3baa
diff --git a/letta/__init__.py b/letta/__init__.pyindex 33e2b6735..8fce88dcb 100644--- a/letta/__init__.py+++ b/letta/__init__.py@@ -15,7 +15,6 @@ from letta.schemas.letta_message import LettaMessagefrom letta.schemas.llm_config import LLMConfigfrom letta.schemas.memory import ArchivalMemorySummary, BasicBlockMemory, ChatMemory, Memory, RecallMemorySummaryfrom letta.schemas.message import Message-from letta.schemas.openai.chat_completion_response import UsageStatisticsfrom letta.schemas.organization import Organizationfrom letta.schemas.passage import Passagefrom letta.schemas.source import Sourcediff --git a/letta/agent.py b/letta/agent.pyindex 3f416e394..cf2cca11f 100644--- a/letta/agent.py+++ b/letta/agent.py@@ -5,6 +5,8 @@ import warningsfrom abc import ABC, abstractmethodfrom typing import List, Optional, Tuple, Union+from openai.types.beta.function_tool import FunctionTool as OpenAITool+from letta.constants import (CLI_WARNING_PREFIX,ERROR_MESSAGE_PREFIX,@@ -33,7 +35,6 @@ from letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.enums import MessageRolefrom letta.schemas.memory import ContextWindowOverview, Memoryfrom letta.schemas.message import Message-from letta.schemas.openai.chat_completion_request import Tool as ChatCompletionRequestToolfrom letta.schemas.openai.chat_completion_response import ChatCompletionResponsefrom letta.schemas.openai.chat_completion_response import Message as ChatCompletionMessagefrom letta.schemas.openai.chat_completion_response import UsageStatistics@@ -1023,7 +1024,7 @@ class Agent(BaseAgent):# tokens taken up by function definitionsagent_state_tool_jsons = [t.json_schema for t in self.agent_state.tools]if agent_state_tool_jsons:- available_functions_definitions = [ChatCompletionRequestTool(type="function", function=f) for f in agent_state_tool_jsons]+ available_functions_definitions = [OpenAITool(type="function", function=f) for f in agent_state_tool_jsons]num_tokens_available_functions_definitions = num_tokens_from_functions(functions=agent_state_tool_jsons, model=self.model)else:available_functions_definitions = []diff --git a/letta/client/client.py b/letta/client/client.pyindex 201b30176..1cacbd448 100644--- a/letta/client/client.py+++ b/letta/client/client.py@@ -3,6 +3,7 @@ import timefrom typing import Callable, Dict, Generator, List, Optional, Unionimport requests+from openai.types.chat.chat_completion_message_tool_call import ChatCompletionMessageToolCall as OpenAIToolCallimport letta.utilsfrom letta.constants import ADMIN_PREFIX, BASE_MEMORY_TOOLS, BASE_TOOLS, DEFAULT_HUMAN, DEFAULT_PERSONA, FUNCTION_RETURN_CHAR_LIMIT@@ -29,7 +30,6 @@ from letta.schemas.llm_config import LLMConfigfrom letta.schemas.memory import ArchivalMemorySummary, ChatMemory, CreateArchivalMemory, Memory, RecallMemorySummaryfrom letta.schemas.message import Message, MessageCreate, MessageUpdatefrom letta.schemas.openai.chat_completion_response import UsageStatistics-from letta.schemas.openai.chat_completions import ToolCallfrom letta.schemas.organization import Organizationfrom letta.schemas.passage import Passagefrom letta.schemas.run import Run@@ -631,7 +631,7 @@ class RESTClient(AbstractClient):role: Optional[MessageRole] = None,text: Optional[str] = None,name: Optional[str] = None,- tool_calls: Optional[List[ToolCall]] = None,+ tool_calls: Optional[List[OpenAIToolCall]] = None,tool_call_id: Optional[str] = None,) -> Message:request = MessageUpdate(@@ -2365,7 +2365,7 @@ class LocalClient(AbstractClient):role: Optional[MessageRole] = None,text: Optional[str] = None,name: Optional[str] = None,- tool_calls: Optional[List[ToolCall]] = None,+ tool_calls: Optional[List[OpenAIToolCall]] = None,tool_call_id: Optional[str] = None,) -> Message:message = self.server.update_agent_message(diff --git a/letta/orm/custom_columns.py b/letta/orm/custom_columns.pyindex f53169d93..c551a7d4b 100644--- a/letta/orm/custom_columns.py+++ b/letta/orm/custom_columns.py@@ -2,13 +2,14 @@ import base64from typing import List, Unionimport numpy as np+from openai.types.chat.chat_completion_message_tool_call import ChatCompletionMessageToolCall as OpenAIToolCall+from openai.types.chat.chat_completion_message_tool_call import Function as OpenAIFunctionfrom sqlalchemy import JSONfrom sqlalchemy.types import BINARY, TypeDecoratorfrom letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.enums import ToolRuleTypefrom letta.schemas.llm_config import LLMConfig-from letta.schemas.openai.chat_completions import ToolCall, ToolCallFunctionfrom letta.schemas.tool_rule import ChildToolRule, ConditionalToolRule, InitToolRule, TerminalToolRule@@ -109,7 +110,7 @@ class ToolCallColumn(TypeDecorator):if value:values = []for v in value:- if isinstance(v, ToolCall):+ if isinstance(v, OpenAIToolCall):values.append(v.model_dump())else:values.append(v)@@ -122,11 +123,11 @@ class ToolCallColumn(TypeDecorator):tools = []for tool_value in value:if "function" in tool_value:- tool_call_function = ToolCallFunction(**tool_value["function"])+ tool_call_function = OpenAIFunction(**tool_value["function"])del tool_value["function"]else:tool_call_function = None- tools.append(ToolCall(function=tool_call_function, **tool_value))+ tools.append(OpenAIToolCall(function=tool_call_function, **tool_value))return toolsreturn valuediff --git a/letta/orm/message.py b/letta/orm/message.pyindex e06fae3d0..809bcdf53 100644--- a/letta/orm/message.py+++ b/letta/orm/message.py@@ -1,5 +1,6 @@from typing import Optional+from openai.types.chat.chat_completion_message_tool_call import ChatCompletionMessageToolCall as OpenAIToolCallfrom sqlalchemy import ForeignKey, Indexfrom sqlalchemy.orm import Mapped, mapped_column, relationship@@ -7,7 +8,6 @@ from letta.orm.custom_columns import ToolCallColumnfrom letta.orm.mixins import AgentMixin, OrganizationMixinfrom letta.orm.sqlalchemy_base import SqlalchemyBasefrom letta.schemas.message import Message as PydanticMessage-from letta.schemas.openai.chat_completions import ToolCallclass Message(SqlalchemyBase, OrganizationMixin, AgentMixin):@@ -22,7 +22,7 @@ class Message(SqlalchemyBase, OrganizationMixin, AgentMixin):text: Mapped[Optional[str]] = mapped_column(nullable=True, doc="Message content")model: Mapped[Optional[str]] = mapped_column(nullable=True, doc="LLM model used")name: Mapped[Optional[str]] = mapped_column(nullable=True, doc="Name for multi-agent scenarios")- tool_calls: Mapped[ToolCall] = mapped_column(ToolCallColumn, doc="Tool call information")+ tool_calls: Mapped[OpenAIToolCall] = mapped_column(ToolCallColumn, doc="Tool call information")tool_call_id: Mapped[Optional[str]] = mapped_column(nullable=True, doc="ID of the tool call")step_id: Mapped[Optional[str]] = mapped_column(ForeignKey("steps.id", ondelete="SET NULL"), nullable=True, doc="ID of the step that this message belongs to"diff --git a/letta/schemas/letta_message.py b/letta/schemas/letta_message.pyindex a49ac049a..6794a15ff 100644--- a/letta/schemas/letta_message.py+++ b/letta/schemas/letta_message.py@@ -222,22 +222,22 @@ LettaMessageUnion = Annotated[def create_letta_message_union_schema():return {"oneOf": [- {"$ref": "#/components/schemas/SystemMessage-Output"},- {"$ref": "#/components/schemas/UserMessage-Output"},+ {"$ref": "#/components/schemas/SystemMessage"},+ {"$ref": "#/components/schemas/UserMessage"},{"$ref": "#/components/schemas/ReasoningMessage"},{"$ref": "#/components/schemas/ToolCallMessage"},{"$ref": "#/components/schemas/ToolReturnMessage"},- {"$ref": "#/components/schemas/AssistantMessage-Output"},+ {"$ref": "#/components/schemas/AssistantMessage"},],"discriminator": {"propertyName": "message_type","mapping": {- "system_message": "#/components/schemas/SystemMessage-Output",- "user_message": "#/components/schemas/UserMessage-Output",+ "system_message": "#/components/schemas/SystemMessage",+ "user_message": "#/components/schemas/UserMessage","reasoning_message": "#/components/schemas/ReasoningMessage","tool_call_message": "#/components/schemas/ToolCallMessage","tool_return_message": "#/components/schemas/ToolReturnMessage",- "assistant_message": "#/components/schemas/AssistantMessage-Output",+ "assistant_message": "#/components/schemas/AssistantMessage",},},}diff --git a/letta/schemas/memory.py b/letta/schemas/memory.pyindex ab877949a..1f60a09a1 100644--- a/letta/schemas/memory.py+++ b/letta/schemas/memory.py@@ -7,10 +7,11 @@ from pydantic import BaseModel, Fieldif TYPE_CHECKING:pass+from openai.types.beta.function_tool import FunctionTool as OpenAITool+from letta.constants import CORE_MEMORY_BLOCK_CHAR_LIMITfrom letta.schemas.block import Blockfrom letta.schemas.message import Message-from letta.schemas.openai.chat_completion_request import Toolclass ContextWindowOverview(BaseModel):@@ -47,7 +48,7 @@ class ContextWindowOverview(BaseModel):summary_memory: Optional[str] = Field(None, description="The content of the summary memory.")num_tokens_functions_definitions: int = Field(..., description="The number of tokens in the functions definitions.")- functions_definitions: Optional[List[Tool]] = Field(..., description="The content of the functions definitions.")+ functions_definitions: Optional[List[OpenAITool]] = Field(..., description="The content of the functions definitions.")num_tokens_messages: int = Field(..., description="The number of tokens in the messages list.")# TODO make list of messages?diff --git a/letta/schemas/message.py b/letta/schemas/message.pyindex 41b85259b..9b84ce5ae 100644--- a/letta/schemas/message.py+++ b/letta/schemas/message.py@@ -4,24 +4,32 @@ import warningsfrom datetime import datetime, timezonefrom typing import List, Literal, Optional+from openai.types.chat.chat_completion_message_tool_call import ChatCompletionMessageToolCall as OpenAIToolCall+from openai.types.chat.chat_completion_message_tool_call import Function as OpenAIFunctionfrom pydantic import BaseModel, Field, field_validatorfrom letta.constants import DEFAULT_MESSAGE_TOOL, DEFAULT_MESSAGE_TOOL_KWARG, TOOL_CALL_ID_MAX_LENfrom letta.local_llm.constants import INNER_THOUGHTS_KWARGfrom letta.schemas.enums import MessageRolefrom letta.schemas.letta_base import OrmMetadataBase-from letta.schemas.letta_message import AssistantMessage, LettaMessage, ReasoningMessage, SystemMessage-from letta.schemas.letta_message import ToolCall as LettaToolCall-from letta.schemas.letta_message import ToolCallMessage, ToolReturnMessage, UserMessage-from letta.schemas.openai.chat_completions import ToolCall, ToolCallFunction+from letta.schemas.letta_message import (+ AssistantMessage,+ LettaMessage,+ ReasoningMessage,+ SystemMessage,+ ToolCall,+ ToolCallMessage,+ ToolReturnMessage,+ UserMessage,+)from letta.utils import get_utc_time, is_utc_datetime, json_dumpsdef add_inner_thoughts_to_tool_call(- tool_call: ToolCall,+ tool_call: OpenAIToolCall,inner_thoughts: str,inner_thoughts_key: str,-) -> ToolCall:+) -> OpenAIToolCall:"""Add inner thoughts (arg + value) to a tool call"""# because the kwargs are stored as strings, we need to load then write the JSON dictstry:@@ -68,7 +76,7 @@ class MessageUpdate(BaseModel):name: Optional[str] = Field(None, description="The name of the participant.")# NOTE: we probably shouldn't allow updating the created_at field, right?# created_at: Optional[datetime] = Field(None, description="The time the message was created.")- tool_calls: Optional[List[ToolCall]] = Field(None, description="The list of tool calls requested.")+ tool_calls: Optional[List[OpenAIToolCall,]] = Field(None, description="The list of tool calls requested.")tool_call_id: Optional[str] = Field(None, description="The id of the tool call.")@@ -85,7 +93,7 @@ class Message(BaseMessage):model (str): The model used to make the function call.name (str): The name of the participant.created_at (datetime): The time the message was created.- tool_calls (List[ToolCall]): The list of tool calls requested.+ tool_calls (List[OpenAIToolCall,]): The list of tool calls requested.tool_call_id (str): The id of the tool call."""@@ -97,7 +105,7 @@ class Message(BaseMessage):agent_id: Optional[str] = Field(None, description="The unique identifier of the agent.")model: Optional[str] = Field(None, description="The model used to make the function call.")name: Optional[str] = Field(None, description="The name of the participant.")- tool_calls: Optional[List[ToolCall]] = Field(None, description="The list of tool calls requested.")+ tool_calls: Optional[List[OpenAIToolCall,]] = Field(None, description="The list of tool calls requested.")tool_call_id: Optional[str] = Field(None, description="The id of the tool call.")step_id: Optional[str] = Field(None, description="The id of the step that this message was created in.")# This overrides the optional base orm schema, created_at MUST exist on all messages objects@@ -165,7 +173,7 @@ class Message(BaseMessage):ToolCallMessage(id=self.id,date=self.created_at,- tool_call=LettaToolCall(+ tool_call=ToolCall(name=tool_call.function.name,arguments=tool_call.function.arguments,tool_call_id=tool_call.id,@@ -304,10 +312,10 @@ class Message(BaseMessage):# Convert a function_call (from an assistant message) into a tool_call# NOTE: this does not conventionally include a tool_call_id (ToolCall.id), it's on the caster to provide ittool_calls = [- ToolCall(+ OpenAIToolCall(id=openai_message_dict["tool_call_id"], # NOTE: unconventional source, not to spectype="function",- function=ToolCallFunction(+ function=OpenAIFunction(name=openai_message_dict["function_call"]["name"],arguments=openai_message_dict["function_call"]["arguments"],),@@ -352,7 +360,7 @@ class Message(BaseMessage):assert openai_message_dict["role"] == "assistant", openai_message_dicttool_calls = [- ToolCall(id=tool_call["id"], type=tool_call["type"], function=tool_call["function"])+ OpenAIToolCall(id=tool_call["id"], type=tool_call["type"], function=tool_call["function"])for tool_call in openai_message_dict["tool_calls"]]else:diff --git a/letta/server/rest_api/app.py b/letta/server/rest_api/app.pyindex 223871ad5..70f7f7454 100644--- a/letta/server/rest_api/app.py+++ b/letta/server/rest_api/app.py@@ -22,8 +22,6 @@ from letta.server.constants import REST_DEFAULT_PORT# NOTE(charles): these are extra routes that are not part of v1 but we still need to mount to pass testsfrom letta.server.rest_api.auth.index import setup_auth_router # TODO: probably remove right?from letta.server.rest_api.interface import StreamingServerInterface-from letta.server.rest_api.routers.openai.assistants.assistants import router as openai_assistants_router-from letta.server.rest_api.routers.openai.chat_completions.chat_completions import router as openai_chat_completions_router# from letta.orm.utilities import get_db_session # TODO(ethan) reenable once we merge ORMfrom letta.server.rest_api.routers.v1 import ROUTERS as v1_routes@@ -62,20 +60,11 @@ def generate_openapi_schema(app: FastAPI):if not app.openapi_schema:app.openapi_schema = app.openapi()- openai_docs, letta_docs = [app.openapi_schema.copy() for _ in range(2)]-- openai_docs["paths"] = {k: v for k, v in openai_docs["paths"].items() if k.startswith("/openai")}- openai_docs["info"]["title"] = "OpenAI Assistants API"+ letta_docs = app.openapi_schema.copy()letta_docs["paths"] = {k: v for k, v in letta_docs["paths"].items() if not k.startswith("/openai")}letta_docs["info"]["title"] = "Letta API"letta_docs["components"]["schemas"]["LettaMessageUnion"] = create_letta_message_union_schema()-- # Split the API docs into Letta API, and OpenAI Assistants compatible APIfor name, docs in [- (- "openai",- openai_docs,- ),("letta",letta_docs,@@ -249,10 +238,6 @@ def create_application() -> "FastAPI":app.include_router(users_router, prefix=ADMIN_PREFIX)app.include_router(organizations_router, prefix=ADMIN_PREFIX)- # openai- app.include_router(openai_assistants_router, prefix=OPENAI_API_PREFIX)- app.include_router(openai_chat_completions_router, prefix=OPENAI_API_PREFIX)-# /api/auth endpointsapp.include_router(setup_auth_router(server, interface, password), prefix=API_PREFIX)diff --git a/letta/server/rest_api/routers/openai/__init__.py b/letta/server/rest_api/routers/openai/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/letta/server/rest_api/routers/openai/assistants/__init__.py b/letta/server/rest_api/routers/openai/assistants/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/letta/server/rest_api/routers/openai/assistants/assistants.py b/letta/server/rest_api/routers/openai/assistants/assistants.pydeleted file mode 100644index 2b646f931..000000000--- a/letta/server/rest_api/routers/openai/assistants/assistants.py+++ /dev/null@@ -1,115 +0,0 @@-from typing import List--from fastapi import APIRouter, Body, HTTPException, Path, Query--from letta.constants import DEFAULT_PRESET-from letta.schemas.openai.openai import AssistantFile, OpenAIAssistant-from letta.server.rest_api.routers.openai.assistants.schemas import (- CreateAssistantFileRequest,- CreateAssistantRequest,- DeleteAssistantFileResponse,- DeleteAssistantResponse,-)-from letta.utils import get_utc_time--router = APIRouter()---# TODO: implement mechanism for creating/authenticating users associated with a bearer token-router = APIRouter(prefix="/v1/assistants", tags=["assistants"])---# create assistant (Letta agent)[email protected]("/", response_model=OpenAIAssistant)-def create_assistant(request: CreateAssistantRequest = Body(...)):- # TODO: create preset- return OpenAIAssistant(- id=DEFAULT_PRESET,- name="default_preset",- description=request.description,- created_at=int(get_utc_time().timestamp()),- model=request.model,- instructions=request.instructions,- tools=request.tools,- file_ids=request.file_ids,- metadata=request.metadata,- )--[email protected]("/{assistant_id}/files", response_model=AssistantFile)-def create_assistant_file(- assistant_id: str = Path(..., description="The unique identifier of the assistant."),- request: CreateAssistantFileRequest = Body(...),-):- # TODO: add file to assistant- return AssistantFile(- id=request.file_id,- created_at=int(get_utc_time().timestamp()),- assistant_id=assistant_id,- )--[email protected]("/", response_model=List[OpenAIAssistant])-def list_assistants(- limit: int = Query(1000, description="How many assistants to retrieve."),- order: str = Query("asc", description="Order of assistants to retrieve (either 'asc' or 'desc')."),- after: str = Query(None, description="A cursor for use in pagination. `after` is an object ID that defines your place in the list."),- before: str = Query(None, description="A cursor for use in pagination. `after` is an object ID that defines your place in the list."),-):- # TODO: implement list assistants (i.e. list available Letta presets)- raise HTTPException(status_code=404, detail="Not yet implemented (coming soon)")--[email protected]("/{assistant_id}/files", response_model=List[AssistantFile])-def list_assistant_files(- assistant_id: str = Path(..., description="The unique identifier of the assistant."),- limit: int = Query(1000, description="How many files to retrieve."),- order: str = Query("asc", description="Order of files to retrieve (either 'asc' or 'desc')."),- after: str = Query(None, description="A cursor for use in pagination. `after` is an object ID that defines your place in the list."),- before: str = Query(None, description="A cursor for use in pagination. `after` is an object ID that defines your place in the list."),-):- # TODO: list attached data sources to preset- raise HTTPException(status_code=404, detail="Not yet implemented (coming soon)")--[email protected]("/{assistant_id}", response_model=OpenAIAssistant)-def retrieve_assistant(- assistant_id: str = Path(..., description="The unique identifier of the assistant."),-):- # TODO: get and return preset- raise HTTPException(status_code=404, detail="Not yet implemented (coming soon)")--[email protected]("/{assistant_id}/files/{file_id}", response_model=AssistantFile)-def retrieve_assistant_file(- assistant_id: str = Path(..., description="The unique identifier of the assistant."),- file_id: str = Path(..., description="The unique identifier of the file."),-):- # TODO: return data source attached to preset- raise HTTPException(status_code=404, detail="Not yet implemented (coming soon)")--[email protected]("/{assistant_id}", response_model=OpenAIAssistant)-def modify_assistant(- assistant_id: str = Path(..., description="The unique identifier of the assistant."),- request: CreateAssistantRequest = Body(...),-):- # TODO: modify preset- raise HTTPException(status_code=404, detail="Not yet implemented (coming soon)")--[email protected]("/{assistant_id}", response_model=DeleteAssistantResponse)-def delete_assistant(- assistant_id: str = Path(..., description="The unique identifier of the assistant."),-):- # TODO: delete preset- raise HTTPException(status_code=404, detail="Not yet implemented (coming soon)")--[email protected]("/{assistant_id}/files/{file_id}", response_model=DeleteAssistantFileResponse)-def delete_assistant_file(- assistant_id: str = Path(..., description="The unique identifier of the assistant."),- file_id: str = Path(..., description="The unique identifier of the file."),-):- # TODO: delete source on preset- raise HTTPException(status_code=404, detail="Not yet implemented (coming soon)")diff --git a/letta/server/rest_api/routers/openai/assistants/schemas.py b/letta/server/rest_api/routers/openai/assistants/schemas.pydeleted file mode 100644index 07263ff2d..000000000--- a/letta/server/rest_api/routers/openai/assistants/schemas.py+++ /dev/null@@ -1,115 +0,0 @@-from typing import List, Optional--from pydantic import BaseModel, Field--from letta.schemas.openai.openai import MessageRoleType, OpenAIMessage, OpenAIThread, ToolCall, ToolCallOutput---class CreateAssistantRequest(BaseModel):- model: str = Field(..., description="The model to use for the assistant.")- name: str = Field(..., description="The name of the assistant.")- description: str = Field(None, description="The description of the assistant.")- instructions: str = Field(..., description="The instructions for the assistant.")- tools: List[str] = Field(None, description="The tools used by the assistant.")- file_ids: List[str] = Field(None, description="List of file IDs associated with the assistant.")- metadata: dict = Field(None, description="Metadata associated with the assistant.")-- # letta-only (not openai)- embedding_model: str = Field(None, description="The model to use for the assistant.")-- ## TODO: remove- # user_id: str = Field(..., description="The unique identifier of the user.")---class CreateThreadRequest(BaseModel):- messages: Optional[List[str]] = Field(None, description="List of message IDs associated with the thread.")- metadata: Optional[dict] = Field(None, description="Metadata associated with the thread.")-- # letta-only- assistant_name: Optional[str] = Field(None, description="The name of the assistant (i.e. Letta preset)")---class ModifyThreadRequest(BaseModel):- metadata: dict = Field(None, description="Metadata associated with the thread.")---class ModifyMessageRequest(BaseModel):- metadata: dict = Field(None, description="Metadata associated with the message.")---class ModifyRunRequest(BaseModel):- metadata: dict = Field(None, description="Metadata associated with the run.")---class CreateMessageRequest(BaseModel):- role: str = Field(..., description="Role of the message sender (either 'user' or 'system')")- content: str = Field(..., description="The message content to be processed by the agent.")- file_ids: Optional[List[str]] = Field(None, description="List of file IDs associated with the message.")- metadata: Optional[dict] = Field(None, description="Metadata associated with the message.")---class UserMessageRequest(BaseModel):- user_id: str = Field(..., description="The unique identifier of the user.")- agent_id: str = Field(..., description="The unique identifier of the agent.")- message: str = Field(..., description="The message content to be processed by the agent.")- stream: bool = Field(default=False, description="Flag to determine if the response should be streamed. Set to True for streaming.")- role: MessageRoleType = Field(default=MessageRoleType.user, description="Role of the message sender (either 'user' or 'system')")---class UserMessageResponse(BaseModel):- messages: List[dict] = Field(..., description="List of messages generated by the agent in response to the received message.")---class GetAgentMessagesRequest(BaseModel):- user_id: str = Field(..., description="The unique identifier of the user.")- agent_id: str = Field(..., description="The unique identifier of the agent.")- start: int = Field(..., description="Message index to start on (reverse chronological).")- count: int = Field(..., description="How many messages to retrieve.")---class ListMessagesResponse(BaseModel):- messages: List[OpenAIMessage] = Field(..., description="List of message objects.")---class CreateAssistantFileRequest(BaseModel):- file_id: str = Field(..., description="The unique identifier of the file.")---class CreateRunRequest(BaseModel):- assistant_id: str = Field(..., description="The unique identifier of the assistant.")- model: Optional[str] = Field(None, description="The model used by the run.")- instructions: str = Field(..., description="The instructions for the run.")- additional_instructions: Optional[str] = Field(None, description="Additional instructions for the run.")- tools: Optional[List[ToolCall]] = Field(None, description="The tools used by the run (overrides assistant).")- metadata: Optional[dict] = Field(None, description="Metadata associated with the run.")---class CreateThreadRunRequest(BaseModel):- assistant_id: str = Field(..., description="The unique identifier of the assistant.")- thread: OpenAIThread = Field(..., description="The thread to run.")- model: str = Field(..., description="The model used by the run.")- instructions: str = Field(..., description="The instructions for the run.")- tools: Optional[List[ToolCall]] = Field(None, description="The tools used by the run (overrides assistant).")- metadata: Optional[dict] = Field(None, description="Metadata associated with the run.")---class DeleteAssistantResponse(BaseModel):- id: str = Field(..., description="The unique identifier of the agent.")- object: str = "assistant.deleted"- deleted: bool = Field(..., description="Whether the agent was deleted.")---class DeleteAssistantFileResponse(BaseModel):- id: str = Field(..., description="The unique identifier of the file.")- object: str = "assistant.file.deleted"- deleted: bool = Field(..., description="Whether the file was deleted.")---class DeleteThreadResponse(BaseModel):- id: str = Field(..., description="The unique identifier of the agent.")- object: str = "thread.deleted"- deleted: bool = Field(..., description="Whether the agent was deleted.")---class SubmitToolOutputsToRunRequest(BaseModel):- tools_outputs: List[ToolCallOutput] = Field(..., description="The tool outputs to submit.")diff --git a/letta/server/rest_api/routers/openai/chat_completions/__init__.py b/letta/server/rest_api/routers/openai/chat_completions/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/letta/server/rest_api/routers/openai/chat_completions/chat_completions.py b/letta/server/rest_api/routers/openai/chat_completions/chat_completions.pydeleted file mode 100644index f1485da3c..000000000--- a/letta/server/rest_api/routers/openai/chat_completions/chat_completions.py+++ /dev/null@@ -1,120 +0,0 @@-import json-from typing import TYPE_CHECKING, Optional--from fastapi import APIRouter, Body, Depends, Header, HTTPException--from letta.schemas.letta_message import LettaMessage, ToolCall-from letta.schemas.openai.chat_completion_request import ChatCompletionRequest-from letta.schemas.openai.chat_completion_response import ChatCompletionResponse, Choice, Message, UsageStatistics--# TODO this belongs in a controller!-from letta.server.rest_api.utils import get_letta_server--if TYPE_CHECKING:- pass-- from letta.server.server import SyncServer- from letta.utils import get_utc_time--router = APIRouter(prefix="/v1/chat/completions", tags=["chat_completions"])--[email protected]("/", response_model=ChatCompletionResponse)-async def create_chat_completion(- completion_request: ChatCompletionRequest = Body(...),- server: "SyncServer" = Depends(get_letta_server),- user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present-):- """Send a message to a Letta agent via a /chat/completions completion_request- The bearer token will be used to identify the user.- The 'user' field in the completion_request should be set to the agent ID.- """- actor = server.user_manager.get_user_or_default(user_id=user_id)-- agent_id = completion_request.user- if agent_id is None:- raise HTTPException(status_code=400, detail="Must pass agent_id in the 'user' field")-- messages = completion_request.messages- if messages is None:- raise HTTPException(status_code=400, detail="'messages' field must not be empty")- if len(messages) > 1:- raise HTTPException(status_code=400, detail="'messages' field must be a list of length 1")- if messages[0].role != "user":- raise HTTPException(status_code=400, detail="'messages[0].role' must be a 'user'")-- input_message = completion_request.messages[0]- if completion_request.stream:- print("Starting streaming OpenAI proxy response")-- # TODO(charles) support multimodal parts- assert isinstance(input_message.content, str)-- return await server.send_message_to_agent(- agent_id=agent_id,- actor=actor,- message=input_message.content, # TODO: This is broken- # Turn streaming ON- stream_steps=True,- stream_tokens=True,- # Turn on ChatCompletion mode (eg remaps send_message to content)- chat_completion_mode=True,- )-- else:- print("Starting non-streaming OpenAI proxy response")-- # TODO(charles) support multimodal parts- assert isinstance(input_message.content, str)-- response_messages = await server.send_message_to_agent(- agent_id=agent_id,- actor=actor,- message=input_message.content, # TODO: This is broken- # Turn streaming OFF- stream_steps=False,- stream_tokens=False,- )- # print(response_messages)-- # Concatenate all send_message outputs together- id = ""- visible_message_str = ""- created_at = None- for letta_msg in response_messages.messages:- assert isinstance(letta_msg, LettaMessage)- if isinstance(letta_msg, ToolCall):- if letta_msg.name and letta_msg.name == "send_message":- try:- letta_function_call_args = json.loads(letta_msg.arguments)- visible_message_str += letta_function_call_args["message"]- id = letta_msg.id- created_at = letta_msg.date- except:- print(f"Failed to parse Letta message: {str(letta_msg)}")- else:- print(f"Skipping function_call: {str(letta_msg)}")- else:- print(f"Skipping message: {str(letta_msg)}")-- response = ChatCompletionResponse(- id=id,- created=created_at if created_at else get_utc_time(),- choices=[- Choice(- finish_reason="stop",- index=0,- message=Message(- role="assistant",- content=visible_message_str,- ),- )- ],- # TODO add real usage- usage=UsageStatistics(- completion_tokens=0,- prompt_tokens=0,- total_tokens=0,- ),- )- return responsediff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.pyindex 4d3720ddb..988d9ede1 100644--- a/letta/server/rest_api/routers/v1/agents.py+++ b/letta/server/rest_api/routers/v1/agents.py@@ -398,7 +398,7 @@ AgentMessagesResponse = Annotated[Field(json_schema_extra={"anyOf": [- {"type": "array", "items": {"$ref": "#/components/schemas/letta__schemas__message__Message"}},+ {"type": "array", "items": {"$ref": "#/components/schemas/Message"}},{"type": "array", "items": {"$ref": "#/components/schemas/LettaMessageUnion"}},]}diff --git a/tests/test_managers.py b/tests/test_managers.pyindex 8a133852f..ad825db5a 100644--- a/tests/test_managers.py+++ b/tests/test_managers.py@@ -3,6 +3,8 @@ import timefrom datetime import datetime, timedeltaimport pytest+from openai.types.chat.chat_completion_message_tool_call import ChatCompletionMessageToolCall as OpenAIToolCall+from openai.types.chat.chat_completion_message_tool_call import Function as OpenAIFunctionfrom sqlalchemy import deletefrom sqlalchemy.exc import IntegrityError@@ -48,7 +50,6 @@ from letta.schemas.llm_config import LLMConfigfrom letta.schemas.message import Message as PydanticMessagefrom letta.schemas.message import MessageCreate, MessageUpdatefrom letta.schemas.openai.chat_completion_response import UsageStatistics-from letta.schemas.openai.chat_completions import ToolCall, ToolCallFunctionfrom letta.schemas.organization import Organization as PydanticOrganizationfrom letta.schemas.passage import Passage as PydanticPassagefrom letta.schemas.run import Run as PydanticRun@@ -2766,9 +2767,10 @@ def test_job_messages_filter(server: SyncServer, default_run, default_user, saraorganization_id=default_user.organization_id,agent_id=sarah_agent.id,tool_calls=[- ToolCall(+ OpenAIToolCall(id="call_1",- function=ToolCallFunction(+ type="function",+ function=OpenAIFunction(name="test_tool",arguments='{"arg1": "value1"}',),@@ -2818,7 +2820,9 @@ def test_get_run_messages_cursor(server: SyncServer, default_user: PydanticUser,role=MessageRole.user if i % 2 == 0 else MessageRole.assistant,text=f"Test message {i}",tool_calls=(- [{"id": f"call_{i}", "function": {"name": "custom_tool", "arguments": '{"custom_arg": "test"}'}}] if i % 2 == 1 else None+ [{"type": "function", "id": f"call_{i}", "function": {"name": "custom_tool", "arguments": '{"custom_arg": "test"}'}}]+ if i % 2 == 1+ else None),)for i in range(4)