| 663 | } |
| 664 | |
| 665 | function handleStreamChunk({ |
| 666 | data, |
| 667 | state, |
| 668 | startTime, |
| 669 | logger, |
| 670 | userId, |
| 671 | agentId, |
| 672 | model, |
| 673 | }: { |
| 674 | data: Record<string, unknown> |
| 675 | state: StreamState |
| 676 | startTime: Date |
| 677 | logger: Logger |
| 678 | userId: string |
| 679 | agentId: string |
| 680 | model: string |
| 681 | }): StreamState { |
| 682 | const MAX_BUFFER_SIZE = 1 * 1024 * 1024 |
| 683 | |
| 684 | if ('error' in data) { |
| 685 | const errorData = data.error as Record<string, unknown> |
| 686 | logger.error( |
| 687 | { |
| 688 | userId, |
| 689 | agentId, |
| 690 | model, |
| 691 | errorCode: errorData?.code, |
| 692 | errorType: errorData?.type, |
| 693 | errorMessage: errorData?.message, |
| 694 | }, |
| 695 | 'Received error chunk in Fireworks stream', |
| 696 | ) |
| 697 | return state |
| 698 | } |
| 699 | |
| 700 | const choices = data.choices as Array<Record<string, unknown>> | undefined |
| 701 | if (!choices?.length) { |
| 702 | return state |
| 703 | } |
| 704 | const choice = choices[0] |
| 705 | const delta = choice.delta as Record<string, unknown> | undefined |
| 706 | |
| 707 | const contentDelta = typeof delta?.content === 'string' ? delta.content : '' |
| 708 | if (state.responseText.length < MAX_BUFFER_SIZE) { |
| 709 | state.responseText += contentDelta |
| 710 | if (state.responseText.length >= MAX_BUFFER_SIZE) { |
| 711 | state.responseText = |
| 712 | state.responseText.slice(0, MAX_BUFFER_SIZE) + '\n---[TRUNCATED]---' |
| 713 | logger.warn( |
| 714 | { userId, agentId, model }, |
| 715 | 'Response text buffer truncated at 1MB', |
| 716 | ) |
| 717 | } |
| 718 | } |
| 719 | |
| 720 | const reasoningDelta = |
| 721 | typeof delta?.reasoning_content === 'string' |
| 722 | ? delta.reasoning_content |