Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: Allow timestamp in `send_message` POST (#1161)
Charles Packerb6864e0e2b90
diff --git a/memgpt/server/rest_api/agents/message.py b/memgpt/server/rest_api/agents/message.pyindex 7b514eda3..4455d9e6c 100644--- a/memgpt/server/rest_api/agents/message.py+++ b/memgpt/server/rest_api/agents/message.py@@ -1,6 +1,7 @@import asyncioimport jsonimport uuid+from datetime import datetimefrom asyncio import AbstractEventLoopfrom enum import Enumfrom functools import partial@@ -27,6 +28,10 @@ class UserMessageRequest(BaseModel):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')")+ timestamp: Optional[datetime] = Field(+ None,+ description="Timestamp to tag the message with (in ISO format). If null, timestamp will be created server-side on receipt of message.",+ )class UserMessageResponse(BaseModel):@@ -116,7 +121,14 @@ def setup_agents_message_router(server: SyncServer, interface: QueuingInterface,# Check if server.user_message is an async functionif asyncio.iscoroutinefunction(message_func):# Start the async task- await asyncio.create_task(message_func(user_id=user_id, agent_id=agent_id, message=request.message))+ await asyncio.create_task(+ message_func(+ user_id=user_id,+ agent_id=agent_id,+ message=request.message,+ timestamp=request.timestamp,+ )+ )else:def handle_exception(exception_loop: AbstractEventLoop, context):@@ -128,7 +140,14 @@ def setup_agents_message_router(server: SyncServer, interface: QueuingInterface,# Run the synchronous function in a thread poolloop = asyncio.get_event_loop()loop.set_exception_handler(handle_exception)- loop.run_in_executor(None, message_func, user_id, agent_id, request.message)+ loop.run_in_executor(+ None,+ message_func,+ user_id,+ agent_id,+ request.message,+ request.timestamp,+ )async def formatted_message_generator():async for message in interface.message_generator():diff --git a/memgpt/server/server.py b/memgpt/server/server.pyindex af92d4c94..4a2dd3f3e 100644--- a/memgpt/server/server.py+++ b/memgpt/server/server.py@@ -3,6 +3,7 @@ import subprocessimport loggingimport uuidfrom abc import abstractmethod+from datetime import datetimefrom functools import wrapsfrom threading import Lockfrom typing import Union, Callable, Optional, List@@ -486,7 +487,9 @@ class SyncServer(LockingServer):self._step(user_id=user_id, agent_id=agent_id, input_message=input_message)@LockingServer.agent_lock_decorator- def user_message(self, user_id: uuid.UUID, agent_id: uuid.UUID, message: Union[str, Message]) -> None:+ def user_message(+ self, user_id: uuid.UUID, agent_id: uuid.UUID, message: Union[str, Message], timestamp: Optional[datetime] = None+ ) -> None:"""Process an incoming user message and feed it through the MemGPT agent"""if self.ms.get_user(user_id=user_id) is None:raise ValueError(f"User user_id={user_id} does not exist")@@ -501,23 +504,41 @@ class SyncServer(LockingServer):# If the input begins with a command prefix, rejectelif message.startswith("/"):raise ValueError(f"Invalid input: '{message}'")+packaged_user_message = system.package_user_message(user_message=message)- elif isinstance(message, Message):- if len(message.text) == 0:- raise ValueError(f"Invalid input: '{message.text}'")+ # NOTE: eventually deprecate and only allow passing Message types+ # Convert to a Message object+ message = Message(+ user_id=user_id,+ agent_id=agent_id,+ role="user",+ text=packaged_user_message,+ # name=None, # TODO handle name via API+ )++ if isinstance(message, Message):+ # Can't have a null text field+ if len(message.text) == 0 or message.text is None:+ raise ValueError(f"Invalid input: '{message.text}'")# If the input begins with a command prefix, rejectelif message.text.startswith("/"):raise ValueError(f"Invalid input: '{message.text}'")- packaged_user_message = message+else:- raise ValueError(f"Invalid input: '{message}'")+ 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 forwardself._step(user_id=user_id, agent_id=agent_id, input_message=packaged_user_message)@LockingServer.agent_lock_decorator- def system_message(self, user_id: uuid.UUID, agent_id: uuid.UUID, message: str) -> None:+ def system_message(+ self, user_id: uuid.UUID, agent_id: uuid.UUID, message: Union[str, Message], timestamp: Optional[datetime] = None+ ) -> None:"""Process an incoming system message and feed it through the MemGPT agent"""if self.ms.get_user(user_id=user_id) is None:raise ValueError(f"User user_id={user_id} does not exist")@@ -525,19 +546,43 @@ class SyncServer(LockingServer):raise ValueError(f"Agent agent_id={agent_id} does not exist")# Basic input sanitization- if not isinstance(message, str) or len(message) == 0:- raise ValueError(f"Invalid input: '{message}'")+ if isinstance(message, str):+ if len(message) == 0:+ raise ValueError(f"Invalid input: '{message}'")- # If the input begins with a command prefix, reject- elif message.startswith("/"):- raise ValueError(f"Invalid input: '{message}'")+ # If the input begins with a command prefix, reject+ elif message.startswith("/"):+ raise ValueError(f"Invalid input: '{message}'")- # Else, process it as a user message to be fed to the agent- else:- # Package the user message firstpackaged_system_message = system.package_system_message(system_message=message)- # Run the agent state forward- self._step(user_id=user_id, agent_id=agent_id, input_message=packaged_system_message)++ # NOTE: eventually deprecate and only allow passing Message types+ # Convert to a Message object+ message = Message(+ user_id=user_id,+ agent_id=agent_id,+ role="user",+ text=packaged_system_message,+ # name=None, # TODO handle name via API+ )++ if isinstance(message, Message):+ # Can't have a null text field+ if len(message.text) == 0 or message.text is None:+ raise ValueError(f"Invalid input: '{message.text}'")+ # If the input begins with a command prefix, reject+ elif message.text.startswith("/"):+ raise ValueError(f"Invalid input: '{message.text}'")++ 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+ self._step(user_id=user_id, agent_id=agent_id, input_message=packaged_system_message)@LockingServer.agent_lock_decoratordef run_command(self, user_id: uuid.UUID, agent_id: uuid.UUID, command: str) -> Union[str, None]: