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: use timestamp passed by request for user message created date (#1503)

Robin Goetzd6fd28b18b13
diff --git a/memgpt/agent.py b/memgpt/agent.py
index 52f70d210..1430f4fb0 100644
--- a/memgpt/agent.py
+++ b/memgpt/agent.py
@@ -549,6 +549,7 @@ class Agent(object):
return_dicts: bool = True, # if True, return dicts, if False, return Message objects
recreate_message_timestamp: bool = True, # if True, when input is a Message type, recreated the 'created_at' field
stream: bool = False, # TODO move to config?
+ timestamp: Optional[datetime] = None,
) -> Tuple[List[Union[dict, Message]], bool, bool, bool]:
"""Top-level event message handler for the MemGPT agent"""
@@ -608,6 +609,7 @@ class Agent(object):
user_id=self.agent_state.user_id,
model=self.model,
openai_message_dict={"role": "user", "content": cleaned_user_message_text, "name": name},
+ created_at=timestamp,
)
else:
diff --git a/memgpt/log.py b/memgpt/log.py
index 3b179cab4..ed2a8bab4 100644
--- a/memgpt/log.py
+++ b/memgpt/log.py
@@ -1,6 +1,5 @@
import logging
from logging.config import dictConfig
-from logging.handlers import RotatingFileHandler
from pathlib import Path
from sys import stdout
from typing import Optional
diff --git a/memgpt/server/rest_api/agents/message.py b/memgpt/server/rest_api/agents/message.py
index 1a5e660d7..776b980b0 100644
--- a/memgpt/server/rest_api/agents/message.py
+++ b/memgpt/server/rest_api/agents/message.py
@@ -91,6 +91,7 @@ async def send_message_to_agent(
stream_steps: bool,
stream_tokens: bool,
chat_completion_mode: Optional[bool] = False,
+ timestamp: Optional[datetime] = None,
) -> Union[StreamingResponse, UserMessageResponse]:
"""Split off into a separate function so that it can be imported in the /chat/completion proxy."""
@@ -133,7 +134,9 @@ async def send_message_to_agent(
# Offload the synchronous message_func to a separate thread
streaming_interface.stream_start()
- task = asyncio.create_task(asyncio.to_thread(message_func, user_id=user_id, agent_id=agent_id, message=message))
+ task = asyncio.create_task(
+ asyncio.to_thread(message_func, user_id=user_id, agent_id=agent_id, message=message, timestamp=timestamp)
+ )
if stream_steps:
# return a stream
@@ -229,6 +232,7 @@ def setup_agents_message_router(server: SyncServer, interface: QueuingInterface,
message=request.message,
stream_steps=request.stream_steps,
stream_tokens=request.stream_tokens,
+ timestamp=request.timestamp,
# legacy
stream_legacy=request.stream,
)
diff --git a/memgpt/server/rest_api/auth/index.py b/memgpt/server/rest_api/auth/index.py
index 790cd3119..0c3727a69 100644
--- a/memgpt/server/rest_api/auth/index.py
+++ b/memgpt/server/rest_api/auth/index.py
@@ -1,6 +1,6 @@
from uuid import UUID
-from fastapi import APIRouter, HTTPException
+from fastapi import APIRouter
from pydantic import BaseModel, Field
from memgpt.log import get_logger
diff --git a/memgpt/server/server.py b/memgpt/server/server.py
index 80be4230c..cc5baf504 100644
--- a/memgpt/server/server.py
+++ b/memgpt/server/server.py
@@ -363,7 +363,9 @@ class SyncServer(LockingServer):
memgpt_agent = self._load_agent(user_id=user_id, agent_id=agent_id)
return memgpt_agent
- def _step(self, user_id: uuid.UUID, agent_id: uuid.UUID, input_message: Union[str, Message]) -> MemGPTUsageStatistics:
+ def _step(
+ self, user_id: uuid.UUID, agent_id: uuid.UUID, input_message: Union[str, Message], timestamp: Optional[datetime]
+ ) -> MemGPTUsageStatistics:
"""Send the input message through the agent"""
logger.debug(f"Got input message: {input_message}")
@@ -389,6 +391,7 @@ class SyncServer(LockingServer):
skip_verify=no_verify,
return_dicts=False,
stream=token_streaming,
+ timestamp=timestamp,
)
step_count += 1
total_usage += usage
@@ -560,7 +563,10 @@ class SyncServer(LockingServer):
elif message.startswith("/"):
raise ValueError(f"Invalid input: '{message}'")
- packaged_user_message = system.package_user_message(user_message=message)
+ packaged_user_message = system.package_user_message(
+ user_message=message,
+ time=timestamp.isoformat() if timestamp else None,
+ )
# NOTE: eventually deprecate and only allow passing Message types
# Convert to a Message object
@@ -569,9 +575,11 @@ class SyncServer(LockingServer):
agent_id=agent_id,
role="user",
text=packaged_user_message,
+ created_at=timestamp,
# name=None, # TODO handle name via API
)
+ # TODO: I don't think this does anything because all we care about is packaged_user_message which only exists if message is str
if isinstance(message, Message):
# Can't have a null text field
if len(message.text) == 0 or message.text is None:
@@ -580,15 +588,15 @@ class SyncServer(LockingServer):
elif message.text.startswith("/"):
raise ValueError(f"Invalid input: '{message.text}'")
+ if timestamp:
+ # Override the timestamp with what the caller provided
+ message.created_at = timestamp
+
else:
raise TypeError(f"Invalid input: '{message}' - type {type(message)}")
- if timestamp:
- # Override the timestamp with what the caller provided
- message.created_at = timestamp
-
# Run the agent state forward
- usage = self._step(user_id=user_id, agent_id=agent_id, input_message=packaged_user_message)
+ usage = self._step(user_id=user_id, agent_id=agent_id, input_message=packaged_user_message, timestamp=timestamp)
return usage
# @LockingServer.agent_lock_decorator
diff --git a/memgpt/system.py b/memgpt/system.py
index f6640198d..97d3b199c 100644
--- a/memgpt/system.py
+++ b/memgpt/system.py
@@ -1,5 +1,6 @@
import json
import uuid
+from typing import Optional
from .constants import (
INITIAL_BOOT_MESSAGE,
@@ -115,7 +116,13 @@ def get_login_event(last_login="Never (first login)", include_location=False, lo
return json.dumps(packaged_message, ensure_ascii=JSON_ENSURE_ASCII)
-def package_user_message(user_message, time=None, include_location=False, location_name="San Francisco, CA, USA", name=None):
+def package_user_message(
+ user_message: str,
+ time: Optional[str] = None,
+ include_location: bool = False,
+ location_name: Optional[str] = "San Francisco, CA, USA",
+ name: Optional[str] = None,
+):
# Package the message with time and location
formatted_time = time if time else get_local_time()
packaged_message = {