| 103 | } |
| 104 | |
| 105 | function toChatCompletionResponse(response) { |
| 106 | const text = []; |
| 107 | const toolCalls = []; |
| 108 | |
| 109 | for (const block of response.content ?? []) { |
| 110 | if (block.type === "text") { |
| 111 | text.push(block.text); |
| 112 | continue; |
| 113 | } |
| 114 | |
| 115 | if (block.type === "tool_use") { |
| 116 | toolCalls.push({ |
| 117 | id: block.id, |
| 118 | type: "function", |
| 119 | function: { |
| 120 | name: block.name, |
| 121 | arguments: JSON.stringify(block.input ?? {}), |
| 122 | }, |
| 123 | }); |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | const message = { role: "assistant" }; |
| 128 | const content = text.join("\n").trim(); |
| 129 | |
| 130 | if (content) { |
| 131 | message.content = content; |
| 132 | } |
| 133 | |
| 134 | if (toolCalls.length) { |
| 135 | message.tool_calls = toolCalls; |
| 136 | } |
| 137 | |
| 138 | return { |
| 139 | choices: [ |
| 140 | { |
| 141 | message, |
| 142 | }, |
| 143 | ], |
| 144 | }; |
| 145 | } |
| 146 | |
| 147 | export async function chat({ apiKey, model, messages, tools }) { |
| 148 | const request = splitSystemAndMessages(messages); |