:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(llm-gateway): reject invalid chat content part types with 400 (#107551)
Alessandro Pogliaghi3e9d36596a53
diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.mdindex 880dacaf6ae2..cec26d9d0624 100644--- a/services/llm-gateway/PARITY.md+++ b/services/llm-gateway/PARITY.md@@ -85,6 +85,7 @@ These are compatibility checks, not automatic blockers:| Routing and failure behavior | Operator-managed provider plans, health-aware ordering, circuit breakers, hosted-provider failover, and strict provider pinning. | Caller opt-in Bedrock fallback and provider-specific Python routing. || Event metadata | One `X-PostHog-Properties` JSON object plus dedicated product, user, obo, distinct ID, trace ID, and provider headers. | `X-POSTHOG-PROPERTY-*` and `X-POSTHOG-FLAG-*` headers. || Session attribution | `X-PostHog-Session-Id` is recorded as the gateway-owned `$ai_session_id`. | The per-key property header can also emit `$ai_session_id`. |+| Request validation | Not verified for a bare-string or unknown-type content part in a Chat Completions user message. | The Chat Completions route answers 400 `invalid_request_error` before choosing a provider when a user message carries a content part outside litellm's allowed types. PostHog Code and Desktop send these through the Python gateway, and litellm otherwise raises an error with no status code that the handler reports as 500. |## Migration checklistdiff --git a/services/llm-gateway/src/llm_gateway/api/openai.py b/services/llm-gateway/src/llm_gateway/api/openai.pyindex 98db2ee91689..df6aa4fb6cf5 100644--- a/services/llm-gateway/src/llm_gateway/api/openai.py+++ b/services/llm-gateway/src/llm_gateway/api/openai.py@@ -3,6 +3,7 @@ from typing import Annotated, Any, castimport litellmfrom fastapi import APIRouter, File, Form, HTTPException, Request, UploadFilefrom fastapi.responses import StreamingResponse+from litellm.types.llms.openai import ValidUserMessageContentTypesfrom llm_gateway.api.handler import (OPENAI_CONFIG,@@ -34,11 +35,29 @@ def _invalid_request_error(message: str) -> HTTPException:)+def _reject_invalid_user_content_parts(messages: list[dict[str, Any]]) -> None:+ for index, message in enumerate(messages):+ content = message.get("content")+ if message.get("role") != "user" or not isinstance(content, list):+ continue+ for part in content:+ if not isinstance(part, dict):+ raise _invalid_request_error(+ f"Invalid user message at index {index}: each content part must be an object"+ )+ if part.get("type") not in ValidUserMessageContentTypes:+ raise _invalid_request_error(+ f"Invalid user message at index {index}: content part type '{part.get('type')}' "+ f"is not a chat completion content type ({', '.join(ValidUserMessageContentTypes)})"+ )++async def _handle_chat_completions(body: ChatCompletionRequest,user: RateLimitedUser,product: str = "llm_gateway",) -> dict[str, Any] | StreamingResponse:+ _reject_invalid_user_content_parts(body.messages)data = body.model_dump(exclude_none=True)if is_inference_routed_model(body.model):diff --git a/services/llm-gateway/tests/test_openai.py b/services/llm-gateway/tests/test_openai.pyindex 4620c81bbbaa..f9d954d2c37d 100644--- a/services/llm-gateway/tests/test_openai.py+++ b/services/llm-gateway/tests/test_openai.py@@ -376,6 +376,46 @@ class TestChatCompletionsEndpoint:mock_ensure_configured.assert_not_called()mock_make_call.assert_not_called()+ @pytest.mark.parametrize(+ ("content", "expected_message"),+ [+ pytest.param(+ [{"type": "input_image", "image_url": "data:image/png;base64,AAAA"}],+ "input_image",+ id="unknown_part_type",+ ),+ pytest.param(["just text"], "must be an object", id="bare_string_part"),+ ],+ )+ @patch("llm_gateway.api.openai.send_modal_chat_completions")+ @patch("llm_gateway.api.openai.litellm.acompletion")+ def test_invalid_user_content_part_rejected_before_routing(+ self,+ mock_acompletion: AsyncMock,+ mock_modal: AsyncMock,+ authenticated_client: TestClient,+ content: list[Any],+ expected_message: str,+ ) -> None:+ response = authenticated_client.post(+ "/v1/chat/completions",+ json={+ "model": "moonshotai/kimi-k3",+ "messages": [+ {"role": "system", "content": "You are helpful"},+ {"role": "user", "content": content},+ ],+ },+ headers={"Authorization": "Bearer phx_test_key"},+ )++ assert response.status_code == 400+ assert response.json()["error"]["type"] == "invalid_request_error"+ assert "index 1" in response.json()["error"]["message"]+ assert expected_message in response.json()["error"]["message"]+ mock_acompletion.assert_not_called()+ mock_modal.assert_not_called()+# CF-served models (@cf/...) on the Responses endpoint must route through the CF responses adapter,# not litellm.aresponses (which prefixes openai/ and hits the real OpenAI Responses API ->