( model: string, messages: NormalizedMessage[], responseStartIndex: number, workDir: string, )
| 1354 | |
| 1355 | // Turns a normalized message back into a full OpenAI ChatCompletion that we can replay as a response |
| 1356 | function createOpenAIResponse( |
| 1357 | model: string, |
| 1358 | messages: NormalizedMessage[], |
| 1359 | responseStartIndex: number, |
| 1360 | workDir: string, |
| 1361 | ): ChatCompletion { |
| 1362 | // Here we recreate the strange CAPI/productcode behavior of using multiple choices to represent |
| 1363 | // multiple assistant messages in a row. This is the inverse of the logic in transformOpenAIResponseChoice(). |
| 1364 | // So, find all successive assistant messages starting from responseStartIndex. |
| 1365 | const choices: ChatCompletion.Choice[] = []; |
| 1366 | for ( |
| 1367 | let index = 0; |
| 1368 | messages[responseStartIndex + index]?.role === "assistant"; |
| 1369 | index++ |
| 1370 | ) { |
| 1371 | const assistantMessage = messages[responseStartIndex + index]; |
| 1372 | const toolCalls = assistantMessage.tool_calls?.map((tc, idx) => ({ |
| 1373 | id: tc.id || `call_${idx}`, |
| 1374 | type: "function" as const, |
| 1375 | function: { |
| 1376 | name: expandToolName(tc.function?.name ?? ""), |
| 1377 | arguments: expandWorkDir(tc.function?.arguments, workDir, true) ?? "{}", |
| 1378 | }, |
| 1379 | })); |
| 1380 | |
| 1381 | choices.push({ |
| 1382 | index, |
| 1383 | message: { |
| 1384 | role: "assistant", |
| 1385 | content: |
| 1386 | expandWorkDir(assistantMessage.content, workDir, false) ?? null, |
| 1387 | refusal: assistantMessage.refusal ?? null, |
| 1388 | tool_calls: toolCalls, |
| 1389 | }, |
| 1390 | finish_reason: toolCalls?.length ? "tool_calls" : "stop", |
| 1391 | logprobs: null, |
| 1392 | }); |
| 1393 | } |
| 1394 | |
| 1395 | return { |
| 1396 | id: "cached-completion", |
| 1397 | object: "chat.completion", |
| 1398 | created: Math.floor(Date.now() / 1000), |
| 1399 | model, |
| 1400 | choices, |
| 1401 | usage: { |
| 1402 | prompt_tokens: 0, |
| 1403 | completion_tokens: 0, |
| 1404 | total_tokens: 0, |
| 1405 | }, |
| 1406 | }; |
| 1407 | } |
| 1408 | |
| 1409 | const STREAM_CHUNK_SIZE = 200; |
| 1410 |
no test coverage detected
searching dependent graphs…