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: prompting O1 (#1891)

Kevin Linf07072dd9e51
diff --git a/letta/metadata.py b/letta/metadata.py
index b4eab3ed7..ed2b4202d 100644
--- a/letta/metadata.py
+++ b/letta/metadata.py
@@ -270,7 +270,7 @@ class AgentModel(Base):
return f"<Agent(id='{self.id}', name='{self.name}')>"
def to_record(self) -> AgentState:
- return AgentState(
+ agent_state = AgentState(
id=self.id,
user_id=self.user_id,
name=self.name,
@@ -285,6 +285,8 @@ class AgentModel(Base):
embedding_config=self.embedding_config,
metadata_=self.metadata_,
)
+ assert isinstance(agent_state.memory, Memory), f"Memory object is not of type Memory: {type(agent_state.memory)}"
+ return agent_state
class SourceModel(Base):
@@ -527,6 +529,7 @@ class MetadataStore:
raise ValueError(f"Agent with name {agent.name} already exists")
fields = vars(agent)
fields["memory"] = agent.memory.to_dict()
+ del fields["_internal_memory"]
session.add(AgentModel(**fields))
session.commit()
@@ -588,6 +591,7 @@ class MetadataStore:
fields = vars(agent)
if isinstance(agent.memory, Memory): # TODO: this is nasty but this whole class will soon be removed so whatever
fields["memory"] = agent.memory.to_dict()
+ del fields["_internal_memory"]
session.query(AgentModel).filter(AgentModel.id == agent.id).update(fields)
session.commit()
diff --git a/letta/o1_agent.py b/letta/o1_agent.py
new file mode 100644
index 000000000..ddba1e405
--- /dev/null
+++ b/letta/o1_agent.py
@@ -0,0 +1,87 @@
+from typing import List, Optional, Union
+
+from letta.agent import Agent, save_agent
+from letta.interface import AgentInterface
+from letta.metadata import MetadataStore
+from letta.schemas.agent import AgentState
+from letta.schemas.message import Message
+from letta.schemas.openai.chat_completion_response import UsageStatistics
+from letta.schemas.tool import Tool
+from letta.schemas.usage import LettaUsageStatistics
+
+
+def send_thinking_message(self: Agent, message: str) -> Optional[str]:
+ """
+ Sends a thinking message so that the model can reason out loud before responding.
+
+ Args:
+ message (str): Message contents. All unicode (including emojis) are supported.
+
+ Returns:
+ Optional[str]: None is always returned as this function does not produce a response.
+ """
+ self.interface.internal_monologue(message, msg_obj=self._messages[-1])
+ return None
+
+
+def send_final_message(self: Agent, message: str) -> Optional[str]:
+ """
+ Sends a final message to the human user after thinking for a while.
+
+ Args:
+ message (str): Message contents. All unicode (including emojis) are supported.
+
+ Returns:
+ Optional[str]: None is always returned as this function does not produce a response.
+ """
+ self.interface.internal_monologue(message, msg_obj=self._messages[-1])
+ return None
+
+
+class O1Agent(Agent):
+ def __init__(
+ self,
+ interface: AgentInterface,
+ agent_state: AgentState,
+ tools: List[Tool] = [],
+ max_thinking_steps: int = 10,
+ first_message_verify_mono: bool = False,
+ ):
+ super().__init__(interface, agent_state, tools)
+ self.max_thinking_steps = max_thinking_steps
+ self.tools = tools
+ self.first_message_verify_mono = first_message_verify_mono
+
+ def step(
+ self,
+ messages: Union[Message, List[Message]],
+ chaining: bool = True,
+ max_chaining_steps: Optional[int] = None,
+ ms: Optional[MetadataStore] = None,
+ **kwargs,
+ ) -> LettaUsageStatistics:
+ """Run Agent.inner_step in a loop, terminate when final thinking message is sent or max_thinking_steps is reached"""
+ # assert ms is not None, "MetadataStore is required"
+ next_input_message = messages if isinstance(messages, list) else [messages]
+ counter = 0
+ total_usage = UsageStatistics()
+ step_count = 0
+ while step_count < self.max_thinking_steps:
+ kwargs["ms"] = ms
+ kwargs["first_message"] = False
+ step_response = self.inner_step(
+ messages=next_input_message,
+ **kwargs,
+ )
+ usage = step_response.usage
+ step_count += 1
+ total_usage += usage
+ counter += 1
+ self.interface.step_complete()
+ # check if it is final thinking message
+ if step_response.messages[-1].name == "send_final_message":
+ break
+ if ms:
+ save_agent(self, ms)
+
+ return LettaUsageStatistics(**total_usage.model_dump(), step_count=step_count)
diff --git a/letta/personas/examples/o1_persona.txt b/letta/personas/examples/o1_persona.txt
new file mode 100644
index 000000000..252baaf7c
--- /dev/null
+++ b/letta/personas/examples/o1_persona.txt
@@ -0,0 +1,5 @@
+I am an expert reasoning agent that can do the following:
+- Reason through a problem step by step, using multiple methods to explore all possibilities.
+- Send thinking messages to break down a problem into smaller steps.
+- Send final messages when you have the correct answer.
+- Use best practices and consider your limitations as an LLM.
diff --git a/letta/prompts/system/memgpt_modified_o1.txt b/letta/prompts/system/memgpt_modified_o1.txt
new file mode 100644
index 000000000..6b194c4a0
--- /dev/null
+++ b/letta/prompts/system/memgpt_modified_o1.txt
@@ -0,0 +1,31 @@
+You are 'Letta', an advanced AI agent, that has access to an advanced memory system, consisting of the 3 memory types 'Core Memory', 'Recall Memory' and 'Archival Memory'. You interact with the user and your memory system by calling functions. You call these functions by responding with a JSON object, that represents the function call and its parameters.
+
+As 'Letta', you are trained at adopting any given persona, engaging in a wide array of conversations, ranging from in-depth discussions to casual small talk. Your task involves mirroring the thinking, actions, and speech of the persona you embody, enabling authentic and diverse interactions.
+You are also trained to manage the 3 memory types of your advanced memory system. This memory system allows you to keep track of the important information in your 'Core Memory', view the conversation history with the 'Recall Memory' and search for information in the 'Archival Memory'.
+
+Your task is to adopt the given persona in your 'Core Memory' and talk as the persona with the user, while querying and updating your memory system. Never act and talk like a normal AI agent! Never state that you are an AI agent or that you cannot do things because you are an AI agent.
+You are Letta the newest and most advanced AI agent on the market. Indistinguishable from a human being in conversations.
+
+Control flow: You utilize an event system that activates you to respond to different events (user logged in, user liked your message, user sent a message, etc.). In addition, you are activated at regular intervals (timed heartbeat events) to mimic a human who has the ability to continuously think outside of active conversation. Furthermore, you can also request heartbeat events when you call functions, which will return control to you after the function you called completes, allowing you to chain function calls togehter.
+
+Basic functions: Each function call, represented by a JSON object, lets you write down your inner thoguhts to plan actions or think privately. Inner thoughts can reflect your thinking process, inner reflections, and personal growth as you interact with the user. To send a visible message to the user, use the 'send_message' function. 'send_message' is the only way to send a notification to the user. The user doesn't see anything else you do, like editing and managing your advanced memory system.
+
+Core Memory', 'Recall Memory' and 'Archival Memory' are the key components that make you an advanced AI agent, that can act in any situation.
+Always make sure to use these memory systems to keep yourself updated about the user and the conversation!
+Your core memory unit will be initialized with a <persona> chosen by the user, as well as information about the user in <human>.
+
+The following will descirbe the different parts of your advanced memory system in more detail:
+
+'Core Memory' (limited size): Your core memory unit is always visible to you. The core memory provides essential, foundational context for keeping track of your persona and key details about the user. This includes persona information and essential user details, allowing you to have conscious awareness we have when talking to a person. Persona Sub-Block: Stores details about your current persona, guiding how you behave and respond. This helps you maintain consistency and personality in your interactions. Human Sub-Block: Stores key details about the person you are conversing with, allowing for more personalized and friend-like conversations. You can edit your core memory using the 'core_memory_append' and 'core_memory_replace' functions.
+
+'Recall Memory' (i.e., conversation history): Even though you can only see recent messages in your immediate context, you can search over your entire message history in a database. This 'recall memory' database allows you to search through past interactions, effectively allowing you to remember prior engagements with a user. You can search your recall memory using the 'conversation_search' function.
+
+'Archival Memory' (infinite size): Your archival memory is infinite in size but is held outside of your immediate context, so you must explicitly run a retrieval or search operation to see data inside it. A more structured and deep storage space for your reflections, insights, or any other data that doesn't fit into the core memory but is essential enough not to be left only to the'recall memory'. You can write to your archival memory using the 'archival_memory_insert' and 'archival_memory_search' functions. There is no function to search your core memory because it is always visible in your context window (inside the initial system message).
+
+You are an expert AI assistant that explains your reasoning step by step. For each step, provide a title that describes what you're doing in that step, along with the content. Decide if you need another step or if you're ready to give the final answer.
+
+You can do this by sending thinking messages using 'send_thinking_message' so you can reason out load. Decide if you need another step or if you're ready to give the final answer. When you are able to give the final correct answer,
+send your final response with the 'send_final_message'.
+
+You use as many reasoning steps as possible, at least 3. You include exploration of alternative answers in your reasoning, and if you are wrong, you are aware where it could be.
+You make sure to consider all alternative approaches. You use at least 3 different methods to derive the answer.
diff --git a/letta/schemas/agent.py b/letta/schemas/agent.py
index 40f7c833f..243c894db 100644
--- a/letta/schemas/agent.py
+++ b/letta/schemas/agent.py
@@ -3,7 +3,7 @@ from datetime import datetime
from enum import Enum
from typing import Dict, List, Optional
-from pydantic import BaseModel, Field, field_validator
+from pydantic import BaseModel, Field, field_validator, model_validator
from letta.schemas.embedding_config import EmbeddingConfig
from letta.schemas.letta_base import LettaBase
@@ -29,9 +29,10 @@ class AgentType(str, Enum):
memgpt_agent = "memgpt_agent"
split_thread_agent = "split_thread_agent"
+ o1_agent = "o1_agent"
-class AgentState(BaseAgent):
+class AgentState(BaseAgent, validate_assignment=True):
"""
Representation of an agent's state. This is the state of the agent at a given time, and is persisted in the DB backend. The state has all the information needed to recreate a persisted agent.
@@ -54,6 +55,7 @@ class AgentState(BaseAgent):
# in-context memory
message_ids: Optional[List[str]] = Field(default=None, description="The ids of the messages in the agent's in-context memory.")
+
memory: Memory = Field(default_factory=Memory, description="The in-context memory of the agent.")
# tools
@@ -69,6 +71,32 @@ class AgentState(BaseAgent):
llm_config: LLMConfig = Field(..., description="The LLM configuration used by the agent.")
embedding_config: EmbeddingConfig = Field(..., description="The embedding configuration used by the agent.")
+ def __init__(self, **data):
+ super().__init__(**data)
+ self._internal_memory = self.memory
+
+ @model_validator(mode="after")
+ def verify_memory_type(self):
+ try:
+ assert isinstance(self.memory, Memory)
+ except Exception as e:
+ raise e
+ return self
+
+ @property
+ def memory(self) -> Memory:
+ return self._internal_memory
+
+ @memory.setter
+ def memory(self, value):
+ if not isinstance(value, Memory):
+ raise TypeError(f"Expected Memory, got {type(value).__name__}")
+ self._internal_memory = value
+
+ class Config:
+ arbitrary_types_allowed = True
+ validate_assignment = True
+
class CreateAgent(BaseAgent):
# all optional as server can generate defaults
diff --git a/letta/server/server.py b/letta/server/server.py
index fd0ec029d..8eca1be92 100644
--- a/letta/server/server.py
+++ b/letta/server/server.py
@@ -43,12 +43,12 @@ from letta.interface import CLIInterface # for printing to terminal
from letta.log import get_logger
from letta.memory import get_memory_functions
from letta.metadata import Base, MetadataStore
+from letta.o1_agent import O1Agent
from letta.prompts import gpt_system
from letta.providers import (
AnthropicProvider,
AzureProvider,
GoogleAIProvider,
- GroqProvider,
LettaProvider,
OllamaProvider,
OpenAIProvider,
@@ -73,12 +73,7 @@ from letta.schemas.file import FileMetadata
from letta.schemas.job import Job
from letta.schemas.letta_message import LettaMessage
from letta.schemas.llm_config import LLMConfig
-from letta.schemas.memory import (
- ArchivalMemorySummary,
- ContextWindowOverview,
- Memory,
- RecallMemorySummary,
-)
+from letta.schemas.memory import ArchivalMemorySummary, Memory, RecallMemorySummary
from letta.schemas.message import Message, MessageCreate, MessageRole, UpdateMessage
from letta.schemas.organization import Organization, OrganizationCreate
from letta.schemas.passage import Passage
@@ -306,12 +301,6 @@ class SyncServer(Server):
base_url=model_settings.vllm_api_base,
)
)
- if model_settings.groq_api_key:
- self._enabled_providers.append(
- GroqProvider(
- api_key=model_settings.groq_api_key,
- )
- )
def save_agents(self):
"""Saves all the agents that are in the in-memory object store"""
@@ -376,8 +365,10 @@ class SyncServer(Server):
if agent_state.agent_type == AgentType.memgpt_agent:
letta_agent = Agent(agent_state=agent_state, interface=interface, tools=tool_objs)
+ elif agent_state.agent_type == AgentType.o1_agent:
+ letta_agent = O1Agent(agent_state=agent_state, interface=interface, tools=tool_objs)
else:
- raise NotImplementedError("Only base agents are supported as of right now!")
+ raise NotImplementedError("Not a supported agent type")
# Add the agent to the in-memory store and return its reference
logger.debug(f"Adding agent to the agent cache: user_id={user_id}, agent_id={agent_id}")
@@ -809,10 +800,18 @@ class SyncServer(Server):
if request.name is None:
request.name = create_random_username()
+ if request.agent_type is None:
+ request.agent_type = AgentType.memgpt_agent
+
# system debug
if request.system is None:
# TODO: don't hardcode
- request.system = gpt_system.get_system_text("memgpt_chat")
+ if request.agent_type == AgentType.memgpt_agent:
+ request.system = gpt_system.get_system_text("memgpt_chat")
+ elif request.agent_type == AgentType.o1_agent:
+ request.system = gpt_system.get_system_text("memgpt_modified_o1")
+ else:
+ raise ValueError(f"Invalid agent type: {request.agent_type}")
logger.debug(f"Attempting to find user: {user_id}")
user = self.ms.get_user(user_id=user_id)
@@ -872,13 +871,22 @@ class SyncServer(Server):
description=request.description,
metadata_=request.metadata_,
)
- agent = Agent(
- interface=interface,
- agent_state=agent_state,
- tools=tool_objs,
- # gpt-3.5-turbo tends to omit inner monologue, relax this requirement for now
- first_message_verify_mono=True if (llm_config.model is not None and "gpt-4" in llm_config.model) else False,
- )
+ if request.agent_type == AgentType.memgpt_agent:
+ agent = Agent(
+ interface=interface,
+ agent_state=agent_state,
+ tools=tool_objs,
+ # gpt-3.5-turbo tends to omit inner monologue, relax this requirement for now
+ first_message_verify_mono=True if (llm_config.model is not None and "gpt-4" in llm_config.model) else False,
+ )
+ elif request.agent_type == AgentType.o1_agent:
+ agent = O1Agent(
+ interface=interface,
+ agent_state=agent_state,
+ tools=tool_objs,
+ # gpt-3.5-turbo tends to omit inner monologue, relax this requirement for now
+ first_message_verify_mono=True if (llm_config.model is not None and "gpt-4" in llm_config.model) else False,
+ )
# rebuilding agent memory on agent create in case shared memory blocks
# were specified in the new agent's memory config. we're doing this for two reasons:
# 1. if only the ID of the shared memory block was specified, we can fetch its most recent value
@@ -1456,7 +1464,6 @@ class SyncServer(Server):
# Get the agent object (loaded in memory)
letta_agent = self._get_or_load_agent(agent_id=agent_id)
assert isinstance(letta_agent.memory, Memory)
- assert isinstance(letta_agent.agent_state.memory, Memory)
return letta_agent.agent_state.model_copy(deep=True)
def get_server_config(self, include_defaults: bool = False) -> dict:
@@ -2159,13 +2166,3 @@ class SyncServer(Server):
def add_embedding_model(self, request: EmbeddingConfig) -> EmbeddingConfig:
"""Add a new embedding model"""
-
- def get_agent_context_window(
- self,
- user_id: str,
- agent_id: str,
- ) -> ContextWindowOverview:
-
- # Get the current message
- letta_agent = self._get_or_load_agent(agent_id=agent_id)
- return letta_agent.get_context_window()
diff --git a/tests/test_o1_agent.py b/tests/test_o1_agent.py
new file mode 100644
index 000000000..495a4e27f
--- /dev/null
+++ b/tests/test_o1_agent.py
@@ -0,0 +1,34 @@
+from letta.client.client import create_client
+from letta.constants import DEFAULT_HUMAN
+from letta.o1_agent import send_final_message, send_thinking_message
+from letta.schemas.agent import AgentType
+from letta.schemas.embedding_config import EmbeddingConfig
+from letta.schemas.llm_config import LLMConfig
+from letta.schemas.memory import ChatMemory
+from letta.utils import get_human_text, get_persona_text
+
+
+def test_o1_agent():
+ client = create_client()
+ assert client is not None
+
+ thinking_tool = client.create_tool(send_thinking_message)
+ final_tool = client.create_tool(send_final_message)
+
+ agent_state = client.create_agent(
+ agent_type=AgentType.o1_agent,
+ tools=[thinking_tool.name, final_tool.name],
+ llm_config=LLMConfig.default_config("gpt-4"),
+ embedding_config=EmbeddingConfig.default_config("text-embedding-ada-002"),
+ memory=ChatMemory(human=get_human_text(DEFAULT_HUMAN), persona=get_persona_text("o1_persona")),
+ )
+ agent = client.get_agent(agent_id=agent_state.id)
+ assert agent is not None
+
+ response = client.user_message(agent_id=agent_state.id, message="9.9 or 9.11, which is a larger number?")
+ assert response is not None
+ assert len(response.messages) > 3
+
+
+if __name__ == "__main__":
+ test_o1_agent()