|
| 1 | +import { HYPERBOLIC } from '../../globals'; |
| 2 | +interface HyperbolicStreamChunk { |
| 3 | + id: string; |
| 4 | + object: string; |
| 5 | + created: number; |
| 6 | + model: string; |
| 7 | + choices: { |
| 8 | + index: number; |
| 9 | + message: { |
| 10 | + role?: string | null; |
| 11 | + content?: string; |
| 12 | + }; |
| 13 | + finish_reason: string | null; |
| 14 | + }[]; |
| 15 | + usage: { |
| 16 | + prompt_tokens: number; |
| 17 | + total_tokens: number; |
| 18 | + completion_tokens: number; |
| 19 | + }; |
| 20 | +} |
| 21 | + |
| 22 | +export const HyperbolicChatCompleteStreamChunkTransform = ( |
| 23 | + responseChunk: string |
| 24 | +) => { |
| 25 | + let chunk = responseChunk.trim(); |
| 26 | + chunk = chunk.replace(/^data: /, ''); |
| 27 | + chunk = chunk.trim(); |
| 28 | + |
| 29 | + if (chunk === '[DONE]') { |
| 30 | + return `data: ${chunk}\n\n`; |
| 31 | + } |
| 32 | + |
| 33 | + try { |
| 34 | + const parsedChunk: HyperbolicStreamChunk = JSON.parse(chunk); |
| 35 | + return ( |
| 36 | + `data: ${JSON.stringify({ |
| 37 | + id: parsedChunk.id, |
| 38 | + object: parsedChunk.object, |
| 39 | + created: parsedChunk.created, |
| 40 | + model: parsedChunk.model, |
| 41 | + provider: HYPERBOLIC, |
| 42 | + choices: [ |
| 43 | + { |
| 44 | + index: parsedChunk.choices[0].index, |
| 45 | + message: parsedChunk.choices[0].message, |
| 46 | + finish_reason: parsedChunk.choices[0].finish_reason, |
| 47 | + }, |
| 48 | + ], |
| 49 | + usage: { |
| 50 | + prompt_tokens: parsedChunk.usage.prompt_tokens, |
| 51 | + total_tokens: parsedChunk.usage.total_tokens, |
| 52 | + completion_tokens: parsedChunk.usage.completion_tokens, |
| 53 | + }, |
| 54 | + })}` + '\n\n' |
| 55 | + ); |
| 56 | + } catch (error) { |
| 57 | + console.error('Error parsing Hyperbolic stream chunk:', error); |
| 58 | + return `data: ${chunk}\n\n`; |
| 59 | + } |
| 60 | +}; |
0 commit comments