diff --git a/.changeset/openai-stream-response-model.md b/.changeset/openai-stream-response-model.md new file mode 100644 index 00000000..80b8031d --- /dev/null +++ b/.changeset/openai-stream-response-model.md @@ -0,0 +1,5 @@ +--- +"PostHog.AI": patch +--- + +The OpenAI handler now takes `$ai_model` from the streamed response (Chat Completions chunks and Responses API events), as it already does for non-streaming calls. Previously a streamed call reported only the request's model, or an empty one when the model came from a stored prompt. diff --git a/src/PostHog.AI/PostHogOpenAIHandler.cs b/src/PostHog.AI/PostHogOpenAIHandler.cs index 0ec7f589..94be2846 100644 --- a/src/PostHog.AI/PostHogOpenAIHandler.cs +++ b/src/PostHog.AI/PostHogOpenAIHandler.cs @@ -94,7 +94,7 @@ CancellationToken cancellationToken var trackingStream = new TrackingStream( originalStream, privacyMode, - (accumulatedResponse, usage, responseOutput, streamError, toolCalls) => + (accumulatedResponse, usage, responseOutput, streamError, toolCalls, responseModel) => { stopwatch.Stop(); // Construct a pseudo-response JSON object from accumulated data @@ -129,6 +129,11 @@ CancellationToken cancellationToken responseNode["error"] = streamError; } + if (!string.IsNullOrEmpty(responseModel)) + { + responseNode["model"] = responseModel; + } + CaptureEvent( capturedContext, request, @@ -657,7 +662,7 @@ private sealed class TrackingStream : Stream { private readonly Stream _innerStream; private readonly bool _privacyMode; - private readonly Action _onComplete; + private readonly Action _onComplete; private readonly StringBuilder? _accumulatedContent; private readonly StringBuilder _lineBuffer = new(capacity: 512); // Stateful so a multibyte character split across two reads is decoded once complete. @@ -665,6 +670,7 @@ private sealed class TrackingStream : Stream private JsonNode? _usage; private JsonArray? _responseOutput; private JsonNode? _streamError; + private string? _model; // Chat Completions streams tool calls as fragments keyed by `index`; rebuilt here into full calls. private readonly SortedDictionary _toolCalls = new(); private bool _completed; @@ -705,7 +711,7 @@ private sealed class StreamedToolCall return result; } - public TrackingStream(Stream innerStream, bool privacyMode, Action onComplete) + public TrackingStream(Stream innerStream, bool privacyMode, Action onComplete) { _innerStream = innerStream; _privacyMode = privacyMode; @@ -914,6 +920,24 @@ private void ProcessLine(ReadOnlySpan line) _usage = JsonNode.Parse(usageElement.GetRawText()); } + // Chat Completions chunks carry `model` at the top level; Responses API events nest it in `response` + if ( + root.TryGetProperty("model", out var chunkModel) + && chunkModel.ValueKind == JsonValueKind.String + ) + { + _model = chunkModel.GetString(); + } + else if ( + root.TryGetProperty("response", out var eventResponse) + && eventResponse.ValueKind == JsonValueKind.Object + && eventResponse.TryGetProperty("model", out var eventModel) + && eventModel.ValueKind == JsonValueKind.String + ) + { + _model = eventModel.GetString(); + } + // Terminal failure of a streamed Responses API call (HTTP status is already 200) if ( root.TryGetProperty("type", out var failTypeElement) @@ -1074,7 +1098,7 @@ protected override void Dispose(bool disposing) if (disposing && !_completed) { _completed = true; - _onComplete(_accumulatedContent?.ToString(), _usage, _responseOutput, _streamError, BuildToolCalls()); + _onComplete(_accumulatedContent?.ToString(), _usage, _responseOutput, _streamError, BuildToolCalls(), _model); } if (disposing) diff --git a/tests/PostHog.AI.Tests/PostHogOpenAIHandlerTests.cs b/tests/PostHog.AI.Tests/PostHogOpenAIHandlerTests.cs index b33abb16..040b2a5b 100644 --- a/tests/PostHog.AI.Tests/PostHogOpenAIHandlerTests.cs +++ b/tests/PostHog.AI.Tests/PostHogOpenAIHandlerTests.cs @@ -1072,6 +1072,60 @@ bool emptyOutput } } + [Fact] + public async Task SendAsyncTakesModelFromResponsesStreamWhenRequestHasNoModel() + { + // A stored prompt carries the model, so the request body has none + var requestBody = new { prompt = new { id = "pmpt_123" }, input = "Tell me a joke", stream = true }; + var sse = "data: {\"type\":\"response.created\",\"response\":{\"model\":\"gpt-4o-2024-08-06\",\"status\":\"in_progress\",\"output\":[]}}\n\n" + + "data: {\"type\":\"response.output_text.delta\",\"delta\":\"Why did\"}\n\n" + + "data: {\"type\":\"response.completed\",\"response\":{\"model\":\"gpt-4o-2024-08-06\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":10,\"output_tokens\":5,\"total_tokens\":15}}}\n\n"; + _innerHandler.Response = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(sse, Encoding.UTF8, "text/event-stream"), + }; + using var requestContent = new StringContent( + JsonSerializer.Serialize(requestBody), + Encoding.UTF8, + "application/json" + ); + + using (var response = await _client.PostAsync(new Uri("/v1/responses", UriKind.Relative), requestContent)) + { + await response.Content.ReadAsStringAsync(); + } + + var capture = Assert.Single(_postHogClient.ReceivedCalls()); + var props = Assert.IsType>(capture.GetArguments()[2]); + Assert.Equal("gpt-4o-2024-08-06", props[PostHogAIFieldNames.Model]); + } + + [Fact] + public async Task SendAsyncTakesModelFromChatCompletionStreamChunks() + { + var requestBody = new { model = "gpt-4o", messages = new[] { new { role = "user", content = "Hi" } }, stream = true }; + var sse = "data: {\"id\":\"chatcmpl-1\",\"model\":\"gpt-4o-2024-08-06\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hello\"}}]}\n\n" + + "data: [DONE]\n\n"; + _innerHandler.Response = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(sse, Encoding.UTF8, "text/event-stream"), + }; + using var requestContent = new StringContent( + JsonSerializer.Serialize(requestBody), + Encoding.UTF8, + "application/json" + ); + + using (var response = await _client.PostAsync(new Uri("/v1/chat/completions", UriKind.Relative), requestContent)) + { + await response.Content.ReadAsStringAsync(); + } + + var capture = Assert.Single(_postHogClient.ReceivedCalls()); + var props = Assert.IsType>(capture.GetArguments()[2]); + Assert.Equal("gpt-4o-2024-08-06", props[PostHogAIFieldNames.Model]); + } + private static bool VerifyStreamingProps(Dictionary props) { if (