| 533 | } |
| 534 | |
| 535 | function handleStreamChunk({ |
| 536 | data, |
| 537 | state, |
| 538 | startTime, |
| 539 | logger, |
| 540 | userId, |
| 541 | agentId, |
| 542 | model, |
| 543 | }: { |
| 544 | data: Record<string, unknown> |
| 545 | state: StreamState |
| 546 | startTime: Date |
| 547 | logger: Logger |
| 548 | userId: string |
| 549 | agentId: string |
| 550 | model: string |
| 551 | }): StreamState { |
| 552 | const MAX_BUFFER_SIZE = 1 * 1024 * 1024 |
| 553 | |
| 554 | if ('error' in data) { |
| 555 | const errorData = data.error as Record<string, unknown> |
| 556 | logger.error( |
| 557 | { |
| 558 | userId, |
| 559 | agentId, |
| 560 | model, |
| 561 | errorCode: errorData?.code, |
| 562 | errorType: errorData?.type, |
| 563 | errorMessage: errorData?.message, |
| 564 | }, |
| 565 | 'Received error chunk in CanopyWave stream', |
| 566 | ) |
| 567 | return state |
| 568 | } |
| 569 | |
| 570 | const choices = data.choices as Array<Record<string, unknown>> | undefined |
| 571 | if (!choices?.length) { |
| 572 | return state |
| 573 | } |
| 574 | const choice = choices[0] |
| 575 | const delta = choice.delta as Record<string, unknown> | undefined |
| 576 | |
| 577 | const contentDelta = typeof delta?.content === 'string' ? delta.content : '' |
| 578 | if (state.responseText.length < MAX_BUFFER_SIZE) { |
| 579 | state.responseText += contentDelta |
| 580 | if (state.responseText.length >= MAX_BUFFER_SIZE) { |
| 581 | state.responseText = |
| 582 | state.responseText.slice(0, MAX_BUFFER_SIZE) + '\n---[TRUNCATED]---' |
| 583 | logger.warn({ userId, agentId, model }, 'Response text buffer truncated at 1MB') |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | const reasoningDelta = typeof delta?.reasoning_content === 'string' ? delta.reasoning_content |
| 588 | : typeof delta?.reasoning === 'string' ? delta.reasoning |
| 589 | : '' |
| 590 | |
| 591 | // Track time to first token (TTFT) - set on first meaningful delta (content, reasoning, or tool_calls) |
| 592 | const hasToolCallsDelta = delta?.tool_calls != null && (delta.tool_calls as unknown[])?.length > 0 |