Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
using uuid and datetime [LET-5508] (#5430)
Ari Webb9e94c344b8b6
diff --git a/letta/__init__.py b/letta/__init__.pyindex a40c00c88..127733d24 100644--- a/letta/__init__.py+++ b/letta/__init__.py@@ -28,8 +28,7 @@ from letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.enums import JobStatusfrom letta.schemas.file import FileMetadatafrom letta.schemas.job import Job-from letta.schemas.letta_message import LettaMessage-from letta.schemas.letta_ping import LettaPing+from letta.schemas.letta_message import LettaMessage, LettaPingfrom letta.schemas.letta_stop_reason import LettaStopReasonfrom letta.schemas.llm_config import LLMConfigfrom letta.schemas.memory import ArchivalMemorySummary, BasicBlockMemory, ChatMemory, Memory, RecallMemorySummarydiff --git a/letta/schemas/letta_message.py b/letta/schemas/letta_message.pyindex 0d104230a..de170708f 100644--- a/letta/schemas/letta_message.py+++ b/letta/schemas/letta_message.py@@ -348,6 +348,21 @@ class AssistantMessage(LettaMessage):)+class LettaPing(LettaMessage):+ """+ A ping message used as a keepalive to prevent SSE streams from timing out during long running requests.++ Args:+ id (str): The ID of the message+ date (datetime): The date the message was created in ISO format+ """++ message_type: Literal["ping"] = Field(+ "ping",+ description="The type of the message. Ping messages are a keep-alive to prevent SSE streams from timing out during long running requests.",+ )++# NOTE: use Pydantic's discriminated unions feature: https://docs.pydantic.dev/latest/concepts/unions/#discriminated-unionsLettaMessageUnion = Annotated[Union[@@ -395,6 +410,24 @@ def create_letta_message_union_schema():}+def create_letta_ping_schema():+ return {+ "properties": {+ "message_type": {+ "type": "string",+ "const": "ping",+ "title": "Message Type",+ "description": "The type of the message.",+ "default": "ping",+ }+ },+ "type": "object",+ "required": ["message_type"],+ "title": "LettaPing",+ "description": "Ping messages are a keep-alive to prevent SSE streams from timing out during long running requests.",+ }++# --------------------------# Message Update API Schemas# --------------------------diff --git a/letta/schemas/letta_ping.py b/letta/schemas/letta_ping.pydeleted file mode 100644index 05ba9c65a..000000000--- a/letta/schemas/letta_ping.py+++ /dev/null@@ -1,28 +0,0 @@-from typing import Literal--from pydantic import BaseModel, Field---def create_letta_ping_schema():- return {- "properties": {- "message_type": {- "type": "string",- "const": "ping",- "title": "Message Type",- "description": "The type of the message.",- "default": "ping",- }- },- "type": "object",- "required": ["message_type"],- "title": "LettaPing",- "description": "Ping messages are a keep-alive to prevent SSE streams from timing out during long running requests.",- }---class LettaPing(BaseModel):- message_type: Literal["ping"] = Field(- "ping",- description="The type of the message. Ping messages are a keep-alive to prevent SSE streams from timing out during long running requests.",- )diff --git a/letta/schemas/letta_stop_reason.py b/letta/schemas/letta_stop_reason.pyindex fe62d7428..d0f709153 100644--- a/letta/schemas/letta_stop_reason.py+++ b/letta/schemas/letta_stop_reason.py@@ -48,28 +48,3 @@ class LettaStopReason(BaseModel):message_type: Literal["stop_reason"] = Field("stop_reason", description="The type of the message.")stop_reason: StopReasonType = Field(..., description="The reason why execution stopped.")---def create_letta_ping_schema():- return {- "properties": {- "message_type": {- "type": "string",- "const": "ping",- "title": "Message Type",- "description": "The type of the message.",- "default": "ping",- }- },- "type": "object",- "required": ["message_type"],- "title": "LettaPing",- "description": "Ping messages are a keep-alive to prevent SSE streams from timing out during long running requests.",- }---class LettaPing(BaseModel):- message_type: Literal["ping"] = Field(- "ping",- description="The type of the message. Ping messages are a keep-alive to prevent SSE streams from timing out during long running requests.",- )diff --git a/letta/server/rest_api/app.py b/letta/server/rest_api/app.pyindex 34113bd39..4761d76a0 100644--- a/letta/server/rest_api/app.py+++ b/letta/server/rest_api/app.py@@ -42,13 +42,12 @@ from letta.helpers.pinecone_utils import get_pinecone_indices, should_use_pinecofrom letta.jobs.scheduler import start_scheduler_with_leader_electionfrom letta.log import get_loggerfrom letta.orm.errors import DatabaseTimeoutError, ForeignKeyConstraintViolationError, NoResultFound, UniqueConstraintViolationError-from letta.schemas.letta_message import create_letta_message_union_schema+from letta.schemas.letta_message import create_letta_message_union_schema, create_letta_ping_schemafrom letta.schemas.letta_message_content import (create_letta_assistant_message_content_union_schema,create_letta_message_content_union_schema,create_letta_user_message_content_union_schema,)-from letta.schemas.letta_ping import create_letta_ping_schemafrom letta.server.constants import REST_DEFAULT_PORTfrom letta.server.db import db_registrydiff --git a/letta/server/rest_api/routers/v1/runs.py b/letta/server/rest_api/routers/v1/runs.pyindex 8822722bc..4348724e0 100644--- a/letta/server/rest_api/routers/v1/runs.py+++ b/letta/server/rest_api/routers/v1/runs.py@@ -370,7 +370,7 @@ async def retrieve_stream()if request.include_pings and settings.enable_keepalive:- stream = add_keepalive_to_stream(stream, keepalive_interval=settings.keepalive_interval)+ stream = add_keepalive_to_stream(stream, keepalive_interval=settings.keepalive_interval, run_id=run_id)return StreamingResponseWithStatusCode(stream,diff --git a/letta/server/rest_api/streaming_response.py b/letta/server/rest_api/streaming_response.pyindex ee332af7f..6dab5f238 100644--- a/letta/server/rest_api/streaming_response.py+++ b/letta/server/rest_api/streaming_response.py@@ -5,6 +5,8 @@import asyncioimport jsonfrom collections.abc import AsyncIterator+from datetime import datetime, timezone+from uuid import uuid4import anyiofrom fastapi import HTTPException@@ -14,7 +16,7 @@ from starlette.types import Sendfrom letta.errors import LettaUnexpectedStreamCancellationError, PendingApprovalErrorfrom letta.log import get_loggerfrom letta.schemas.enums import RunStatus-from letta.schemas.letta_ping import LettaPing+from letta.schemas.letta_message import LettaPingfrom letta.schemas.user import Userfrom letta.server.rest_api.utils import capture_sentry_exceptionfrom letta.services.run_manager import RunManager@@ -34,6 +36,7 @@ class RunCancelledException(Exception):async def add_keepalive_to_stream(stream_generator: AsyncIterator[str | bytes],+ run_id: str,keepalive_interval: float = 30.0,) -> AsyncIterator[str | bytes]:"""@@ -83,7 +86,7 @@ async def add_keepalive_to_stream(# No data received within keepalive intervalif not stream_exhausted:# Send keepalive ping in the same format as [DONE]- yield f"data: {LettaPing().model_dump_json()}\n\n"+ yield f"data: {LettaPing(id=f'ping-{uuid4()}', date=datetime.now(timezone.utc), run_id=run_id).model_dump_json()}\n\n"else:# Stream is done but queue might be processing# Check if there's anything leftdiff --git a/letta/services/streaming_service.py b/letta/services/streaming_service.pyindex 66c03ae44..c6ea8e91b 100644--- a/letta/services/streaming_service.py+++ b/letta/services/streaming_service.py@@ -143,7 +143,7 @@ class StreamingService:# conditionally wrap with keepalive based on request parameterif request.include_pings and settings.enable_keepalive:- stream = add_keepalive_to_stream(raw_stream, keepalive_interval=settings.keepalive_interval)+ stream = add_keepalive_to_stream(raw_stream, keepalive_interval=settings.keepalive_interval, run_id=run.id)else:stream = raw_streamdiff --git a/tests/integration_test_send_message.py b/tests/integration_test_send_message.pyindex fce27cfcf..91322936e 100644--- a/tests/integration_test_send_message.py+++ b/tests/integration_test_send_message.py@@ -36,7 +36,7 @@ from letta.helpers.reasoning_helper import is_reasoning_completely_disabledfrom letta.llm_api.openai_client import is_openai_reasoning_modelfrom letta.log import get_loggerfrom letta.schemas.agent import AgentState-from letta.schemas.letta_ping import LettaPing+from letta.schemas.letta_message import LettaPingfrom letta.schemas.llm_config import LLMConfiglogger = get_logger(__name__)diff --git a/tests/integration_test_send_message_v2.py b/tests/integration_test_send_message_v2.pyindex c56daffb6..9553fbbba 100644--- a/tests/integration_test_send_message_v2.py+++ b/tests/integration_test_send_message_v2.py@@ -36,7 +36,7 @@ from letta_client.types import (from letta.log import get_loggerfrom letta.schemas.agent import AgentStatefrom letta.schemas.enums import AgentType, JobStatus-from letta.schemas.letta_ping import LettaPing+from letta.schemas.letta_message import LettaPingfrom letta.schemas.llm_config import LLMConfiglogger = get_logger(__name__)