### Add and Run Example Script Source: https://github.com/letta-ai/letta-python/blob/main/CONTRIBUTING.md Add your example code to a Python file in the 'examples/' directory and make it executable. Then, run the example against your API. ```python # add an example to examples/.py #!/usr/bin/env -S rye run python … ``` ```sh chmod +x examples/.py # run the example against your api ./examples/.py ``` -------------------------------- ### Install Letta Python SDK Source: https://github.com/letta-ai/letta-python/blob/main/README.md Install the Letta Python SDK using pip. ```bash pip install letta-client ``` -------------------------------- ### Install from Wheel File Source: https://github.com/letta-ai/letta-python/blob/main/CONTRIBUTING.md Install the Letta Python package efficiently using the generated wheel file. ```sh pip install ./path-to-wheel-file.whl ``` -------------------------------- ### Install from Git Repository Source: https://github.com/letta-ai/letta-python/blob/main/CONTRIBUTING.md Install the Letta Python package directly from its Git repository using pip. ```sh pip install git+ssh://git@github.com/letta-ai/letta-python.git ``` -------------------------------- ### Create Stateful Agent and Send Message Source: https://github.com/letta-ai/letta-python/blob/main/README.md Example of creating a stateful agent with initial memory blocks and tools, then sending a message to it. Requires a Letta API key or a configured base URL for a local server. ```python from letta_client import Letta client = Letta(api_key="LETTA_API_KEY") agent_state = client.agents.create( model="openai/gpt-4o-mini", embedding="openai/text-embedding-3-small", memory_blocks=[ { "label": "human", "value": "The human's name is Chad. They like vibe coding." }, { "label": "persona", "value": "My name is Sam, a helpful assistant." } ], tools=["web_search", "run_code"] ) print(agent_state.id) # agent-d9be...0846 response = client.agents.messages.create( agent_id=agent_state.id, messages=[ { "role": "user", "content": "Hey, nice to meet you, my name is Brad." } ] ) # the agent will think, then edit its memory using a tool for message in response.messages: print(message) # The content of this memory block will be something like # "The human's name is Brad. They like vibe coding." # Fetch this block's content with: human_block = client.agents.blocks.retrieve(agent_id=agent_state.id, block_label="human") print(human_block.value) ``` -------------------------------- ### Install Development Dependencies with Pip Source: https://github.com/letta-ai/letta-python/blob/main/CONTRIBUTING.md If not using Rye, install development dependencies using pip and the requirements-dev.lock file. ```sh pip install -r requirements-dev.lock ``` -------------------------------- ### Create a New Stateful AI Agent Source: https://context7.com/letta-ai/letta-python/llms.txt Shows how to create a new agent with specified model, embedding, memory blocks, tools, tags, timezone, and system prompt. Includes an example with tool rules and secrets, as well as an asynchronous variant. ```python from letta_client import Letta client = Letta(api_key="LETTA_API_KEY") # Basic agent with memory blocks and built-in tools agent = client.agents.create( model="openai/gpt-4o-mini", embedding="openai/text-embedding-3-small", name="support-bot", description="Customer support agent with persistent user memory", memory_blocks=[ {"label": "human", "value": "The user's name is Alice. She is a software engineer."}, {"label": "persona", "value": "I am a helpful support assistant named Sam."}, ], tools=["web_search", "run_code"], tags=["production", "support"], timezone="America/New_York", enable_sleeptime=True, # offloads memory management to background thread system="You are a helpful customer support agent. Always be concise.", ) print(agent.id) # agent-d9be...0846 print(agent.name) # support-bot print(agent.model) # openai/gpt-4o-mini # Agent with tool rules (enforce tool call ordering) agent_with_rules = client.agents.create( model="openai/gpt-4o", embedding="openai/text-embedding-3-small", memory_blocks=[{"label": "persona", "value": "I am an analyst."} ], tool_rules=[ {"type": "InitToolRule", "tool_name": "think"}, {"type": "TerminalToolRule", "tool_name": "send_message"}, ], secrets={"OPENAI_API_KEY": "sk-..."}, # injected into tool execution env ) # Async variant import asyncio from letta_client import AsyncLetta async def create_async(): aclient = AsyncLetta(api_key="LETTA_API_KEY") agent = await aclient.agents.create( model="openai/gpt-4o-mini", memory_blocks=[{"label": "persona", "value": "I am async Sam."} ], ) return agent ``` -------------------------------- ### Configure Agent Creation with Timeouts Source: https://github.com/letta-ai/letta-python/blob/main/README.md Set a custom timeout in seconds for agent creation requests. The default is 60 seconds, and this example sets it to 30. ```python response = client.agents.create( {...}, request_options={"timeout_in_seconds": 30} # Default: 60 ) ``` -------------------------------- ### Sync Dependencies with Rye Source: https://github.com/letta-ai/letta-python/blob/main/CONTRIBUTING.md After installing Rye manually, use this command to sync all dependencies and features. ```sh rye sync --all-features ``` -------------------------------- ### Configure Agent Creation with Retries Source: https://github.com/letta-ai/letta-python/blob/main/README.md Customize the number of retries for agent creation requests. The default is 2, and this example sets it to 3. ```python response = client.agents.create( {...}, request_options={"max_retries": 3} # Default: 2 ) ``` -------------------------------- ### Add Custom Headers to Agent Creation Source: https://github.com/letta-ai/letta-python/blob/main/README.md Include custom headers in agent creation requests. This example adds an 'X-Custom-Header' with a specified value. ```python response = client.agents.create( {...}, request_options={ "additional_headers": { "X-Custom-Header": "value" } } ) ``` -------------------------------- ### Create Multi-agent Shared Memory Source: https://github.com/letta-ai/letta-python/blob/main/README.md Example of creating a shared memory block and attaching it to multiple agents, ensuring all agents have an up-to-date view of its content. ```python # Create shared block shared_block = client.blocks.create( label="organization", value="Shared team context" ) # Attach to multiple agents agent1 = client.agents.create( memory_blocks=[{"label": "persona", "value": "I am a supervisor"}], block_ids=[shared_block.id] ) agent2 = client.agents.create( memory_blocks=[{"label": "persona", "value": "I am a worker"}], block_ids=[shared_block.id] ) ``` -------------------------------- ### Search, List, and Retrieve Messages Globally Source: https://context7.com/letta-ai/letta-python/llms.txt Provides examples for performing full-text and semantic searches across all messages, listing recent global messages, and retrieving a specific message by its ID. Useful for auditing and analytics. ```python results = client.messages.search( query="authentication error", limit=20, message_type="assistant_message", # filter by message type ) for r in results.messages: print(f"[agent:{r.agent_id}] {r.content[:80]}") ``` ```python all_msgs = client.messages.list(limit=50) for m in all_msgs: print(f"{m.id}: {m.message_type}") ``` ```python msg = client.messages.retrieve("msg-abc123") print(msg.content) ``` -------------------------------- ### Initialize Letta Clients (Sync and Async) Source: https://github.com/letta-ai/letta-python/blob/main/README.md Demonstrates how to initialize both synchronous and asynchronous clients for the Letta SDK. Requires an API key. ```python from letta_client import Letta from letta_client.types import CreateAgentRequest # Sync client client = Letta(api_key="LETTA_API_KEY") # Async client from letta_client import AsyncLetta async_client = AsyncLetta(api_key="LETTA_API_KEY") agent = await async_client.agents.create( model="openai/gpt-4o-mini", memory_blocks=[...] ) ``` -------------------------------- ### Initialize Letta Python Client Source: https://context7.com/letta-ai/letta-python/llms.txt Demonstrates synchronous and asynchronous client initialization with default and custom configurations, including API key, environment, project ID, timeouts, and retries. Also shows basic health check and error handling. ```python import os import asyncio from letta_client import Letta, AsyncLetta from letta_client.core.api_error import ApiError # --- Sync client (reads LETTA_API_KEY from environment) --- client = Letta() # --- Sync client with explicit key and local Docker server --- local_client = Letta( api_key="", # no key needed for local server environment="local", # http://localhost:8283 ) # --- Sync client with full options --- client = Letta( api_key=os.environ["LETTA_API_KEY"], project_id="proj-abc123", # scopes all calls to a project timeout=60.0, max_retries=3, ) # --- Async client --- async_client = AsyncLetta(api_key=os.environ["LETTA_API_KEY"]) # --- Health check --- health = client.health() print(health) # HealthResponse(status='ok') # --- Error handling --- try: client.agents.retrieve("agent-does-not-exist") except ApiError as e: print(e.status_code) # 404 print(e.message) print(e.body) # --- Clone client with overrides (useful for per-request project isolation) --- scoped = client.with_options(project_id="proj-xyz") ``` -------------------------------- ### Connect to MCP Server and List Tools Source: https://github.com/letta-ai/letta-python/blob/main/README.md Create an MCP server instance and retrieve a list of available tools. Requires server configuration details. ```python # First, create an MCP server (example: weather server) weather_server = client.mcp_servers.create( server_name="weather-server", config={ "mcp_server_type": "streamable_http", "server_url": "https://weather-mcp.example.com/mcp", } ) # List tools available from the MCP server tools = client.mcp_servers.tools.list(weather_server.id) # Create agent with MCP tool agent = client.agents.create( model="openai/gpt-4o-mini", tool_ids=[tool.id] ) ``` -------------------------------- ### Client Initialization Source: https://context7.com/letta-ai/letta-python/llms.txt Demonstrates how to initialize the synchronous and asynchronous Letta clients, including options for API keys, environments, timeouts, and project scoping. Also shows basic health checks and error handling. ```APIDOC ## Client Initialization `Letta` / `AsyncLetta` — synchronous and asynchronous entry points for the entire API surface. The API key is read from `LETTA_API_KEY` by default; `environment` selects between `"cloud"` (default, `https://api.letta.com`) and `"local"` (`http://localhost:8283`). Supply `base_url` to point at any custom server. ```python import os import asyncio from letta_client import Letta, AsyncLetta from letta_client.core.api_error import ApiError # --- Sync client (reads LETTA_API_KEY from environment) --- client = Letta() # --- Sync client with explicit key and local Docker server --- local_client = Letta( api_key="", # no key needed for local server environment="local", # http://localhost:8283 ) # --- Sync client with full options --- client = Letta( api_key=os.environ["LETTA_API_KEY"], project_id="proj-abc123", # scopes all calls to a project timeout=60.0, max_retries=3, ) # --- Async client --- async_client = AsyncLetta(api_key=os.environ["LETTA_API_KEY"]) # --- Health check --- health = client.health() print(health) # HealthResponse(status='ok') # --- Error handling --- try: client.agents.retrieve("agent-does-not-exist") except ApiError as e: print(e.status_code) # 404 print(e.message) print(e.body) # --- Clone client with overrides (useful for per-request project isolation) --- scoped = client.with_options(project_id="proj-xyz") ``` ``` -------------------------------- ### Get Health Status Source: https://github.com/letta-ai/letta-python/blob/main/api.md Retrieves the health status of the Letta service. ```APIDOC ## GET /v1/health/ ### Description Retrieves the health status of the Letta service. ### Method GET ### Endpoint /v1/health/ ### Response #### Success Response (200) - **body** (HealthResponse) - The health status of the service. ``` -------------------------------- ### Create, Save, and Instantiate Agent Templates Source: https://context7.com/letta-ai/letta-python/llms.txt Demonstrates creating a new agent template, saving a new version from a live agent, and instantiating a new agent from a specific template version. Use `templates.create` to define a blueprint, `templates.save` to snapshot a live agent, and `templates.agents.create` to launch an agent from a version. ```python template = client.templates.create( name="customer-support-v1", description="Standard customer support agent template", agent_id="agent-d9be0846", # source agent to template from ) print(template.template_name) ``` ```python saved = client.templates.save( template_name="customer-support-v1", agent_id="agent-updated-9999", version_label="v2.0", ) ``` ```python rolled_back = client.templates.rollback( template_name="customer-support-v1", version="v1.0", ) ``` ```python new_agent = client.templates.agents.create( template_version="customer-support-v1@v2.0", name="support-agent-prod-42", memory_variables={"user_name": "Bob", "user_tier": "Enterprise"}, ) print(new_agent.agent_id) ``` ```python client.templates.update( template_name="customer-support-v1", description="Updated support template with tool approval workflow", ) ``` ```python client.templates.delete("customer-support-v1") ``` -------------------------------- ### Use Custom HTTP Client for Letta Source: https://github.com/letta-ai/letta-python/blob/main/README.md Initialize the Letta client with a custom httpx client, allowing configuration of proxies and transport settings. ```python import httpx from letta_client import Letta client = Letta( httpx_client=httpx.Client( proxies="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ) ) ``` -------------------------------- ### Import and Export Agent Files Source: https://github.com/letta-ai/letta-python/blob/main/README.md Demonstrates how to import an agent from a `.af` file and export an agent's schema to a file. ```python # Import agent with open('/path/to/agent.af', 'rb') as f: agent = client.agents.import_file(file=f) # Export agent schema = client.agents.export_file(agent_id=agent.id) ``` -------------------------------- ### Async Agent Creation and Interaction Source: https://context7.com/letta-ai/letta-python/llms.txt Demonstrates asynchronous agent creation, message interaction, and agent deletion using AsyncLetta. Ensure asyncio is imported. ```python import asyncio async def main(): aclient = AsyncLetta(api_key="LETTA_API_KEY") agent = await aclient.agents.create( model="openai/gpt-4o-mini", embedding="openai/text-embedding-3-small", memory_blocks=[{"label": "persona", "value": "I am async Sam."}] ) response = await aclient.agents.messages.create( agent_id=agent.id, messages=[{"role": "user", "content": "Hello async world!"}] ) for msg in response.messages: print(msg) await aclient.agents.delete(agent.id) asyncio.run(main()) ``` -------------------------------- ### Bootstrap Environment with Rye Source: https://github.com/letta-ai/letta-python/blob/main/CONTRIBUTING.md Run this script to automatically provision a Python environment with the expected Python version using Rye. ```sh ./scripts/bootstrap ``` -------------------------------- ### Manage Agent Memory Blocks Source: https://github.com/letta-ai/letta-python/blob/main/README.md Demonstrates creating an agent with initial memory blocks, updating an existing block, and retrieving a specific block's content. ```python # Create agent with memory blocks agent = client.agents.create( memory_blocks=[ {"label": "persona", "value": "I'm a helpful assistant."}, {"label": "human", "value": "User preferences and info."} ] ) # Update blocks manually client.agents.blocks.update( agent_id=agent.id, block_label="human", value="Updated user information" ) # Retrieve a block block = client.agents.blocks.retrieve(agent_id=agent.id, block_label="human") ``` -------------------------------- ### Folders: Create, Upload, Attach Source: https://context7.com/letta-ai/letta-python/llms.txt Create file-system folders, upload files into them, and attach them to agents for retrieval-augmented generation. Files are chunked and embedded automatically. ```APIDOC ## folders.create / folders.files.upload / agents.folders.attach `POST /v1/folders/` — Create file-system folders, upload files into them, and attach them to agents for retrieval-augmented generation. Files uploaded to folders are chunked and embedded automatically. Agents with an attached folder can search and open files using built-in filesystem tools. ### Create a folder ```python folder = client.folders.create(name="product-docs") ``` ### Upload files to folder ```python with open("product_manual.pdf", "rb") as f: upload = client.folders.files.upload(file=f, folder_id=folder.id) with open("release_notes.txt", "rb") as f: client.folders.files.upload(file=f, folder_id=folder.id) ``` ### List files in folder ```python files = client.folders.files.list(folder_id=folder.id) ``` ### Create agent and attach folder ```python agent = client.agents.create( model="openai/gpt-4o-mini", embedding="openai/text-embedding-3-small", memory_blocks=[{"label": "persona", "value": "I am a product expert."}], ) client.agents.folders.attach(agent_id=agent.id, folder_id=folder.id) ``` ### Manage open files in agent context ```python open_files = client.agents.files.list(agent_id=agent.id) client.agents.files.close_all(agent_id=agent.id) ``` ### Detach folder from agent ```python client.agents.folders.detach(agent_id=agent.id, folder_id=folder.id) ``` ### Delete folder ```python client.folders.delete(folder.id) ``` ``` -------------------------------- ### Run Tests Source: https://github.com/letta-ai/letta-python/blob/main/CONTRIBUTING.md Execute the test suite for the Letta Python project. ```sh ./scripts/test ``` -------------------------------- ### MCP Servers: Create, List, Tools, Run Source: https://context7.com/letta-ai/letta-python/llms.txt Register Model Context Protocol (MCP) servers and use their tools in agents. Supports streamable_http, sse, and stdio transport types. ```APIDOC ## mcp_servers.create / mcp_servers.list / mcp_servers.tools.list / mcp_servers.tools.run `POST/GET /v1/mcp-servers/` — Register Model Context Protocol (MCP) servers and use their tools in agents. Letta supports three MCP transport types: `streamable_http`, `sse`, and `stdio`. Once a server is registered, its tools appear in the tool library and can be attached to agents. ### Register a Streamable HTTP MCP server ```python client.mcp_servers.create( server_name="weather-server", config={ "mcp_server_type": "streamable_http", "server_url": "https://weather-mcp.example.com/mcp", }, ) ``` ### Register an SSE MCP server ```python client.mcp_servers.create( server_name="analytics-sse", config={ "mcp_server_type": "sse", "url": "https://analytics.example.com/sse", }, ) ``` ### Register a stdio MCP server ```python client.mcp_servers.create( server_name="local-fs-server", config={ "mcp_server_type": "stdio", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"], }, ) ``` ### List tools from an MCP server ```python tools = client.mcp_servers.tools.list(weather_server.id) ``` ### Run a tool directly ```python result = client.mcp_servers.tools.run( tool_id=tools[0].id, mcp_server_id=weather_server.id, args={"location": "New York, NY"}, ) ``` ### Refresh tools from server ```python client.mcp_servers.refresh(weather_server.id) ``` ### Attach MCP tool to agent ```python agent = client.agents.create( model="openai/gpt-4o-mini", memory_blocks=[{"label": "persona", "value": "I am a weather assistant."}], tool_ids=[tools[0].id], ) ``` ``` -------------------------------- ### Create a Folder Source: https://github.com/letta-ai/letta-python/blob/main/api.md Use this method to create a new folder. Requires folder creation parameters. ```python from letta_client.types import Folder # Example usage (assuming client is initialized) # folder: Folder = client.folders.create(name="My New Folder") ``` -------------------------------- ### Register and Use MCP Servers Source: https://context7.com/letta-ai/letta-python/llms.txt Register MCP servers of different types (streamable_http, sse, stdio), list their tools, and run tools directly. Refresh tools after server updates and attach them to agents. ```python from letta_client import Letta client = Letta(api_key="LETTA_API_KEY") # --- Register a Streamable HTTP MCP server --- weather_server = client.mcp_servers.create( server_name="weather-server", config={ "mcp_server_type": "streamable_http", "server_url": "https://weather-mcp.example.com/mcp", }, ) print(weather_server.id) # --- Register an SSE MCP server --- see_server = client.mcp_servers.create( server_name="analytics-sse", config={ "mcp_server_type": "sse", "url": "https://analytics.example.com/sse", }, ) # --- Register a stdio MCP server --- stdio_server = client.mcp_servers.create( server_name="local-fs-server", config={ "mcp_server_type": "stdio", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"], }, ) # --- List tools from an MCP server --- tools = client.mcp_servers.tools.list(weather_server.id) for t in tools: print(f"{t.name}: {t.description}") # --- Run a tool directly --- result = client.mcp_servers.tools.run( tool_id=tools[0].id, mcp_server_id=weather_server.id, args={"location": "New York, NY"}, ) print(result.tool_return) # --- Refresh tools from server (after server updates) --- client.mcp_servers.refresh(weather_server.id) # --- Attach MCP tool to agent --- agent = client.agents.create( model="openai/gpt-4o-mini", memory_blocks=[{"label": "persona", "value": "I am a weather assistant."}], tool_ids=[tools[0].id], ) ``` -------------------------------- ### agents.create Source: https://context7.com/letta-ai/letta-python/llms.txt Creates a new stateful agent with specified configurations including model, memory blocks, tools, and system prompts. Supports both synchronous and asynchronous initialization. ```APIDOC ## agents.create `POST /v1/agents/` — Create a new stateful agent with memory blocks, tools, model config, and optional sleep-time memory management. Accepts `model` (format `provider/model-name`), `embedding`, `memory_blocks` (in-context persistent blocks), `tools` (by name) or `tool_ids` (by id), `system` (custom system prompt), `tags`, `secrets`, and dozens of other options. Returns `AgentState`. ```python from letta_client import Letta client = Letta(api_key="LETTA_API_KEY") # Basic agent with memory blocks and built-in tools agent = client.agents.create( model="openai/gpt-4o-mini", embedding="openai/text-embedding-3-small", name="support-bot", description="Customer support agent with persistent user memory", memory_blocks=[ {"label": "human", "value": "The user's name is Alice. She is a software engineer."}, {"label": "persona", "value": "I am a helpful support assistant named Sam."}, ], tools=["web_search", "run_code"], tags=["production", "support"], timezone="America/New_York", enable_sleeptime=True, # offloads memory management to background thread system="You are a helpful customer support agent. Always be concise.", ) print(agent.id) # agent-d9be...0846 print(agent.name) # support-bot print(agent.model) # openai/gpt-4o-mini # Agent with tool rules (enforce tool call ordering) agent_with_rules = client.agents.create( model="openai/gpt-4o", embedding="openai/text-embedding-3-small", memory_blocks=[{"label": "persona", "value": "I am an analyst."} ], tool_rules=[ {"type": "InitToolRule", "tool_name": "think"}, {"type": "TerminalToolRule", "tool_name": "send_message"}, ], secrets={"OPENAI_API_KEY": "sk-..."}, # injected into tool execution env ) # Async variant import asyncio from letta_client import AsyncLetta async def create_async(): aclient = AsyncLetta(api_key="LETTA_API_KEY") agent = await aclient.agents.create( model="openai/gpt-4o-mini", memory_blocks=[{"label": "persona", "value": "I am async Sam."} ], ) return agent ``` ``` -------------------------------- ### Steps Source: https://github.com/letta-ai/letta-python/blob/main/api.md List steps associated with a specific run. ```APIDOC ## GET /v1/runs/{run_id}/steps ### Description Lists steps for a specific run. ### Method GET ### Endpoint /v1/runs/{run_id}/steps ### Parameters #### Path Parameters - **run_id** (string) - Required - The ID of the run. #### Query Parameters - **params** (object) - Optional - Parameters for listing steps. See `StepListParams` type. ### Response #### Success Response (200) - **SyncArrayPage[Step]** - A paginated list of steps. ``` -------------------------------- ### Build Wheel File Source: https://github.com/letta-ai/letta-python/blob/main/CONTRIBUTING.md Build a distributable wheel file for the library using Rye or Python's build module. This creates files in the 'dist/' directory. ```sh rye build ``` ```sh python -m build ``` -------------------------------- ### Custom httpx Client Configuration Source: https://context7.com/letta-ai/letta-python/llms.txt Configure a Letta client with a custom httpx.Client to specify proxies, local addresses, and connection pool limits. ```python proxied_client = Letta( api_key="LETTA_API_KEY", http_client=httpx.Client( proxies="http://my.proxy.example.com:8080", transport=httpx.HTTPTransport(local_address="0.0.0.0"), limits=httpx.Limits(max_connections=100, max_keepalive_connections=20), ), ) ``` -------------------------------- ### Manage Folders and Upload Files Source: https://context7.com/letta-ai/letta-python/llms.txt Create folders, upload files into them, and attach folders to agents for RAG. Files are automatically chunked and embedded. Agents can search and open files using built-in tools. ```python from letta_client import Letta client = Letta(api_key="LETTA_API_KEY") # --- Create a folder --- folder = client.folders.create(name="product-docs") print(folder.id) # folder-abc # --- Upload files to folder --- with open("product_manual.pdf", "rb") as f: upload = client.folders.files.upload(file=f, folder_id=folder.id) print(upload.file_id) with open("release_notes.txt", "rb") as f: client.folders.files.upload(file=f, folder_id=folder.id) # --- List files in folder --- files = client.folders.files.list(folder_id=folder.id) for file in files: print(f"{file.file_name}: {file.file_size} bytes") # --- Create agent and attach folder --- agent = client.agents.create( model="openai/gpt-4o-mini", embedding="openai/text-embedding-3-small", memory_blocks=[{"label": "persona", "value": "I am a product expert."}], ) client.agents.folders.attach(agent_id=agent.id, folder_id=folder.id) # --- Manage open files in agent context --- open_files = client.agents.files.list(agent_id=agent.id) client.agents.files.close_all(agent_id=agent.id) # free context window # --- Detach folder from agent --- client.agents.folders.detach(agent_id=agent.id, folder_id=folder.id) # --- Delete folder --- client.folders.delete(folder.id) ``` -------------------------------- ### Create Template Source: https://github.com/letta-ai/letta-python/blob/main/api.md Creates a new template with the provided parameters. This is the entry point for defining new reusable template structures. ```APIDOC ## POST /v1/templates ### Description Creates a new template. ### Method POST ### Endpoint /v1/templates ### Parameters #### Request Body - **params** (object) - Optional - Parameters for creating the template. ``` -------------------------------- ### Publish Manually to PyPI Source: https://github.com/letta-ai/letta-python/blob/main/CONTRIBUTING.md Manually release a package by running the 'bin/publish-pypi' script with a PYPI_TOKEN set in the environment. ```sh bin/publish-pypi ``` -------------------------------- ### Steps API Source: https://context7.com/letta-ai/letta-python/llms.txt Inspect individual agent reasoning steps, attach human feedback labels, and retrieve performance metrics. Steps are the atomic units of an agent run. ```APIDOC ## steps.retrieve / steps.feedback.create / steps.metrics.retrieve `GET /v1/steps/{step_id}` — Inspect individual agent reasoning steps, attach human feedback labels, and retrieve performance metrics. Steps are the atomic units of an agent run (one LLM call = one step). Feedback (thumbs up/down) can be recorded per-step for RLHF workflows. ### Retrieve a step ```python client.steps.retrieve("step-abc123") ``` ### List all steps (global, paginated) ```python client.steps.list(limit=50) ``` ### Attach human feedback to a step ```python client.steps.feedback.create(step_id="step-abc123", feedback="positive", comment="The agent correctly identified the issue.") ``` ### Retrieve step metrics (latency, token counts) ```python client.steps.metrics.retrieve("step-abc123") ``` ### Retrieve provider-level trace ```python client.steps.trace.retrieve("step-abc123") ``` ``` -------------------------------- ### Inspect Agent Steps and Add Feedback Source: https://context7.com/letta-ai/letta-python/llms.txt Inspects individual agent reasoning steps, attaches human feedback labels, and retrieves performance metrics. Steps are the atomic units of an agent run (one LLM call = one step). ```python from letta_client import Letta client = Letta(api_key="LETTA_API_KEY") # --- Retrieve a step --- step = client.steps.retrieve("step-abc123") print(step.step_type) print(step.run_id) ``` ```python # --- List all steps (global, paginated) --- all_steps = client.steps.list(limit=50) for s in all_steps: print(f"{s.id}: {s.step_type}") ``` ```python # --- Attach human feedback to a step --- updated_step = client.steps.feedback.create( step_id="step-abc123", feedback="positive", # "positive" | "negative" | "neutral" comment="The agent correctly identified the issue.", ) print(updated_step.feedback) ``` ```python # --- Retrieve step metrics (latency, token counts) --- metrics = client.steps.metrics.retrieve("step-abc123") print(f"Latency: {metrics.latency_ms}ms") print(f"Tokens: {metrics.total_tokens}") ``` ```python # --- Retrieve provider-level trace --- trace = client.steps.trace.retrieve("step-abc123") if trace: print(trace.provider, trace.model) ``` -------------------------------- ### Import Agent Configuration Source: https://github.com/letta-ai/letta-python/blob/main/api.md Import an agent configuration from a file. This method returns an AgentImportFileResponse. ```python client.agents.import_file(**params) ``` -------------------------------- ### Create and Attach Archives Source: https://context7.com/letta-ai/letta-python/llms.txt Create external vector databases (archives) for text passages and attach them to agents. Supports bulk passage ingestion and attachment to multiple agents. ```python from letta_client import Letta client = Letta(api_key="LETTA_API_KEY") # --- Create an archive --- archive = client.archives.create( name="knowledge-base", description="Company product knowledge base", ) print(archive.id) # archive-xyz # --- Add a single passage --- passage = client.archives.passages.create( archive_id=archive.id, text="Our product supports OAuth 2.0, SAML 2.0, and API key authentication.", ) # --- Bulk insert passages --- result = client.archives.passages.create_many( archive_id=archive.id, passages=[ {"text": "Pricing: Starter $29/mo, Pro $99/mo, Enterprise custom."}, {"text": "SLA: 99.9% uptime guarantee with 24/7 monitoring."}, {"text": "Support: Email (all tiers), Slack (Pro+), dedicated CSM (Enterprise)."}, ], ) print(f"Inserted {result.num_passages} passages") # --- Attach archive to agent --- agent_id = "agent-d9be0846" client.agents.archives.attach(agent_id=agent_id, archive_id=archive.id) ``` -------------------------------- ### Grant Agents Filesystem Access Source: https://github.com/letta-ai/letta-python/blob/main/README.md Create a folder, upload a file to it, and attach the folder to an agent. Ensure the file exists locally before uploading. ```python # Create folder and upload file folder = client.folders.create( name="my_folder", ) with open("file.txt", "rb") as f: client.folders.files.upload(file=f, folder_id=folder.id) # Attach to agent client.agents.folders.attach(agent_id=agent.id, folder_id=folder.id) ``` -------------------------------- ### Configure Request Options (Timeout, Retries, Headers) Source: https://context7.com/letta-ai/letta-python/llms.txt Illustrates how to configure request-level options such as timeouts, retry counts, and custom headers for individual API calls. This allows for fine-grained control over request behavior. ```python agent = client.agents.create( model="openai/gpt-4o-mini", memory_blocks=[{"label": "persona", "value": "I am patient."} request_options={"timeout_in_seconds": 120, "max_retries": 5}, ) ``` ```python response = client.agents.messages.create( agent_id=agent.id, messages=[{"role": "user", "content": "Hello"}], request_options={"additional_headers": {"X-Request-ID": "trace-abc123"}}, ) ``` -------------------------------- ### Manage Reusable Tools with Letta SDK Source: https://context7.com/letta-ai/letta-python/llms.txt Define and manage reusable Python tools that agents can invoke. Tools require source code, type, and optionally pip requirements and tags. Upsert creates or updates by name, and search finds tools by text. ```python from letta_client import Letta client = Letta(api_key="LETTA_API_KEY") # --- Create a tool --- tool = client.tools.create( name="search_wikipedia", description="Search Wikipedia for a given query and return a summary.", source_code=""" def search_wikipedia(query: str) -> str: '''Search Wikipedia and return a summary for the given query. Args: query: The search term to look up on Wikipedia. Returns: A string summary from Wikipedia. ''' import wikipedia try: return wikipedia.summary(query, sentences=3) except Exception as e: return f"Error: {e}" """, source_type="python", pip_requirements=[{"name": "wikipedia", "version": "1.4.0"}], tags=["research", "web"], ) print(tool.id) # tool-xyz789 # --- Upsert (create or update) --- tool = client.tools.upsert( name="search_wikipedia", source_code="def search_wikipedia(query: str) -> str: ...", source_type="python", ) # --- List tools --- tools = client.tools.list(limit=50) for t in tools: print(f"{t.name}: {t.description[:60]}") # --- Search tools by text --- results = client.tools.search(query_text="weather") for r in results.tools: print(r.name) # --- Delete a tool --- client.tools.delete(tool.id) ``` -------------------------------- ### Create Agent Source: https://github.com/letta-ai/letta-python/blob/main/api.md Create a new agent using the provided parameters. This method returns the created AgentState. ```python client.agents.create(**params) ``` -------------------------------- ### List Folders Source: https://github.com/letta-ai/letta-python/blob/main/api.md Use this method to list all folders, with support for pagination and filtering via parameters. ```python from letta_client.types import Folder from letta_client.types.folder import SyncArrayPage # Example usage (assuming client is initialized) # folders: SyncArrayPage[Folder] = client.folders.list(limit=10, offset=0) ``` -------------------------------- ### List Steps Source: https://github.com/letta-ai/letta-python/blob/main/api.md Retrieves a paginated list of steps. This method can be used with various parameters to filter and sort the steps. ```APIDOC ## GET /v1/steps/ ### Description Lists available steps with optional filtering and sorting. ### Method GET ### Endpoint /v1/steps/ #### Query Parameters - **params** (object) - Optional - Parameters for filtering and pagination of the step list. ``` -------------------------------- ### List Models Source: https://github.com/letta-ai/letta-python/blob/main/api.md Use this method to list available models, with support for filtering via parameters. ```python from letta_client.types import ModelListResponse # Example usage (assuming client is initialized) # models: ModelListResponse = client.models.list(provider_type="openai") ``` -------------------------------- ### Usage Source: https://github.com/letta-ai/letta-python/blob/main/api.md Retrieve usage information for a specific run. ```APIDOC ## GET /v1/runs/{run_id}/usage ### Description Retrieves usage details for a specific run. ### Method GET ### Endpoint /v1/runs/{run_id}/usage ### Parameters #### Path Parameters - **run_id** (string) - Required - The ID of the run. ### Response #### Success Response (200) - **UsageRetrieveResponse** - Usage details for the run. ``` -------------------------------- ### Create Agent Schedule Source: https://github.com/letta-ai/letta-python/blob/main/api.md Schedules a message to be sent by an agent at a future time. ```python client.agents.schedule.create(agent_id, **params) ``` -------------------------------- ### Folders API Source: https://github.com/letta-ai/letta-python/blob/main/api.md Methods for creating, retrieving, updating, listing, and deleting folders. ```APIDOC ## POST /v1/folders/ ### Description Creates a new folder. ### Method POST ### Endpoint /v1/folders/ ### Parameters #### Request Body - **params** (object) - Required - Parameters for creating the folder. Refer to `src/letta_client/types/folder_create_params.py` for details. ### Response #### Success Response (200) - **Folder** (object) - The created folder object. Refer to `src/letta_client/types/folder.py` for details. ``` ```APIDOC ## GET /v1/folders/{folder_id} ### Description Retrieves a specific folder by its ID. ### Method GET ### Endpoint /v1/folders/{folder_id} ### Parameters #### Path Parameters - **folder_id** (string) - Required - The ID of the folder to retrieve. ``` ```APIDOC ## PATCH /v1/folders/{folder_id} ### Description Updates an existing folder. ### Method PATCH ### Endpoint /v1/folders/{folder_id} ### Parameters #### Path Parameters - **folder_id** (string) - Required - The ID of the folder to update. #### Request Body - **params** (object) - Required - Parameters for updating the folder. Refer to `src/letta_client/types/folder_update_params.py` for details. ``` ```APIDOC ## GET /v1/folders/ ### Description Lists all folders. ### Method GET ### Endpoint /v1/folders/ ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering and pagination. Refer to `src/letta_client/types/folder_list_params.py` for details. ### Response #### Success Response (200) - **SyncArrayPage[Folder]** (object) - A paginated list of folder objects. Refer to `src/letta_client/types/folder.py` for details. ``` ```APIDOC ## DELETE /v1/folders/{folder_id} ### Description Deletes a specific folder by its ID. ### Method DELETE ### Endpoint /v1/folders/{folder_id} ### Parameters #### Path Parameters - **folder_id** (string) - Required - The ID of the folder to delete. ``` -------------------------------- ### Tools Source: https://github.com/letta-ai/letta-python/blob/main/api.md Manage tools associated with MCP servers, including retrieval, listing, and running. ```APIDOC ## GET /v1/mcp-servers/{mcp_server_id}/tools/{tool_id} ### Description Retrieves details of a specific tool. ### Method GET ### Endpoint /v1/mcp-servers/{mcp_server_id}/tools/{tool_id} ### Parameters #### Path Parameters - **mcp_server_id** (string) - Required - The ID of the MCP server. - **tool_id** (string) - Required - The ID of the tool to retrieve. ### Response #### Success Response (200) - **Tool** - Details of the retrieved tool. ``` ```APIDOC ## GET /v1/mcp-servers/{mcp_server_id}/tools ### Description Lists all tools for a specific MCP server. ### Method GET ### Endpoint /v1/mcp-servers/{mcp_server_id}/tools ### Parameters #### Path Parameters - **mcp_server_id** (string) - Required - The ID of the MCP server. ### Response #### Success Response (200) - **ToolListResponse** - A list of tools. ``` ```APIDOC ## POST /v1/mcp-servers/{mcp_server_id}/tools/{tool_id}/run ### Description Runs a specific tool. ### Method POST ### Endpoint /v1/mcp-servers/{mcp_server_id}/tools/{tool_id}/run ### Parameters #### Path Parameters - **mcp_server_id** (string) - Required - The ID of the MCP server. - **tool_id** (string) - Required - The ID of the tool to run. #### Request Body - **params** (object) - Required - Parameters for running the tool. See `ToolRunParams` type. ### Response #### Success Response (200) - **ToolExecutionResult** - The result of the tool execution. ``` -------------------------------- ### Export Agent Configuration Source: https://github.com/letta-ai/letta-python/blob/main/api.md Export the configuration of a specific agent as a file. Optional parameters can be used to customize the export. ```python client.agents.export_file(agent_id, **params) ``` -------------------------------- ### Templates API Source: https://context7.com/letta-ai/letta-python/llms.txt Manage agent templates, create new versions, and instantiate agents from templates. ```APIDOC ## templates.create / templates.save / templates.agents.create `POST /v1/templates` — Create versioned agent templates and instantiate agents from them. Templates are versioned blueprints for agents. `save` snapshots a live agent as a new template version. `templates.agents.create` instantiates a new agent from a specific template version with optional memory variable overrides. ```python from letta_client import Letta client = Letta(api_key="LETTA_API_KEY") # --- Create a template --- template = client.templates.create( name="customer-support-v1", description="Standard customer support agent template", agent_id="agent-d9be0846", # source agent to template from ) print(template.template_name) # --- Save a new version from a live agent --- saved = client.templates.save( template_name="customer-support-v1", agent_id="agent-updated-9999", version_label="v2.0", ) # --- Rollback to a previous version --- rolled_back = client.templates.rollback( template_name="customer-support-v1", version="v1.0", ) # --- Instantiate agent from template version --- new_agent = client.templates.agents.create( template_version="customer-support-v1@v2.0", name="support-agent-prod-42", memory_variables={"user_name": "Bob", "user_tier": "Enterprise"}, ) print(new_agent.agent_id) # --- Update template metadata --- client.templates.update( template_name="customer-support-v1", description="Updated support template with tool approval workflow", ) # --- Delete template --- client.templates.delete("customer-support-v1") ``` ``` -------------------------------- ### Create Agent Source: https://github.com/letta-ai/letta-python/blob/main/api.md Creates a new agent with the specified parameters. ```APIDOC ## POST /v1/agents/ ### Description Creates a new agent with the specified parameters. ### Method POST ### Endpoint /v1/agents/ ### Parameters #### Request Body - **params** (AgentCreateParams) - Required - Parameters for creating the agent. ### Response #### Success Response (200) - **body** (AgentState) - The state of the newly created agent. ``` -------------------------------- ### Lint and Format Code Source: https://github.com/letta-ai/letta-python/blob/main/CONTRIBUTING.md Run the linting script to check code quality and formatting. Use the format script to automatically fix ruff issues. ```sh ./scripts/lint ``` ```sh ./scripts/format ``` -------------------------------- ### Publish PyPI with GitHub Action Source: https://github.com/letta-ai/letta-python/blob/main/CONTRIBUTING.md Release to package managers by using the 'Publish PyPI' GitHub action. This requires organization or repository secrets to be set up. ```yaml https://www.github.com/letta-ai/letta-python/actions/workflows/publish-pypi.yml ```