### Add and Run Examples Source: https://github.com/letta-ai/letta-node/blob/main/CONTRIBUTING.md Create new example files in the `examples/` directory and make them executable. Run examples against your API using `yarn tsn`. ```ts // add an example to examples/.ts #!/usr/bin/env -S npm run tsn -T … ``` ```sh $ chmod +x examples/.ts # run the example against your api $ yarn tsn -T examples/.ts ``` -------------------------------- ### Full Client Configuration Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/configuration.md A comprehensive example demonstrating the use of multiple configuration options simultaneously. ```typescript const client = new Letta({ apiKey: process.env.LETTA_API_KEY, projectID: 'project-123', environment: 'cloud', timeout: 45000, maxRetries: 3, logLevel: 'debug', defaultHeaders: { 'X-Custom-Header': 'value' }, defaultQuery: { format: 'json' } }); ``` -------------------------------- ### Install from Git Source: https://github.com/letta-ai/letta-node/blob/main/CONTRIBUTING.md Use this command to install the repository directly from a Git URL. ```sh $ npm install git+ssh://git@github.com:letta-ai/letta-node.git ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/letta-ai/letta-node/blob/main/CONTRIBUTING.md Run these commands to install all necessary dependencies and build the project output files. ```sh $ yarn $ yarn build ``` -------------------------------- ### Full Usage Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Models.md A comprehensive example demonstrating client initialization, listing all models, creating an agent with a specific model, and filtering models by provider and category. ```typescript import Letta from '@letta-ai/letta-client'; const client = new Letta(); // List all available models const response = await client.models.list(); console.log('Available models:', response.models.length); // Create agent with specific model const agent = await client.agents.create({ name: 'GPT-4 Agent', model: 'openai/gpt-4', system: 'You are a helpful assistant' }); // List only OpenAI models const openaiModels = await client.models.list({ provider: 'openai' }); openaiModels.models.forEach(model => { console.log(`- ${model.name}`); }); // List only embedding models const embeddingModels = await client.models.list({ category: 'embedding' }); ``` -------------------------------- ### Install Letta Node API Client Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/README.md Install the Letta Node API Client using npm. ```bash npm install @letta-ai/letta-client ``` -------------------------------- ### Create Archive Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Archives.md Demonstrates how to create a new archive with a name, description, and specified embedding model. Ensure you have the necessary client setup. ```typescript const archive = await client.archives.create({ name: 'Knowledge Base', description: 'Main knowledge repository', embedding: 'openai/text-embedding-3-small' }); console.log('Created archive:', archive.id); ``` -------------------------------- ### List Archives Examples Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Archives.md Provides examples for listing archives, including fetching all archives, filtering by agent ID, and demonstrating auto-pagination for iterating through all results. ```typescript // List all archives const archives = await client.archives.list(); for (const archive of archives.items) { console.log(archive.name); } // Filter by agent const agentArchives = await client.archives.list({ agent_id: 'agent-123' }); // Auto-paginate for await (const archive of client.archives.list()) { console.log(archive.name); } ``` -------------------------------- ### Create Folder Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Folders.md Use this snippet to create a new folder with a name and an optional description. ```typescript const folder = await client.folders.create({ name: 'Documentation', description: 'API and product documentation' }); console.log('Created folder:', folder.id); ``` -------------------------------- ### Custom System Knowledge Block Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Blocks.md Example of a custom block, specifically for system knowledge or important internal information. ```typescript { label: 'system_knowledge', value: 'Important system information...' } ``` -------------------------------- ### Basic Usage Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/README.md Demonstrates how to initialize the Letta client and perform basic operations like creating an agent, starting a conversation, and sending a message. ```APIDOC ## Basic Usage ```typescript import Letta from '@letta-ai/letta-client'; const client = new Letta({ apiKey: process.env['LETTA_API_KEY'] }); // Create an agent const agent = await client.agents.create({ name: 'My Agent', model: 'openai/gpt-4', system: 'You are a helpful assistant.' }); // Send a message const conversation = await client.conversations.create({ agent_id: agent.id }); const response = await client.conversations.messages.create(conversation.id, { role: 'user', content: 'Hello!' }); ``` ``` -------------------------------- ### Create an Agent with Memory and Tools Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/README.md Demonstrates the creation of an agent with a name, model, system prompt, persona block, tools, and tags. This is a comprehensive example of agent initialization. ```typescript const agent = await client.agents.create({ name: 'Research Assistant', model: 'openai/gpt-4', system: 'You are a helpful research assistant.', blocks: [ { label: 'persona', value: 'Expert in AI and machine learning' } ], tools: ['web_search', 'summarize'], tags: ['research', 'assistant'] }); ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/configuration.md Example of initializing the Letta client with debug logging enabled. This will output detailed information about requests and responses. ```javascript const client = new Letta({ apiKey: process.env.LETTA_API_KEY, logLevel: 'debug' }); // Output includes: // [log_xxxxxx] sending request // [log_xxxxxx] GET /v1/agents/ with headers {...} // [log_xxxxxx] response succeeded with status 200 in 123ms ``` -------------------------------- ### List All Models Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Models.md Demonstrates how to list all available models and iterate through the response. This is useful for displaying all options to a user or for general inspection. ```typescript // List all models const response = await client.models.list(); response.models.forEach(model => { console.log(`${model.name} (${model.provider})`); }); ``` -------------------------------- ### Auto-Pagination Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/README.md Shows how to use the auto-pagination feature for list endpoints. ```APIDOC ## Auto-Pagination Automatic pagination for list endpoints: ```typescript // Auto-paginate all agents for await (const agent of client.agents.list()) { console.log(agent.name); } ``` ``` -------------------------------- ### Background Block Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Blocks.md Example of a background block, providing contextual information or company history. ```typescript { label: 'background', value: 'Company background: Founded in 2020, focuses on AI...' } ``` -------------------------------- ### List Folders Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Folders.md Lists all folders, with options for filtering by agent ID and pagination. Supports auto-pagination. ```typescript // List all folders const folders = await client.folders.list(); folders.items.forEach(folder => { console.log(folder.name); }); // Auto-paginate for await (const folder of client.folders.list()) { console.log(folder.name); } ``` -------------------------------- ### Full Blocks API Usage Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Blocks.md Demonstrates creating, updating, listing, and deleting blocks, as well as creating an agent with blocks using the Letta client. ```typescript import Letta from '@letta-ai/letta-client'; const client = new Letta(); // Create a block with agent persona const personaBlock = await client.blocks.create({ label: 'persona', value: 'You are a helpful research assistant with expertise in AI, machine learning, and data science.' }); // Create a block with background info const backgroundBlock = await client.blocks.create({ label: 'background', value: `Company Background: - Founded: 2023 - Mission: Democratize AI - Locations: US, EU, Asia` }); // Create agent with blocks const agent = await client.agents.create({ name: 'Research Assistant', model: 'openai/gpt-4', system: 'You are a helpful assistant', blocks: [ { label: 'persona', value: 'Expert researcher' }, { label: 'knowledge', value: 'You have access to academic databases' } ] }); // Update a block value await client.blocks.update(personaBlock.id, { value: 'Updated persona description' }); // List blocks for an agent const blocks = await client.blocks.list({ agent_id: agent.id }); blocks.items.forEach(block => { console.log(`${block.label}: ${block.value}`); }); // Delete a block await client.blocks.delete(personaBlock.id); ``` -------------------------------- ### Streaming Responses Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/README.md Demonstrates how to handle streaming responses using server-sent events. ```APIDOC ## Streaming Responses Server-sent events support for streaming: ```typescript const stream = await client.conversations.messages.create(convId, { role: 'user', content: 'Hello!', streaming: true }); for await (const chunk of stream) { console.log(chunk); } ``` ``` -------------------------------- ### Basic Usage of Letta Client Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/README.md Initialize the Letta client, create an agent, start a conversation, and send a message. ```typescript import Letta from '@letta-ai/letta-client'; const client = new Letta({ apiKey: process.env['LETTA_API_KEY'] }); // Create an agent const agent = await client.agents.create({ name: 'My Agent', model: 'openai/gpt-4', system: 'You are a helpful assistant.' }); // Send a message const conversation = await client.conversations.create({ agent_id: agent.id }); const response = await client.conversations.messages.create(conversation.id, { role: 'user', content: 'Hello!' }); ``` -------------------------------- ### Create, Attach, and Search Tools Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Tools.md Demonstrates the full lifecycle of a custom tool: creating a tool with TypeScript source code, attaching it to an agent, and then searching for tools semantically. Ensure the '@letta-ai/letta-client' is installed. ```typescript import Letta from '@letta-ai/letta-client'; const client = new Letta(); // Create a custom tool const tool = await client.tools.create({ name: 'send_email', description: 'Send an email to a recipient', source_code: ` function send_email(to: string, subject: string, body: string): string { // Email sending implementation return 'Email sent successfully'; } `, source_type: 'typescript', args_json_schema: { type: 'object', properties: { to: { type: 'string', description: 'Recipient email' }, subject: { type: 'string', description: 'Email subject' }, body: { type: 'string', description: 'Email body' } }, required: ['to', 'subject', 'body'] }, npm_requirements: [{ name: 'nodemailer', version: '^6.0.0' }] }); // Attach tool to an agent await client.agents.tools.attach('agent-123', { tool_ids: [tool.id] }); // Search for tools const results = await client.tools.search({ query: 'communication', mode: 'semantic' }); ``` -------------------------------- ### Set Environment Variables for Letta Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/README.md Provides an example of how to configure Letta using environment variables in a .env file. This includes setting the API key and optionally the base URL and log level. ```bash # .env LETTA_API_KEY=your-api-key LETTA_BASE_URL=https://api.letta.com # Optional LETTA_LOG=debug # Optional ``` -------------------------------- ### Full Conversation Management Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Conversations.md Demonstrates a complete workflow for managing conversations using the Letta client. This includes creating a conversation, sending messages, listing messages, forking the conversation, continuing in the forked conversation, and finally deleting the original conversation. ```typescript import Letta from '@letta-ai/letta-client'; const client = new Letta(); // Create a conversation with an agent const conversation = await client.conversations.create({ agent_id: 'agent-123', description: 'Customer support conversation' }); // Send a message to the conversation const response = await client.conversations.messages.create(conversation.id, { role: 'user', content: 'What are your business hours?' }); // List messages in the conversation const messages = await client.conversations.messages.list(conversation.id); messages.items.forEach(msg => { console.log(`${msg.role}: ${msg.content}`); }); // Fork conversation at a certain point const fork = await client.conversations.fork(conversation.id, { message_id: response.id }); // Continue in the fork const forkResponse = await client.conversations.messages.create(fork.id, { role: 'user', content: 'What about weekends?' }); // Delete original conversation await client.conversations.delete(conversation.id); ``` -------------------------------- ### Update Folder Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Folders.md Updates the name or description of an existing folder using its ID. ```typescript const updated = await client.folders.update('folder-123', { name: 'Updated Folder Name', description: 'New description' }); ``` -------------------------------- ### Type Safety Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/README.md Illustrates the type-safe nature of the client library using TypeScript. ```APIDOC ## Type Safety Full TypeScript support with comprehensive type definitions: ```typescript const agent: Letta.AgentState = await client.agents.create({ name: 'Agent', model: 'openai/gpt-4' }); ``` ``` -------------------------------- ### Retrieve Archive Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Archives.md Shows how to fetch an existing archive using its unique identifier. This is useful for accessing archive details or verifying its existence. ```typescript const archive = await client.archives.retrieve('archive-123'); console.log('Archive name:', archive.name); console.log('Vector DB provider:', archive.vector_db_provider); ``` -------------------------------- ### Comprehensive Error Handling Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/errors.md Demonstrates handling various specific Letta client errors within a try-catch block, including API errors, connection errors, and authentication errors. ```typescript import Letta from '@letta-ai/letta-client'; const client = new Letta({ apiKey: process.env.LETTA_API_KEY }); async function safeAgentCreation(agentConfig) { try { const agent = await client.agents.create(agentConfig); return agent; } catch (err) { // Handle specific errors if (err instanceof Letta.BadRequestError) { console.error('Invalid parameters:', err.error.message); throw new Error('Please check your agent configuration'); } if (err instanceof Letta.ConflictError) { console.error('Agent name already exists'); throw new Error('Choose a different agent name'); } if (err instanceof Letta.AuthenticationError) { console.error('Authentication failed'); throw new Error('Check your API key'); } if (err instanceof Letta.APIConnectionTimeoutError) { console.error('Request timeout'); throw new Error('Server is slow, please try again'); } if (err instanceof Letta.RateLimitError) { console.error('Rate limited'); throw new Error('Too many requests, please slow down'); } if (err instanceof Letta.InternalServerError) { console.error('Server error:', err.status); throw new Error('Server error, please try again later'); } // Catch-all for other errors if (err instanceof Letta.APIError) { console.error('API error:', err.status, err.message); throw new Error('API error occurred'); } // Unknown error throw err; } } ``` -------------------------------- ### Configuring Bun Proxy Source: https://github.com/letta-ai/letta-node/blob/main/README.md For Bun runtime, you can configure proxy settings directly within `fetchOptions` using the `proxy` property. This example sets a proxy on `http://localhost:8888`. ```typescript import Letta from '@letta-ai/letta-client'; const client = new Letta({ fetchOptions: { proxy: 'http://localhost:8888', }, }); ``` -------------------------------- ### Configuring Deno Proxy Source: https://github.com/letta-ai/letta-node/blob/main/README.md In Deno, configure proxy settings by creating a custom `Deno.HttpClient` with proxy details and passing it via `fetchOptions.client`. This example configures a proxy at `http://localhost:8888`. ```typescript import Letta from 'npm:@letta-ai/letta-client'; const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } }); const client = new Letta({ fetchOptions: { client: httpClient, }, }); ``` -------------------------------- ### Retrieve Folder Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Folders.md Fetches a specific folder using its unique identifier. Throws NotFoundError if the folder does not exist. ```typescript const folder = await client.folders.retrieve('folder-123'); console.log('Folder name:', folder.name); ``` -------------------------------- ### Filter Models by Provider Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Models.md Shows how to filter the list of available models to include only those from a specific provider, such as OpenAI. This is useful for targeting models from a particular service. ```typescript // Filter by provider const openaiModels = await client.models.list({ provider: 'openai' }); ``` -------------------------------- ### Facts Block Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Blocks.md Example of a facts block, used for storing specific factual information. ```typescript { label: 'facts', value: 'Key facts:\n- Established 2020\n- HQ in San Francisco' } ``` -------------------------------- ### Comprehensive Error Handling with Letta Client Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/README.md Provides detailed examples of how to catch and handle various Letta client errors, including AuthenticationError, BadRequestError, NotFoundError, RateLimitError, APIConnectionError, and InternalServerError. It shows how to inspect error details and headers. ```typescript import Letta from '@letta-ai/letta-client'; const client = new Letta(); try { const agent = await client.agents.create({ name: 'Agent', model: 'openai/gpt-4' }); } catch (err) { // Authentication failed if (err instanceof Letta.AuthenticationError) { console.error('API key is invalid'); } // Bad request (validation error) if (err instanceof Letta.BadRequestError) { console.error('Invalid parameters:', err.error); } // Resource not found if (err instanceof Letta.NotFoundError) { console.error('Resource not found'); } // Rate limited if (err instanceof Letta.RateLimitError) { const retryAfter = err.headers?.get('Retry-After'); console.error('Rate limited, retry after:', retryAfter); } // Network error if (err instanceof Letta.APIConnectionError) { console.error('Connection failed:', err.cause); } // Server error (automatically retried) if (err instanceof Letta.InternalServerError) { console.error('Server error:', err.status); } } ``` -------------------------------- ### Persona Block Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Blocks.md Example of a persona block, used to define an agent's role or personality. ```typescript { label: 'persona', value: 'You are a helpful research assistant with expertise in...' } ``` -------------------------------- ### Use TypeScript Definitions Source: https://github.com/letta-ai/letta-node/blob/main/README.md Import and utilize TypeScript definitions for request parameters and response fields to enhance type safety. This example shows creating an archive with explicit types. ```ts import Letta from '@letta-ai/letta-client'; const client = new Letta({ apiKey: process.env['LETTA_API_KEY'], // This is the default and can be omitted environment: 'local', // defaults to 'cloud' }); const params: Letta.ArchiveCreateParams = { name: 'name' }; const archive: Letta.Archive = await client.archives.create(params); ``` -------------------------------- ### Letta Client Initialization and Archive Operations Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Archives.md Demonstrates initializing the Letta client, creating an archive, adding passages, searching within an archive, and attaching an archive to an agent. ```typescript import Letta from '@letta-ai/letta-client'; const client = new Letta({ apiKey: process.env.LETTA_API_KEY }); // Create an archive const archive = await client.archives.create({ name: 'Company Documents', description: 'Internal documentation and procedures', embedding: 'openai/text-embedding-3-small' }); // Add passages to the archive await client.archives.passages.create(archive.id, { text: 'Our company values innovation and collaboration...', embedding: [0.1, 0.2, 0.3, ...] }); // Search passages in the archive const results = await client.archives.passages.search(archive.id, { query: 'company values' }); // Attach archive to an agent await client.agents.archives.attach('agent-123', { archive_ids: [archive.id] }); ``` -------------------------------- ### Client Initialization with Environment Selection Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/configuration.md Configure the client for either the cloud environment (default) or a local development environment. ```typescript // Cloud environment (default) const cloudClient = new Letta({ apiKey: process.env.LETTA_API_KEY, environment: 'cloud' }); // Local development const localClient = new Letta({ apiKey: 'dev-key', environment: 'local' // http://localhost:8283 }); ``` -------------------------------- ### get Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Letta-Client.md Makes a GET request to the specified API endpoint path. It returns a promise that resolves with the parsed response. ```APIDOC ## Method: get ```typescript get(path: string, options?: RequestOptions): APIPromise ``` Make a GET request to the API. **Parameters:** - `path`: API endpoint path - `options`: Request options **Returns:** `APIPromise` - Parsed response ``` -------------------------------- ### Create Letta Client Instance Source: https://github.com/letta-ai/letta-node/blob/main/README.md Instantiate the Letta client with an API key and environment. The API key defaults to the LETTA_API_KEY environment variable, and the environment defaults to 'cloud'. ```js import Letta from '@letta-ai/letta-client'; const client = new Letta({ apiKey: process.env['LETTA_API_KEY'], // This is the default and can be omitted environment: 'local', // defaults to 'cloud' }); const archive = await client.archives.create({ name: 'name' }); console.log(archive.id); ``` -------------------------------- ### Initialize Letta Client with Environment Variables Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Letta-Client.md Instantiate the Letta client using API key and environment from environment variables. Ensure the LETTA_API_KEY is set in your environment. ```typescript import Letta from '@letta-ai/letta-client'; // Using environment variables const client = new Letta({ apiKey: process.env['LETTA_API_KEY'], environment: 'cloud' // or 'local' }); ``` -------------------------------- ### Delete Folder Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Folders.md Deletes a folder by its unique identifier. ```typescript await client.folders.delete('folder-123'); console.log('Folder deleted'); ``` -------------------------------- ### Handling RateLimitError Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/errors.md Example of catching a RateLimitError and accessing the 'Retry-After' header. ```typescript try { // Make many requests quickly for (let i = 0; i < 1000; i++) { await client.agents.list(); } } catch (err) { if (err instanceof Letta.RateLimitError) { console.error('Rate limit exceeded. Retry-After:', err.headers.get('Retry-After')); } } ``` -------------------------------- ### Handling APIUserAbortError Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/errors.md Example of catching an APIUserAbortError when a request is aborted using AbortController. ```typescript const controller = new AbortController(); setTimeout(() => controller.abort(), 1000); try { await client.agents.list({}, { signal: controller.signal }); } catch (err) { if (err instanceof Letta.APIUserAbortError) { console.error('Request was aborted by user'); } } ``` -------------------------------- ### Handling APIConnectionTimeoutError Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/errors.md Example of catching an APIConnectionTimeoutError when a request exceeds the configured timeout. ```typescript try { const client = new Letta({ timeout: 5000 }); await client.agents.list(); } catch (err) { if (err instanceof Letta.APIConnectionTimeoutError) { console.error('Request timed out'); } } ``` -------------------------------- ### Client Initialization with Default Headers and Query Parameters Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/configuration.md Set default headers and query parameters that will be included with every request. ```typescript const client = new Letta({ apiKey: process.env.LETTA_API_KEY, defaultHeaders: { 'X-Custom-Header': 'value', 'X-Request-ID': 'your-request-id' }, defaultQuery: { includeArchived: 'false' } }); ``` -------------------------------- ### Basic Client Initialization Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/configuration.md Initialize the Letta client using the LETTA_API_KEY environment variable or by providing the API key directly. ```typescript import Letta from '@letta-ai/letta-client'; // Uses LETTA_API_KEY environment variable const client = new Letta(); // Or provide API key const client = new Letta({ apiKey: 'your-api-key' }); ``` -------------------------------- ### Handling APIConnectionError Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/errors.md Example of catching an APIConnectionError and logging its message and underlying cause. ```typescript try { const client = new Letta({ baseURL: 'https://api.invalid-domain.com' }); await client.agents.list(); } catch (err) { if (err instanceof Letta.APIConnectionError) { console.error('Connection error:', err.message); console.error('Cause:', err.cause); } } ``` -------------------------------- ### withOptions Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Letta-Client.md Creates a new client instance with overridden options, re-using settings from the current client. This is useful for making requests with specific configurations without re-initializing the entire client. ```APIDOC ## Method: withOptions ```typescript withOptions(options: Partial): Letta ``` Creates a new client instance with overridden options, re-using settings from the current client. **Parameters:** - `options`: Partial client options to override **Returns:** New Letta client instance **Example:** ```typescript const client = new Letta({ apiKey: 'key1' }); const customClient = client.withOptions({ timeout: 5000, maxRetries: 1 }); ``` ``` -------------------------------- ### Handling InternalServerError Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/errors.md Example of catching an InternalServerError and accessing its status and error properties. ```typescript try { await client.agents.create({ name: 'Agent' }); } catch (err) { if (err instanceof Letta.InternalServerError) { console.error('Server error:', err.status, err.error); } } ``` -------------------------------- ### client.environments.list Source: https://github.com/letta-ai/letta-node/blob/main/api.md Retrieves a list of environments. This method corresponds to the GET /v1/environments endpoint. ```APIDOC ## GET /v1/environments ### Description Retrieves a list of environments. ### Method GET ### Endpoint /v1/environments ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering or paginating the list. ### Response #### Success Response (200) - **EnvironmentListResponse** (object) - A list of environments. ``` -------------------------------- ### client.conversations.list Source: https://github.com/letta-ai/letta-node/blob/main/api.md Retrieves a list of conversations. This method corresponds to the GET /v1/conversations/ endpoint. ```APIDOC ## GET /v1/conversations/ ### Description Retrieves a list of conversations. ### Method GET ### Endpoint /v1/conversations/ ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering or paginating the list. ### Response #### Success Response (200) - **ConversationListResponse** (object) - A list of conversations. ``` -------------------------------- ### Initialize Letta Client with Custom Configuration Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Letta-Client.md Create a Letta client instance with specific configuration parameters like API key, base URL, timeout, and retry settings. ```typescript // With custom configuration const client = new Letta({ apiKey: 'your-api-key', baseURL: 'https://api.letta.com', timeout: 30000, maxRetries: 3, logLevel: 'debug' }); ``` -------------------------------- ### Client Initialization with Logging Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/configuration.md Configure custom logging by specifying the log level and providing a logger instance. ```typescript import Letta from '@letta-ai/letta-client'; import pino from 'pino'; const logger = pino(); const client = new Letta({ apiKey: process.env.LETTA_API_KEY, logLevel: 'debug', logger: logger.child({ name: 'Letta' }) }); ``` -------------------------------- ### retrieve Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Tools.md Get a tool by its unique identifier. This is useful for fetching the details of a specific tool. ```APIDOC ## GET /tools/{toolID} ### Description Get a tool by its ID. ### Method GET ### Endpoint /tools/{toolID} ### Parameters #### Path Parameters - **toolID** (string) - Required - The tool's unique identifier. ### Response #### Success Response (200) - **id** (string) - The unique identifier of the tool. - **name** (string) - The name of the tool. - **description** (string) - The description of the tool. - **source_code** (string) - The source code of the tool. - **source_type** (string) - The type of the source code. - **args_json_schema** (object) - The JSON schema for the tool's arguments. - **created_at** (string) - Timestamp of creation. - **updated_at** (string) - Timestamp of last update. #### Error Response (404) - **message** (string) - "Tool not found" ``` -------------------------------- ### retrieve Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Archives.md Get an archive by its ID. This method retrieves detailed information about a specific archive. ```APIDOC ## retrieve ### Description Get an archive by its ID. ### Method GET ### Endpoint /v1/archives/{archiveID} ### Parameters #### Path Parameters - **archiveID** (string) - Required - The archive's unique identifier. ### Response #### Success Response (200) - **id** (string) - The unique identifier of the archive. - **name** (string) - The name of the archive. - **description** (string) - The description of the archive. - **vector_db_provider** (string) - The vector database provider used. - **created_at** (string) - The timestamp when the archive was created. #### Response Example ```json { "id": "archive-123", "name": "My Archive", "description": "An example archive.", "vector_db_provider": "native", "created_at": "2023-10-27T10:00:00Z" } ``` ### Error Handling - **NotFoundError**: Archive not found. ``` -------------------------------- ### client.conversations.retrieve Source: https://github.com/letta-ai/letta-node/blob/main/api.md Retrieves a specific conversation by its ID. This method corresponds to the GET /v1/conversations/{conversation_id} endpoint. ```APIDOC ## GET /v1/conversations/{conversation_id} ### Description Retrieves a specific conversation by its ID. ### Method GET ### Endpoint /v1/conversations/{conversation_id} ### Parameters #### Path Parameters - **conversation_id** (string) - Required - The ID of the conversation to retrieve. ### Response #### Success Response (200) - **Conversation** (object) - Details of the retrieved conversation. ``` -------------------------------- ### create Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Folders.md Create a new folder with a name and optional description. ```APIDOC ## POST /folders ### Description Create a new folder to organize documents and passages. ### Method POST ### Endpoint /folders ### Parameters #### Request Body - **name** (string) - Required - The name of the folder. - **description** (string) - Optional - A description for the folder. ### Request Example ```json { "name": "Documentation", "description": "API and product documentation" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the created folder. - **name** (string) - The name of the folder. - **description** (string) - The description of the folder. - **created_at** (string) - The timestamp when the folder was created. - **updated_at** (string) - The timestamp when the folder was last updated. ### Response Example ```json { "id": "folder-xyz789", "name": "Documentation", "description": "API and product documentation", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Organize Documents into Folders and Attach to Agents Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/README.md Demonstrates how to create a folder, add files to it, and then attach the folder to an agent. This helps in organizing and associating documents with specific agents. ```typescript // Create folder const folder = await client.folders.create({ name: 'Documentation', description: 'API and technical docs' }); // Add files to folder await client.folders.files.create(folder.id, { file: new File(['content'], 'readme.md') }); // Attach to agent await client.agents.folders.attach(agent.id, { folder_ids: [folder.id] }); ``` -------------------------------- ### client.mcpServers.create Source: https://github.com/letta-ai/letta-node/blob/main/api.md Creates a new MCP server. Supports SSE, stdio, and Streamable HTTP configurations. ```APIDOC ## POST /v1/mcp-servers/ ### Description Creates a new MCP server. This method can be used to set up servers with different communication protocols like Server-Sent Events (SSE), standard input/output (stdio), or Streamable HTTP. ### Method POST ### Endpoint /v1/mcp-servers/ ### Parameters #### Request Body - **params** (object) - Required - Configuration parameters for the new MCP server. The exact structure depends on the type of server being created (SSE, stdio, or Streamable HTTP). ### Response #### Success Response (200) - **McpServerCreateResponse** - An object containing details of the newly created MCP server. ``` -------------------------------- ### client.environments.retrieve Source: https://github.com/letta-ai/letta-node/blob/main/api.md Retrieves environment details by device ID. This method corresponds to the GET /v1/environments/{deviceId} endpoint. ```APIDOC ## GET /v1/environments/{deviceId} ### Description Retrieves environment details by device ID. ### Method GET ### Endpoint /v1/environments/{deviceId} ### Parameters #### Path Parameters - **deviceId** (string) - Required - The ID of the device for which to retrieve environment details. ### Response #### Success Response (200) - **EnvironmentRetrieveResponse** (object) - Details of the environment. ``` -------------------------------- ### Letta Client Constructor Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Letta-Client.md Initializes a new Letta API client instance. It can be configured with various options such as API key, environment, base URL, timeout, and retry settings. ```APIDOC ## Constructor Letta ```typescript new Letta(options?: ClientOptions): Letta ``` Creates a new Letta API client instance. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | `ClientOptions` | No | `{}` | Configuration object for the client | ### Example ```typescript import Letta from '@letta-ai/letta-client'; // Using environment variables const client = new Letta({ apiKey: process.env['LETTA_API_KEY'], environment: 'cloud' // or 'local' }); // With custom configuration const client = new Letta({ apiKey: 'your-api-key', baseURL: 'https://api.letta.com', timeout: 30000, maxRetries: 3, logLevel: 'debug' }); ``` ``` -------------------------------- ### retrieve Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Conversations.md Get a conversation by its ID. This allows you to fetch the details of a specific conversation, including its history and status. ```APIDOC ## retrieve ### Description Get a conversation by its ID. ### Method GET ### Endpoint /conversations/{conversationID} ### Parameters #### Path Parameters - **conversationID** (string) - Required - The conversation's unique identifier. ### Response #### Success Response (200) - **Conversation** (object) - The conversation object. #### Error Response - **NotFoundError** - Conversation not found. ### Response Example ```json { "id": "conv-123", "agent_id": "agent-123", "description": "Initial discussion", "created_at": "2023-10-27T10:00:00Z", "last_message_at": "2023-10-27T10:05:00Z" } ``` ``` -------------------------------- ### retrieve Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Blocks.md Get a memory block by its unique identifier. This is useful for retrieving previously stored agent state. ```APIDOC ## GET /blocks/{blockID} ### Description Get a block by its ID. ### Method GET ### Endpoint /blocks/{blockID} ### Parameters #### Path Parameters - **blockID** (string) - Required - The block's unique identifier ### Response #### Success Response (200) - **id** (string) - Block unique identifier - **label** (string) - Block label/name - **value** (string) - Block content - **created_at** (string) - Creation timestamp - **updated_at** (string) - Last update timestamp #### Response Example ```json { "id": "block-123", "label": "persona", "value": "You are an expert AI assistant", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z" } ``` ### Errors - **NotFoundError**: Block not found ``` -------------------------------- ### Full Folder Management Workflow Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Folders.md Demonstrates the complete lifecycle of creating, attaching, listing, updating, and deleting folders associated with an agent. ```typescript import Letta from '@letta-ai/letta-client'; const client = new Letta(); // Create folders for organization const docFolder = await client.folders.create({ name: 'Documentation', description: 'API and technical documentation' }); const kbFolder = await client.folders.create({ name: 'Knowledge Base', description: 'General knowledge articles' }); // Attach folders to an agent const agent = await client.agents.create({ name: 'Knowledge Agent', model: 'openai/gpt-4', system: 'You are a helpful assistant' }); await client.agents.folders.attach(agent.id, { folder_ids: [docFolder.id, kbFolder.id] }); // List folders for agent const agentFolders = await client.folders.list({ agent_id: agent.id }); agentFolders.items.forEach(folder => { console.log(`${folder.name}: ${folder.description}`); }); // Update a folder await client.folders.update(docFolder.id, { description: 'Updated API documentation' }); // Delete a folder await client.folders.delete(kbFolder.id); ``` -------------------------------- ### Abort a Long-Running Request Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/configuration.md Example of using an AbortController to cancel a request after a specified duration. Handles potential APIUserAbortError. ```typescript const controller = new AbortController(); // Abort after 5 seconds const timeoutId = setTimeout(() => controller.abort(), 5000); try { const agents = await client.agents.list( {}, { signal: controller.signal } ); } catch (err) { if (err instanceof Letta.APIUserAbortError) { console.log('Request was aborted'); } } finally { clearTimeout(timeoutId); } ``` -------------------------------- ### Configure Letta Client Logging Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/README.md Demonstrates how to configure logging for the Letta client, either by setting the logLevel option directly or by providing a custom logger instance (e.g., from pino). ```typescript const client = new Letta({ apiKey: process.env.LETTA_API_KEY, logLevel: 'debug' }); // Or use custom logger import pino from 'pino'; const logger = pino(); const client = new Letta({ apiKey: process.env.LETTA_API_KEY, logger: logger.child({ name: 'Letta' }), logLevel: 'debug' }); ``` -------------------------------- ### Custom Request Timeout Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/configuration.md Example of overriding the default timeout for a specific API request, setting it to 2 minutes. ```typescript const agent = await client.agents.create( { name: 'Agent' }, { timeout: 120000 } // 2 minute timeout ); ``` -------------------------------- ### Client Initialization with Custom Fetch Implementation Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/configuration.md Use a custom fetch implementation, such as for routing requests through a proxy. ```typescript import Letta from '@letta-ai/letta-client'; import * as undici from 'undici'; // Use custom proxy const proxyAgent = new undici.ProxyAgent('http://localhost:8888'); const client = new Letta({ apiKey: process.env.LETTA_API_KEY, fetchOptions: { dispatcher: proxyAgent } }); ``` -------------------------------- ### Delete Archive Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Archives.md Demonstrates the permanent deletion of an archive using its ID. This action is irreversible and should be used with caution. ```typescript await client.archives.delete('archive-123'); console.log('Archive deleted'); ``` -------------------------------- ### create Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Tools.md Create a new tool that can be used by agents. This involves providing details like name, description, source code, and argument schema. ```APIDOC ## POST /tools ### Description Create a new tool that can be used by agents. ### Method POST ### Endpoint /tools ### Parameters #### Request Body - **name** (string) - Required - The name of the tool. - **description** (string) - Required - A description of what the tool does. - **source_code** (string) - Required - The source code of the tool. - **source_type** (string) - Required - The programming language of the source code (e.g., 'typescript'). - **args_json_schema** (object) - Required - A JSON schema defining the arguments the tool accepts. - **default_requires_approval** (boolean) - Optional - Whether the tool requires approval by default. ### Request Example ```json { "name": "get_weather", "description": "Get the current weather for a location", "source_code": "function get_weather(location: string): string { return \"Sunny, 72°F\"; }", "source_type": "typescript", "args_json_schema": { "type": "object", "properties": { "location": { "type": "string", "description": "City name" } }, "required": ["location"] } } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the created tool. - **name** (string) - The name of the tool. - **description** (string) - The description of the tool. - **source_code** (string) - The source code of the tool. - **source_type** (string) - The type of the source code. - **args_json_schema** (object) - The JSON schema for the tool's arguments. - **created_at** (string) - Timestamp of creation. - **updated_at** (string) - Timestamp of last update. ``` -------------------------------- ### client.conversations.messages.list Source: https://github.com/letta-ai/letta-node/blob/main/api.md Retrieves a list of messages within a conversation. This method corresponds to the GET /v1/conversations/{conversation_id}/messages endpoint. ```APIDOC ## GET /v1/conversations/{conversation_id}/messages ### Description Retrieves a list of messages within a conversation. ### Method GET ### Endpoint /v1/conversations/{conversation_id}/messages ### Parameters #### Path Parameters - **conversation_id** (string) - Required - The ID of the conversation whose messages to retrieve. #### Query Parameters - **params** (object) - Optional - Parameters for filtering or paginating the messages. ### Response #### Success Response (200) - **MessagesArrayPage** (object) - A paginated list of messages. ``` -------------------------------- ### client.runs.steps.list Source: https://github.com/letta-ai/letta-node/blob/main/api.md Retrieves a paginated list of steps for a specific run. ```APIDOC ## GET /v1/runs/{run_id}/steps ### Description Retrieves a paginated list of steps that constitute a specific run. This allows for detailed inspection of the run's execution flow. ### Method GET ### Endpoint /v1/runs/{run_id}/steps ### Parameters #### Path Parameters - **run_id** (string) - Required - The unique identifier of the run for which to retrieve steps. #### Query Parameters - **params** (object) - Optional - Parameters for pagination, filtering, or sorting the steps. ``` -------------------------------- ### Reset Conversation Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Messages.md Clear all messages and reset a conversation to its initial state. Use this to start a fresh conversation thread. ```typescript await client.conversations.messages.reset('conv-123'); console.log('Conversation reset'); ``` -------------------------------- ### client.folders.create Source: https://github.com/letta-ai/letta-node/blob/main/api.md Creates a new folder. Accepts parameters for folder creation and returns the created Folder object. ```APIDOC ## POST /v1/folders/ ### Description Creates a new folder. ### Method POST ### Endpoint /v1/folders/ ### Parameters #### Request Body - **params** (object) - Required - Parameters for folder creation. ``` -------------------------------- ### Create and Share Folders Across Agents Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Folders.md Demonstrates creating a shared folder and attaching it to multiple agents simultaneously using Promise.all for efficiency. ```typescript // Create shared folder const sharedFolder = await client.folders.create({ name: 'Shared Knowledge', description: 'Shared by multiple agents' }); // Attach to multiple agents await Promise.all([ client.agents.folders.attach('agent-1', { folder_ids: [sharedFolder.id] }), client.agents.folders.attach('agent-2', { folder_ids: [sharedFolder.id] }), client.agents.folders.attach('agent-3', { folder_ids: [sharedFolder.id] }) ]); ``` -------------------------------- ### Get Service Health Source: https://github.com/letta-ai/letta-node/blob/main/api.md Retrieves the health status of the Letta AI service. This is a basic check to ensure the service is operational. ```APIDOC ## GET /v1/health/ ### Description Retrieves the health status of the Letta AI service. ### Method GET ### Endpoint /v1/health/ ``` -------------------------------- ### Update Archive Example Source: https://github.com/letta-ai/letta-node/blob/main/_autodocs/api-reference/Archives.md Illustrates how to modify the name and description of an existing archive. Only metadata fields like name and description can be updated. ```typescript const updated = await client.archives.update('archive-123', { name: 'Updated Archive Name', description: 'New description' }); ```