({ apiKey, model, messages, tools })
| 145 | } |
| 146 | |
| 147 | export async function chat({ apiKey, model, messages, tools }) { |
| 148 | const request = splitSystemAndMessages(messages); |
| 149 | const anthropicTools = toAnthropicTools(tools); |
| 150 | |
| 151 | // Mark the last tool with cache_control so the entire tool list is cached |
| 152 | if (anthropicTools.length > 0) { |
| 153 | anthropicTools[anthropicTools.length - 1].cache_control = { type: "ephemeral" }; |
| 154 | } |
| 155 | |
| 156 | const body = { |
| 157 | model, |
| 158 | max_tokens: 4096, |
| 159 | messages: request.messages, |
| 160 | tools: anthropicTools, |
| 161 | }; |
| 162 | |
| 163 | if (request.system) { |
| 164 | body.system = [{ type: "text", text: request.system, cache_control: { type: "ephemeral" } }]; |
| 165 | } |
| 166 | |
| 167 | const res = await fetch("https://api.anthropic.com/v1/messages", { |
| 168 | method: "POST", |
| 169 | headers: { |
| 170 | "Content-Type": "application/json", |
| 171 | "x-api-key": apiKey, |
| 172 | "anthropic-version": "2023-06-01", |
| 173 | "anthropic-dangerous-direct-browser-access": "true", |
| 174 | }, |
| 175 | body: JSON.stringify(body), |
| 176 | }); |
| 177 | |
| 178 | if (!res.ok) { |
| 179 | const text = await res.text(); |
| 180 | throw new Error(`Anthropic error ${res.status}: ${text}`); |
| 181 | } |
| 182 | |
| 183 | return toChatCompletionResponse(await res.json()); |
| 184 | } |
nothing calls this directly
no test coverage detected