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.

fix: Fix per-agent environment variable updates (#527)

Matthew Zhouc03efab3580d
diff --git a/letta/orm/__init__.py b/letta/orm/__init__.py
index 4bf7e44c1..437956a55 100644
--- a/letta/orm/__init__.py
+++ b/letta/orm/__init__.py
@@ -8,7 +8,7 @@ from letta.orm.job import Job
from letta.orm.message import Message
from letta.orm.organization import Organization
from letta.orm.passage import AgentPassage, BasePassage, SourcePassage
-from letta.orm.sandbox_config import SandboxConfig, SandboxEnvironmentVariable, AgentEnvironmentVariable
+from letta.orm.sandbox_config import AgentEnvironmentVariable, SandboxConfig, SandboxEnvironmentVariable
from letta.orm.source import Source
from letta.orm.sources_agents import SourcesAgents
from letta.orm.tool import Tool
diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.py
index 92044a0cb..9ec76b233 100644
--- a/letta/services/agent_manager.py
+++ b/letta/services/agent_manager.py
@@ -338,11 +338,30 @@ class AgentManager:
# Retrieve the agent
agent = AgentModel.read(db_session=session, identifier=agent_id, actor=actor)
- # Replace the environment variables
- agent.tool_exec_environment_variables = [
- AgentEnvironmentVariableModel(key=key, value=value, agent_id=agent_id, organization_id=actor.organization_id)
- for key, value in env_vars.items()
- ]
+ # Fetch existing environment variables as a dictionary
+ existing_vars = {var.key: var for var in agent.tool_exec_environment_variables}
+
+ # Update or create environment variables
+ updated_vars = []
+ for key, value in env_vars.items():
+ if key in existing_vars:
+ # Update existing variable
+ existing_vars[key].value = value
+ updated_vars.append(existing_vars[key])
+ else:
+ # Create new variable
+ updated_vars.append(
+ AgentEnvironmentVariableModel(
+ key=key,
+ value=value,
+ agent_id=agent_id,
+ organization_id=actor.organization_id,
+ )
+ )
+
+ # Remove stale variables
+ stale_keys = set(existing_vars) - set(env_vars)
+ agent.tool_exec_environment_variables = [var for var in updated_vars if var.key not in stale_keys]
# Update the agent in the database
agent.update(session, actor=actor)
diff --git a/tests/test_managers.py b/tests/test_managers.py
index 2b0ff7517..f1b2c621e 100644
--- a/tests/test_managers.py
+++ b/tests/test_managers.py
@@ -560,7 +560,7 @@ def test_update_agent(server: SyncServer, comprehensive_test_agent_fixture, othe
embedding_config=EmbeddingConfig.default_config(model_name="letta"),
message_ids=["10", "20"],
metadata_={"train_key": "train_value"},
- tool_exec_environment_variables={"new_tool_exec_key": "new_tool_exec_value"},
+ tool_exec_environment_variables={"test_env_var_key_a": "a", "new_tool_exec_key": "n"},
)
updated_agent = server.agent_manager.update_agent(agent.id, update_agent_request, actor=default_user)