|
| 1 | +import { z } from 'zod'; |
| 2 | +import { |
| 3 | + LanguageModelV1, |
| 4 | + LanguageModelV1CallWarning, |
| 5 | + LanguageModelV1FinishReason, |
| 6 | + LanguageModelV1StreamPart, |
| 7 | + ParseResult, |
| 8 | + UnsupportedFunctionalityError, |
| 9 | + createEventSourceResponseHandler, |
| 10 | + createJsonResponseHandler, |
| 11 | + postJsonToApi, |
| 12 | +} from '../spec'; |
| 13 | +import { anthropicFailedResponseHandler } from './anthropic-error'; |
| 14 | +import { |
| 15 | + AnthropicMessagesModelId, |
| 16 | + AnthropicMessagesSettings, |
| 17 | +} from './anthropic-messages-settings'; |
| 18 | +import { mapAnthropicFinishReason } from './map-anthropic-finish-reason'; |
| 19 | +import { convertToAnthropicMessagesPrompt } from './convert-to-anthropic-messages-prompt'; |
| 20 | + |
| 21 | +type AnthropicMessagesConfig = { |
| 22 | + provider: string; |
| 23 | + baseUrl: string; |
| 24 | + headers: () => Record<string, string | undefined>; |
| 25 | + generateId: () => string; |
| 26 | +}; |
| 27 | + |
| 28 | +export class AnthropicMessagesLanguageModel implements LanguageModelV1 { |
| 29 | + readonly specificationVersion = 'v1'; |
| 30 | + readonly defaultObjectGenerationMode = 'json'; |
| 31 | + |
| 32 | + readonly modelId: AnthropicMessagesModelId; |
| 33 | + readonly settings: AnthropicMessagesSettings; |
| 34 | + |
| 35 | + private readonly config: AnthropicMessagesConfig; |
| 36 | + |
| 37 | + constructor( |
| 38 | + modelId: AnthropicMessagesModelId, |
| 39 | + settings: AnthropicMessagesSettings, |
| 40 | + config: AnthropicMessagesConfig, |
| 41 | + ) { |
| 42 | + this.modelId = modelId; |
| 43 | + this.settings = settings; |
| 44 | + this.config = config; |
| 45 | + } |
| 46 | + |
| 47 | + get provider(): string { |
| 48 | + return this.config.provider; |
| 49 | + } |
| 50 | + |
| 51 | + private getArgs({ |
| 52 | + mode, |
| 53 | + prompt, |
| 54 | + maxTokens, |
| 55 | + temperature, |
| 56 | + topP, |
| 57 | + frequencyPenalty, |
| 58 | + presencePenalty, |
| 59 | + seed, |
| 60 | + }: Parameters<LanguageModelV1['doGenerate']>[0]) { |
| 61 | + const type = mode.type; |
| 62 | + |
| 63 | + const warnings: LanguageModelV1CallWarning[] = []; |
| 64 | + |
| 65 | + if (frequencyPenalty != null) { |
| 66 | + warnings.push({ |
| 67 | + type: 'unsupported-setting', |
| 68 | + setting: 'frequencyPenalty', |
| 69 | + }); |
| 70 | + } |
| 71 | + |
| 72 | + if (presencePenalty != null) { |
| 73 | + warnings.push({ |
| 74 | + type: 'unsupported-setting', |
| 75 | + setting: 'presencePenalty', |
| 76 | + }); |
| 77 | + } |
| 78 | + |
| 79 | + if (seed != null) { |
| 80 | + warnings.push({ |
| 81 | + type: 'unsupported-setting', |
| 82 | + setting: 'seed', |
| 83 | + }); |
| 84 | + } |
| 85 | + |
| 86 | + const messagesPrompt = convertToAnthropicMessagesPrompt({ |
| 87 | + provider: this.provider, |
| 88 | + prompt, |
| 89 | + }); |
| 90 | + |
| 91 | + const baseArgs = { |
| 92 | + // model id: |
| 93 | + model: this.modelId, |
| 94 | + |
| 95 | + // model specific settings: |
| 96 | + top_k: this.settings.topK, |
| 97 | + |
| 98 | + // standardized settings: |
| 99 | + max_tokens: maxTokens ?? 4096, // 4096: max model output tokens |
| 100 | + temperature, // uses 0..1 scale |
| 101 | + top_p: topP, |
| 102 | + |
| 103 | + // prompt: |
| 104 | + system: messagesPrompt.system, |
| 105 | + messages: messagesPrompt.messages, |
| 106 | + }; |
| 107 | + |
| 108 | + switch (type) { |
| 109 | + case 'regular': { |
| 110 | + // when the tools array is empty, change it to undefined to prevent OpenAI errors: |
| 111 | + const tools = mode.tools?.length ? mode.tools : undefined; |
| 112 | + |
| 113 | + return { |
| 114 | + args: { |
| 115 | + ...baseArgs, |
| 116 | + tools: tools?.map(tool => ({ |
| 117 | + type: 'function', |
| 118 | + function: { |
| 119 | + name: tool.name, |
| 120 | + description: tool.description, |
| 121 | + parameters: tool.parameters, |
| 122 | + }, |
| 123 | + })), |
| 124 | + }, |
| 125 | + warnings, |
| 126 | + }; |
| 127 | + } |
| 128 | + |
| 129 | + case 'object-json': { |
| 130 | + return { |
| 131 | + args: { |
| 132 | + ...baseArgs, |
| 133 | + response_format: { type: 'json_object' }, |
| 134 | + }, |
| 135 | + warnings, |
| 136 | + }; |
| 137 | + } |
| 138 | + |
| 139 | + case 'object-tool': { |
| 140 | + return { |
| 141 | + args: { |
| 142 | + ...baseArgs, |
| 143 | + tool_choice: 'any', |
| 144 | + tools: [{ type: 'function', function: mode.tool }], |
| 145 | + }, |
| 146 | + warnings, |
| 147 | + }; |
| 148 | + } |
| 149 | + |
| 150 | + case 'object-grammar': { |
| 151 | + throw new UnsupportedFunctionalityError({ |
| 152 | + functionality: 'object-grammar mode', |
| 153 | + provider: this.provider, |
| 154 | + }); |
| 155 | + } |
| 156 | + |
| 157 | + default: { |
| 158 | + const _exhaustiveCheck: never = type; |
| 159 | + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); |
| 160 | + } |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + async doGenerate( |
| 165 | + options: Parameters<LanguageModelV1['doGenerate']>[0], |
| 166 | + ): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>> { |
| 167 | + const { args, warnings } = this.getArgs(options); |
| 168 | + |
| 169 | + const response = await postJsonToApi({ |
| 170 | + url: `${this.config.baseUrl}/messages`, |
| 171 | + headers: this.config.headers(), |
| 172 | + body: args, |
| 173 | + failedResponseHandler: anthropicFailedResponseHandler, |
| 174 | + successfulResponseHandler: createJsonResponseHandler( |
| 175 | + anthropicMessagesResponseSchema, |
| 176 | + ), |
| 177 | + abortSignal: options.abortSignal, |
| 178 | + }); |
| 179 | + |
| 180 | + const { messages: rawPrompt, ...rawSettings } = args; |
| 181 | + |
| 182 | + return { |
| 183 | + text: response.content.map(({ text }) => text).join(''), |
| 184 | + finishReason: mapAnthropicFinishReason(response.stop_reason), |
| 185 | + usage: { |
| 186 | + promptTokens: response.usage.input_tokens, |
| 187 | + completionTokens: response.usage.output_tokens, |
| 188 | + }, |
| 189 | + rawCall: { rawPrompt, rawSettings }, |
| 190 | + warnings, |
| 191 | + }; |
| 192 | + } |
| 193 | + |
| 194 | + async doStream( |
| 195 | + options: Parameters<LanguageModelV1['doStream']>[0], |
| 196 | + ): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>> { |
| 197 | + const { args, warnings } = this.getArgs(options); |
| 198 | + |
| 199 | + const response = await postJsonToApi({ |
| 200 | + url: `${this.config.baseUrl}/messages`, |
| 201 | + headers: this.config.headers(), |
| 202 | + body: { |
| 203 | + ...args, |
| 204 | + stream: true, |
| 205 | + }, |
| 206 | + failedResponseHandler: anthropicFailedResponseHandler, |
| 207 | + successfulResponseHandler: createEventSourceResponseHandler( |
| 208 | + anthropicMessagesChunkSchema, |
| 209 | + ), |
| 210 | + abortSignal: options.abortSignal, |
| 211 | + }); |
| 212 | + |
| 213 | + const { messages: rawPrompt, ...rawSettings } = args; |
| 214 | + |
| 215 | + let finishReason: LanguageModelV1FinishReason = 'other'; |
| 216 | + const usage: { promptTokens: number; completionTokens: number } = { |
| 217 | + promptTokens: Number.NaN, |
| 218 | + completionTokens: Number.NaN, |
| 219 | + }; |
| 220 | + |
| 221 | + const generateId = this.config.generateId; |
| 222 | + |
| 223 | + return { |
| 224 | + stream: response.pipeThrough( |
| 225 | + new TransformStream< |
| 226 | + ParseResult<z.infer<typeof anthropicMessagesChunkSchema>>, |
| 227 | + LanguageModelV1StreamPart |
| 228 | + >({ |
| 229 | + transform(chunk, controller) { |
| 230 | + if (!chunk.success) { |
| 231 | + controller.enqueue({ type: 'error', error: chunk.error }); |
| 232 | + return; |
| 233 | + } |
| 234 | + |
| 235 | + const value = chunk.value; |
| 236 | + |
| 237 | + switch (value.type) { |
| 238 | + case 'ping': |
| 239 | + case 'content_block_start': |
| 240 | + case 'content_block_stop': { |
| 241 | + return; // ignored |
| 242 | + } |
| 243 | + |
| 244 | + case 'content_block_delta': { |
| 245 | + controller.enqueue({ |
| 246 | + type: 'text-delta', |
| 247 | + textDelta: value.delta.text, |
| 248 | + }); |
| 249 | + return; |
| 250 | + } |
| 251 | + |
| 252 | + case 'message_start': { |
| 253 | + usage.promptTokens = value.message.usage.input_tokens; |
| 254 | + usage.completionTokens = value.message.usage.output_tokens; |
| 255 | + return; |
| 256 | + } |
| 257 | + |
| 258 | + case 'message_delta': { |
| 259 | + usage.completionTokens = value.usage.output_tokens; |
| 260 | + finishReason = mapAnthropicFinishReason( |
| 261 | + value.delta.stop_reason, |
| 262 | + ); |
| 263 | + return; |
| 264 | + } |
| 265 | + |
| 266 | + case 'message_stop': { |
| 267 | + controller.enqueue({ type: 'finish', finishReason, usage }); |
| 268 | + return; |
| 269 | + } |
| 270 | + |
| 271 | + default: { |
| 272 | + const _exhaustiveCheck: never = value; |
| 273 | + throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`); |
| 274 | + } |
| 275 | + } |
| 276 | + }, |
| 277 | + }), |
| 278 | + ), |
| 279 | + rawCall: { rawPrompt, rawSettings }, |
| 280 | + warnings, |
| 281 | + }; |
| 282 | + } |
| 283 | +} |
| 284 | + |
| 285 | +// limited version of the schema, focussed on what is needed for the implementation |
| 286 | +// this approach limits breakages when the API changes and increases efficiency |
| 287 | +const anthropicMessagesResponseSchema = z.object({ |
| 288 | + type: z.literal('message'), |
| 289 | + content: z.array( |
| 290 | + z.object({ |
| 291 | + type: z.literal('text'), |
| 292 | + text: z.string(), |
| 293 | + }), |
| 294 | + ), |
| 295 | + stop_reason: z.string().optional().nullable(), |
| 296 | + usage: z.object({ |
| 297 | + input_tokens: z.number(), |
| 298 | + output_tokens: z.number(), |
| 299 | + }), |
| 300 | +}); |
| 301 | + |
| 302 | +// limited version of the schema, focussed on what is needed for the implementation |
| 303 | +// this approach limits breakages when the API changes and increases efficiency |
| 304 | +const anthropicMessagesChunkSchema = z.discriminatedUnion('type', [ |
| 305 | + z.object({ |
| 306 | + type: z.literal('message_start'), |
| 307 | + message: z.object({ |
| 308 | + usage: z.object({ |
| 309 | + input_tokens: z.number(), |
| 310 | + output_tokens: z.number(), |
| 311 | + }), |
| 312 | + }), |
| 313 | + }), |
| 314 | + z.object({ |
| 315 | + type: z.literal('content_block_start'), |
| 316 | + index: z.number(), |
| 317 | + content_block: z.object({ |
| 318 | + type: z.literal('text'), |
| 319 | + text: z.string(), |
| 320 | + }), |
| 321 | + }), |
| 322 | + z.object({ |
| 323 | + type: z.literal('content_block_delta'), |
| 324 | + index: z.number(), |
| 325 | + delta: z.object({ |
| 326 | + type: z.literal('text_delta'), |
| 327 | + text: z.string(), |
| 328 | + }), |
| 329 | + }), |
| 330 | + z.object({ |
| 331 | + type: z.literal('content_block_stop'), |
| 332 | + index: z.number(), |
| 333 | + }), |
| 334 | + z.object({ |
| 335 | + type: z.literal('message_delta'), |
| 336 | + delta: z.object({ stop_reason: z.string().optional().nullable() }), |
| 337 | + usage: z.object({ output_tokens: z.number() }), |
| 338 | + }), |
| 339 | + z.object({ |
| 340 | + type: z.literal('message_stop'), |
| 341 | + }), |
| 342 | + z.object({ |
| 343 | + type: z.literal('ping'), |
| 344 | + }), |
| 345 | +]); |
0 commit comments