| 498 | } |
| 499 | |
| 500 | function handleStreamChunk({ |
| 501 | data, |
| 502 | state, |
| 503 | startTime, |
| 504 | logger, |
| 505 | userId, |
| 506 | agentId, |
| 507 | model, |
| 508 | }: { |
| 509 | data: Record<string, unknown> |
| 510 | state: StreamState |
| 511 | startTime: Date |
| 512 | logger: Logger |
| 513 | userId: string |
| 514 | agentId: string |
| 515 | model: string |
| 516 | }): StreamState { |
| 517 | const MAX_BUFFER_SIZE = 1 * 1024 * 1024 |
| 518 | |
| 519 | if ('error' in data) { |
| 520 | const errorData = data.error as Record<string, unknown> |
| 521 | logger.error( |
| 522 | { |
| 523 | userId, |
| 524 | agentId, |
| 525 | model, |
| 526 | errorCode: errorData?.code, |
| 527 | errorType: errorData?.type, |
| 528 | errorMessage: errorData?.message, |
| 529 | }, |
| 530 | 'Received error chunk in SiliconFlow stream', |
| 531 | ) |
| 532 | return state |
| 533 | } |
| 534 | |
| 535 | const choices = data.choices as Array<Record<string, unknown>> | undefined |
| 536 | if (!choices?.length) { |
| 537 | return state |
| 538 | } |
| 539 | const choice = choices[0] |
| 540 | const delta = choice.delta as Record<string, unknown> | undefined |
| 541 | |
| 542 | const contentDelta = typeof delta?.content === 'string' ? delta.content : '' |
| 543 | if (state.responseText.length < MAX_BUFFER_SIZE) { |
| 544 | state.responseText += contentDelta |
| 545 | if (state.responseText.length >= MAX_BUFFER_SIZE) { |
| 546 | state.responseText = |
| 547 | state.responseText.slice(0, MAX_BUFFER_SIZE) + '\n---[TRUNCATED]---' |
| 548 | logger.warn({ userId, agentId, model }, 'Response text buffer truncated at 1MB') |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | const reasoningDelta = typeof delta?.reasoning_content === 'string' ? delta.reasoning_content |
| 553 | : typeof delta?.reasoning === 'string' ? delta.reasoning |
| 554 | : '' |
| 555 | |
| 556 | // Track time to first token (TTFT) - set on first meaningful delta (content, reasoning, or tool_calls) |
| 557 | const hasToolCallsDelta = delta?.tool_calls != null && (delta.tool_calls as unknown[])?.length > 0 |