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.

feat: include usage statistics in message response (#1482)

Sarah Woodersa8f8e7ae8156
diff --git a/memgpt/agent.py b/memgpt/agent.py
index e81fd0d04..f31f38918 100644
--- a/memgpt/agent.py
+++ b/memgpt/agent.py
@@ -770,7 +770,7 @@ class Agent(object):
self._append_to_messages(all_new_messages)
messages_to_return = [msg.to_openai_dict() for msg in all_new_messages] if return_dicts else all_new_messages
- return messages_to_return, heartbeat_request, function_failed, active_memory_warning, response.usage.completion_tokens
+ return messages_to_return, heartbeat_request, function_failed, active_memory_warning, response.usage
except Exception as e:
printd(f"step() failed\nuser_message = {user_message}\nerror = {e}")
diff --git a/memgpt/client/client.py b/memgpt/client/client.py
index 30cb4c821..ec86471f2 100644
--- a/memgpt/client/client.py
+++ b/memgpt/client/client.py
@@ -654,11 +654,11 @@ class LocalClient(AbstractClient):
# messages
def send_message(self, agent_id: uuid.UUID, message: str, role: str, stream: Optional[bool] = False) -> UserMessageResponse:
self.interface.clear()
- self.server.user_message(user_id=self.user_id, agent_id=agent_id, message=message)
+ usage = self.server.user_message(user_id=self.user_id, agent_id=agent_id, message=message)
if self.auto_save:
self.save()
else:
- return UserMessageResponse(messages=self.interface.to_list())
+ return UserMessageResponse(messages=self.interface.to_list(), usage=usage)
# agents
@@ -745,11 +745,11 @@ class LocalClient(AbstractClient):
def user_message(self, agent_id: str, message: str) -> Union[List[Dict], Tuple[List[Dict], int]]:
self.interface.clear()
- self.server.user_message(user_id=self.user_id, agent_id=agent_id, message=message)
+ usage = self.server.user_message(user_id=self.user_id, agent_id=agent_id, message=message)
if self.auto_save:
self.save()
else:
- return UserMessageResponse(messages=self.interface.to_list())
+ return UserMessageResponse(messages=self.interface.to_list(), usage=usage)
def run_command(self, agent_id: str, command: str) -> Union[str, None]:
self.interface.clear()
diff --git a/memgpt/models/chat_completion_response.py b/memgpt/models/chat_completion_response.py
index e6e3efa64..7b74ca88f 100644
--- a/memgpt/models/chat_completion_response.py
+++ b/memgpt/models/chat_completion_response.py
@@ -49,9 +49,16 @@ class Choice(BaseModel):
class UsageStatistics(BaseModel):
- completion_tokens: int
- prompt_tokens: int
- total_tokens: int
+ completion_tokens: int = 0
+ prompt_tokens: int = 0
+ total_tokens: int = 0
+
+ def __add__(self, other: "UsageStatistics") -> "UsageStatistics":
+ return UsageStatistics(
+ completion_tokens=self.completion_tokens + other.completion_tokens,
+ prompt_tokens=self.prompt_tokens + other.prompt_tokens,
+ total_tokens=self.total_tokens + other.total_tokens,
+ )
class ChatCompletionResponse(BaseModel):
diff --git a/memgpt/models/pydantic_models.py b/memgpt/models/pydantic_models.py
index 4a813a555..74558c380 100644
--- a/memgpt/models/pydantic_models.py
+++ b/memgpt/models/pydantic_models.py
@@ -13,6 +13,13 @@ from memgpt.constants import DEFAULT_HUMAN, DEFAULT_PERSONA
from memgpt.utils import get_human_text, get_persona_text, get_utc_time
+class MemGPTUsageStatistics(BaseModel):
+ completion_tokens: int
+ prompt_tokens: int
+ total_tokens: int
+ step_count: int
+
+
class LLMConfigModel(BaseModel):
model: Optional[str] = "gpt-4"
model_endpoint_type: Optional[str] = "openai"
diff --git a/memgpt/server/rest_api/agents/message.py b/memgpt/server/rest_api/agents/message.py
index d68e0b0cf..1a5e660d7 100644
--- a/memgpt/server/rest_api/agents/message.py
+++ b/memgpt/server/rest_api/agents/message.py
@@ -9,6 +9,7 @@ from fastapi import APIRouter, Body, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from starlette.responses import StreamingResponse
+from memgpt.models.pydantic_models import MemGPTUsageStatistics
from memgpt.server.rest_api.auth_token import get_current_user
from memgpt.server.rest_api.interface import QueuingInterface, StreamingServerInterface
from memgpt.server.rest_api.utils import sse_async_generator
@@ -63,6 +64,7 @@ class UserMessageRequest(BaseModel):
class UserMessageResponse(BaseModel):
messages: List[dict] = Field(..., description="List of messages generated by the agent in response to the received message.")
+ usage: MemGPTUsageStatistics = Field(..., description="Usage statistics for the completion.")
class GetAgentMessagesRequest(BaseModel):
@@ -147,7 +149,8 @@ async def send_message_to_agent(
if "data" in message and message["data"] == "[DONE]":
break
filtered_stream = [d for d in generated_stream if d not in ["[DONE_GEN]", "[DONE_STEP]", "[DONE]"]]
- return UserMessageResponse(messages=filtered_stream)
+ usage = await task
+ return UserMessageResponse(messages=filtered_stream, usage=usage)
except HTTPException:
raise
diff --git a/memgpt/server/server.py b/memgpt/server/server.py
index 1912f1cc9..09a95076b 100644
--- a/memgpt/server/server.py
+++ b/memgpt/server/server.py
@@ -38,9 +38,11 @@ from memgpt.interface import AgentInterface # abstract
from memgpt.interface import CLIInterface # for printing to terminal
from memgpt.log import get_logger
from memgpt.metadata import MetadataStore
+from memgpt.models.chat_completion_response import UsageStatistics
from memgpt.models.pydantic_models import (
DocumentModel,
HumanModel,
+ MemGPTUsageStatistics,
PassageModel,
PresetModel,
SourceModel,
@@ -356,7 +358,7 @@ 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]) -> int:
+ def _step(self, user_id: uuid.UUID, agent_id: uuid.UUID, input_message: Union[str, Message]) -> MemGPTUsageStatistics:
"""Send the input message through the agent"""
logger.debug(f"Got input message: {input_message}")
@@ -373,14 +375,18 @@ class SyncServer(LockingServer):
no_verify = True
next_input_message = input_message
counter = 0
+ total_usage = UsageStatistics()
+ step_count = 0
while True:
- new_messages, heartbeat_request, function_failed, token_warning, tokens_accumulated = memgpt_agent.step(
+ new_messages, heartbeat_request, function_failed, token_warning, usage = memgpt_agent.step(
next_input_message,
first_message=False,
skip_verify=no_verify,
return_dicts=False,
stream=token_streaming,
)
+ step_count += 1
+ total_usage += usage
counter += 1
memgpt_agent.interface.step_complete()
@@ -411,7 +417,7 @@ class SyncServer(LockingServer):
# save updated state
save_agent(memgpt_agent, self.ms)
- return tokens_accumulated
+ return MemGPTUsageStatistics(**total_usage.dict(), step_count=step_count)
def _command(self, user_id: uuid.UUID, agent_id: uuid.UUID, command: str) -> Union[str, None]:
"""Process a CLI command"""
@@ -534,7 +540,7 @@ class SyncServer(LockingServer):
agent_id: uuid.UUID,
message: Union[str, Message],
timestamp: Optional[datetime] = None,
- ) -> None:
+ ) -> MemGPTUsageStatistics:
"""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")
@@ -578,7 +584,8 @@ class SyncServer(LockingServer):
message.created_at = timestamp
# Run the agent state forward
- 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)
+ return usage
# @LockingServer.agent_lock_decorator
def system_message(
@@ -587,7 +594,7 @@ class SyncServer(LockingServer):
agent_id: uuid.UUID,
message: Union[str, Message],
timestamp: Optional[datetime] = None,
- ) -> None:
+ ) -> MemGPTUsageStatistics:
"""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")
@@ -631,10 +638,10 @@ class SyncServer(LockingServer):
message.created_at = timestamp
# Run the agent state forward
- self._step(user_id=user_id, agent_id=agent_id, input_message=packaged_system_message)
+ return self._step(user_id=user_id, agent_id=agent_id, input_message=packaged_system_message)
# @LockingServer.agent_lock_decorator
- def run_command(self, user_id: uuid.UUID, agent_id: uuid.UUID, command: str) -> Union[str, None]:
+ def run_command(self, user_id: uuid.UUID, agent_id: uuid.UUID, command: str) -> Union[MemGPTUsageStatistics, None]:
"""Run a command on the agent"""
if self.ms.get_user(user_id=user_id) is None:
raise ValueError(f"User user_id={user_id} does not exist")