Skip to content
Open
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
4 changes: 2 additions & 2 deletions src/__tests__/tool-calling.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1467,8 +1467,8 @@ describe('Tool Calling', () => {
expect(eventTypes).toContain('tool-call');
expect(eventTypes).toContain('finish');

// Verify text content comes first and finish comes last
expect(eventTypes[0]).toBe('text-delta');
// Verify text-start comes first and finish comes last
expect(eventTypes[0]).toBe('text-start');
expect(eventTypes[eventTypes.length - 1]).toBe('finish');

// Verify tool call was completed correctly
Expand Down
37 changes: 36 additions & 1 deletion src/helicone-language-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,10 @@ export class HeliconeLanguageModel implements LanguageModelV2 {
// Map tool call index to ID for streaming chunks
const indexToId: Map<number, string> = new Map();

// Track text parts for start/end events
const textStarted = new Set<string>();
const textEnded = new Set<string>();

const textDecoder = new TextDecoder();
const reader = response.body!.getReader();

Expand Down Expand Up @@ -314,6 +318,17 @@ export class HeliconeLanguageModel implements LanguageModelV2 {
}
}

// Complete any outstanding text parts before finishing
for (const id of textStarted) {
if (!textEnded.has(id)) {
controller.enqueue({
type: 'text-end',
id
} as LanguageModelV2StreamPart);
textEnded.add(id);
}
}

controller.enqueue({
type: 'finish',
usage: usage as LanguageModelV2Usage,
Expand Down Expand Up @@ -371,17 +386,37 @@ export class HeliconeLanguageModel implements LanguageModelV2 {
toolCall.completed = true;
}
}

// Complete any outstanding text parts
for (const id of textStarted) {
if (!textEnded.has(id)) {
controller.enqueue({
type: 'text-end',
id
} as LanguageModelV2StreamPart);
textEnded.add(id);
}
}
}

const delta = choice.delta;
if (!delta) continue;

// Transform text content to text-delta events
if (delta.content) {
const id = 'text-0';
// Emit text-start before first text-delta
if (!textStarted.has(id)) {
controller.enqueue({
type: 'text-start',
id
} as LanguageModelV2StreamPart);
textStarted.add(id);
}
controller.enqueue({
type: 'text-delta',
delta: delta.content,
id: 'text-0'
id
} as LanguageModelV2StreamPart);
}

Expand Down