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
20 changes: 17 additions & 3 deletions src/extra/observability/streaming.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
CompletionChunk,
completionChunkFromJSON,
} from "../../models/components/completionchunk.js";
import { ContentChunk } from "../../models/components/contentchunk.js";
import {
UsageInfo,
UsageInfo$outboundSchema,
Expand Down Expand Up @@ -125,9 +126,7 @@ export function accumulateChunksToResponseDict(
if (typeof delta.role === "string") {
msg.role = delta.role;
}
if (typeof delta.content === "string" && delta.content) {
msg.content += delta.content;
}
msg.content += extractOutputText(delta.content);
if (typeof choice.finishReason === "string") {
accumulated.finish_reason = choice.finishReason;
}
Expand Down Expand Up @@ -172,3 +171,18 @@ export function accumulateChunksToResponseDict(
}
return result;
}

function extractOutputText(
content: string | Array<ContentChunk> | null | undefined
): string {
if (typeof content === "string") {
return content;
}
if (!Array.isArray(content)) {
return "";
}
return content
.filter((block): block is ContentChunk & { type: "text" } => block.type === "text")
.map((block) => block.text)
.join("");
}
24 changes: 24 additions & 0 deletions tests/extra/observability/streaming.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,30 @@ describe("accumulateChunksToResponseDict", () => {
]);
});

test("accumulates content when delta.content is an array of ContentChunk objects", () => {
const arrayContentChunk: Record<string, unknown> = {
id: "id-1",
model: "m",
choices: [{
index: 0,
delta: {
role: "assistant",
content: [{ type: "text", text: "Bonjour" }],
},
finish_reason: null,
}],
};
const chunks = parseSseChunks(toSse([
arrayContentChunk,
chunk({ content: " monde", finishReason: "stop" }),
]));
const result = accumulateChunksToResponseDict(chunks);
expect(result.choices).toEqual([{
message: { role: "assistant", content: "Bonjour monde" },
finish_reason: "stop",
}]);
});

test("handles empty chunks", () => {
expect(accumulateChunksToResponseDict([])).toEqual({ id: undefined, model: undefined, choices: [] });
});
Expand Down
Loading