Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
fix: handle non-JSON responses from LLM provider endpoints (#9362)
Kian Jones4c753f3f3c6e
diff --git a/letta/llm_api/anthropic_client.py b/letta/llm_api/anthropic_client.pyindex 9d777e7b3..f3903dfe8 100644--- a/letta/llm_api/anthropic_client.py+++ b/letta/llm_api/anthropic_client.py@@ -1110,6 +1110,11 @@ class AnthropicClient(LLMClientBase):input_messages: List[PydanticMessage],llm_config: LLMConfig,) -> ChatCompletionResponse:+ if isinstance(response_data, str):+ raise LLMServerError(+ message="Anthropic endpoint returned a raw string instead of a JSON object. This usually indicates the endpoint URL is incorrect or returned an error page.",+ code=ErrorCode.INTERNAL_SERVER_ERROR,+ )"""Example response from Claude 3:response.json = {diff --git a/letta/llm_api/openai_client.py b/letta/llm_api/openai_client.pyindex 9bfc7c5d0..7257fc04e 100644--- a/letta/llm_api/openai_client.py+++ b/letta/llm_api/openai_client.py@@ -708,6 +708,12 @@ class OpenAIClient(LLMClientBase):Converts raw OpenAI response dict into the ChatCompletionResponse Pydantic model.Handles potential extraction of inner thoughts if they were added via kwargs."""+ if isinstance(response_data, str):+ raise LLMServerError(+ message="LLM endpoint returned a raw string instead of a JSON object. This usually indicates the endpoint URL is incorrect or returned an error page.",+ code=ErrorCode.INTERNAL_SERVER_ERROR,+ details={"raw_response": response_data[:500]},+ )if "object" in response_data and response_data["object"] == "response":# Map Responses API shape to Chat Completions shape# See example payload in tests/integration_test_send_message_v2.pydiff --git a/letta/schemas/providers/anthropic.py b/letta/schemas/providers/anthropic.pyindex 9c18feb82..803426e04 100644--- a/letta/schemas/providers/anthropic.py+++ b/letta/schemas/providers/anthropic.py@@ -176,7 +176,16 @@ class AnthropicProvider(Provider):else:raise ValueError("No API key provided")- models = await anthropic_client.models.list()+ try:+ models = await anthropic_client.models.list()+ except AttributeError as e:+ if "_set_private_attributes" in str(e):+ raise LLMError(+ message="Anthropic API returned an unexpected non-JSON response. Verify the API key and endpoint.",+ code=ErrorCode.INTERNAL_SERVER_ERROR,+ )+ raise+models_json = models.model_dump()assert "data" in models_json, f"Anthropic model query response missing 'data' field: {models_json}"models_data = models_json["data"]diff --git a/letta/schemas/providers/azure.py b/letta/schemas/providers/azure.pyindex b9ef75607..cc552dea2 100644--- a/letta/schemas/providers/azure.py+++ b/letta/schemas/providers/azure.py@@ -7,6 +7,9 @@ from pydantic import Field, field_validatorfrom letta.constants import DEFAULT_EMBEDDING_CHUNK_SIZE, LLM_MAX_CONTEXT_WINDOWfrom letta.errors import ErrorCode, LLMAuthenticationError, LLMPermissionDeniedError+from letta.log import get_logger++logger = get_logger(__name__)from letta.schemas.embedding_config import EmbeddingConfigfrom letta.schemas.enums import ProviderCategory, ProviderTypefrom letta.schemas.llm_config import LLMConfig@@ -68,6 +71,10 @@ class AzureProvider(Provider):except (AuthenticationError, PermissionDeniedError):# Re-raise auth/permission errors so they're properly handled upstreamraise+ except AttributeError as e:+ if "_set_private_attributes" in str(e):+ logger.warning(f"Azure endpoint at {self.base_url} returned an unexpected non-JSON response: {e}")+ return []except Exception:return []diff --git a/letta/schemas/providers/openai.py b/letta/schemas/providers/openai.pyindex bcbe633cf..c4c979e40 100644--- a/letta/schemas/providers/openai.py+++ b/letta/schemas/providers/openai.py@@ -40,6 +40,13 @@ class OpenAIProvider(Provider):raise LLMAuthenticationError(message=f"Failed to authenticate with OpenAI: {e}", code=ErrorCode.UNAUTHENTICATED)except PermissionDeniedError as e:raise LLMPermissionDeniedError(message=f"Permission denied by OpenAI: {e}", code=ErrorCode.PERMISSION_DENIED)+ except AttributeError as e:+ if "_set_private_attributes" in str(e):+ raise LLMError(+ message=f"OpenAI-compatible endpoint at {self.base_url} returned an unexpected non-JSON response. Verify the base URL and that the endpoint is reachable.",+ code=ErrorCode.INTERNAL_SERVER_ERROR,+ )+ raise LLMError(message=f"{e}", code=ErrorCode.INTERNAL_SERVER_ERROR)except Exception as e:raise LLMError(message=f"{e}", code=ErrorCode.INTERNAL_SERVER_ERROR)diff --git a/letta/schemas/providers/openrouter.py b/letta/schemas/providers/openrouter.pyindex 87fcc6a65..f349a3c01 100644--- a/letta/schemas/providers/openrouter.py+++ b/letta/schemas/providers/openrouter.py@@ -43,6 +43,13 @@ class OpenRouterProvider(OpenAIProvider):raise LLMAuthenticationError(message=f"Failed to authenticate with OpenRouter: {e}", code=ErrorCode.UNAUTHENTICATED)except PermissionDeniedError as e:raise LLMPermissionDeniedError(message=f"Permission denied by OpenRouter: {e}", code=ErrorCode.PERMISSION_DENIED)+ except AttributeError as e:+ if "_set_private_attributes" in str(e):+ raise LLMError(+ message=f"OpenRouter endpoint at {self.base_url} returned an unexpected non-JSON response. Verify the base URL and API key.",+ code=ErrorCode.INTERNAL_SERVER_ERROR,+ )+ raise LLMError(message=f"{e}", code=ErrorCode.INTERNAL_SERVER_ERROR)except Exception as e:raise LLMError(message=f"{e}", code=ErrorCode.INTERNAL_SERVER_ERROR)