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(security): use JSON instead of pickle for sandbox->server tool result transport (#3343)

Kian Jones1131535716e8
diff --git a/letta/functions/composio_helpers.py b/letta/functions/composio_helpers.py
index 40d497916..58f7f6249 100644
--- a/letta/functions/composio_helpers.py
+++ b/letta/functions/composio_helpers.py
@@ -79,7 +79,7 @@ async def execute_composio_action_async(
print(type(e))
raise RuntimeError(f"An unexpected error occurred in Composio SDK while executing action '{action_name}': {str(e)}")
- if "error" in response and response["error"]:
+ if response.get("error"):
raise RuntimeError(f"Error while executing action '{action_name}': {str(response['error'])}")
return response.get("data")
diff --git a/letta/llm_api/chatgpt_oauth_client.py b/letta/llm_api/chatgpt_oauth_client.py
index e508f83d2..9bbb79754 100644
--- a/letta/llm_api/chatgpt_oauth_client.py
+++ b/letta/llm_api/chatgpt_oauth_client.py
@@ -45,7 +45,6 @@ from letta.llm_api.llm_client_base import LLMClientBase
from letta.log import get_logger
from letta.otel.tracing import trace_method
from letta.schemas.enums import AgentType, ProviderCategory
-from letta.schemas.letta_message_content import TextContent
from letta.schemas.llm_config import LLMConfig
from letta.schemas.message import Message as PydanticMessage
from letta.schemas.openai.chat_completion_response import (
diff --git a/letta/llm_api/google_vertex_client.py b/letta/llm_api/google_vertex_client.py
index 5a7511558..7647cd429 100644
--- a/letta/llm_api/google_vertex_client.py
+++ b/letta/llm_api/google_vertex_client.py
@@ -40,7 +40,6 @@ from letta.log import get_logger
from letta.otel.tracing import trace_method
from letta.schemas.agent import AgentType
from letta.schemas.enums import ProviderCategory
-from letta.schemas.letta_message_content import TextContent
from letta.schemas.llm_config import LLMConfig
from letta.schemas.message import Message as PydanticMessage
from letta.schemas.openai.chat_completion_request import Tool, Tool as OpenAITool
diff --git a/letta/schemas/providers.py b/letta/schemas/providers.py
index 747d6836f..9190d26a4 100644
--- a/letta/schemas/providers.py
+++ b/letta/schemas/providers.py
@@ -4,11 +4,11 @@ from typing import List, Literal, Optional
import aiohttp
import requests
+from letta.llm_api.azure_openai import get_azure_chat_completions_endpoint, get_azure_embeddings_endpoint
+from letta.llm_api.azure_openai_constants import AZURE_MODEL_TO_CONTEXT_LENGTH
from pydantic import BaseModel, Field, model_validator
from letta.constants import DEFAULT_EMBEDDING_CHUNK_SIZE, LETTA_MODEL_ENDPOINT, LLM_MAX_TOKENS, MIN_CONTEXT_WINDOW
-from letta.llm_api.azure_openai import get_azure_chat_completions_endpoint, get_azure_embeddings_endpoint
-from letta.llm_api.azure_openai_constants import AZURE_MODEL_TO_CONTEXT_LENGTH
from letta.schemas.embedding_config import EmbeddingConfig
from letta.schemas.embedding_config_overrides import EMBEDDING_HANDLE_OVERRIDES
from letta.schemas.enums import ProviderCategory, ProviderType
@@ -1537,9 +1537,10 @@ class BedrockProvider(Provider):
def check_api_key(self):
"""Check if the Bedrock credentials are valid"""
- from letta.errors import LLMAuthenticationError
from letta.llm_api.aws_bedrock import bedrock_get_model_list
+ from letta.errors import LLMAuthenticationError
+
try:
# For BYOK providers, use the custom credentials
if self.provider_category == ProviderCategory.byok:
diff --git a/letta/server/rest_api/routers/openai/chat_completions/chat_completions.py b/letta/server/rest_api/routers/openai/chat_completions/chat_completions.py
index 92cbf04e2..86e357387 100644
--- a/letta/server/rest_api/routers/openai/chat_completions/chat_completions.py
+++ b/letta/server/rest_api/routers/openai/chat_completions/chat_completions.py
@@ -1,7 +1,7 @@
import asyncio
-from typing import TYPE_CHECKING, List, Optional, Union
+from typing import TYPE_CHECKING, List, Union
-from fastapi import APIRouter, Body, Depends, Header, HTTPException
+from fastapi import APIRouter, Body, Depends, HTTPException
from fastapi.responses import StreamingResponse
from openai.types.chat.completion_create_params import CompletionCreateParams
diff --git a/letta/services/files_agents_manager.py b/letta/services/files_agents_manager.py
index 7d50f93e4..7b312a932 100644
--- a/letta/services/files_agents_manager.py
+++ b/letta/services/files_agents_manager.py
@@ -1,7 +1,7 @@
from datetime import datetime, timezone
from typing import Dict, List, Optional, Union
-from sqlalchemy import and_, func, or_, select, tuple_, update
+from sqlalchemy import and_, func, select, tuple_, update
from letta.log import get_logger
from letta.orm.errors import NoResultFound
diff --git a/letta/services/helpers/tool_parser_helper.py b/letta/services/helpers/tool_parser_helper.py
index 4633f91c7..0142b3670 100644
--- a/letta/services/helpers/tool_parser_helper.py
+++ b/letta/services/helpers/tool_parser_helper.py
@@ -1,6 +1,6 @@
import ast
import base64
-import pickle
+import json
from typing import Any, Union
from letta.constants import REQUEST_HEARTBEAT_DESCRIPTION, REQUEST_HEARTBEAT_PARAM, SEND_MESSAGE_TOOL_NAME
@@ -11,16 +11,25 @@ from letta.types import JsonDict, JsonValue
def parse_stdout_best_effort(text: Union[str, bytes]) -> tuple[Any, AgentState | None]:
"""
- Decode and unpickle the result from the function execution if possible.
+ Decode the JSON-encoded result emitted by the tool sandbox.
Returns (function_return_value, agent_state).
+
+ The transport is JSON; AgentState is rehydrated via pydantic validation.
"""
if not text:
return None, None
- if isinstance(text, str):
- text = base64.b64decode(text)
- result = pickle.loads(text)
- agent_state = result["agent_state"]
- return result["results"], agent_state
+ if isinstance(text, bytes):
+ payload = text.decode("utf-8")
+ else:
+ # Legacy callers (e.g. E2B) may send a base64-encoded blob of JSON bytes.
+ try:
+ payload = base64.b64decode(text, validate=True).decode("utf-8")
+ except Exception:
+ payload = text
+ result = json.loads(payload)
+ agent_state_payload = result.get("agent_state")
+ agent_state = AgentState.model_validate(agent_state_payload) if agent_state_payload else None
+ return result.get("results"), agent_state
def parse_function_arguments(source_code: str, tool_name: str):
diff --git a/letta/services/tool_executor/tool_execution_sandbox.py b/letta/services/tool_executor/tool_execution_sandbox.py
index ebc18dd6e..f29a8ad0f 100644
--- a/letta/services/tool_executor/tool_execution_sandbox.py
+++ b/letta/services/tool_executor/tool_execution_sandbox.py
@@ -1,7 +1,7 @@
import base64
import io
+import json
import os
-import pickle
import subprocess
import sys
import tempfile
@@ -473,13 +473,17 @@ class ToolExecutionSandbox:
# general utility functions
def parse_best_effort(self, text: str) -> Any:
+ """Decode the JSON-encoded payload emitted by the tool sandbox.
+
+ AgentState is rehydrated via pydantic validation.
+ """
if not text:
return None, None
- result = pickle.loads(base64.b64decode(text))
- agent_state = None
- if result["agent_state"] is not None:
- agent_state = result["agent_state"]
- return result["results"], agent_state
+ decoded = base64.b64decode(text).decode("utf-8")
+ result = json.loads(decoded)
+ agent_state_payload = result.get("agent_state")
+ agent_state = AgentState.model_validate(agent_state_payload) if agent_state_payload else None
+ return result.get("results"), agent_state
def generate_execution_script(self, agent_state: AgentState, wrap_print_with_markers: bool = False) -> str:
"""
@@ -501,6 +505,7 @@ class ToolExecutionSandbox:
# dump JSON representation of agent state to re-load
code = "from typing import *\n"
code += "import pickle\n"
+ code += "import json as _letta_json\n"
code += "import sys\n"
code += "import base64\n"
@@ -556,14 +561,23 @@ class ToolExecutionSandbox:
# TODO: handle wrapped print
+ code += "if agent_state is not None:\n"
+ code += " try:\n"
+ code += " _letta_agent_state_payload = agent_state.model_dump(mode='json')\n"
+ code += " except Exception:\n"
+ code += " _letta_agent_state_payload = None\n"
+ code += "else:\n"
+ code += " _letta_agent_state_payload = None\n"
code += (
self.LOCAL_SANDBOX_RESULT_VAR_NAME
+ ' = {"results": '
+ self.invoke_function_call(inject_agent_state=inject_agent_state) # this inject_agent_state is the main difference
- + ', "agent_state": agent_state}\n'
+ + ', "agent_state": _letta_agent_state_payload}\n'
)
code += (
- f"{self.LOCAL_SANDBOX_RESULT_VAR_NAME} = base64.b64encode(pickle.dumps({self.LOCAL_SANDBOX_RESULT_VAR_NAME})).decode('utf-8')\n"
+ f"{self.LOCAL_SANDBOX_RESULT_VAR_NAME} = base64.b64encode("
+ f"_letta_json.dumps({self.LOCAL_SANDBOX_RESULT_VAR_NAME}, default=str).encode('utf-8')"
+ f").decode('utf-8')\n"
)
if wrap_print_with_markers:
diff --git a/letta/services/tool_sandbox/base.py b/letta/services/tool_sandbox/base.py
index d0787087b..f24d4c208 100644
--- a/letta/services/tool_sandbox/base.py
+++ b/letta/services/tool_sandbox/base.py
@@ -199,6 +199,7 @@ class AsyncToolSandboxBase(ABC):
[
"from typing import *",
"import pickle",
+ "import json as _letta_json",
"import sys",
"import base64",
"import struct",
@@ -309,11 +310,18 @@ class AsyncToolSandboxBase(ABC):
' print(f"Failed to serialize result with Pydantic wrapper: {e}")',
" _serialized_result = str(_function_result)",
"",
+ "if agent_state is not None:",
+ " try:",
+ " _letta_agent_state_payload = agent_state.model_dump(mode='json')",
+ " except Exception:",
+ " _letta_agent_state_payload = None",
+ "else:",
+ " _letta_agent_state_payload = None",
f"{local_sandbox_result_var_name} = {{",
' "results": _serialized_result,',
- ' "agent_state": agent_state',
+ ' "agent_state": _letta_agent_state_payload',
"}",
- f"{local_sandbox_result_var_name}_pkl = pickle.dumps({local_sandbox_result_var_name})",
+ f"{local_sandbox_result_var_name}_pkl = _letta_json.dumps({local_sandbox_result_var_name}, default=str).encode('utf-8')",
]
)
else:
@@ -339,9 +347,16 @@ class AsyncToolSandboxBase(ABC):
' print(f"Failed to serialize result with Pydantic wrapper: {e}")',
" _serialized_result = str(_function_result)",
"",
+ " if agent_state is not None:",
+ " try:",
+ " _letta_agent_state_payload = agent_state.model_dump(mode='json')",
+ " except Exception:",
+ " _letta_agent_state_payload = None",
+ " else:",
+ " _letta_agent_state_payload = None",
" return {",
' "results": _serialized_result,',
- ' "agent_state": agent_state',
+ ' "agent_state": _letta_agent_state_payload',
" }",
]
)
@@ -349,7 +364,9 @@ class AsyncToolSandboxBase(ABC):
lines.append(f"{local_sandbox_result_var_name} = await _async_wrapper()")
else:
lines.append(f"{local_sandbox_result_var_name} = asyncio.run(_async_wrapper())")
- lines.append(f"{local_sandbox_result_var_name}_pkl = pickle.dumps({local_sandbox_result_var_name})")
+ lines.append(
+ f"{local_sandbox_result_var_name}_pkl = _letta_json.dumps({local_sandbox_result_var_name}, default=str).encode('utf-8')"
+ )
if wrap_print_with_markers:
lines.extend(
diff --git a/letta/templates/sandbox_code_file.py.j2 b/letta/templates/sandbox_code_file.py.j2
index 13204c3a4..02307c6a9 100644
--- a/letta/templates/sandbox_code_file.py.j2
+++ b/letta/templates/sandbox_code_file.py.j2
@@ -1,6 +1,7 @@
{{ 'from __future__ import annotations' if future_import else '' }}
from typing import *
import pickle
+import json as _letta_json
import sys
import base64
import struct
@@ -46,12 +47,20 @@ except Exception as e:
print(f"Failed to serialize result with Pydantic wrapper: {e}")
_serialized_result = str(_function_result)
+if agent_state is not None:
+ try:
+ _letta_agent_state_payload = agent_state.model_dump(mode='json')
+ except Exception:
+ _letta_agent_state_payload = None
+else:
+ _letta_agent_state_payload = None
+
{{ local_sandbox_result_var_name }} = {
"results": _serialized_result,
- "agent_state": agent_state
+ "agent_state": _letta_agent_state_payload
}
-{{ local_sandbox_result_var_name }}_pkl = pickle.dumps({{ local_sandbox_result_var_name }})
+{{ local_sandbox_result_var_name }}_pkl = _letta_json.dumps({{ local_sandbox_result_var_name }}, default=str).encode('utf-8')
{% if wrap_print_with_markers %}
{# Combine everything to flush and write at once. #}
diff --git a/letta/templates/sandbox_code_file_async.py.j2 b/letta/templates/sandbox_code_file_async.py.j2
index 72e18cb19..42c1fe237 100644
--- a/letta/templates/sandbox_code_file_async.py.j2
+++ b/letta/templates/sandbox_code_file_async.py.j2
@@ -1,6 +1,7 @@
{{ 'from __future__ import annotations' if future_import else '' }}
from typing import *
import pickle
+import json as _letta_json
import sys
import base64
import struct
@@ -48,9 +49,17 @@ async def _async_wrapper():
print(f"Failed to serialize result with Pydantic wrapper: {e}")
_serialized_result = str(_function_result)
+ if agent_state is not None:
+ try:
+ _letta_agent_state_payload = agent_state.model_dump(mode='json')
+ except Exception:
+ _letta_agent_state_payload = None
+ else:
+ _letta_agent_state_payload = None
+
return {
"results": _serialized_result,
- "agent_state": agent_state
+ "agent_state": _letta_agent_state_payload
}
{# Run the async function - method depends on environment #}
@@ -62,7 +71,7 @@ async def _async_wrapper():
{{ local_sandbox_result_var_name }} = asyncio.run(_async_wrapper())
{% endif %}
-{{ local_sandbox_result_var_name }}_pkl = pickle.dumps({{ local_sandbox_result_var_name }})
+{{ local_sandbox_result_var_name }}_pkl = _letta_json.dumps({{ local_sandbox_result_var_name }}, default=str).encode('utf-8')
{% if wrap_print_with_markers %}
{# Combine everything to flush and write at once. #}
diff --git a/pyproject.toml b/pyproject.toml
index 54eafc72b..30469e301 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "letta"
-version = "0.16.7"
+version = "0.16.8"
description = "Create LLM agents with long-term memory and custom tools"
authors = [
{name = "Letta Team", email = "[email protected]"},
diff --git a/tests/test_google_embeddings.py b/tests/test_google_embeddings.py
index 3304135b2..728ddabd6 100644
--- a/tests/test_google_embeddings.py
+++ b/tests/test_google_embeddings.py
@@ -1,7 +1,6 @@
import httpx
import pytest
from dotenv import load_dotenv
-
from letta.embeddings import GoogleEmbeddings # type: ignore[import-untyped] # Adjust the import based on your module structure
load_dotenv()
diff --git a/tests/test_managers.py b/tests/test_managers.py
index 579d79246..83e12e073 100644
--- a/tests/test_managers.py
+++ b/tests/test_managers.py
@@ -10714,7 +10714,7 @@ async def test_create_mcp_server(mock_get_client, server, default_user):
async def test_create_mcp_server_with_tools(mock_get_client, server, default_user):
"""Test that creating an MCP server automatically syncs and persists its tools."""
from letta.functions.mcp_client.types import MCPToolHealth
- from letta.schemas.mcp import MCPServer, MCPServerType, SSEServerConfig
+ from letta.schemas.mcp import MCPServer, MCPServerType
from letta.settings import tool_settings
if tool_settings.mcp_read_from_config:
@@ -11126,7 +11126,7 @@ async def test_mcp_server_delete_removes_all_sessions_for_url_and_user(server, d
@pytest.mark.asyncio
async def test_mcp_server_resync_tools(server, default_user, default_organization):
"""Test that resyncing MCP server tools correctly handles added, deleted, and updated tools."""
- from unittest.mock import AsyncMock, MagicMock, patch
+ from unittest.mock import AsyncMock, patch
from letta.functions.mcp_client.types import MCPTool, MCPToolHealth
from letta.schemas.mcp import MCPServer as PydanticMCPServer, MCPServerType
diff --git a/tests/test_temporal_metrics_local.py b/tests/test_temporal_metrics_local.py
index 9d4f1d6d8..91d625752 100644
--- a/tests/test_temporal_metrics_local.py
+++ b/tests/test_temporal_metrics_local.py
@@ -7,7 +7,6 @@ import os
from unittest.mock import patch
import pytest
-
from letta.agents.temporal.metrics import (
ActivityMetrics,
TemporalMetrics,
diff --git a/uv.lock b/uv.lock
index 7780b8086..2c02da3b6 100644
--- a/uv.lock
+++ b/uv.lock
@@ -2510,7 +2510,7 @@ wheels = [
[[package]]
name = "letta"
-version = "0.16.7"
+version = "0.16.8"
source = { editable = "." }
dependencies = [
{ name = "aiofiles" },