Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: refactor byok logic in llm clients (#3880)
cthomas6289ca55a21b
diff --git a/letta/llm_api/anthropic_client.py b/letta/llm_api/anthropic_client.pyindex 7c6cc744e..68a3feb1d 100644--- a/letta/llm_api/anthropic_client.py+++ b/letta/llm_api/anthropic_client.py@@ -31,14 +31,12 @@ from letta.llm_api.llm_client_base import LLMClientBasefrom letta.local_llm.constants import INNER_THOUGHTS_KWARG, INNER_THOUGHTS_KWARG_DESCRIPTIONfrom letta.log import get_loggerfrom letta.otel.tracing import trace_method-from letta.schemas.enums import ProviderCategoryfrom letta.schemas.llm_config import LLMConfigfrom letta.schemas.message import Message as PydanticMessagefrom letta.schemas.openai.chat_completion_request import Tool as OpenAIToolfrom letta.schemas.openai.chat_completion_response import ChatCompletionResponse, Choice, FunctionCallfrom letta.schemas.openai.chat_completion_response import Message as ChoiceMessagefrom letta.schemas.openai.chat_completion_response import ToolCall, UsageStatistics-from letta.services.provider_manager import ProviderManagerfrom letta.settings import model_settingsDUMMY_FIRST_USER_MESSAGE = "User initializing bootup sequence."@@ -122,19 +120,17 @@ class AnthropicClient(LLMClientBase):def _get_anthropic_client(self, llm_config: LLMConfig, async_client: bool = False) -> Union[anthropic.AsyncAnthropic, anthropic.Anthropic]:- override_key = None- if llm_config.provider_category == ProviderCategory.byok:- override_key = ProviderManager().get_override_key(llm_config.provider_name, actor=self.actor)+ api_key, _, _ = self.get_byok_overrides(llm_config)if async_client:return (- anthropic.AsyncAnthropic(api_key=override_key, max_retries=model_settings.anthropic_max_retries)- if override_key+ anthropic.AsyncAnthropic(api_key=api_key, max_retries=model_settings.anthropic_max_retries)+ if api_keyelse anthropic.AsyncAnthropic(max_retries=model_settings.anthropic_max_retries))return (- anthropic.Anthropic(api_key=override_key, max_retries=model_settings.anthropic_max_retries)- if override_key+ anthropic.Anthropic(api_key=api_key, max_retries=model_settings.anthropic_max_retries)+ if api_keyelse anthropic.Anthropic(max_retries=model_settings.anthropic_max_retries))@@ -142,19 +138,17 @@ class AnthropicClient(LLMClientBase):async def _get_anthropic_client_async(self, llm_config: LLMConfig, async_client: bool = False) -> Union[anthropic.AsyncAnthropic, anthropic.Anthropic]:- override_key = None- if llm_config.provider_category == ProviderCategory.byok:- override_key = await ProviderManager().get_override_key_async(llm_config.provider_name, actor=self.actor)+ api_key, _, _ = await self.get_byok_overrides_async(llm_config)if async_client:return (- anthropic.AsyncAnthropic(api_key=override_key, max_retries=model_settings.anthropic_max_retries)- if override_key+ anthropic.AsyncAnthropic(api_key=api_key, max_retries=model_settings.anthropic_max_retries)+ if api_keyelse anthropic.AsyncAnthropic(max_retries=model_settings.anthropic_max_retries))return (- anthropic.Anthropic(api_key=override_key, max_retries=model_settings.anthropic_max_retries)- if override_key+ anthropic.Anthropic(api_key=api_key, max_retries=model_settings.anthropic_max_retries)+ if api_keyelse anthropic.Anthropic(max_retries=model_settings.anthropic_max_retries))diff --git a/letta/llm_api/bedrock_client.py b/letta/llm_api/bedrock_client.pyindex b7b60a5e0..9ebe5637d 100644--- a/letta/llm_api/bedrock_client.py+++ b/letta/llm_api/bedrock_client.py@@ -21,16 +21,7 @@ class BedrockClient(AnthropicClient):async def _get_anthropic_client_async(self, llm_config: LLMConfig, async_client: bool = False) -> Union[anthropic.AsyncAnthropic, anthropic.Anthropic, anthropic.AsyncAnthropicBedrock, anthropic.AnthropicBedrock]:- override_access_key_id, override_secret_access_key, override_default_region = None, None, None- if llm_config.provider_category == ProviderCategory.byok:- (- override_access_key_id,- override_secret_access_key,- override_default_region,- ) = await ProviderManager().get_bedrock_credentials_async(- llm_config.provider_name,- actor=self.actor,- )+ override_access_key_id, override_secret_access_key, override_default_region = await self.get_byok_overrides_async(llm_config)session = Session()async with session.client(@@ -59,6 +50,19 @@ class BedrockClient(AnthropicClient):max_retries=model_settings.anthropic_max_retries,)+ async def get_byok_overrides_async(self, llm_config: LLMConfig) -> tuple[str, str, str]:+ override_access_key_id, override_secret_access_key, override_default_region = None, None, None+ if llm_config.provider_category == ProviderCategory.byok:+ (+ override_access_key_id,+ override_secret_access_key,+ override_default_region,+ ) = await ProviderManager().get_bedrock_credentials_async(+ llm_config.provider_name,+ actor=self.actor,+ )+ return override_access_key_id, override_secret_access_key, override_default_region+@trace_methoddef build_request_data(self,diff --git a/letta/llm_api/llm_client_base.py b/letta/llm_api/llm_client_base.pyindex 038caaa15..79335f5c7 100644--- a/letta/llm_api/llm_client_base.py+++ b/letta/llm_api/llm_client_base.py@@ -1,6 +1,6 @@import jsonfrom abc import abstractmethod-from typing import TYPE_CHECKING, Dict, List, Optional, Union+from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Unionfrom anthropic.types.beta.messages import BetaMessageBatchfrom openai import AsyncStream, Stream@@ -9,6 +9,7 @@ from openai.types.chat.chat_completion_chunk import ChatCompletionChunkfrom letta.errors import LLMErrorfrom letta.otel.tracing import log_event, trace_methodfrom letta.schemas.embedding_config import EmbeddingConfig+from letta.schemas.enums import ProviderCategoryfrom letta.schemas.llm_config import LLMConfigfrom letta.schemas.message import Messagefrom letta.schemas.openai.chat_completion_response import ChatCompletionResponse@@ -111,6 +112,9 @@ class LLMClientBase:agent_tools_mapping: Dict[str, List[dict]],agent_llm_config_mapping: Dict[str, LLMConfig],) -> Union[BetaMessageBatch]:+ """+ Issues a batch request to the downstream model endpoint and parses response.+ """raise NotImplementedError@abstractmethod@@ -176,6 +180,9 @@ class LLMClientBase:@abstractmethoddef is_reasoning_model(self, llm_config: LLMConfig) -> bool:+ """+ Returns True if the model is a native reasoning model.+ """raise NotImplementedError@abstractmethod@@ -192,6 +199,30 @@ class LLMClientBase:"""return LLMError(f"Unhandled LLM error: {str(e)}")+ def get_byok_overrides(self, llm_config: LLMConfig) -> Tuple[Optional[str], Optional[str], Optional[str]]:+ """+ Returns the override key for the given llm config.+ """+ api_key = None+ if llm_config.provider_category == ProviderCategory.byok:+ from letta.services.provider_manager import ProviderManager++ api_key = ProviderManager().get_override_key(llm_config.provider_name, actor=self.actor)++ return api_key, None, None++ async def get_byok_overrides_async(self, llm_config: LLMConfig) -> Tuple[Optional[str], Optional[str], Optional[str]]:+ """+ Returns the override key for the given llm config.+ """+ api_key = None+ if llm_config.provider_category == ProviderCategory.byok:+ from letta.services.provider_manager import ProviderManager++ api_key = await ProviderManager().get_override_key_async(llm_config.provider_name, actor=self.actor)++ return api_key, None, None+def _fix_truncated_json_response(self, response: ChatCompletionResponse) -> ChatCompletionResponse:"""Fixes truncated JSON responses by ensuring the content is properly formatted.diff --git a/letta/llm_api/openai_client.py b/letta/llm_api/openai_client.pyindex 035a77340..c79867203 100644--- a/letta/llm_api/openai_client.py+++ b/letta/llm_api/openai_client.py@@ -26,7 +26,6 @@ from letta.local_llm.constants import INNER_THOUGHTS_KWARG, INNER_THOUGHTS_KWARGfrom letta.log import get_loggerfrom letta.otel.tracing import trace_methodfrom letta.schemas.embedding_config import EmbeddingConfig-from letta.schemas.enums import ProviderCategoryfrom letta.schemas.letta_message_content import MessageContentTypefrom letta.schemas.llm_config import LLMConfigfrom letta.schemas.message import Message as PydanticMessage@@ -111,11 +110,7 @@ def requires_auto_tool_choice(llm_config: LLMConfig) -> bool:class OpenAIClient(LLMClientBase):def _prepare_client_kwargs(self, llm_config: LLMConfig) -> dict:- api_key = None- if llm_config.provider_category == ProviderCategory.byok:- from letta.services.provider_manager import ProviderManager-- api_key = ProviderManager().get_override_key(llm_config.provider_name, actor=self.actor)+ api_key, _, _ = self.get_byok_overrides(llm_config)if not api_key:api_key = model_settings.openai_api_key or os.environ.get("OPENAI_API_KEY")@@ -133,11 +128,7 @@ class OpenAIClient(LLMClientBase):return kwargsasync def _prepare_client_kwargs_async(self, llm_config: LLMConfig) -> dict:- api_key = None- if llm_config.provider_category == ProviderCategory.byok:- from letta.services.provider_manager import ProviderManager-- api_key = await ProviderManager().get_override_key_async(llm_config.provider_name, actor=self.actor)+ api_key, _, _ = await self.get_byok_overrides_async(llm_config)if not api_key:api_key = model_settings.openai_api_key or os.environ.get("OPENAI_API_KEY")diff --git a/letta/llm_api/together_client.py b/letta/llm_api/together_client.pyindex 949cb6b4b..d9a098b0b 100644--- a/letta/llm_api/together_client.py+++ b/letta/llm_api/together_client.py@@ -7,7 +7,6 @@ from openai.types.chat.chat_completion import ChatCompletionfrom letta.llm_api.openai_client import OpenAIClientfrom letta.otel.tracing import trace_methodfrom letta.schemas.embedding_config import EmbeddingConfig-from letta.schemas.enums import ProviderCategoryfrom letta.schemas.llm_config import LLMConfigfrom letta.settings import model_settings@@ -22,11 +21,7 @@ class TogetherClient(OpenAIClient):"""Performs underlying synchronous request to OpenAI API and returns raw response dict."""- api_key = None- if llm_config.provider_category == ProviderCategory.byok:- from letta.services.provider_manager import ProviderManager-- api_key = ProviderManager().get_override_key(llm_config.provider_name, actor=self.actor)+ api_key, _, _ = self.get_byok_overrides(llm_config)if not api_key:api_key = model_settings.together_api_key or os.environ.get("TOGETHER_API_KEY")@@ -40,11 +35,7 @@ class TogetherClient(OpenAIClient):"""Performs underlying asynchronous request to OpenAI API and returns raw response dict."""- api_key = None- if llm_config.provider_category == ProviderCategory.byok:- from letta.services.provider_manager import ProviderManager-- api_key = ProviderManager().get_override_key(llm_config.provider_name, actor=self.actor)+ api_key, _, _ = await self.get_byok_overrides_async(llm_config)if not api_key:api_key = model_settings.together_api_key or os.environ.get("TOGETHER_API_KEY")