Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: add support for YAML config file (#8999)
Kian Jones74dc6225bad3
diff --git a/conf.yaml b/conf.yamlnew file mode 100644index 000000000..b3b2eb82f--- /dev/null+++ b/conf.yaml@@ -0,0 +1,412 @@+# Letta Configuration File+# Place at ~/.letta/conf.yaml, ./conf.yaml, or set LETTA_CONFIG_PATH+# Environment variables take precedence over config file values+#+# Top-level keys and their env var mappings:+# letta: -> LETTA_*+# model: -> Provider-prefixed (OPENAI_*, ANTHROPIC_*, etc.)+# tool: -> Prefix-based (E2B_*, MCP_*, TOOL_*, etc.)+# datadog: -> DD_*++letta:+ # =============================================================================+ # Core Settings (LETTA_*)+ # =============================================================================+ debug: false+ # environment: ""++ # Default handles+ # default_llm_handle: ""+ # default_embedding_handle: ""++ # SSE Streaming+ enable_keepalive: true+ keepalive_interval: 50.0+ enable_cancellation_aware_streaming: true++ # =============================================================================+ # PostgreSQL (LETTA_PG_*)+ # =============================================================================+ pg:+ # db: ""+ # user: ""+ # password: ""+ # host: ""+ # port: ""+ # uri: ""+ pool_size: 25+ max_overflow: 10+ pool_timeout: 30+ pool_recycle: 1800+ echo: false++ # Connection pool settings (LETTA_POOL_*)+ pool:+ pre_ping: true+ use_lifo: true++ # Database settings (LETTA_DB_*)+ # db:+ # max_concurrent_sessions: ""++ disable_sqlalchemy_pooling: true+ enable_db_pool_monitoring: true+ db_pool_monitoring_interval: 30++ # =============================================================================+ # Redis (LETTA_REDIS_*)+ # =============================================================================+ redis:+ # host: ""+ port: 6379++ # =============================================================================+ # Multi-Agent (LETTA_MULTI_AGENT_*)+ # =============================================================================+ multi_agent:+ send_message_max_retries: 3+ send_message_timeout: 1200+ concurrent_sends: 50++ # =============================================================================+ # OTEL / Observability (LETTA_OTEL_*, LETTA_CLICKHOUSE_*)+ # =============================================================================+ otel:+ # exporter_otlp_endpoint: ""+ preferred_temporality: 1++ clickhouse:+ # endpoint: ""+ database: otel+ username: default+ # password: ""++ disable_tracing: false+ llm_api_logging: true+ track_last_agent_run: false+ track_errored_messages: true+ track_stop_reason: true+ track_agent_run: true+ track_provider_trace: true++ # =============================================================================+ # Uvicorn (LETTA_UVICORN_*)+ # =============================================================================+ uvicorn:+ workers: 1+ reload: false+ timeout_keep_alive: 5++ # Runtime settings+ use_uvloop: false+ use_granian: false+ sqlalchemy_tracing: false+ event_loop_threadpool_max_workers: 43++ # =============================================================================+ # Experimental+ # =============================================================================+ use_vertex_structured_outputs_experimental: false+ use_asyncio_shield: true++ # =============================================================================+ # Lettuce (LETTA_USE_LETTUCE_*)+ # =============================================================================+ use_lettuce_for_file_uploads: false++ # =============================================================================+ # Batch Job Polling (LETTA_POLL_*, LETTA_BATCH_*)+ # =============================================================================+ enable_batch_job_polling: false+ poll_running_llm_batches_interval_seconds: 300+ poll_lock_retry_interval_seconds: 480+ batch_job_polling_lookback_weeks: 2+ # batch_job_polling_batch_size: ""++ # =============================================================================+ # LLM Timeouts (LETTA_LLM_*)+ # =============================================================================+ llm:+ request_timeout_seconds: 60.0+ stream_timeout_seconds: 600.0++ # =============================================================================+ # Pinecone (LETTA_PINECONE_*, LETTA_ENABLE_PINECONE, LETTA_UPSERT_PINECONE_INDICES)+ # =============================================================================+ enable_pinecone: false+ upsert_pinecone_indices: false+ pinecone:+ # api_key: ""+ source_index: sources+ agent_index: recall++ # =============================================================================+ # Turbopuffer (LETTA_TPUF_*, LETTA_USE_TPUF, LETTA_EMBED_*)+ # =============================================================================+ use_tpuf: false+ embed_all_messages: false+ embed_tools: false+ tpuf:+ # api_key: ""+ region: gcp-us-central1++ # =============================================================================+ # File Processing (LETTA_FILE_PROCESSING_*)+ # =============================================================================+ file_processing:+ timeout_minutes: 30+ timeout_error_message: "File processing timed out after {} minutes. Please try again."++ # =============================================================================+ # Letta Client (LETTA_DEFAULT_*)+ # =============================================================================+ default_base_url: http://localhost:8283+ # default_token: ""++ # =============================================================================+ # Agent Architecture+ # =============================================================================+ use_letta_v1_agent: false+ archival_memory_token_limit: 8192++ # =============================================================================+ # Security+ # =============================================================================+ no_default_actor: false+ # encryption_key: ""++ # =============================================================================+ # OCR+ # =============================================================================+ # mistral_api_key: ""++ # =============================================================================+ # Summarizer (LETTA_SUMMARIZER_*)+ # =============================================================================+ summarizer:+ mode: partial_evict_message_buffer_mode+ message_buffer_limit: 60+ message_buffer_min: 15+ enable_summarization: true+ max_summarization_retries: 3+ partial_evict_summarizer_percentage: 0.30+ evict_all_messages: false+ max_summarizer_retries: 3+ memory_warning_threshold: 0.75+ send_memory_warning_message: false+ desired_memory_token_pressure: 0.3+ keep_last_n_messages: 0++ # =============================================================================+ # Logging (LETTA_LOGGING_*)+ # =============================================================================+ logging:+ debug: false+ json_logging: false+ log_level: WARNING+ verbose_telemetry_logging: false++ # =============================================================================+ # Telemetry (LETTA_TELEMETRY_*)+ # =============================================================================+ telemetry:+ enable_datadog: false+ provider_trace_backend: postgres+ socket_path: /var/run/telemetry/telemetry.sock+ provider_trace_pg_metadata_only: false+ # source: ""++ # Datadog settings (LETTA_TELEMETRY_DATADOG_*)+ datadog:+ agent_host: localhost+ agent_port: 8126+ service_name: letta-server+ profiling_enabled: false+ profiling_memory_enabled: false+ profiling_heap_enabled: false+ # git_repository_url: ""+ # git_commit_sha: ""+ main_package: letta++# =============================================================================+# Model Settings (-> OPENAI_*, ANTHROPIC_*, AWS_*, etc.)+# =============================================================================+model:+ # Global settings+ global_max_context_window_limit: 32000+ inner_thoughts_kwarg: thinking+ default_prompt_formatter: chatml++ # OpenAI (-> OPENAI_*)+ openai:+ # api_key: ""+ api_base: https://api.openai.com/v1++ # Anthropic (-> ANTHROPIC_*)+ anthropic:+ # api_key: ""+ max_retries: 3+ sonnet_1m: false++ # Azure OpenAI (-> AZURE_*)+ azure:+ # api_key: ""+ # base_url: ""+ api_version: "2024-09-01-preview"++ # Google Gemini (-> GEMINI_*)+ gemini:+ # api_key: ""+ base_url: https://generativelanguage.googleapis.com/+ force_minimum_thinking_budget: false+ max_retries: 5++ # Google Vertex (-> GOOGLE_CLOUD_*)+ # google_cloud:+ # project: ""+ # location: ""++ # AWS Bedrock (-> AWS_*, BEDROCK_*)+ aws:+ # access_key_id: ""+ # secret_access_key: ""+ default_region: us-east-1++ bedrock:+ anthropic_version: bedrock-2023-05-31++ # OpenRouter (-> OPENROUTER_*)+ # openrouter:+ # api_key: ""+ # referer: ""+ # title: ""+ # handle_base: ""++ # Groq (-> GROQ_*)+ # groq:+ # api_key: ""++ # Together (-> TOGETHER_*)+ # together:+ # api_key: ""++ # DeepSeek (-> DEEPSEEK_*)+ # deepseek:+ # api_key: ""++ # xAI/Grok (-> XAI_*)+ # xai:+ # api_key: ""++ # Z.ai/ZhipuAI (-> ZAI_*)+ zai:+ # api_key: ""+ base_url: https://api.z.ai/api/paas/v4/++ # MiniMax (-> MINIMAX_*)+ # minimax:+ # api_key: ""++ # Ollama (-> OLLAMA_*)+ # ollama:+ # base_url: ""++ # vLLM (-> VLLM_*)+ # vllm:+ # api_base: ""+ # handle_base: ""++ # SGLang (-> SGLANG_*)+ # sglang:+ # api_base: ""+ # handle_base: ""++ # LM Studio (-> LMSTUDIO_*)+ # lmstudio:+ # base_url: ""++ # OpenLLM (-> OPENLLM_*)+ # openllm:+ # auth_type: ""+ # api_key: ""++# =============================================================================+# Tool Settings (-> E2B_*, MCP_*, MODAL_*, TOOL_*, etc.)+# =============================================================================+tool:+ # E2B Sandbox (-> E2B_*)+ # e2b:+ # api_key: ""+ # sandbox_template_id: ""++ # Modal Sandbox (-> MODAL_*)+ # modal:+ # token_id: ""+ # token_secret: ""++ # Search Providers (-> TAVILY_*, EXA_*)+ # tavily:+ # api_key: ""++ # exa:+ # api_key: ""++ # Local Sandbox (-> TOOL_*)+ tool:+ # exec_dir: ""+ sandbox_timeout: 180+ # exec_venv_name: ""+ exec_autoreload_venv: true++ # MCP (-> MCP_*)+ mcp:+ connect_to_server_timeout: 30.0+ list_tools_timeout: 30.0+ execute_tool_timeout: 60.0+ read_from_config: false+ disable_stdio: true++# =============================================================================+# Datadog Agent Settings (-> DD_*)+# =============================================================================+# datadog:+# site: ""+# service: ""+# version: ""+#+# trace:+# enabled: false+# agent_url: ""+# health_metrics_enabled: false+#+# dogstatsd:+# url: ""+#+# logs:+# injection: false+#+# runtime:+# metrics_enabled: false+#+# appsec:+# enabled: false+# sca_enabled: false+#+# iast:+# enabled: false+#+# exception:+# replay_enabled: false+#+# llmobs:+# enabled: false+# ml_app: ""+#+# instrumentation:+# install_type: ""+#+# git:+# repository_url: ""+# commit_sha: ""+#+# main_package: ""diff --git a/letta/config_file.py b/letta/config_file.pynew file mode 100644index 000000000..71c00a7c9--- /dev/null+++ b/letta/config_file.py@@ -0,0 +1,232 @@+"""+Letta Configuration File Support++Loads hierarchical YAML config and maps it to environment variables.++Supported top-level keys and their env var prefixes:+ letta: -> LETTA_*+ model: -> * (provider-prefixed: OPENAI_*, ANTHROPIC_*, etc.)+ tool: -> * (prefix-based: E2B_*, MCP_*, TOOL_*, etc.)+ datadog: -> DD_*++Config file format:+ letta:+ telemetry:+ enable_datadog: true+ pg:+ host: localhost+ model:+ openai:+ api_key: sk-xxx+ anthropic:+ api_key: sk-yyy+ tool:+ e2b:+ api_key: xxx+ mcp:+ disable_stdio: true+ datadog:+ site: us5.datadoghq.com+ service: memgpt-server++This maps to environment variables:+ LETTA_TELEMETRY_ENABLE_DATADOG=true+ LETTA_PG_HOST=localhost+ OPENAI_API_KEY=sk-xxx+ ANTHROPIC_API_KEY=sk-yyy+ E2B_API_KEY=xxx+ MCP_DISABLE_STDIO=true+ DD_SITE=us5.datadoghq.com+ DD_SERVICE=memgpt-server++Config file locations (in order of precedence):+ 1. ~/.letta/conf.yaml+ 2. ./conf.yaml+ 3. LETTA_CONFIG_PATH environment variable+"""++import os+from pathlib import Path+from typing import Any++import yaml++# Config file locations+DEFAULT_USER_CONFIG = Path.home() / ".letta" / "conf.yaml"+DEFAULT_PROJECT_CONFIG = Path.cwd() / "conf.yaml"+++def load_config_file(config_path: str | Path | None = None) -> dict[str, Any]:+ """+ Load configuration from YAML file.++ Args:+ config_path: Optional explicit path to config file++ Returns:+ Loaded config dict, or empty dict if no config found+ """+ paths_to_check = []++ # Check in order of precedence (lowest to highest)+ if DEFAULT_USER_CONFIG.exists():+ paths_to_check.append(DEFAULT_USER_CONFIG)++ if DEFAULT_PROJECT_CONFIG.exists():+ paths_to_check.append(DEFAULT_PROJECT_CONFIG)++ # Environment variable override+ env_path = os.environ.get("LETTA_CONFIG_PATH")+ if env_path and Path(env_path).exists():+ paths_to_check.append(Path(env_path))++ # Explicit path has highest precedence+ if config_path:+ p = Path(config_path)+ if p.exists():+ paths_to_check.append(p)++ # Merge configs (later files override earlier)+ config: dict[str, Any] = {}+ for path in paths_to_check:+ try:+ with open(path, "r") as f:+ file_config = yaml.safe_load(f)+ if file_config:+ config = _deep_merge(config, file_config)+ except Exception:+ pass++ return config+++def _deep_merge(base: dict, override: dict) -> dict:+ """Deep merge two dicts, override values take precedence."""+ result = base.copy()+ for key, value in override.items():+ if key in result and isinstance(result[key], dict) and isinstance(value, dict):+ result[key] = _deep_merge(result[key], value)+ else:+ result[key] = value+ return result+++def _flatten_with_prefix(d: dict, prefix: str, env_vars: dict[str, str]) -> None:+ """Flatten a dict with a given prefix."""+ for key, value in d.items():+ env_key = f"{prefix}_{key}".upper() if prefix else key.upper()+ if isinstance(value, dict):+ _flatten_with_prefix(value, env_key, env_vars)+ elif value is not None:+ if isinstance(value, bool):+ env_vars[env_key] = str(value).lower()+ else:+ env_vars[env_key] = str(value)+++def _flatten_model_settings(d: dict, env_vars: dict[str, str]) -> None:+ """+ Flatten model settings where nested keys become prefixes.++ model:+ openai:+ api_key: xxx -> OPENAI_API_KEY+ api_base: yyy -> OPENAI_API_BASE+ anthropic:+ api_key: zzz -> ANTHROPIC_API_KEY+ global_max_context_window_limit: 32000 -> GLOBAL_MAX_CONTEXT_WINDOW_LIMIT+ """+ for key, value in d.items():+ if isinstance(value, dict):+ # Nested provider config: openai.api_key -> OPENAI_API_KEY+ _flatten_with_prefix(value, key.upper(), env_vars)+ elif value is not None:+ # Top-level model setting+ env_key = key.upper()+ if isinstance(value, bool):+ env_vars[env_key] = str(value).lower()+ else:+ env_vars[env_key] = str(value)+++def _flatten_tool_settings(d: dict, env_vars: dict[str, str]) -> None:+ """+ Flatten tool settings where nested keys become prefixes.++ tool:+ e2b:+ api_key: xxx -> E2B_API_KEY+ sandbox_template_id: y -> E2B_SANDBOX_TEMPLATE_ID+ mcp:+ disable_stdio: true -> MCP_DISABLE_STDIO+ tool_sandbox_timeout: 180 -> TOOL_SANDBOX_TIMEOUT+ """+ for key, value in d.items():+ if isinstance(value, dict):+ # Nested tool config: e2b.api_key -> E2B_API_KEY+ _flatten_with_prefix(value, key.upper(), env_vars)+ elif value is not None:+ # Top-level tool setting+ env_key = key.upper()+ if isinstance(value, bool):+ env_vars[env_key] = str(value).lower()+ else:+ env_vars[env_key] = str(value)+++def config_to_env_vars(config: dict[str, Any]) -> dict[str, str]:+ """+ Convert hierarchical config to flat environment variables.++ Supports multiple top-level keys with different prefix behaviors:+ - letta: -> LETTA_* prefix+ - model: -> provider-prefixed (OPENAI_*, ANTHROPIC_*, etc.)+ - tool: -> prefix-based (E2B_*, MCP_*, TOOL_*, etc.)+ - datadog: -> DD_* prefix++ Args:+ config: Hierarchical config dict++ Returns:+ Dict of environment variable name -> value+ """+ env_vars: dict[str, str] = {}++ # Handle 'letta' section with LETTA_ prefix+ if "letta" in config:+ _flatten_with_prefix(config["letta"], "LETTA", env_vars)++ # Handle 'model' section (provider-prefixed env vars)+ if "model" in config:+ _flatten_model_settings(config["model"], env_vars)++ # Handle 'tool' section (prefix-based env vars)+ if "tool" in config:+ _flatten_tool_settings(config["tool"], env_vars)++ # Handle 'datadog' section with DD_ prefix+ if "datadog" in config:+ _flatten_with_prefix(config["datadog"], "DD", env_vars)++ return env_vars+++def apply_config_to_env(config_path: str | Path | None = None) -> None:+ """+ Load config file and apply values to environment variables.++ Environment variables already set take precedence over config file values.++ Args:+ config_path: Optional explicit path to config file+ """+ config = load_config_file(config_path)+ if not config:+ return++ env_vars = config_to_env_vars(config)++ for key, value in env_vars.items():+ # Only set if not already in environment (env vars take precedence)+ if key not in os.environ:+ os.environ[key] = valuediff --git a/letta/settings.py b/letta/settings.pyindex 5f8d455fc..cb277eec2 100644--- a/letta/settings.py+++ b/letta/settings.py@@ -6,9 +6,14 @@ from typing import Optionalfrom pydantic import AliasChoices, Fieldfrom pydantic_settings import BaseSettings, SettingsConfigDict+# Load config file and apply to environment before settings are created+# This allows YAML config values to be picked up by pydantic-settings+from letta.config_file import apply_config_to_envfrom letta.schemas.enums import SandboxTypefrom letta.services.summarizer.enums import SummarizationMode+apply_config_to_env()+# Define constants here to avoid circular import with letta.logDEFAULT_WRAPPER_NAME = "chatml"INNER_THOUGHTS_KWARG = "thinking"