Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

feat: add baseten as auto provider (#9846)

Ari Webba5678b748ca9
diff --git a/letta/adapters/letta_llm_stream_adapter.py b/letta/adapters/letta_llm_stream_adapter.py
index 83e0580a3..85229d826 100644
--- a/letta/adapters/letta_llm_stream_adapter.py
+++ b/letta/adapters/letta_llm_stream_adapter.py
@@ -101,7 +101,12 @@ class LettaLLMStreamAdapter(LettaLLMAdapter):
run_id=self.run_id,
step_id=step_id,
)
- elif self.llm_config.model_endpoint_type in [ProviderType.openai, ProviderType.openrouter, ProviderType.fireworks]:
+ elif self.llm_config.model_endpoint_type in [
+ ProviderType.openai,
+ ProviderType.openrouter,
+ ProviderType.baseten,
+ ProviderType.fireworks,
+ ]:
# For non-v1 agents, always use Chat Completions streaming interface
self.interface = OpenAIStreamingInterface(
use_assistant_message=use_assistant_message,
diff --git a/letta/adapters/simple_llm_stream_adapter.py b/letta/adapters/simple_llm_stream_adapter.py
index 1a8d950ba..f917341fb 100644
--- a/letta/adapters/simple_llm_stream_adapter.py
+++ b/letta/adapters/simple_llm_stream_adapter.py
@@ -90,6 +90,7 @@ class SimpleLLMStreamAdapter(LettaLLMStreamAdapter):
ProviderType.deepseek,
ProviderType.openrouter,
ProviderType.zai,
+ ProviderType.baseten,
ProviderType.fireworks,
ProviderType.chatgpt_oauth,
]:
diff --git a/letta/llm_api/baseten_client.py b/letta/llm_api/baseten_client.py
new file mode 100644
index 000000000..59c8542a3
--- /dev/null
+++ b/letta/llm_api/baseten_client.py
@@ -0,0 +1,110 @@
+from typing import List, Optional
+
+from openai import AsyncOpenAI, AsyncStream, OpenAI
+from openai.types.chat.chat_completion import ChatCompletion
+from openai.types.chat.chat_completion_chunk import ChatCompletionChunk
+
+from letta.helpers.json_helpers import sanitize_unicode_surrogates
+from letta.llm_api.openai_client import OpenAIClient
+from letta.otel.tracing import trace_method
+from letta.schemas.enums import AgentType
+from letta.schemas.llm_config import LLMConfig
+from letta.schemas.message import Message as PydanticMessage
+from letta.settings import model_settings
+
+
+def _build_base_url(model_id: str) -> str:
+ """Build the Baseten endpoint URL from a model ID."""
+ return f"https://model-{model_id}.api.baseten.co/environments/production/sync/v1"
+
+
+class BasetenClient(OpenAIClient):
+ """Baseten client — serves models via OpenAI-compatible Engine-Builder API."""
+
+ def requires_auto_tool_choice(self, llm_config: LLMConfig) -> bool:
+ return False
+
+ def supports_structured_output(self, llm_config: LLMConfig) -> bool:
+ return False
+
+ def is_reasoning_model(self, llm_config: LLMConfig) -> bool:
+ return False
+
+ @trace_method
+ def build_request_data(
+ self,
+ agent_type: AgentType,
+ messages: List[PydanticMessage],
+ llm_config: LLMConfig,
+ tools: Optional[List[dict]] = None,
+ force_tool_call: Optional[str] = None,
+ requires_subsequent_tool_call: bool = False,
+ tool_return_truncation_chars: Optional[int] = None,
+ ) -> dict:
+ data = super().build_request_data(agent_type, messages, llm_config, tools, force_tool_call, requires_subsequent_tool_call)
+
+ # Baseten expects a generic model name
+ data["model"] = "baseten"
+
+ # Baseten uses max_tokens, not max_completion_tokens
+ if "max_completion_tokens" in data:
+ data["max_tokens"] = data.pop("max_completion_tokens")
+
+ # Sanitize empty text content — rejects empty text blocks
+ if "messages" in data:
+ for msg in data["messages"]:
+ content = msg.get("content") if isinstance(msg, dict) else getattr(msg, "content", None)
+ if isinstance(content, str) and not content.strip():
+ role = msg.get("role") if isinstance(msg, dict) else getattr(msg, "role", None)
+ has_tool_calls = msg.get("tool_calls") if isinstance(msg, dict) else getattr(msg, "tool_calls", None)
+ if role == "assistant" and has_tool_calls:
+ if isinstance(msg, dict):
+ msg["content"] = None
+ else:
+ msg.content = None
+ else:
+ if isinstance(msg, dict):
+ msg["content"] = "."
+ else:
+ msg.content = "."
+ elif isinstance(content, list):
+ for block in content:
+ if isinstance(block, dict) and block.get("type") == "text":
+ if not block.get("text", "").strip():
+ block["text"] = "."
+
+ # Strip reasoning fields that are not in the Baseten schema
+ if "messages" in data:
+ for msg in data["messages"]:
+ for field in ("reasoning_content_signature", "redacted_reasoning_content", "omitted_reasoning_content"):
+ msg.pop(field, None)
+
+ return data
+
+ @trace_method
+ def request(self, request_data: dict, llm_config: LLMConfig) -> dict:
+ api_key = model_settings.baseten_api_key
+ base_url = _build_base_url(llm_config.model)
+ client = OpenAI(api_key="unused", base_url=base_url, default_headers={"Authorization": f"Api-Key {api_key}"})
+ response: ChatCompletion = client.chat.completions.create(**request_data)
+ return response.model_dump()
+
+ @trace_method
+ async def request_async(self, request_data: dict, llm_config: LLMConfig) -> dict:
+ request_data = sanitize_unicode_surrogates(request_data)
+ api_key = model_settings.baseten_api_key
+ base_url = _build_base_url(llm_config.model)
+ client = AsyncOpenAI(api_key="unused", base_url=base_url, default_headers={"Authorization": f"Api-Key {api_key}"})
+ response: ChatCompletion = await client.chat.completions.create(**request_data)
+ return response.model_dump()
+
+ @trace_method
+ async def stream_async(self, request_data: dict, llm_config: LLMConfig) -> AsyncStream[ChatCompletionChunk]:
+ request_data = sanitize_unicode_surrogates(request_data)
+ api_key = model_settings.baseten_api_key
+ base_url = _build_base_url(llm_config.model)
+ client = AsyncOpenAI(api_key="unused", base_url=base_url, default_headers={"Authorization": f"Api-Key {api_key}"})
+ response_stream: AsyncStream[ChatCompletionChunk] = await client.chat.completions.create(
+ **request_data, stream=True, stream_options={"include_usage": True}
+ )
+ return response_stream
diff --git a/letta/llm_api/llm_client.py b/letta/llm_api/llm_client.py
index 713fb1bf6..d1ee5a415 100644
--- a/letta/llm_api/llm_client.py
+++ b/letta/llm_api/llm_client.py
@@ -115,6 +115,13 @@ class LLMClient:
put_inner_thoughts_first=put_inner_thoughts_first,
actor=actor,
)
+ case ProviderType.baseten:
+ from letta.llm_api.baseten_client import BasetenClient
+
+ return BasetenClient(
+ put_inner_thoughts_first=put_inner_thoughts_first,
+ actor=actor,
+ )
case ProviderType.fireworks:
from letta.llm_api.fireworks_client import FireworksClient
diff --git a/letta/schemas/enums.py b/letta/schemas/enums.py
index a82e84047..09db64e2b 100644
--- a/letta/schemas/enums.py
+++ b/letta/schemas/enums.py
@@ -53,6 +53,7 @@ class PrimitiveType(str, Enum):
class ProviderType(str, Enum):
anthropic = "anthropic"
azure = "azure"
+ baseten = "baseten"
bedrock = "bedrock"
cerebras = "cerebras"
chatgpt_oauth = "chatgpt_oauth"
diff --git a/letta/schemas/llm_config.py b/letta/schemas/llm_config.py
index 6b387acca..9f5dc5776 100644
--- a/letta/schemas/llm_config.py
+++ b/letta/schemas/llm_config.py
@@ -51,6 +51,7 @@ class LLMConfig(BaseModel):
"deepseek",
"xai",
"zai",
+ "baseten",
"fireworks",
"openrouter",
"chatgpt_oauth",
diff --git a/letta/services/llm_router/client.py b/letta/services/llm_router/client.py
index d47cc25f7..cb4ed9d17 100644
--- a/letta/services/llm_router/client.py
+++ b/letta/services/llm_router/client.py
@@ -22,7 +22,7 @@ if TYPE_CHECKING:
logger = get_logger(__name__)
# Auto mode model routing
-AUTO_MODE_PRIMARY = "fireworks/glm-5"
+AUTO_MODE_PRIMARY = "baseten/glm-5"
AUTO_MODE_FALLBACK = "zai/glm-5"
# Circuit breaker configuration
@@ -36,6 +36,22 @@ CIRCUIT_STATE_KEY = "circuit:state:"
CIRCUIT_OPENED_AT_KEY = "circuit:opened:"
+def _build_baseten_config() -> "LLMConfig":
+ """Build a hardcoded LLMConfig for Baseten GLM-5 (not discoverable via provider sync)."""
+ from letta.schemas.enums import ProviderCategory
+ from letta.schemas.llm_config import LLMConfig
+
+ return LLMConfig(
+ model="3m5zok9w",
+ model_endpoint_type="baseten",
+ context_window=180000,
+ max_tokens=16384,
+ handle="baseten/glm-5",
+ provider_name="baseten",
+ provider_category=ProviderCategory.base,
+ )
+
+
def _build_fireworks_config() -> "LLMConfig":
"""Build a hardcoded LLMConfig for Fireworks GLM-5 (not discoverable via provider sync)."""
from letta.schemas.enums import ProviderCategory
@@ -95,7 +111,7 @@ class LLMRoutingClient(LLMRoutingClientBase):
if not model_settings.auto_mode_enabled:
logger.info(f"[AUTO MODE]: primary {primary_handle} disabled via kill switch, using {AUTO_MODE_FALLBACK}")
elif await self._is_healthy(primary_handle):
- config = _build_fireworks_config()
+ config = _build_baseten_config()
config = config.model_copy(
update={
"context_window": min(stored_llm_config.context_window, config.context_window),
diff --git a/letta/settings.py b/letta/settings.py
index 8b2e127e3..a7b449a27 100644
--- a/letta/settings.py
+++ b/letta/settings.py
@@ -150,6 +150,9 @@ class ModelSettings(BaseSettings):
# deepseek
deepseek_api_key: Optional[str] = None
+ # baseten
+ baseten_api_key: Optional[str] = None
+
# fireworks
fireworks_api_key: Optional[str] = None
fireworks_api_base: str = "https://api.fireworks.ai/inference/v1"