Skip to content

: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.

fix(gateway): apply posthog property headers on openai routes (#60725)

Joshua Snyder3f687e17db6a
diff --git a/services/llm-gateway/src/llm_gateway/api/openai.py b/services/llm-gateway/src/llm_gateway/api/openai.py
index 8b28e94fb26c..1d0b4b35b3ec 100644
--- a/services/llm-gateway/src/llm_gateway/api/openai.py
+++ b/services/llm-gateway/src/llm_gateway/api/openai.py
@@ -1,7 +1,7 @@
-from typing import Annotated, Any
+from typing import Annotated, Any, cast
import litellm
-from fastapi import APIRouter, File, Form, HTTPException, UploadFile
+from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import StreamingResponse
from llm_gateway.api.handler import (
@@ -14,6 +14,7 @@ from llm_gateway.api.handler import (
from llm_gateway.dependencies import RateLimitedUser
from llm_gateway.models.openai import ChatCompletionRequest, ResponsesRequest, TranscriptionRequest
from llm_gateway.products.config import validate_product
+from llm_gateway.request_context import apply_posthog_context_from_headers
openai_router = APIRouter()
@@ -67,7 +68,9 @@ async def _handle_responses(
async def chat_completions(
body: ChatCompletionRequest,
user: RateLimitedUser,
+ request: Request,
) -> dict[str, Any] | StreamingResponse:
+ apply_posthog_context_from_headers(request)
return await _handle_chat_completions(body, user)
@@ -76,8 +79,10 @@ async def chat_completions_with_product(
body: ChatCompletionRequest,
user: RateLimitedUser,
product: str,
+ request: Request,
) -> dict[str, Any] | StreamingResponse:
validate_product(product)
+ apply_posthog_context_from_headers(request)
return await _handle_chat_completions(body, user, product=product)
@@ -85,7 +90,9 @@ async def chat_completions_with_product(
async def responses_v1(
body: ResponsesRequest,
user: RateLimitedUser,
+ request: Request,
) -> dict[str, Any] | StreamingResponse:
+ apply_posthog_context_from_headers(request)
return await _handle_responses(body, user)
@@ -94,8 +101,10 @@ async def responses_v1_with_product(
body: ResponsesRequest,
user: RateLimitedUser,
product: str,
+ request: Request,
) -> dict[str, Any] | StreamingResponse:
validate_product(product)
+ apply_posthog_context_from_headers(request)
return await _handle_responses(body, user, product=product)
@@ -103,7 +112,9 @@ async def responses_v1_with_product(
async def responses(
body: ResponsesRequest,
user: RateLimitedUser,
+ request: Request,
) -> dict[str, Any] | StreamingResponse:
+ apply_posthog_context_from_headers(request)
return await _handle_responses(body, user)
@@ -112,8 +123,10 @@ async def responses_with_product(
body: ResponsesRequest,
user: RateLimitedUser,
product: str,
+ request: Request,
) -> dict[str, Any] | StreamingResponse:
validate_product(product)
+ apply_posthog_context_from_headers(request)
return await _handle_responses(body, user, product=product)
@@ -148,24 +161,30 @@ async def _handle_transcription(
request = TranscriptionRequest(model=normalized_model, file=file_tuple, language=language)
- return await handle_llm_request(
- request_data=request.model_dump(exclude_none=True),
- user=user,
- model=normalized_model,
- is_streaming=False,
- provider_config=OPENAI_TRANSCRIPTION_CONFIG,
- llm_call=litellm.atranscription,
- product=product,
+ # is_streaming=False, so handle_llm_request always returns a dict here, never a StreamingResponse.
+ return cast(
+ dict[str, Any],
+ await handle_llm_request(
+ request_data=request.model_dump(exclude_none=True),
+ user=user,
+ model=normalized_model,
+ is_streaming=False,
+ provider_config=OPENAI_TRANSCRIPTION_CONFIG,
+ llm_call=litellm.atranscription,
+ product=product,
+ ),
)
@openai_router.post("/v1/audio/transcriptions", response_model=None)
async def audio_transcriptions(
user: RateLimitedUser,
+ request: Request,
file: Annotated[UploadFile, File()],
model: Annotated[str, Form()] = "gpt-4o-transcribe",
language: Annotated[str | None, Form()] = None,
) -> dict[str, Any]:
+ apply_posthog_context_from_headers(request)
return await _handle_transcription(file, model, user, language)
@@ -173,9 +192,11 @@ async def audio_transcriptions(
async def audio_transcriptions_with_product(
user: RateLimitedUser,
product: str,
+ request: Request,
file: Annotated[UploadFile, File()],
model: Annotated[str, Form()] = "gpt-4o-transcribe",
language: Annotated[str | None, Form()] = None,
) -> dict[str, Any]:
validate_product(product)
+ apply_posthog_context_from_headers(request)
return await _handle_transcription(file, model, user, language, product=product)
diff --git a/services/llm-gateway/tests/test_openai.py b/services/llm-gateway/tests/test_openai.py
index 7de0ec4cc495..17a81d86f3bc 100644
--- a/services/llm-gateway/tests/test_openai.py
+++ b/services/llm-gateway/tests/test_openai.py
@@ -1,9 +1,13 @@
from typing import Any
-from unittest.mock import MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi.testclient import TestClient
+from llm_gateway.main import RequestLoggingMiddleware
+from llm_gateway.request_context import get_posthog_properties
+from tests.conftest import create_test_app
+
DANGEROUS_PARAMS: list[tuple[str, str]] = [
("api_key", "sk-stolen-key"),
("api_base", "https://attacker.example.com"),
@@ -87,6 +91,54 @@ class TestChatCompletionsEndpoint:
assert data["object"] == "chat.completion"
assert data["usage"]["total_tokens"] == 15
+ @patch("llm_gateway.api.openai.litellm.acompletion")
+ def test_posthog_property_headers_reach_request_context(
+ self,
+ mock_completion: MagicMock,
+ mock_db_pool: MagicMock,
+ valid_request_body: dict,
+ mock_openai_response: dict,
+ ) -> None:
+ # Build a prod-like app: RequestLoggingMiddleware establishes the base RequestContext
+ # that apply_posthog_context_from_headers mutates. The shared conftest app omits it.
+ app = create_test_app(mock_db_pool)
+ app.add_middleware(RequestLoggingMiddleware)
+ conn = AsyncMock()
+ conn.fetchrow = AsyncMock(
+ return_value={
+ "id": "key_id",
+ "user_id": 1,
+ "scopes": ["llm_gateway:read"],
+ "current_team_id": 1,
+ "distinct_id": "test-distinct-id",
+ }
+ )
+ mock_db_pool.acquire = AsyncMock(return_value=conn)
+
+ mock_response = MagicMock()
+ mock_response.model_dump = MagicMock(return_value=mock_openai_response)
+ captured: dict[str, Any] = {}
+
+ def _capture(*args: Any, **kwargs: Any) -> MagicMock:
+ captured["properties"] = get_posthog_properties()
+ return mock_response
+
+ mock_completion.side_effect = _capture
+
+ with TestClient(app) as client:
+ response = client.post(
+ "/v1/chat/completions",
+ json=valid_request_body,
+ headers={
+ "Authorization": "Bearer phx_test_key",
+ "x-posthog-property-team_id": "42",
+ "x-posthog-property-$ai_billable": "false",
+ },
+ )
+
+ assert response.status_code == 200
+ assert captured["properties"] == {"team_id": "42", "$ai_billable": "false"}
+
@pytest.mark.parametrize(
"error_status,error_message,error_type",
[