Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/openai-stream-response-model.md
Original file line number Diff line number Diff line change
@@ -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.
32 changes: 28 additions & 4 deletions src/PostHog.AI/PostHogOpenAIHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -129,6 +129,11 @@ CancellationToken cancellationToken
responseNode["error"] = streamError;
}

if (!string.IsNullOrEmpty(responseModel))
{
responseNode["model"] = responseModel;
}

CaptureEvent(
capturedContext,
request,
Expand Down Expand Up @@ -657,14 +662,15 @@ private sealed class TrackingStream : Stream
{
private readonly Stream _innerStream;
private readonly bool _privacyMode;
private readonly Action<string?, JsonNode?, JsonArray?, JsonNode?, JsonArray?> _onComplete;
private readonly Action<string?, JsonNode?, JsonArray?, JsonNode?, JsonArray?, string?> _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.
private readonly Decoder _decoder = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetDecoder();
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<int, StreamedToolCall> _toolCalls = new();
private bool _completed;
Expand Down Expand Up @@ -705,7 +711,7 @@ private sealed class StreamedToolCall
return result;
}

public TrackingStream(Stream innerStream, bool privacyMode, Action<string?, JsonNode?, JsonArray?, JsonNode?, JsonArray?> onComplete)
public TrackingStream(Stream innerStream, bool privacyMode, Action<string?, JsonNode?, JsonArray?, JsonNode?, JsonArray?, string?> onComplete)
{
_innerStream = innerStream;
_privacyMode = privacyMode;
Expand Down Expand Up @@ -914,6 +920,24 @@ private void ProcessLine(ReadOnlySpan<char> 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)
Expand Down Expand Up @@ -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)
Expand Down
54 changes: 54 additions & 0 deletions tests/PostHog.AI.Tests/PostHogOpenAIHandlerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Dictionary<string, object>>(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<Dictionary<string, object>>(capture.GetArguments()[2]);
Assert.Equal("gpt-4o-2024-08-06", props[PostHogAIFieldNames.Model]);
}

private static bool VerifyStreamingProps(Dictionary<string, object> props)
{
if (
Expand Down