### Rust Letta Client Quick Start Source: https://github.com/orual/letta-rs/blob/main/README.md A complete asynchronous Rust example demonstrating how to initialize a `LettaClient`, create an AI agent, send a message, and stream the agent's response. ```rust use letta::{ClientConfig, LettaClient}; use letta::types::{CreateAgentRequest, AgentType, ModelEndpointType, EmbeddingEndpointType}; #[tokio::main] async fn main() -> Result<(), Box> { // Create client for local Letta server let config = ClientConfig::new("http://localhost:8283")?; let client = LettaClient::new(config)?; // Create an agent let agent_request = CreateAgentRequest { name: "My Assistant".to_string(), agent_type: Some(AgentType::MemGPT), llm_config: Some(json!({ "model_endpoint_type": ModelEndpointType::Openai, "model_endpoint": "https://api.openai.com/v1", "model": "gpt-4", })), embedding_config: Some(json!({ "embedding_endpoint_type": EmbeddingEndpointType::Openai, "embedding_endpoint": "https://api.openai.com/v1", "embedding_model": "text-embedding-ada-002", })), ..Default::default() }; let agent = client.agents().create(agent_request).await?; println!("Created agent: {}", agent.id); // Send a message to the agent let response = client .messages() .send(&agent.id, "Hello! How are you today?", None) .await?; // Stream responses let mut stream = response.into_stream(); while let Some(chunk) = stream.next().await { match chunk? { MessageChunk::AssistantMessage(msg) => { print!("{}", msg.message); } MessageChunk::FunctionCall(call) => { println!("Function: {} with args: {}", call.name, call.arguments); } _ => {} } } Ok(()) } ``` -------------------------------- ### Letta-rs Development Quick Start Commands Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md This set of commands provides a quick start guide for developers working on `letta-rs`. It includes commands for entering the Nix development shell, setting up auto-recompilation, running all tests, and executing pre-commit hooks for formatting and linting. ```bash nix develop # Enter dev shell with all tools just watch # Auto-recompile on changes just test # Run all tests just pre-commit-all # Format and lint ``` -------------------------------- ### Local Letta Server Setup with Docker Compose Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md This command sequence is used to start a local Letta server for testing purposes. It navigates into the `local-server` directory and then uses `docker compose up -d` to bring up the server in detached mode. ```bash cd local-server && docker compose up -d ``` -------------------------------- ### Install Letta CLI Tool Source: https://github.com/orual/letta-rs/blob/main/README.md Commands to install the optional `letta-client` command-line interface tool from `crates.io` or by building directly from the source repository. ```bash cargo install letta --features cli ``` ```bash git clone https://github.com/orual/letta-rs cd letta-rs cargo install --path . --features cli ``` -------------------------------- ### Rust Client Basic Source Management Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md Demonstrates how to list, create, get, and delete sources using the `letta-rs` client library. It includes an example of creating a source with an embedding configuration and description. ```rust // List sources using existing API client.sources().list(params).await // Create source with embedding config let request = CreateSourceRequest { name: "documentation", embedding_config: EmbeddingConfig::default() .embedding_model("letta/letta-free"), description: Some("Product documentation"), instructions: Some("Use for product-related questions"), }; client.sources().create(request).await // Get/Delete operations client.sources().get(&source_id).await client.sources().delete(&source_id).await ``` -------------------------------- ### Letta CLI Common Usage Examples Source: https://github.com/orual/letta-rs/blob/main/README.md Demonstrates various commands for interacting with the Letta server using the `letta-client` CLI, including health checks, agent management, message sending, memory viewing, and document uploads. ```bash letta-client health ``` ```bash letta-client agent list ``` ```bash letta-client agent create -n "My Assistant" -m letta/letta-free ``` ```bash letta-client message send -a "Hello, how are you?" ``` ```bash letta-client memory view -a ``` ```bash letta-client sources create -n "docs" -e letta/letta-free letta-client sources files upload -f document.pdf ``` ```bash letta-client --help letta-client agent --help ``` -------------------------------- ### Configure Letta-rs Client for Cloud Deployment Source: https://github.com/orual/letta-rs/blob/main/README.md This Rust example shows how to configure the `letta-rs` client for connecting to the Letta Cloud. It emphasizes the use of an API key for authentication, which is crucial for secure access in cloud environments. ```Rust // Use API key for cloud deployment let config = ClientConfig::new("https://api.letta.com")? .with_api_key("your-api-key"); let client = LettaClient::new(config)?; ``` -------------------------------- ### Letta CLI Sources Command Structure Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md Illustrates the command-line interface structure for managing sources, files, and passages using the `letta` CLI tool. It provides examples for listing, creating, getting, and deleting sources, as well as operations for files and passages within a source. ```bash letta sources list # List all sources letta sources create -n "docs" -e "letta/letta-free" # Create a source letta sources get # Get source details letta sources delete # Delete a source # File operations letta sources files list # List files in source letta sources files upload -f file.pdf # Upload file letta sources files get # Get file details letta sources files delete # Delete file # Passage operations letta sources passages list # List passages ``` -------------------------------- ### Python Tool Function Example for Letta Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md This snippet provides an example of a Python function formatted as a tool for the Letta system. It demonstrates the required docstring structure, including `Args:` and `Returns:` sections, which are crucial for validation and proper integration. ```Python def my_tool(arg1: str, arg2: int = 0) -> str: """Tool description here. Args: arg1: Description of arg1 arg2: Description of arg2 Returns: Description of return value """ # Implementation return f"Result: {arg1} {arg2}" ``` -------------------------------- ### Rust LettaClient X-Project Header Examples Source: https://github.com/orual/letta-rs/blob/main/HEADER_PARAMETERS.md This Rust code snippet demonstrates how to effectively use the X-Project header when interacting with the Letta API. It provides examples for associating operations like agent and identity creation/upsert with a specific project, showing both per-call and global client configuration methods. ```rust // Agent creation with project let agent = client.agents() .create_with_project(request, "project-123") .await?; // Identity creation with project let identity = client.identities() .create_with_project(request, "project-123") .await?; // Identity upsert with project let identity = client.identities() .upsert_with_project(request, "project-123") .await?; // Or configure globally on the client let client = LettaClient::builder() .base_url("http://localhost:8283") .header("X-Project", "project-123")? .build()?; ``` -------------------------------- ### Run Local Letta Test Server with Docker Source: https://github.com/orual/letta-rs/blob/main/README.md This snippet outlines the steps to start a local Letta test server using Docker Compose. It also includes the command to run integration tests against this local server, facilitating local development and testing workflows. ```Bash # Start local Letta server for testing cd local-server docker compose up -d # Run integration tests cargo test ``` -------------------------------- ### Create and Add Custom Tools to Letta Agents Source: https://github.com/orual/letta-rs/blob/main/README.md This example demonstrates how to define and manage custom tools within the `letta-rs` SDK. It shows the creation of a `CreateToolRequest` for a Python-based tool, including its source code embedded as a string, and how to associate this created tool with an existing agent. ```Rust use letta::types::{CreateToolRequest, Tool}; // Create a custom tool // Note: this example is simplified, see the tool documentation for details. let tool = CreateToolRequest { name: "get_weather".to_string(), description: Some("Get current weather for a location".to_string()), source_code: r#" def def get_weather(location: str) -> str: """Get weather for a location.""" return f"The weather in {location} is sunny and 72°F" "#.to_string(), source_type: Some("python".to_string()), ..Default::default() }; let created_tool = client.tools().create(tool).await?; // Add tool to agent client .agents() .add_tool(&agent.id, &created_tool.id) .await?; ``` -------------------------------- ### Git Workflow: Create Feature Branch Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md This snippet demonstrates the `git checkout -b` command used to create a new feature branch before starting any development work. It includes examples of descriptive branch names following project conventions for features, fixes, and documentation. ```bash git checkout -b feature/descriptive-name # Examples: feature/add-default-impls, fix/batch-api-errors, docs/improve-examples ``` -------------------------------- ### JSON Schema Example for Letta Tools Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md This snippet illustrates the required JSON schema format for defining a tool's parameters in the Letta system. It specifies the `name`, `description`, and `parameters` structure, including `type`, `properties`, and `required` fields for arguments. ```JSON { "name": "my_tool", "description": "Tool description here", "parameters": { "type": "object", "properties": { "arg1": { "type": "string", "description": "Description of arg1" }, "arg2": { "type": "integer", "description": "Description of arg2", "default": 0 } }, "required": ["arg1"] } } ``` -------------------------------- ### Rust LettaClient Query Parameter Usage Example Source: https://github.com/orual/letta-rs/blob/main/HEADER_PARAMETERS.md This Rust code snippet demonstrates how to interact with Letta API endpoints that utilize query parameters for user context. It provides an example of listing MCP servers by passing a user-id as a query parameter through the LettaClient's list_mcp_servers_with_user method. ```rust // MCP servers with user-id query parameter let servers = client.tools() .list_mcp_servers_with_user("user-123") .await?; ``` -------------------------------- ### Handle Errors in Letta-rs SDK Source: https://github.com/orual/letta-rs/blob/main/README.md This Rust example demonstrates the comprehensive error handling capabilities of the `letta-rs` library. It shows how to use a `match` statement to differentiate between API-specific errors, identified by `LettaError::Api`, and other types of errors, providing detailed context for debugging. ```Rust use letta::error::LettaError; match client.agents().get(&agent_id).await { Ok(agent) => println!("Found agent: {}", agent.name), Err(LettaError::Api { status, message, .. }) => { eprintln!("API error {}: {}", status, message); } Err(e) => eprintln!("Other error: {}", e), } ``` -------------------------------- ### Git Workflow: Commit with Descriptive Message Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md This example illustrates how to commit changes regularly using `git commit -m` with a clear and descriptive message. It emphasizes the importance of concise and informative commit messages for tracking logical changes within the project. ```bash git commit -m "Add Default impl for UpdateMemoryBlockRequest" ``` -------------------------------- ### Rust LettaClient Global Header Configuration Methods Source: https://github.com/orual/letta-rs/blob/main/HEADER_PARAMETERS.md This comprehensive Rust example demonstrates various approaches to configure HTTP headers globally on the LettaClient. It covers using convenient builder methods like .project() and .user_id(), the generic .header() method, initializing with ClientConfig, and utilizing HeaderMap for bulk header assignments, ensuring these headers are sent with every request. ```rust use letta_rs::{LettaClient, ClientConfig}; use reqwest::header::HeaderMap; // Using convenient helper methods (recommended) let client = LettaClient::builder() .base_url("http://localhost:8283") .project("my-project")? // Sets X-Project header .user_id("user-123")? // Sets user-id header .build()?; // For cloud clients with project let client = LettaClient::cloud_with_project("api-token", "my-project")?; // Using generic header method let client = LettaClient::builder() .base_url("http://localhost:8283") .header("X-Project", "my-project")? .header("user-id", "user-123")? .build()?; // Using ClientConfig let config = ClientConfig::new("http://localhost:8283")? .project("my-project")? .user_id("user-123")?; let client = LettaClient::new(config)?; // Using HeaderMap for bulk headers let mut headers = HeaderMap::new(); headers.insert("X-Project", "my-project".parse()?); headers.insert("user-id", "user-123".parse()?); let config = ClientConfig::new("http://localhost:8283")? .headers(headers); let client = LettaClient::new(config)?; ``` -------------------------------- ### Letta Tools CLI Subcommand Overview and Features Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md This section provides an overview of the `letta tools` CLI subcommand, detailing its purpose for managing custom tools and the core functionalities it supports, such as creation, listing, retrieval, and deletion of tools, along with their respective command examples. ```APIDOC Overview: The tools subcommand allows users to manage custom tools (functions) that agents can use. Supports: 1. Creating tools from Python files with separate JSON schema files 2. Listing available tools with pagination 3. Getting tool details including source code and schemas 4. Deleting tools with confirmation 5. Comprehensive validation of JSON schemas and Python docstrings Implemented Features: 1. Create Tool from Python File: - Description: Accept Python file path containing the tool implementation and JSON file path for function schema. Read both files and create the tool via API. - Example: letta tools create --python tool.py --schema tool_schema.json 2. List Tools: - Description: Show all available tools with pagination support. Display tool names, descriptions, and IDs. - Example: letta tools list --limit 20 3. Get Tool Details: - Description: Show full tool information including source code. - Example: letta tools get 4. Delete Tool: - Description: Remove a tool with confirmation. - Example: letta tools delete --yes ``` -------------------------------- ### Global Tools Management API Endpoints Source: https://github.com/orual/letta-rs/blob/main/PHASE1_ARCHIVE.md Provides a comprehensive API for managing tools globally within the system. This includes operations for listing, creating, retrieving, updating, deleting, and upserting tools, as well as getting a total count of available tools. ```APIDOC GET /v1/tools/ Description: List all tools POST /v1/tools/ Description: Create a new tool GET /v1/tools/{tool_id} Description: Get a tool by ID PATCH /v1/tools/{tool_id} Description: Update a tool DELETE /v1/tools/{tool_id} Description: Delete a tool GET /v1/tools/count Description: Get tools count PUT /v1/tools/ Description: Upsert a tool ``` -------------------------------- ### Manage Archival Memory in Letta-rs Source: https://github.com/orual/letta-rs/blob/main/README.md This Rust example illustrates how to interact with an agent's archival memory. It covers adding new facts to memory using `insert_archival_memory` and searching existing memories based on a query using `search_archival_memory`, demonstrating the SDK's capabilities for persistent knowledge storage and retrieval. ```Rust // Add to archival memory client .memory() .insert_archival_memory(&agent.id, "Important fact: Rust is memory safe") .await?; // Search archival memory let memories = client .memory() .search_archival_memory(&agent.id, "Rust safety", Some(10)) .await?; for memory in memories { println!("Found: {}", memory.text); } ``` -------------------------------- ### System Health Check API Endpoint Source: https://github.com/orual/letta-rs/blob/main/PHASE1_ARCHIVE.md Defines the simple health check endpoint for the system. This unauthenticated GET request returns a `Health` struct containing version and status information, allowing for basic service availability monitoring. ```APIDOC Endpoint: GET /v1/health/ Description: Simple health check Authentication: Not required Returns: Health struct (version, status fields) Note: Trailing slash required ``` -------------------------------- ### Rust LettaClient user-id Header Examples Source: https://github.com/orual/letta-rs/blob/main/HEADER_PARAMETERS.md This snippet illustrates the application of the user-id header within Rust code using the Letta API. It shows how to pass a user identifier for specific requests, such as voice chat completions, and how to set this header globally on the LettaClient for consistent application across multiple calls. ```rust // Voice API with user-id let response = client.voice() .create_voice_chat_completions(&agent_id, request, Some("user-123")) .await?; // Or configure globally on the client let client = LettaClient::builder() .base_url("http://localhost:8283") .header("user-id", "user-123")? .build()?; ``` -------------------------------- ### Rust LettaClient Per-Request Header Overrides Source: https://github.com/orual/letta-rs/blob/main/HEADER_PARAMETERS.md This Rust code snippet illustrates how to apply headers on a per-request basis, allowing specific API calls to use different header values than those configured globally on the LettaClient. This is useful for dynamic contexts, as shown with examples for agent creation and voice API calls. ```rust // Agent creation with project let agent = client.agents() .create_with_project(request, "specific-project") .await?; // Voice API with user-id let response = client.voice() .create_voice_chat_completions(&agent_id, request, Some("specific-user")) .await?; ``` -------------------------------- ### Build Letta-rs from Source Source: https://github.com/orual/letta-rs/blob/main/README.md This snippet provides instructions for building the `letta-rs` library from its source code. It includes standard Git and Cargo commands for cloning the repository, compiling the project, running tests, and generating documentation. ```Bash # Clone the repository git clone https://github.com/yourusername/letta cd letta # Build the library cargo build # Run tests cargo test # Build documentation cargo doc --open ``` -------------------------------- ### Client Environment Management Configuration Source: https://github.com/orual/letta-rs/blob/main/PHASE1_ARCHIVE.md Outlines the environment management system, including the `LettaEnvironment` enum for Cloud and SelfHosted variants, each with predefined base URLs and authentication requirements. It describes how the `ClientBuilder` and convenience constructors (`LettaClient::cloud()`, `LettaClient::local()`) facilitate environment switching and configuration. ```APIDOC Enum: LettaEnvironment Variants: - Cloud (requires authentication, predefined base URL) - SelfHosted (does not require authentication, predefined base URL) Client Configuration: - ClientBuilder supports .environment() method - Convenience constructors: - LettaClient::cloud() - LettaClient::local() - Base URL can override environment settings - Environment defaults to Cloud if not specified ``` -------------------------------- ### Execute Letta-rs Project Tests Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md This snippet provides various commands to run tests for the Letta-rs project. It includes commands for unit tests (without server), local server integration tests requiring Docker, and cloud API tests that need an API key. It also shows how to run all tests combined. ```bash # Unit tests only (no server required) cargo test --lib --bins cargo test --doc # Local server integration tests (requires Docker) nix run .#test-local # Cloud API tests (requires LETTA_API_KEY) LETTA_API_KEY=your-key nix run .#test-cloud # Run all tests LETTA_API_KEY=your-key nix run .#test-all ``` -------------------------------- ### Letta-rs CLI Tool Execution Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md This command demonstrates how to run the `letta-rs` command-line interface tool, which is fully functional for all API operations. The `--features cli` flag enables the CLI feature, and `-- --help` displays its usage instructions. ```bash cargo run --features cli -- --help ``` -------------------------------- ### Rust Client File Management for Sources Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md Illustrates how to upload files to a source, list files with pagination, and retrieve file metadata using the `letta-rs` client library. It shows reading a PDF file and performing multipart form upload. ```rust // Upload file with multipart form let file_data = std::fs::read("document.pdf")?; client.sources().upload_file(&source_id, "document.pdf", file_data).await // List files with pagination let params = ListFilesParams { limit: Some(20), ..Default::default() }; client.sources().paginated_files(&source_id, Some(params)).await // Get file metadata and optionally content client.sources().get_file(&source_id, &file_id).await ``` -------------------------------- ### Configure Letta CLI Environment Variables Source: https://github.com/orual/letta-rs/blob/main/README.md Environment variable settings for configuring the `letta-client`. Set `LETTA_API_KEY` for cloud deployments or `LETTA_BASE_URL` for local Letta servers. ```bash export LETTA_API_KEY=your-api-key ``` ```bash export LETTA_BASE_URL=http://localhost:8283 ``` -------------------------------- ### Tools API Overview Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md Outlines the Tools API, which provides full tool lifecycle management and supports pagination using string-based cursors. ```APIDOC Tools API: - Pagination support added with string-based cursors - Full tool lifecycle management ``` -------------------------------- ### Create Letta Agent using Rust Builder Pattern Source: https://github.com/orual/letta-rs/blob/main/README.md This Rust snippet demonstrates how to create a new agent using the `letta-rs` SDK's builder pattern. It shows how to specify agent properties like name, type, description, and associate LLM and embedding configurations. It also illustrates the creation of custom memory blocks for human and persona data. ```Rust use letta::types::{CreateAgentRequest, AgentType, Block, LLMConfig}; // Create agent using builder pattern let request = CreateAgentRequest::builder() .name("My Assistant") .agent_type(AgentType::MemGPT) .description("A helpful coding assistant") .model("letta/letta-free") // Shorthand for LLM config .embedding("letta/letta-free") // Shorthand for embedding config .build(); let agent = client.agents().create(request).await?; // Create custom memory blocks with builder let human_block = Block::human("Name: Alice\nRole: Software Engineer") .label("human"); let persona_block = Block::persona("You are a helpful coding assistant.") .label("persona"); ``` -------------------------------- ### Letta Rust Client API Coverage Source: https://github.com/orual/letta-rs/blob/main/README.md Overview of the core API functionalities covered by the `letta-rs` client library, including management of agents, messages, memory, tools, sources, and blocks. ```APIDOC Core APIs: - Agents: Create, update, delete, and manage AI agents - Messages: Send messages and stream responses with SSE - Memory: Manage core and archival memory with semantic search - Tools: Register and manage agent tools (functions) - Sources: Upload documents and manage knowledge sources - Blocks: Manage memory blocks and persistent storage ``` -------------------------------- ### Add Letta Rust Client Dependency Source: https://github.com/orual/letta-rs/blob/main/README.md Instructions to add the `letta` crate as a dependency to your Rust project's `Cargo.toml` file. ```toml [dependencies] letta = "0.1.3" ``` -------------------------------- ### Letta-rs CLI Directory Structure Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md This snippet illustrates the modular directory structure of the `letta-rs` command-line interface, showing the organization of binary entry points, main CLI modules, and specific command implementations within the `src/` directory. ```Rust src/ ├── bin/ │ └── letta.rs # Binary entry point ├── cli/ │ ├── mod.rs # Main CLI module with Args and run() │ └── commands/ │ ├── mod.rs # Commands module with health check │ ├── agent.rs # Agent commands (✅ fully implemented) │ ├── message.rs # Message commands (✅ fully implemented) │ ├── memory.rs # Memory commands (✅ fully implemented) │ ├── tools.rs # Tools commands (✅ fully implemented) │ └── sources.rs # Sources commands (✅ fully implemented) ``` -------------------------------- ### Sources API Overview Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md Details the Sources API, adding pagination for files (`paginated_files()`) and passages (`paginated_passages()`), both utilizing string-based cursor pagination. ```APIDOC Sources API: - Added pagination for files (`paginated_files()`) and passages (`paginated_passages()`) - Both use string-based cursor pagination ``` -------------------------------- ### Configure Letta-rs Client for Local Server Source: https://github.com/orual/letta-rs/blob/main/README.md This Rust snippet demonstrates how to configure the `letta-rs` client to connect to a local development server. It highlights that no authentication is required when connecting to a local server at the specified URL. ```Rust // No authentication required for local server let config = ClientConfig::new("http://localhost:8283")?; let client = LettaClient::new(config)?; ``` -------------------------------- ### Letta-rs Advanced API Capabilities Overview Source: https://github.com/orual/letta-rs/blob/main/README.md This section outlines the advanced API functionalities available in the Letta platform, covering multi-agent conversations, execution tracking, asynchronous job management, batch processing, templating, project organization, model configuration, provider management, identity, tagging, and telemetry. ```APIDOC Groups - Multi-agent conversations Runs - Execution tracking and debugging Jobs - Asynchronous job management Batch - Batch message processing Templates - Agent templates for quick deployment Projects - Project organization Models - LLM and embedding model configuration Providers - LLM provider management Identities - Identity and permissions management Tags - Tag-based organization Telemetry - Usage tracking and monitoring Voice - Voice conversation support (beta) ``` -------------------------------- ### Rust Client Passage Management for Sources Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md Demonstrates how to list processed passages (document chunks after processing) associated with a source using the `letta-rs` client library, including support for pagination. ```rust // List passages (document chunks after processing) let params = ListPassagesParams { limit: Some(50), ..Default::default() }; client.sources().paginated_passages(&source_id, Some(params)).await ``` -------------------------------- ### Rust Serialization Best Practices Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md Highlights common serialization patterns and edge cases in Rust using `serde` attributes, including skipping `None` fields and flattening generic JSON. Also notes the pattern for array query parameters. ```Rust // Skip None fields #[serde(skip_serializing_if = "Option::is_none")] // Flatten for generic JSON #[serde(flatten)] ``` -------------------------------- ### Stream Paginated Agent Lists in Letta-rs Source: https://github.com/orual/letta-rs/blob/main/README.md This Rust snippet shows how to retrieve a paginated list of agents using a streaming approach. It demonstrates initializing a paginated stream with a limit and iterating through the stream using `next().await` to process agents one by one, which is efficient for large datasets. ```Rust // Get paginated list of agents let mut agent_stream = client .agents() .paginated() .limit(10) .build(); while let Some(agent) = agent_stream.next().await { let agent = agent?; println!("Agent: {} ({})", agent.name, agent.id); } ``` -------------------------------- ### Voice API (Beta) Reference Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md Documents the beta Voice API, providing a basic voice chat completions endpoint at `/v1/voice-beta/{agent_id}/chat/completions`. It uses generic JSON values (`serde_json::Value`) due to its undocumented structure, expects OpenAI-compatible requests, and supports an optional `user-id` header. Designed for streaming interactions with `voice_convo_agent` type, requiring `OPENAI_API_KEY` on the server. The API is undocumented and subject to change. ```APIDOC Voice API (Beta): - Basic voice chat completions endpoint at `/v1/voice-beta/{agent_id}/chat/completions` - Uses generic JSON values (`serde_json::Value`) due to undocumented API structure - Expects OpenAI-compatible chat completion requests based on docs - `create_voice_chat_completions` endpoint with optional `user-id` header support - Designed for streaming voice agent interactions with `voice_convo_agent` type - Note: Requires OPENAI_API_KEY environment variable configured on server - API structure is undocumented and subject to change ``` -------------------------------- ### Add Custom Headers to Letta-rs Client Configuration Source: https://github.com/orual/letta-rs/blob/main/README.md This Rust snippet illustrates how to add custom HTTP headers, such as `X-Project`, to the `letta-rs` client configuration. This is useful for passing additional context, project identifiers, or custom authentication information with API requests. ```Rust // Add custom headers like X-Project let config = ClientConfig::new("http://localhost:8283")? .with_header("X-Project", "my-project")?; ``` -------------------------------- ### Telemetry API Overview Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md Describes the Telemetry API, which supports provider trace retrieval by step ID, returning `ProviderTrace` objects with telemetry data. Currently, it only supports trace retrieval. ```APIDOC Telemetry API: - Provider trace retrieval by step ID - Returns `ProviderTrace` objects with telemetry data - Currently supports trace retrieval only (not full usage tracking) ``` -------------------------------- ### Tags API Overview Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md Details the Tags API, a simple string-based API returning `Vec`. It supports pagination with `after`/`limit` and query text filtering, utilizing string-based cursor pagination. ```APIDOC Tags API: - Simple string-based API returning Vec - Supports pagination with after/limit and query text filtering - Uses string-based cursor pagination ``` -------------------------------- ### Models API Overview Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md Describes the Models API, which supports filtering by provider category using repeated query parameters. It leverages the `ProviderCategory` enum for filtering and handles `Vec` serialization. ```APIDOC Models API: - Supports filtering by provider category using repeated query parameters for arrays - ProviderCategory enum with values: Base, Byok - Query parameters properly handle Vec serialization ``` -------------------------------- ### Composio Integration API Endpoints Source: https://github.com/orual/letta-rs/blob/main/PHASE2_ARCHIVE.md Defines API endpoints for integrating with Composio. This includes listing available Composio applications, actions within a specific app, and adding Composio actions as tools to the Letta system. ```APIDOC GET /v1/tools/composio/apps - List all Composio applications GET /v1/tools/composio/apps/{composio_app_name}/actions - List actions for a specific Composio application POST /v1/tools/composio/{composio_action_name} - Add a Composio tool (action) to Letta ``` -------------------------------- ### MCP Integration API Endpoints Source: https://github.com/orual/letta-rs/blob/main/PHASE2_ARCHIVE.md Defines API endpoints for integrating with MCP (Multi-Component Protocol) servers. This includes managing MCP server configurations, listing tools available from a specific MCP server, and adding MCP tools to the Letta system. ```APIDOC GET /v1/tools/mcp/servers - List all configured MCP servers PUT /v1/tools/mcp/servers - Add a new MCP server configuration GET /v1/tools/mcp/servers/{mcp_server_name}/tools - List tools for a specific MCP server POST /v1/tools/mcp/servers/{mcp_server_name}/{mcp_tool_name} - Add an MCP tool to Letta DELETE /v1/tools/mcp/servers/{mcp_server_name} - Delete an MCP server configuration PATCH /v1/tools/mcp/servers/{mcp_server_name} - Update an MCP server configuration POST /v1/tools/mcp/servers/test - Test an MCP server connection ``` -------------------------------- ### Batch API Reference Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md Documents the Batch API for full batch message processing. It allows listing batch messages with optional filtering by run/step IDs using `ListBatchMessagesParams` (limit parameter, no cursor). Notes server support variations and a rename of `BatchMessageCreate` to `BatchMessage`. ```APIDOC Batch API: - Full batch message processing implementation - List batch messages with optional filtering by run/step IDs - Uses `ListBatchMessagesParams` with limit parameter (no cursor pagination) - Note: Server support varies - requires `LETTA_ENABLE_BATCH_JOB_POLLING=true` environment variable - Some server versions may return `NotImplementedError` when creating batches - Renamed `BatchMessageCreate` to `BatchMessage` with additional optional fields (name, tool_calls, tool_call_id) ``` -------------------------------- ### Providers API Reference Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md Documents the Providers API, offering full CRUD operations using `LettaId`-based IDs (format: `provider-`). `api_key` is required for creation, and updates are limited to `api_key`, `access_key`, `region`. It supports various provider types and returns 204 No Content on delete. ```APIDOC Providers API: - Full CRUD operations with LettaId-based IDs (format: `provider-`) - `api_key` is required for creation - Updates limited to: `api_key`, `access_key`, `region` only - Provider types include: OpenAI, Anthropic, Azure, Google AI, Groq, Cohere, etc. - Delete endpoint returns null response (204 No Content) ``` -------------------------------- ### Letta Tools CLI Validation Features Source: https://github.com/orual/letta-rs/blob/main/CLAUDE.md This section describes the validation mechanisms implemented within the `letta tools` CLI, focusing on the checks performed for JSON schemas and Python docstrings to ensure proper tool definition and functionality. ```APIDOC Validation Features: 1. JSON Schema Validation: - Validates required fields (name, parameters) - Checks parameter structure (type: "object", properties) - Ensures each property has type and description fields - Provides helpful error messages with examples 2. Python Docstring Validation: - Ensures functions have docstrings - Validates presence of Args: section (required by Letta) - Warns if Returns: section is missing - Shows proper format in error messages ``` -------------------------------- ### Core Tool Management API Endpoints Source: https://github.com/orual/letta-rs/blob/main/PHASE2_ARCHIVE.md Defines the RESTful API endpoints for managing tools within the Letta Rust SDK. This includes standard CRUD operations, an upsert mechanism, and the ability to run a tool directly from its source code. ```APIDOC GET /v1/tools/ - List all tools POST /v1/tools/ - Create a new tool GET /v1/tools/{tool_id} - Get a tool by ID PATCH /v1/tools/{tool_id} - Update a tool DELETE /v1/tools/{tool_id} - Delete a tool GET /v1/tools/count - Get the total count of tools PUT /v1/tools/ - Upsert (create or update) a tool POST /v1/tools/run - Run a tool from its source code ``` -------------------------------- ### API Error Handling and Mapping Logic Source: https://github.com/orual/letta-rs/blob/main/PHASE1_ARCHIVE.md Explains the system's enhanced error handling mechanism, which includes automatic mapping of HTTP status codes to specific error types (e.g., 404 to NotFound). It details how resource information, validation fields, and retry-after values are extracted from API responses to provide rich error context. ```APIDOC Error Mapping (from_response() method): - 401 -> Auth - 404 -> NotFound (extracts resource info, e.g., 'Agent with ID xxx not found') - 422 -> Validation (extracts validation fields) - 429 -> RateLimit (extracts retry-after values) - 408/504 -> RequestTimeout General: - Matches error patterns from Python/TypeScript SDKs - Provides better error context for common failures ``` -------------------------------- ### Letta API User Context via Query Parameters Source: https://github.com/orual/letta-rs/blob/main/HEADER_PARAMETERS.md This section clarifies that some Letta API endpoints use query parameters instead of HTTP headers to convey user context. It specifically highlights the user-id query parameter, which is used for operations like listing MCP servers. ```APIDOC user-id Query Parameter: - GET /v1/tools/mcp/servers?user-id={user_id} - List MCP servers (optional query param) ``` -------------------------------- ### Base Tools Upsert API Endpoint Source: https://github.com/orual/letta-rs/blob/main/PHASE2_ARCHIVE.md Defines the API endpoint for upserting (adding or updating) a set of default or base tools into the Letta system. ```APIDOC POST /v1/tools/add-base-tools - Upsert base tools (adds/updates default tool set) ``` -------------------------------- ### Letta API Standard and Custom Header Reference Source: https://github.com/orual/letta-rs/blob/main/HEADER_PARAMETERS.md This section details the essential HTTP headers used across the Letta API. It distinguishes between standard headers like Authorization and Content-Type, and custom headers such as X-Project and user-id, listing the specific API endpoints where each custom header is applicable. ```APIDOC Standard Headers: - Authorization: Bearer token authentication (when configured) - Content-Type: application/json (for POST/PUT/PATCH requests) Custom Headers: X-Project Header: Endpoints that accept X-Project: - POST /v1/agents - Create agent (optional) - POST /v1/identities/ - Create identity (optional) - PUT /v1/identities/ - Upsert identity (optional) user-id Header: Endpoints that accept user-id: - POST /v1/voice-beta/{agent_id}/chat/completions - Voice chat completions (optional header) ```