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 ability to specify agent env vars on import (#3753)

cthomas7efd65136639
diff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.py
index 1cc10f8c0..2eaf65e0e 100644
--- a/letta/server/rest_api/routers/v1/agents.py
+++ b/letta/server/rest_api/routers/v1/agents.py
@@ -4,7 +4,7 @@ import traceback
from datetime import datetime, timezone
from typing import Annotated, Any, Dict, List, Optional, Union
-from fastapi import APIRouter, Body, Depends, File, Header, HTTPException, Query, Request, UploadFile, status
+from fastapi import APIRouter, Body, Depends, File, Form, Header, HTTPException, Query, Request, UploadFile, status
from fastapi.responses import JSONResponse
from marshmallow import ValidationError
from orjson import orjson
@@ -169,16 +169,17 @@ def import_agent_serialized(
file: UploadFile = File(...),
server: "SyncServer" = Depends(get_letta_server),
actor_id: str | None = Header(None, alias="user_id"),
- 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(
+ append_copy_suffix: bool = Form(True, description='If set to True, appends "_copy" to the end of the agent name.'),
+ override_existing_tools: bool = Form(
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.",
),
- project_id: str | None = Query(None, description="The project ID to associate the uploaded agent with."),
- strip_messages: bool = Query(
+ project_id: str | None = Form(None, description="The project ID to associate the uploaded agent with."),
+ strip_messages: bool = Form(
False,
description="If set to True, strips all messages from the agent before importing.",
),
+ env_vars: Optional[Dict[str, Any]] = Form(None, description="Environment variables to pass to the agent for tool execution."),
):
"""
Import a serialized agent file and recreate the agent in the system.
@@ -199,6 +200,7 @@ def import_agent_serialized(
override_existing_tools=override_existing_tools,
project_id=project_id,
strip_messages=strip_messages,
+ env_vars=env_vars,
)
return new_agent
diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.py
index ced867ab7..c93025990 100644
--- a/letta/services/agent_manager.py
+++ b/letta/services/agent_manager.py
@@ -1,7 +1,7 @@
import asyncio
import os
from datetime import datetime, timezone
-from typing import Dict, List, Optional, Set, Tuple
+from typing import Any, Dict, List, Optional, Set, Tuple
import sqlalchemy as sa
from sqlalchemy import delete, func, insert, literal, or_, select, tuple_
@@ -1442,6 +1442,7 @@ class AgentManager:
override_existing_tools: bool = True,
project_id: Optional[str] = None,
strip_messages: Optional[bool] = False,
+ env_vars: Optional[dict[str, Any]] = None,
) -> PydanticAgentState:
serialized_agent_dict = serialized_agent.model_dump()
tool_data_list = serialized_agent_dict.pop("tools", [])
@@ -1472,6 +1473,11 @@ class AgentManager:
if strip_messages:
# we want to strip all but the first (system) message
agent.message_ids = [agent.message_ids[0]]
+
+ if env_vars:
+ for var in agent.tool_exec_environment_variables:
+ var.value = env_vars.get(var.key, "")
+
agent = agent.create(session, actor=actor)
pydantic_agent = agent.to_pydantic()
diff --git a/letta/services/agent_serialization_manager.py b/letta/services/agent_serialization_manager.py
index 7c8d4de71..a045d1a41 100644
--- a/letta/services/agent_serialization_manager.py
+++ b/letta/services/agent_serialization_manager.py
@@ -1,5 +1,5 @@
from datetime import datetime, timezone
-from typing import Dict, List
+from typing import Any, Dict, List, Optional
from letta.constants import MCP_TOOL_TAG_NAME_PREFIX
from letta.errors import AgentFileExportError, AgentFileImportError
@@ -419,7 +419,13 @@ class AgentSerializationManager:
logger.error(f"Failed to export agent file: {e}")
raise AgentFileExportError(f"Export failed: {e}") from e
- async def import_file(self, schema: AgentFileSchema, actor: User, dry_run: bool = False) -> ImportResult:
+ async def import_file(
+ self,
+ schema: AgentFileSchema,
+ actor: User,
+ dry_run: bool = False,
+ env_vars: Optional[Dict[str, Any]] = None,
+ ) -> ImportResult:
"""
Import AgentFileSchema into the database.
@@ -586,6 +592,10 @@ class AgentSerializationManager:
if agent_data.get("block_ids"):
agent_data["block_ids"] = [file_to_db_ids[file_id] for file_id in agent_data["block_ids"]]
+ if env_vars:
+ for var in agent_data["tool_exec_environment_variables"]:
+ var["value"] = env_vars.get(var["key"], "")
+
agent_create = CreateAgent(**agent_data)
created_agent = await self.agent_manager.create_agent_async(agent_create, actor, _init_with_no_messages=True)
file_to_db_ids[agent_schema.id] = created_agent.id
diff --git a/tests/test_agent_serialization.py b/tests/test_agent_serialization.py
index d0ccc36f4..01aada728 100644
--- a/tests/test_agent_serialization.py
+++ b/tests/test_agent_serialization.py
@@ -636,15 +636,20 @@ def test_agent_download_upload_flow(server, server_url, serialize_test_agent, de
# Step 2: Upload the serialized agent as a copy
agent_bytes = BytesIO(json.dumps(agent_json).encode("utf-8"))
files = {"file": ("agent.json", agent_bytes, "application/json")}
+
+ # Send parameters as form data instead of query parameters
+ form_data = {
+ "append_copy_suffix": str(append_copy_suffix).lower(), # Convert bool to string 'true'/'false'
+ "override_existing_tools": "false",
+ }
+ if project_id:
+ form_data["project_id"] = project_id
+
upload_response = requests.post(
f"{server_url}/v1/agents/import",
headers={"user_id": other_user.id},
- params={
- "append_copy_suffix": append_copy_suffix,
- "override_existing_tools": False,
- "project_id": project_id,
- },
files=files,
+ data=form_data, # Send as form data
)
assert upload_response.status_code == 200, f"Upload failed: {upload_response.text}"
@@ -681,11 +686,18 @@ def test_upload_agentfile_from_disk(server, server_url, disable_e2b_api_key, oth
with open(file_path, "rb") as f:
files = {"file": (filename, f, "application/json")}
+
+ # Send parameters as form data instead of query parameters
+ form_data = {
+ "append_copy_suffix": "true",
+ "override_existing_tools": "false",
+ }
+
response = requests.post(
f"{server_url}/v1/agents/import",
headers={"user_id": other_user.id},
- params={"append_copy_suffix": True, "override_existing_tools": False},
files=files,
+ data=form_data, # Send as form data
)
assert response.status_code == 200, f"Failed to upload {filename}: {response.text}"