Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

fix: Fix broken message DB writing (#1134)

Matthew Zhoueed05716ac42
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.py
index 428dbbd92..3ba586045 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
@@ -38,7 +38,8 @@ from letta.server.rest_api.optimistic_json_parser import OptimisticJSONParser
# TODO this belongs in a controller!
from letta.server.rest_api.utils import (
convert_letta_messages_to_openai,
- create_assistant_message_from_openai_response,
+ create_assistant_messages_from_openai_response,
+ create_tool_call_messages_from_openai_response,
create_user_message,
get_letta_server,
get_messages_from_completion_request,
@@ -226,10 +227,10 @@ async def create_fast_chat_completions(
conversation.append({"role": "assistant", "content": content})
# Create an assistant message here to persist later
- assistant_message = create_assistant_message_from_openai_response(
+ assistant_messages = create_assistant_messages_from_openai_response(
response_text=content, agent_id=agent_id, model=agent_state.llm_config.model, actor=actor
)
- message_db_queue.append(assistant_message)
+ message_db_queue.extend(assistant_messages)
if tool_call_happened:
# Parse the tool call arguments
@@ -267,8 +268,10 @@ async def create_fast_chat_completions(
actor=actor,
allow_agent_state_modifications=False,
)
+ function_call_success = True
except Exception as e:
tool_result = f"Failed to call tool. Error: {e}"
+ function_call_success = False
# 3) Insert the "tool" message referencing the same tool_call_id
tool_message = ToolMessage(content=json.dumps({"result": tool_result}), tool_call_id=tool_call_id)
@@ -284,10 +287,23 @@ async def create_fast_chat_completions(
# Now, re-invoke OpenAI with the updated conversation
openai_request.messages = conversation
+ # Create a tool call message and append to message_db_queue
+ tool_call_messages = create_tool_call_messages_from_openai_response(
+ agent_id=agent_state.id,
+ model=agent_state.llm_config.model,
+ function_name=tool_call_name,
+ function_arguments=tool_args,
+ tool_call_id=tool_call_id,
+ function_call_success=function_call_success,
+ function_response=tool_result,
+ actor=actor,
+ add_heartbeat_request_system_message=True,
+ )
+ message_db_queue.extend(tool_call_messages)
+
continue # Start the while loop again
if finish_reason_stop:
- # Model is done, no more calls
break
# If we reach here, no tool call, no "stop", but we've ended streaming
diff --git a/letta/server/rest_api/utils.py b/letta/server/rest_api/utils.py
index 8008d056d..104318fdf 100644
--- a/letta/server/rest_api/utils.py
+++ b/letta/server/rest_api/utils.py
@@ -3,7 +3,6 @@ import json
import os
import uuid
import warnings
-from datetime import datetime, timezone
from enum import Enum
from typing import TYPE_CHECKING, AsyncGenerator, Dict, Iterable, List, Optional, Union, cast
@@ -14,8 +13,9 @@ from openai.types.chat.chat_completion_message_tool_call import Function as Open
from openai.types.chat.completion_create_params import CompletionCreateParams
from pydantic import BaseModel
-from letta.constants import DEFAULT_MESSAGE_TOOL, DEFAULT_MESSAGE_TOOL_KWARG
+from letta.constants import DEFAULT_MESSAGE_TOOL, DEFAULT_MESSAGE_TOOL_KWARG, REQ_HEARTBEAT_MESSAGE
from letta.errors import ContextWindowExceededError, RateLimitExceededError
+from letta.helpers.datetime_helpers import get_utc_time
from letta.log import get_logger
from letta.schemas.enums import MessageRole
from letta.schemas.letta_message import TextContent
@@ -23,6 +23,7 @@ from letta.schemas.message import Message
from letta.schemas.usage import LettaUsageStatistics
from letta.schemas.user import User
from letta.server.rest_api.interface import StreamingServerInterface
+from letta.system import get_heartbeat, package_function_response
if TYPE_CHECKING:
from letta.server.server import SyncServer
@@ -144,7 +145,8 @@ def create_user_message(input_message: dict, agent_id: str, actor: User) -> Mess
Converts a user input message into the internal structured format.
"""
# Generate timestamp in the correct format
- now = datetime.now(timezone.utc).isoformat()
+ # Skip pytz for performance reasons
+ now = get_utc_time().isoformat()
# Format message as structured JSON
structured_message = {"type": "user_message", "message": input_message["content"], "time": now}
@@ -159,37 +161,36 @@ def create_user_message(input_message: dict, agent_id: str, actor: User) -> Mess
model=None,
tool_calls=None,
tool_call_id=None,
- created_at=datetime.now(timezone.utc),
+ created_at=get_utc_time(),
)
return user_message
-def create_assistant_message_from_openai_response(
- response_text: str,
+def create_tool_call_messages_from_openai_response(
agent_id: str,
model: str,
+ function_name: str,
+ function_arguments: Dict,
+ tool_call_id: str,
+ function_call_success: bool,
+ function_response: Optional[str],
actor: User,
-) -> Message:
- """
- Converts an OpenAI response into a Message that follows the internal
- paradigm where LLM responses are structured as tool calls instead of content.
- """
- tool_call_id = str(uuid.uuid4())
+ add_heartbeat_request_system_message: bool = False,
+) -> List[Message]:
+ messages = []
# Construct the tool call with the assistant's message
+ function_arguments["request_heartbeat"] = True
tool_call = OpenAIToolCall(
id=tool_call_id,
function=OpenAIFunction(
- name=DEFAULT_MESSAGE_TOOL,
- arguments='{\n "' + DEFAULT_MESSAGE_TOOL_KWARG + '": ' + f'"{response_text}",\n "request_heartbeat": true\n' + "}",
+ name=function_name,
+ arguments=json.dumps(function_arguments),
),
type="function",
)
-
- # Construct the Message object
assistant_message = Message(
- id=f"message-{uuid.uuid4()}",
role=MessageRole.assistant,
content=[],
organization_id=actor.organization_id,
@@ -197,10 +198,62 @@ def create_assistant_message_from_openai_response(
model=model,
tool_calls=[tool_call],
tool_call_id=tool_call_id,
- created_at=datetime.now(timezone.utc),
+ created_at=get_utc_time(),
)
+ messages.append(assistant_message)
+
+ tool_message = Message(
+ role=MessageRole.tool,
+ content=[TextContent(text=package_function_response(function_call_success, function_response))],
+ organization_id=actor.organization_id,
+ agent_id=agent_id,
+ model=model,
+ tool_calls=[],
+ tool_call_id=tool_call_id,
+ created_at=get_utc_time(),
+ name=function_name,
+ )
+ messages.append(tool_message)
+
+ if add_heartbeat_request_system_message:
+ heartbeat_system_message = Message(
+ role=MessageRole.user,
+ content=[TextContent(text=get_heartbeat(REQ_HEARTBEAT_MESSAGE))],
+ organization_id=actor.organization_id,
+ agent_id=agent_id,
+ model=model,
+ tool_calls=[],
+ tool_call_id=None,
+ created_at=get_utc_time(),
+ )
+ messages.append(heartbeat_system_message)
+
+ return messages
+
- return assistant_message
+def create_assistant_messages_from_openai_response(
+ response_text: str,
+ agent_id: str,
+ model: str,
+ actor: User,
+) -> List[Message]:
+ """
+ Converts an OpenAI response into Messages that follow the internal
+ paradigm where LLM responses are structured as tool calls instead of content.
+ """
+ tool_call_id = str(uuid.uuid4())
+
+ return create_tool_call_messages_from_openai_response(
+ agent_id=agent_id,
+ model=model,
+ function_name=DEFAULT_MESSAGE_TOOL,
+ function_arguments={DEFAULT_MESSAGE_TOOL_KWARG: response_text}, # Avoid raw string manipulation
+ tool_call_id=tool_call_id,
+ function_call_success=True,
+ function_response=None,
+ actor=actor,
+ add_heartbeat_request_system_message=False,
+ )
def convert_letta_messages_to_openai(messages: List[Message]) -> List[dict]:
diff --git a/tests/integration_test_chat_completions.py b/tests/integration_test_chat_completions.py
index 4b501de33..0dfea79e7 100644
--- a/tests/integration_test_chat_completions.py
+++ b/tests/integration_test_chat_completions.py
@@ -153,20 +153,7 @@ def _assert_valid_chunk(chunk, idx, chunks):
# --- Test Cases --- #
[email protected]("message", ["What's the weather in SF?"])
[email protected]("endpoint", ["fast/chat/completions"])
-def test_tool_usage_fast_chat_completions(mock_e2b_api_key_none, client, agent, message, endpoint):
- """Tests chat completion streaming via SSE."""
- request = _get_chat_request(agent.id, message)
-
- response = _sse_post(f"{client.base_url}/openai/{client.api_prefix}/{endpoint}", request.model_dump(exclude_none=True), client.headers)
-
- for chunk in response:
- if isinstance(chunk, ChatCompletionChunk) and chunk.choices:
- print(chunk.choices[0].delta.content)
-
-
[email protected]("message", ["Tell me something interesting about bananas."])
[email protected]("message", ["Tell me something interesting about bananas.", "What's the weather in SF?"])
@pytest.mark.parametrize("endpoint", ["chat/completions", "fast/chat/completions"])
def test_chat_completions_streaming(mock_e2b_api_key_none, client, agent, message, endpoint):
"""Tests chat completion streaming via SSE."""
@@ -185,14 +172,18 @@ def test_chat_completions_streaming(mock_e2b_api_key_none, client, agent, messag
except Exception as e:
pytest.fail(f"Streaming failed with exception: {e}")
+ # Test that we can still follow up and send a message
+ client.user_message(agent_id=agent.id, message="So what should I wear today?")
+
@pytest.mark.asyncio
[email protected]("message", ["Tell me something interesting about bananas.", "Roll a dice!"])
-async def test_chat_completions_streaming_async(client, agent, message):
[email protected]("message", ["Tell me something interesting about bananas.", "What's the weather in SF?"])
[email protected]("endpoint", ["", "fast"])
+async def test_chat_completions_streaming_async(mock_e2b_api_key_none, client, agent, message, endpoint):
"""Tests chat completion streaming using the Async OpenAI client."""
request = _get_chat_request(agent.id, message)
- async_client = AsyncOpenAI(base_url=f"{client.base_url}/openai/{client.api_prefix}", max_retries=0)
+ async_client = AsyncOpenAI(base_url=f"{client.base_url}/openai/{client.api_prefix}/{endpoint}", max_retries=0)
stream = await async_client.chat.completions.create(**request.model_dump(exclude_none=True))
received_chunks = 0
@@ -226,4 +217,3 @@ async def test_chat_completions_streaming_async(client, agent, message):
# Ensure the last chunk is the expected stop chunk
assert last_chunk is not None, "No last chunk received."
- assert last_chunk.choices[0].finish_reason == "stop", f"Last chunk did not indicate stop: {last_chunk.model_dump_json(indent=4)}"