( completion: ChatCompletion, )
| 1409 | const STREAM_CHUNK_SIZE = 200; |
| 1410 | |
| 1411 | function convertToStreamingResponseChunks( |
| 1412 | completion: ChatCompletion, |
| 1413 | ): ChatCompletionChunk[] { |
| 1414 | const choice = completion.choices[0]; |
| 1415 | const content = choice.message.content ?? ""; |
| 1416 | const toolCalls = choice.message.tool_calls?.filter( |
| 1417 | (tc): tc is ChatCompletionMessageFunctionToolCall => tc.type === "function", |
| 1418 | ); |
| 1419 | |
| 1420 | const makeChunk = ( |
| 1421 | delta: ChatCompletionChunk.Choice.Delta, |
| 1422 | ): ChatCompletionChunk => ({ |
| 1423 | id: completion.id, |
| 1424 | object: "chat.completion.chunk", |
| 1425 | created: completion.created, |
| 1426 | model: completion.model, |
| 1427 | choices: [{ index: 0, delta, finish_reason: null, logprobs: null }], |
| 1428 | }); |
| 1429 | |
| 1430 | const chunks: ChatCompletionChunk[] = []; |
| 1431 | |
| 1432 | // Content chunks |
| 1433 | for (let i = 0; i < content.length; i += STREAM_CHUNK_SIZE) { |
| 1434 | chunks.push( |
| 1435 | makeChunk({ |
| 1436 | role: "assistant", |
| 1437 | content: content.slice(i, i + STREAM_CHUNK_SIZE), |
| 1438 | }), |
| 1439 | ); |
| 1440 | } |
| 1441 | |
| 1442 | // Tool call argument chunks |
| 1443 | for (const [tcIdx, tc] of (toolCalls ?? []).entries()) { |
| 1444 | const args = tc.function.arguments; |
| 1445 | for (let i = 0; i < args.length; i += STREAM_CHUNK_SIZE) { |
| 1446 | chunks.push( |
| 1447 | makeChunk({ |
| 1448 | role: "assistant", |
| 1449 | tool_calls: [ |
| 1450 | { |
| 1451 | index: tcIdx, |
| 1452 | id: tc.id, |
| 1453 | type: "function", |
| 1454 | function: { |
| 1455 | name: i === 0 ? tc.function.name : "", |
| 1456 | arguments: args.slice(i, i + STREAM_CHUNK_SIZE), |
| 1457 | }, |
| 1458 | }, |
| 1459 | ], |
| 1460 | }), |
| 1461 | ); |
| 1462 | } |
| 1463 | } |
| 1464 | |
| 1465 | // Set finish_reason on last chunk |
| 1466 | if (chunks.length === 0) { |
| 1467 | chunks.push(makeChunk({ role: "assistant" })); |
| 1468 | } |
no test coverage detected
searching dependent graphs…