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: Add conditional to control overriding existing tools (#1201)

Matthew Zhou11e8c031bff6
diff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.py
index 3814aaa20..e859c605a 100644
--- a/letta/server/rest_api/routers/v1/agents.py
+++ b/letta/server/rest_api/routers/v1/agents.py
@@ -91,7 +91,7 @@ def list_agents(
return agents
[email protected]("/{agent_id}/download", response_model=None, operation_id="download_agent_serialized")
[email protected]("/{agent_id}/download", operation_id="download_agent_serialized")
def download_agent_serialized(
agent_id: str,
server: "SyncServer" = Depends(get_letta_server),
@@ -114,7 +114,11 @@ async def upload_agent_serialized(
file: UploadFile = File(...),
server: "SyncServer" = Depends(get_letta_server),
actor_id: Optional[str] = Header(None, alias="user_id"),
- mark_as_copy: bool = Query(True, description="Whether to mark the uploaded agent as a copy"),
+ append_copy_suffix: bool = Query(True, description='If set to True, appends "_copy" to the end of the agent name.'),
+ override_existing_tools: bool = Query(
+ True,
+ description="If set to True, existing tools can get their source code overwritten by the uploaded tool definitions. Note that Letta core tools can never be updated externally.",
+ ),
):
"""
Upload a serialized agent JSON file and recreate the agent in the system.
@@ -124,7 +128,9 @@ async def upload_agent_serialized(
try:
serialized_data = await file.read()
agent_json = json.loads(serialized_data)
- new_agent = server.agent_manager.deserialize(serialized_agent=agent_json, actor=actor, mark_as_copy=mark_as_copy)
+ new_agent = server.agent_manager.deserialize(
+ serialized_agent=agent_json, actor=actor, append_copy_suffix=append_copy_suffix, override_existing_tools=override_existing_tools
+ )
return new_agent
except json.JSONDecodeError:
diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.py
index 3aa32e4d0..6b754dd3f 100644
--- a/letta/services/agent_manager.py
+++ b/letta/services/agent_manager.py
@@ -15,6 +15,7 @@ from letta.orm import Identity as IdentityModel
from letta.orm import Source as SourceModel
from letta.orm import SourcePassage, SourcesAgents
from letta.orm import Tool as ToolModel
+from letta.orm.enums import ToolType
from letta.orm.errors import NoResultFound
from letta.orm.sandbox_config import AgentEnvironmentVariable as AgentEnvironmentVariableModel
from letta.orm.sqlite_functions import adapt_array
@@ -399,13 +400,15 @@ class AgentManager:
return schema.dump(agent)
@enforce_types
- def deserialize(self, serialized_agent: dict, actor: PydanticUser, mark_as_copy: bool = True) -> PydanticAgentState:
+ def deserialize(
+ self, serialized_agent: dict, actor: PydanticUser, append_copy_suffix: bool = True, override_existing_tools: bool = True
+ ) -> PydanticAgentState:
tool_data_list = serialized_agent.pop("tools", [])
with self.session_maker() as session:
schema = SerializedAgentSchema(session=session, actor=actor)
agent = schema.load(serialized_agent, session=session)
- if mark_as_copy:
+ if append_copy_suffix:
agent.name += "_copy"
agent.create(session, actor=actor)
pydantic_agent = agent.to_pydantic()
@@ -413,7 +416,20 @@ class AgentManager:
# Need to do this separately as there's some fancy upsert logic that SqlAlchemy cannot handle
for tool_data in tool_data_list:
pydantic_tool = SerializedToolSchema(actor=actor).load(tool_data, transient=True).to_pydantic()
- pydantic_tool = self.tool_manager.create_or_update_tool(pydantic_tool, actor=actor)
+
+ existing_pydantic_tool = self.tool_manager.get_tool_by_name(pydantic_tool.name, actor=actor)
+ # If the tool exists
+ # AND EITHER:
+ # 1) override_existing_tools is set to False
+ # 2) existing_pydantic_tool is NOT any type of Letta core tool
+ if existing_pydantic_tool and (
+ existing_pydantic_tool.tool_type in {ToolType.LETTA_CORE, ToolType.LETTA_MULTI_AGENT_CORE, ToolType.LETTA_MEMORY_CORE}
+ or not override_existing_tools
+ ):
+ pydantic_tool = existing_pydantic_tool
+ else:
+ pydantic_tool = self.tool_manager.create_or_update_tool(pydantic_tool, actor=actor)
+
pydantic_agent = self.attach_tool(agent_id=pydantic_agent.id, tool_id=pydantic_tool.id, actor=actor)
return pydantic_agent
diff --git a/tests/conftest.py b/tests/conftest.py
index 6ac509fa6..78e60df17 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -60,7 +60,7 @@ def check_composio_key_set():
yield
def weather_tool_func():
def get_weather(location: str) -> str:
"""
@@ -87,3 +87,21 @@ def weather_tool_func():
raise RuntimeError(f"Failed to get weather data, status code: {response.status_code}")
yield get_weather
+
+
+def print_tool_func():
+ """Fixture to create a tool with default settings and clean up after the test."""
+
+ def print_tool(message: str):
+ """
+ Args:
+ message (str): The message to print.
+
+ Returns:
+ str: The message that was printed.
+ """
+ print(message)
+ return message
+
+ yield print_tool
diff --git a/tests/test_agent_serialization.py b/tests/test_agent_serialization.py
index 1a533d43c..facbd552b 100644
--- a/tests/test_agent_serialization.py
+++ b/tests/test_agent_serialization.py
@@ -12,6 +12,7 @@ from rich.syntax import Syntax
from letta import create_client
from letta.config import LettaConfig
from letta.orm import Base
+from letta.orm.enums import ToolType
from letta.schemas.agent import AgentState, CreateAgent
from letta.schemas.block import Block, CreateBlock
from letta.schemas.embedding_config import EmbeddingConfig
@@ -98,6 +99,12 @@ def weather_tool(local_client, weather_tool_func):
yield weather_tool
+def print_tool(local_client, print_tool_func):
+ print_tool = local_client.create_or_update_tool(func=print_tool_func)
+ yield print_tool
+
+
@pytest.fixture
def default_block(server: SyncServer, default_user):
"""Fixture to create and return a default block."""
@@ -258,9 +265,9 @@ def _compare_agent_state_model_dump(d1: Dict[str, Any], d2: Dict[str, Any], log:
return True
-def compare_agent_state(original: AgentState, copy: AgentState, mark_as_copy: bool) -> bool:
+def compare_agent_state(original: AgentState, copy: AgentState, append_copy_suffix: bool) -> bool:
"""Wrapper function that provides a default set of ignored prefix fields."""
- if not mark_as_copy:
+ if not append_copy_suffix:
assert original.name == copy.name
return _compare_agent_state_model_dump(original.model_dump(exclude="name"), copy.model_dump(exclude="name"))
@@ -338,17 +345,53 @@ def test_sanity_datetime_mismatch():
# Agent serialize/deserialize tests
[email protected]("mark_as_copy", [True, False])
-def test_mark_as_copy_simple(local_client, server, serialize_test_agent, default_user, other_user, mark_as_copy):
[email protected]("append_copy_suffix", [True, False])
+def test_append_copy_suffix_simple(local_client, server, serialize_test_agent, default_user, other_user, append_copy_suffix):
"""Test deserializing JSON into an Agent instance."""
result = server.agent_manager.serialize(agent_id=serialize_test_agent.id, actor=default_user)
# Deserialize the agent
- agent_copy = server.agent_manager.deserialize(serialized_agent=result, actor=other_user, mark_as_copy=mark_as_copy)
+ agent_copy = server.agent_manager.deserialize(serialized_agent=result, actor=other_user, append_copy_suffix=append_copy_suffix)
# Compare serialized representations to check for exact match
print_dict_diff(json.loads(serialize_test_agent.model_dump_json()), json.loads(agent_copy.model_dump_json()))
- assert compare_agent_state(agent_copy, serialize_test_agent, mark_as_copy=mark_as_copy)
+ assert compare_agent_state(agent_copy, serialize_test_agent, append_copy_suffix=append_copy_suffix)
+
+
[email protected]("override_existing_tools", [True, False])
+def test_deserialize_override_existing_tools(
+ local_client, server, serialize_test_agent, default_user, weather_tool, print_tool, override_existing_tools
+):
+ """
+ Test deserializing an agent with tools and ensure correct behavior for overriding existing tools.
+ """
+ append_copy_suffix = False
+ result = server.agent_manager.serialize(agent_id=serialize_test_agent.id, actor=default_user)
+
+ # Extract tools before upload
+ tool_data_list = result.get("tools", [])
+ tool_names = {tool["name"]: tool for tool in tool_data_list}
+
+ # Rewrite all the tool source code to the print_tool source code
+ for tool in result["tools"]:
+ tool["source_code"] = print_tool.source_code
+
+ # Deserialize the agent with different override settings
+ server.agent_manager.deserialize(
+ serialized_agent=result, actor=default_user, append_copy_suffix=append_copy_suffix, override_existing_tools=override_existing_tools
+ )
+
+ # Verify tool behavior
+ for tool_name, expected_tool_data in tool_names.items():
+ existing_tool = server.tool_manager.get_tool_by_name(tool_name, actor=default_user)
+
+ if existing_tool.tool_type in {ToolType.LETTA_CORE, ToolType.LETTA_MULTI_AGENT_CORE, ToolType.LETTA_MEMORY_CORE}:
+ assert existing_tool.source_code != print_tool.source_code
+ elif override_existing_tools:
+ if existing_tool.name == weather_tool.name:
+ assert existing_tool.source_code == print_tool.source_code, f"Tool {tool_name} should be overridden"
+ else:
+ assert existing_tool.source_code == weather_tool.source_code, f"Tool {tool_name} should NOT be overridden"
def test_in_context_message_id_remapping(local_client, server, serialize_test_agent, default_user, other_user):
@@ -369,21 +412,21 @@ def test_in_context_message_id_remapping(local_client, server, serialize_test_ag
def test_agent_serialize_with_user_messages(local_client, server, serialize_test_agent, default_user, other_user):
"""Test deserializing JSON into an Agent instance."""
- mark_as_copy = False
+ append_copy_suffix = False
server.send_messages(
actor=default_user, agent_id=serialize_test_agent.id, messages=[MessageCreate(role=MessageRole.user, content="hello")]
)
result = server.agent_manager.serialize(agent_id=serialize_test_agent.id, actor=default_user)
# Deserialize the agent
- agent_copy = server.agent_manager.deserialize(serialized_agent=result, actor=other_user, mark_as_copy=mark_as_copy)
+ agent_copy = server.agent_manager.deserialize(serialized_agent=result, actor=other_user, append_copy_suffix=append_copy_suffix)
# Get most recent original agent instance
serialize_test_agent = server.agent_manager.get_agent_by_id(agent_id=serialize_test_agent.id, actor=default_user)
# Compare serialized representations to check for exact match
print_dict_diff(json.loads(serialize_test_agent.model_dump_json()), json.loads(agent_copy.model_dump_json()))
- assert compare_agent_state(agent_copy, serialize_test_agent, mark_as_copy=mark_as_copy)
+ assert compare_agent_state(agent_copy, serialize_test_agent, append_copy_suffix=append_copy_suffix)
# Make sure both agents can receive messages after
server.send_messages(
@@ -396,7 +439,7 @@ def test_agent_serialize_with_user_messages(local_client, server, serialize_test
def test_agent_serialize_tool_calls(mock_e2b_api_key_none, local_client, server, serialize_test_agent, default_user, other_user):
"""Test deserializing JSON into an Agent instance."""
- mark_as_copy = False
+ append_copy_suffix = False
server.send_messages(
actor=default_user,
agent_id=serialize_test_agent.id,
@@ -405,14 +448,14 @@ def test_agent_serialize_tool_calls(mock_e2b_api_key_none, local_client, server,
result = server.agent_manager.serialize(agent_id=serialize_test_agent.id, actor=default_user)
# Deserialize the agent
- agent_copy = server.agent_manager.deserialize(serialized_agent=result, actor=other_user, mark_as_copy=mark_as_copy)
+ agent_copy = server.agent_manager.deserialize(serialized_agent=result, actor=other_user, append_copy_suffix=append_copy_suffix)
# Get most recent original agent instance
serialize_test_agent = server.agent_manager.get_agent_by_id(agent_id=serialize_test_agent.id, actor=default_user)
# Compare serialized representations to check for exact match
print_dict_diff(json.loads(serialize_test_agent.model_dump_json()), json.loads(agent_copy.model_dump_json()))
- assert compare_agent_state(agent_copy, serialize_test_agent, mark_as_copy=mark_as_copy)
+ assert compare_agent_state(agent_copy, serialize_test_agent, append_copy_suffix=append_copy_suffix)
# Make sure both agents can receive messages after
original_agent_response = server.send_messages(
@@ -433,8 +476,8 @@ def test_agent_serialize_tool_calls(mock_e2b_api_key_none, local_client, server,
# FastAPI endpoint tests
[email protected]("mark_as_copy", [True])
-def test_agent_download_upload_flow(fastapi_client, server, serialize_test_agent, default_user, other_user, mark_as_copy):
[email protected]("append_copy_suffix", [True])
+def test_agent_download_upload_flow(fastapi_client, server, serialize_test_agent, default_user, other_user, append_copy_suffix):
"""
Test the full E2E serialization and deserialization flow using FastAPI endpoints.
"""
@@ -452,7 +495,7 @@ def test_agent_download_upload_flow(fastapi_client, server, serialize_test_agent
upload_response = fastapi_client.post(
"/v1/agents/upload",
headers={"user_id": other_user.id},
- params={"mark_as_copy": mark_as_copy},
+ params={"append_copy_suffix": append_copy_suffix, "override_existing_tools": False},
files=files,
)
assert upload_response.status_code == 200, f"Upload failed: {upload_response.text}"
@@ -467,7 +510,7 @@ def test_agent_download_upload_flow(fastapi_client, server, serialize_test_agent
serialize_test_agent = server.agent_manager.get_agent_by_id(agent_id=serialize_test_agent.id, actor=default_user)
agent_copy = server.agent_manager.get_agent_by_id(agent_id=copied_agent_id, actor=other_user)
print_dict_diff(json.loads(serialize_test_agent.model_dump_json()), json.loads(agent_copy.model_dump_json()))
- assert compare_agent_state(agent_copy, serialize_test_agent, mark_as_copy=mark_as_copy)
+ assert compare_agent_state(agent_copy, serialize_test_agent, append_copy_suffix=append_copy_suffix)
# Step 4: Ensure copied agent receives messages correctly
server.send_messages(