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 new types and other changes (#2348)

Matthew Zhoue346d26811a8
diff --git a/.github/workflows/integration_tests.yml b/.github/workflows/integration_tests.yml
index 3d2292f3d..a094f2679 100644
--- a/.github/workflows/integration_tests.yml
+++ b/.github/workflows/integration_tests.yml
@@ -29,7 +29,6 @@ jobs:
- "integration_test_tool_execution_sandbox.py"
- "integration_test_offline_memory_agent.py"
- "integration_test_agent_tool_graph.py"
- - "integration_test_o1_agent.py"
services:
qdrant:
image: qdrant/qdrant
diff --git a/letta/agent.py b/letta/agent.py
index 91db2e8a3..34713616e 100644
--- a/letta/agent.py
+++ b/letta/agent.py
@@ -16,7 +16,6 @@ from letta.constants import (
MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST,
MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC,
MESSAGE_SUMMARY_WARNING_FRAC,
- O1_BASE_TOOLS,
REQ_HEARTBEAT_MESSAGE,
)
from letta.errors import ContextWindowExceededError
@@ -212,7 +211,7 @@ class Agent(BaseAgent):
# TODO: This is NO BUENO
# TODO: Matching purely by names is extremely problematic, users can create tools with these names and run them in the agent loop
# TODO: We will have probably have to match the function strings exactly for safety
- if function_name in BASE_TOOLS or function_name in O1_BASE_TOOLS:
+ if function_name in BASE_TOOLS:
# base tools are allowed to access the `Agent` object and run on the database
function_args["self"] = self # need to attach self to arg since it's dynamically linked
function_response = callable_func(**function_args)
diff --git a/letta/constants.py b/letta/constants.py
index 5a51ef9b4..e721b1dbc 100644
--- a/letta/constants.py
+++ b/letta/constants.py
@@ -42,7 +42,6 @@ DEFAULT_PRESET = "memgpt_chat"
# Base tools that cannot be edited, as they access agent state directly
# Note that we don't include "conversation_search_date" for now
BASE_TOOLS = ["send_message", "conversation_search", "archival_memory_insert", "archival_memory_search"]
-O1_BASE_TOOLS = ["send_thinking_message", "send_final_message"]
# Base memory tools CAN be edited, and are added by default by the server
BASE_MEMORY_TOOLS = ["core_memory_append", "core_memory_replace"]
diff --git a/letta/o1_agent.py b/letta/o1_agent.py
deleted file mode 100644
index 285ed966f..000000000
--- a/letta/o1_agent.py
+++ /dev/null
@@ -1,86 +0,0 @@
-from typing import List, Optional, Union
-
-from letta.agent import Agent, save_agent
-from letta.interface import AgentInterface
-from letta.schemas.agent import AgentState
-from letta.schemas.message import Message
-from letta.schemas.openai.chat_completion_response import UsageStatistics
-from letta.schemas.usage import LettaUsageStatistics
-from letta.schemas.user import User
-
-
-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)
- 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)
- return None
-
-
-class O1Agent(Agent):
- def __init__(
- self,
- interface: AgentInterface,
- agent_state: AgentState,
- user: User,
- max_thinking_steps: int = 10,
- first_message_verify_mono: bool = False,
- ):
- super().__init__(interface, agent_state, user)
- self.max_thinking_steps = max_thinking_steps
- 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,
- **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:
- if counter > 0:
- next_input_message = []
-
- 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
- save_agent(self)
-
- return LettaUsageStatistics(**total_usage.model_dump(), step_count=step_count)
diff --git a/letta/orm/enums.py b/letta/orm/enums.py
index c9a7b0602..e9f753490 100644
--- a/letta/orm/enums.py
+++ b/letta/orm/enums.py
@@ -1,6 +1,12 @@
from enum import Enum
+class ToolType(str, Enum):
+ CUSTOM = "custom"
+ LETTA_CORE = "letta_core"
+ LETTA_MEMORY_CORE = "letta_memory_core"
+
+
class ToolSourceType(str, Enum):
"""Defines what a tool was derived from"""
diff --git a/letta/schemas/agent.py b/letta/schemas/agent.py
index a114f6939..16b051f03 100644
--- a/letta/schemas/agent.py
+++ b/letta/schemas/agent.py
@@ -25,7 +25,6 @@ class AgentType(str, Enum):
memgpt_agent = "memgpt_agent"
split_thread_agent = "split_thread_agent"
- o1_agent = "o1_agent"
offline_memory_agent = "offline_memory_agent"
chat_only_agent = "chat_only_agent"
diff --git a/letta/schemas/tool.py b/letta/schemas/tool.py
index 8066f9b2c..40a8fbf30 100644
--- a/letta/schemas/tool.py
+++ b/letta/schemas/tool.py
@@ -206,19 +206,16 @@ class ToolUpdate(LettaBase):
json_schema: Optional[Dict] = Field(
None, description="The JSON schema of the function (auto-generated from source_code if not provided)"
)
+ return_char_limit: Optional[int] = Field(None, description="The maximum number of characters in the response.")
class Config:
extra = "ignore" # Allows extra fields without validation errors
# TODO: Remove this, and clean usage of ToolUpdate everywhere else
-class ToolRun(LettaBase):
- id: str = Field(..., description="The ID of the tool to run.")
- args: str = Field(..., description="The arguments to pass to the tool (as stringified JSON).")
-
-
class ToolRunFromSource(LettaBase):
source_code: str = Field(..., description="The source code of the function.")
- args: str = Field(..., description="The arguments to pass to the tool (as stringified JSON).")
+ args: Dict[str, str] = Field(..., description="The arguments to pass to the tool.")
+ env_vars: Dict[str, str] = Field(None, description="The environment variables to pass to the tool.")
name: Optional[str] = Field(None, description="The name of the tool to run.")
source_type: Optional[str] = Field(None, description="The type of the source code.")
diff --git a/letta/server/rest_api/routers/v1/sandbox_configs.py b/letta/server/rest_api/routers/v1/sandbox_configs.py
index d5c16c04a..edd4383ca 100644
--- a/letta/server/rest_api/routers/v1/sandbox_configs.py
+++ b/letta/server/rest_api/routers/v1/sandbox_configs.py
@@ -69,11 +69,12 @@ def delete_sandbox_config(
def list_sandbox_configs(
limit: int = Query(1000, description="Number of results to return"),
cursor: Optional[str] = Query(None, description="Pagination cursor to fetch the next set of results"),
+ sandbox_type: Optional[SandboxType] = Query(None, description="Filter for this specific sandbox type"),
server: SyncServer = Depends(get_letta_server),
user_id: str = Depends(get_user_id),
):
actor = server.user_manager.get_user_or_default(user_id=user_id)
- return server.sandbox_config_manager.list_sandbox_configs(actor, limit=limit, cursor=cursor)
+ return server.sandbox_config_manager.list_sandbox_configs(actor, limit=limit, cursor=cursor, sandbox_type=sandbox_type)
### Sandbox Environment Variable Routes
diff --git a/letta/server/rest_api/routers/v1/tools.py b/letta/server/rest_api/routers/v1/tools.py
index ffc2b2124..8ea4d0377 100644
--- a/letta/server/rest_api/routers/v1/tools.py
+++ b/letta/server/rest_api/routers/v1/tools.py
@@ -181,6 +181,7 @@ def run_tool_from_source(
tool_source=request.source_code,
tool_source_type=request.source_type,
tool_args=request.args,
+ tool_env_vars=request.env_vars,
tool_name=request.name,
actor=actor,
)
diff --git a/letta/server/server.py b/letta/server/server.py
index 4b86544a2..5c16ccfb4 100644
--- a/letta/server/server.py
+++ b/letta/server/server.py
@@ -1,11 +1,10 @@
# inspecting tools
-import json
import os
import traceback
import warnings
from abc import abstractmethod
from datetime import datetime
-from typing import Callable, List, Optional, Tuple, Union
+from typing import Callable, Dict, List, Optional, Tuple, Union
from composio.client import Composio
from composio.client.collections import ActionModel, AppModel
@@ -23,7 +22,6 @@ from letta.data_sources.connectors import DataConnector, load_data
from letta.interface import AgentInterface # abstract
from letta.interface import CLIInterface # for printing to terminal
from letta.log import get_logger
-from letta.o1_agent import O1Agent
from letta.offline_memory_agent import OfflineMemoryAgent
from letta.orm import Base
from letta.orm.errors import NoResultFound
@@ -391,8 +389,6 @@ class SyncServer(Server):
interface = interface or self.default_interface_factory()
if agent_state.agent_type == AgentType.memgpt_agent:
agent = Agent(agent_state=agent_state, interface=interface, user=actor)
- elif agent_state.agent_type == AgentType.o1_agent:
- agent = O1Agent(agent_state=agent_state, interface=interface, user=actor)
elif agent_state.agent_type == AgentType.offline_memory_agent:
agent = OfflineMemoryAgent(agent_state=agent_state, interface=interface, user=actor)
elif agent_state.agent_type == AgentType.chat_only_agent:
@@ -1117,22 +1113,17 @@ class SyncServer(Server):
def run_tool_from_source(
self,
actor: User,
- tool_args: str,
+ tool_args: Dict[str, str],
tool_source: str,
+ tool_env_vars: Optional[Dict[str, str]] = None,
tool_source_type: Optional[str] = None,
tool_name: Optional[str] = None,
) -> ToolReturnMessage:
"""Run a tool from source code"""
-
- try:
- tool_args_dict = json.loads(tool_args)
- except json.JSONDecodeError:
- raise ValueError("Invalid JSON string for tool_args")
-
if tool_source_type is not None and tool_source_type != "python":
raise ValueError("Only Python source code is supported at this time")
- # NOTE: we're creating a floating Tool object and NOT persiting to DB
+ # NOTE: we're creating a floating Tool object and NOT persisting to DB
tool = Tool(
name=tool_name,
source_code=tool_source,
@@ -1144,7 +1135,9 @@ class SyncServer(Server):
# Next, attempt to run the tool with the sandbox
try:
- sandbox_run_result = ToolExecutionSandbox(tool.name, tool_args_dict, actor, tool_object=tool).run(agent_state=agent_state)
+ sandbox_run_result = ToolExecutionSandbox(tool.name, tool_args, actor, tool_object=tool).run(
+ agent_state=agent_state, additional_env_vars=tool_env_vars
+ )
return ToolReturnMessage(
id="null",
tool_call_id="null",
diff --git a/letta/services/helpers/agent_manager_helper.py b/letta/services/helpers/agent_manager_helper.py
index 2d7ac2805..0846a0c74 100644
--- a/letta/services/helpers/agent_manager_helper.py
+++ b/letta/services/helpers/agent_manager_helper.py
@@ -89,8 +89,6 @@ def derive_system_message(agent_type: AgentType, system: Optional[str] = None):
# TODO: don't hardcode
if agent_type == AgentType.memgpt_agent:
system = gpt_system.get_system_text("memgpt_chat")
- elif agent_type == AgentType.o1_agent:
- system = gpt_system.get_system_text("memgpt_modified_o1")
elif agent_type == AgentType.offline_memory_agent:
system = gpt_system.get_system_text("memgpt_offline_memory")
elif agent_type == AgentType.chat_only_agent:
diff --git a/letta/services/sandbox_config_manager.py b/letta/services/sandbox_config_manager.py
index 0511d3ec6..391d4aad7 100644
--- a/letta/services/sandbox_config_manager.py
+++ b/letta/services/sandbox_config_manager.py
@@ -111,16 +111,15 @@ class SandboxConfigManager:
@enforce_types
def list_sandbox_configs(
- self, actor: PydanticUser, cursor: Optional[str] = None, limit: Optional[int] = 50
+ self, actor: PydanticUser, cursor: Optional[str] = None, limit: Optional[int] = 50, sandbox_type: Optional[SandboxType] = None
) -> List[PydanticSandboxConfig]:
"""List all sandbox configurations with optional pagination."""
+ kwargs = {"organization_id": actor.organization_id}
+ if sandbox_type:
+ kwargs.update({"type": sandbox_type})
+
with self.session_maker() as session:
- sandboxes = SandboxConfigModel.list(
- db_session=session,
- cursor=cursor,
- limit=limit,
- organization_id=actor.organization_id,
- )
+ sandboxes = SandboxConfigModel.list(db_session=session, cursor=cursor, limit=limit, **kwargs)
return [sandbox.to_pydantic() for sandbox in sandboxes]
@enforce_types
diff --git a/letta/services/tool_execution_sandbox.py b/letta/services/tool_execution_sandbox.py
index 93e3e265e..e07c4ea2d 100644
--- a/letta/services/tool_execution_sandbox.py
+++ b/letta/services/tool_execution_sandbox.py
@@ -59,22 +59,23 @@ class ToolExecutionSandbox:
self.sandbox_config_manager = SandboxConfigManager(tool_settings)
self.force_recreate = force_recreate
- def run(self, agent_state: Optional[AgentState] = None) -> SandboxRunResult:
+ def run(self, agent_state: Optional[AgentState] = None, additional_env_vars: Optional[Dict] = None) -> SandboxRunResult:
"""
Run the tool in a sandbox environment.
Args:
agent_state (Optional[AgentState]): The state of the agent invoking the tool
+ additional_env_vars (Optional[Dict]): Environment variables to inject into the sandbox
Returns:
Tuple[Any, Optional[AgentState]]: Tuple containing (tool_result, agent_state)
"""
if tool_settings.e2b_api_key:
logger.debug(f"Using e2b sandbox to execute {self.tool_name}")
- result = self.run_e2b_sandbox(agent_state=agent_state)
+ result = self.run_e2b_sandbox(agent_state=agent_state, additional_env_vars=additional_env_vars)
else:
logger.debug(f"Using local sandbox to execute {self.tool_name}")
- result = self.run_local_dir_sandbox(agent_state=agent_state)
+ result = self.run_local_dir_sandbox(agent_state=agent_state, additional_env_vars=additional_env_vars)
# Log out any stdout/stderr from the tool run
logger.debug(f"Executed tool '{self.tool_name}', logging output from tool run: \n")
@@ -98,19 +99,25 @@ class ToolExecutionSandbox:
os.environ.clear()
os.environ.update(original_env) # Restore original environment variables
- def run_local_dir_sandbox(self, agent_state: Optional[AgentState] = None) -> SandboxRunResult:
+ def run_local_dir_sandbox(
+ self, agent_state: Optional[AgentState] = None, additional_env_vars: Optional[Dict] = None
+ ) -> SandboxRunResult:
sbx_config = self.sandbox_config_manager.get_or_create_default_sandbox_config(sandbox_type=SandboxType.LOCAL, actor=self.user)
local_configs = sbx_config.get_local_config()
# Get environment variables for the sandbox
- env_vars = self.sandbox_config_manager.get_sandbox_env_vars_as_dict(sandbox_config_id=sbx_config.id, actor=self.user, limit=100)
env = os.environ.copy()
+ env_vars = self.sandbox_config_manager.get_sandbox_env_vars_as_dict(sandbox_config_id=sbx_config.id, actor=self.user, limit=100)
env.update(env_vars)
# Get environment variables for this agent specifically
if agent_state:
env.update(agent_state.get_agent_env_vars_as_dict())
+ # Finally, get any that are passed explicitly into the `run` function call
+ if additional_env_vars:
+ env.update(additional_env_vars)
+
# Safety checks
if not os.path.isdir(local_configs.sandbox_dir):
raise FileNotFoundError(f"Sandbox directory does not exist: {local_configs.sandbox_dir}")
@@ -277,7 +284,7 @@ class ToolExecutionSandbox:
# e2b sandbox specific functions
- def run_e2b_sandbox(self, agent_state: Optional[AgentState] = None) -> SandboxRunResult:
+ def run_e2b_sandbox(self, agent_state: Optional[AgentState] = None, additional_env_vars: Optional[Dict] = None) -> SandboxRunResult:
sbx_config = self.sandbox_config_manager.get_or_create_default_sandbox_config(sandbox_type=SandboxType.E2B, actor=self.user)
sbx = self.get_running_e2b_sandbox_with_same_state(sbx_config)
if not sbx or self.force_recreate:
@@ -300,6 +307,9 @@ class ToolExecutionSandbox:
if agent_state:
env_vars.update(agent_state.get_agent_env_vars_as_dict())
+ # Finally, get any that are passed explicitly into the `run` function call
+ if additional_env_vars:
+ env_vars.update(additional_env_vars)
code = self.generate_execution_script(agent_state=agent_state)
execution = sbx.run_code(code, envs=env_vars)
diff --git a/tests/integration_test_composio.py b/tests/integration_test_composio.py
index 1b2c2e3f8..8bb615672 100644
--- a/tests/integration_test_composio.py
+++ b/tests/integration_test_composio.py
@@ -1,28 +1,59 @@
import pytest
from fastapi.testclient import TestClient
+from letta.log import get_logger
from letta.server.rest_api.app import app
+from letta.settings import tool_settings
+
+logger = get_logger(__name__)
@pytest.fixture
-def client():
+def fastapi_client():
return TestClient(app)
-def test_list_composio_apps(client):
- response = client.get("/v1/tools/composio/apps")
+def test_list_composio_apps(fastapi_client):
+ response = fastapi_client.get("/v1/tools/composio/apps")
assert response.status_code == 200
assert isinstance(response.json(), list)
-def test_list_composio_actions_by_app(client):
- response = client.get("/v1/tools/composio/apps/github/actions")
+def test_list_composio_actions_by_app(fastapi_client):
+ response = fastapi_client.get("/v1/tools/composio/apps/github/actions")
assert response.status_code == 200
assert isinstance(response.json(), list)
-def test_add_composio_tool(client):
- response = client.post("/v1/tools/composio/GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER")
+def test_add_composio_tool(fastapi_client):
+ response = fastapi_client.post("/v1/tools/composio/GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER")
assert response.status_code == 200
assert "id" in response.json()
assert "name" in response.json()
+
+
+def test_composio_version_on_e2b_matches_server(check_e2b_key_is_set):
+ import composio
+ from e2b_code_interpreter import Sandbox
+ from packaging.version import Version
+
+ sbx = Sandbox(tool_settings.e2b_sandbox_template_id)
+ result = sbx.run_code(
+ """
+ import composio
+ print(str(composio.__version__))
+ """
+ )
+ e2b_composio_version = result.logs.stdout[0].strip()
+ composio_version = str(composio.__version__)
+
+ # Compare versions
+ if Version(composio_version) > Version(e2b_composio_version):
+ raise AssertionError(f"Local composio version {composio_version} is greater than server version {e2b_composio_version}")
+ elif Version(composio_version) < Version(e2b_composio_version):
+ logger.warning(
+ f"Local version of composio {composio_version} is less than the E2B version: {e2b_composio_version}. Please upgrade your local composio version."
+ )
+
+ # Print concise summary
+ logger.info(f"Server version: {composio_version}, E2B version: {e2b_composio_version}")
diff --git a/tests/integration_test_o1_agent.py b/tests/integration_test_o1_agent.py
deleted file mode 100644
index 6c8c62a1f..000000000
--- a/tests/integration_test_o1_agent.py
+++ /dev/null
@@ -1,34 +0,0 @@
-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_or_update_tool(send_thinking_message)
- final_tool = client.create_or_update_tool(send_final_message)
-
- agent_state = client.create_agent(
- agent_type=AgentType.o1_agent,
- tool_ids=[thinking_tool.id, final_tool.id],
- 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()
diff --git a/tests/test_managers.py b/tests/test_managers.py
index f1b2c621e..76001f3a1 100644
--- a/tests/test_managers.py
+++ b/tests/test_managers.py
@@ -1391,9 +1391,10 @@ def test_list_tools(server: SyncServer, print_tool, default_user):
def test_update_tool_by_id(server: SyncServer, print_tool, default_user):
updated_description = "updated_description"
+ return_char_limit = 10000
# Create a ToolUpdate object to modify the print_tool's description
- tool_update = ToolUpdate(description=updated_description)
+ tool_update = ToolUpdate(description=updated_description, return_char_limit=return_char_limit)
# Update the tool using the manager method
server.tool_manager.update_tool_by_id(print_tool.id, tool_update, actor=default_user)
@@ -1403,6 +1404,7 @@ def test_update_tool_by_id(server: SyncServer, print_tool, default_user):
# Assertions to check if the update was successful
assert updated_tool.description == updated_description
+ assert updated_tool.return_char_limit == return_char_limit
def test_update_tool_source_code_refreshes_schema_and_name(server: SyncServer, print_tool, default_user):
@@ -2055,16 +2057,16 @@ def test_get_sandbox_config_by_type(server: SyncServer, sandbox_config_fixture,
def test_list_sandbox_configs(server: SyncServer, default_user):
# Creating multiple sandbox configs
- config_a = SandboxConfigCreate(
+ config_e2b_create = SandboxConfigCreate(
config=E2BSandboxConfig(),
)
- config_b = SandboxConfigCreate(
+ config_local_create = SandboxConfigCreate(
config=LocalSandboxConfig(sandbox_dir=""),
)
- server.sandbox_config_manager.create_or_update_sandbox_config(config_a, actor=default_user)
+ config_e2b = server.sandbox_config_manager.create_or_update_sandbox_config(config_e2b_create, actor=default_user)
if USING_SQLITE:
time.sleep(CREATE_DELAY_SQLITE)
- server.sandbox_config_manager.create_or_update_sandbox_config(config_b, actor=default_user)
+ config_local = server.sandbox_config_manager.create_or_update_sandbox_config(config_local_create, actor=default_user)
# List configs without pagination
configs = server.sandbox_config_manager.list_sandbox_configs(actor=default_user)
@@ -2078,6 +2080,15 @@ def test_list_sandbox_configs(server: SyncServer, default_user):
assert len(next_page) == 1
assert next_page[0].id != paginated_configs[0].id
+ # List configs using sandbox_type filter
+ configs = server.sandbox_config_manager.list_sandbox_configs(actor=default_user, sandbox_type=SandboxType.E2B)
+ assert len(configs) == 1
+ assert configs[0].id == config_e2b.id
+
+ configs = server.sandbox_config_manager.list_sandbox_configs(actor=default_user, sandbox_type=SandboxType.LOCAL)
+ assert len(configs) == 1
+ assert configs[0].id == config_local.id
+
# ======================================================================================================================
# SandboxConfigManager Tests - Environment Variables
diff --git a/tests/test_server.py b/tests/test_server.py
index fe0fcdc44..763400b66 100644
--- a/tests/test_server.py
+++ b/tests/test_server.py
@@ -687,6 +687,18 @@ def ingest(message: str):
'''
+EXAMPLE_TOOL_SOURCE_WITH_ENV_VAR = '''
+def ingest():
+ """
+ Ingest a message into the system.
+
+ Returns:
+ str: The result of ingesting the message.
+ """
+ import os
+ return os.getenv("secret")
+'''
+
EXAMPLE_TOOL_SOURCE_WITH_DISTRACTOR = '''
def util_do_nothing():
@@ -721,7 +733,7 @@ def test_tool_run(server, mock_e2b_api_key_none, user, agent_id):
actor=user,
tool_source=EXAMPLE_TOOL_SOURCE,
tool_source_type="python",
- tool_args=json.dumps({"message": "Hello, world!"}),
+ tool_args={"message": "Hello, world!"},
# tool_name="ingest",
)
print(result)
@@ -730,11 +742,24 @@ def test_tool_run(server, mock_e2b_api_key_none, user, agent_id):
assert not result.stdout
assert not result.stderr
+ result = server.run_tool_from_source(
+ actor=user,
+ tool_source=EXAMPLE_TOOL_SOURCE_WITH_ENV_VAR,
+ tool_source_type="python",
+ tool_args={},
+ tool_env_vars={"secret": "banana"},
+ )
+ print(result)
+ assert result.status == "success"
+ assert result.tool_return == "banana", result.tool_return
+ assert not result.stdout
+ assert not result.stderr
+
result = server.run_tool_from_source(
actor=user,
tool_source=EXAMPLE_TOOL_SOURCE,
tool_source_type="python",
- tool_args=json.dumps({"message": "Well well well"}),
+ tool_args={"message": "Well well well"},
# tool_name="ingest",
)
print(result)
@@ -747,7 +772,7 @@ def test_tool_run(server, mock_e2b_api_key_none, user, agent_id):
actor=user,
tool_source=EXAMPLE_TOOL_SOURCE,
tool_source_type="python",
- tool_args=json.dumps({"bad_arg": "oh no"}),
+ tool_args={"bad_arg": "oh no"},
# tool_name="ingest",
)
print(result)
@@ -763,7 +788,7 @@ def test_tool_run(server, mock_e2b_api_key_none, user, agent_id):
actor=user,
tool_source=EXAMPLE_TOOL_SOURCE_WITH_DISTRACTOR,
tool_source_type="python",
- tool_args=json.dumps({"message": "Well well well"}),
+ tool_args={"message": "Well well well"},
# tool_name="ingest",
)
print(result)
@@ -778,7 +803,7 @@ def test_tool_run(server, mock_e2b_api_key_none, user, agent_id):
actor=user,
tool_source=EXAMPLE_TOOL_SOURCE_WITH_DISTRACTOR,
tool_source_type="python",
- tool_args=json.dumps({"message": "Well well well"}),
+ tool_args={"message": "Well well well"},
tool_name="ingest",
)
print(result)
@@ -793,7 +818,7 @@ def test_tool_run(server, mock_e2b_api_key_none, user, agent_id):
actor=user,
tool_source=EXAMPLE_TOOL_SOURCE_WITH_DISTRACTOR,
tool_source_type="python",
- tool_args=json.dumps({}),
+ tool_args={},
tool_name="util_do_nothing",
)
print(result)