|
| 1 | +import { |
| 2 | + LanguageModelV1, |
| 3 | + LanguageModelV1CallWarning, |
| 4 | + LanguageModelV1FinishReason, |
| 5 | + LanguageModelV1StreamPart, |
| 6 | + UnsupportedFunctionalityError, |
| 7 | +} from '@ai-sdk/provider'; |
| 8 | +import { ParseResult } from '@ai-sdk/provider-utils'; |
| 9 | +import { |
| 10 | + BedrockRuntimeClient, |
| 11 | + ConverseCommand, |
| 12 | + ConverseCommandInput, |
| 13 | + ConverseStreamCommand, |
| 14 | + ConverseStreamOutput, |
| 15 | + Tool, |
| 16 | + ToolConfiguration, |
| 17 | +} from '@aws-sdk/client-bedrock-runtime'; |
| 18 | +import { |
| 19 | + BedrockChatModelId, |
| 20 | + BedrockChatSettings, |
| 21 | +} from './bedrock-chat-settings'; |
| 22 | +import { convertToBedrockChatMessages } from './convert-to-bedrock-chat-messages'; |
| 23 | +import { mapBedrockFinishReason } from './map-bedrock-finish-reason'; |
| 24 | + |
| 25 | +type BedrockChatConfig = { |
| 26 | + client: BedrockRuntimeClient; |
| 27 | + generateId: () => string; |
| 28 | +}; |
| 29 | + |
| 30 | +export class BedrockChatLanguageModel implements LanguageModelV1 { |
| 31 | + readonly specificationVersion = 'v1'; |
| 32 | + readonly provider = 'amazon-bedrock'; |
| 33 | + readonly defaultObjectGenerationMode = 'tool'; |
| 34 | + |
| 35 | + readonly modelId: BedrockChatModelId; |
| 36 | + readonly settings: BedrockChatSettings; |
| 37 | + |
| 38 | + private readonly config: BedrockChatConfig; |
| 39 | + |
| 40 | + constructor( |
| 41 | + modelId: BedrockChatModelId, |
| 42 | + settings: BedrockChatSettings, |
| 43 | + config: BedrockChatConfig, |
| 44 | + ) { |
| 45 | + this.modelId = modelId; |
| 46 | + this.settings = settings; |
| 47 | + this.config = config; |
| 48 | + } |
| 49 | + |
| 50 | + private async getArgs({ |
| 51 | + mode, |
| 52 | + prompt, |
| 53 | + maxTokens, |
| 54 | + temperature, |
| 55 | + topP, |
| 56 | + frequencyPenalty, |
| 57 | + presencePenalty, |
| 58 | + seed, |
| 59 | + }: Parameters<LanguageModelV1['doGenerate']>[0]) { |
| 60 | + const type = mode.type; |
| 61 | + |
| 62 | + const warnings: LanguageModelV1CallWarning[] = []; |
| 63 | + |
| 64 | + if (frequencyPenalty != null) { |
| 65 | + warnings.push({ |
| 66 | + type: 'unsupported-setting', |
| 67 | + setting: 'frequencyPenalty', |
| 68 | + }); |
| 69 | + } |
| 70 | + |
| 71 | + if (presencePenalty != null) { |
| 72 | + warnings.push({ |
| 73 | + type: 'unsupported-setting', |
| 74 | + setting: 'presencePenalty', |
| 75 | + }); |
| 76 | + } |
| 77 | + |
| 78 | + if (seed != null) { |
| 79 | + warnings.push({ |
| 80 | + type: 'unsupported-setting', |
| 81 | + setting: 'seed', |
| 82 | + }); |
| 83 | + } |
| 84 | + |
| 85 | + const { system, messages } = await convertToBedrockChatMessages({ prompt }); |
| 86 | + |
| 87 | + const baseArgs: ConverseCommandInput = { |
| 88 | + modelId: this.modelId, |
| 89 | + system: system ? [{ text: system }] : undefined, |
| 90 | + additionalModelRequestFields: this.settings.additionalModelRequestFields, |
| 91 | + inferenceConfig: { |
| 92 | + maxTokens, |
| 93 | + temperature, |
| 94 | + topP, |
| 95 | + }, |
| 96 | + messages, |
| 97 | + }; |
| 98 | + |
| 99 | + switch (type) { |
| 100 | + case 'regular': { |
| 101 | + const toolConfig = prepareToolsAndToolChoice(mode); |
| 102 | + |
| 103 | + return { |
| 104 | + ...baseArgs, |
| 105 | + ...(toolConfig.tools?.length ? { toolConfig } : {}), |
| 106 | + } satisfies ConverseCommandInput; |
| 107 | + } |
| 108 | + |
| 109 | + case 'object-json': { |
| 110 | + throw new UnsupportedFunctionalityError({ |
| 111 | + functionality: 'json-mode object generation', |
| 112 | + }); |
| 113 | + } |
| 114 | + |
| 115 | + case 'object-tool': { |
| 116 | + return { |
| 117 | + ...baseArgs, |
| 118 | + toolConfig: { |
| 119 | + tools: [ |
| 120 | + { |
| 121 | + toolSpec: { |
| 122 | + name: mode.tool.name, |
| 123 | + description: mode.tool.description, |
| 124 | + inputSchema: { json: JSON.stringify(mode.tool.parameters) }, |
| 125 | + }, |
| 126 | + }, |
| 127 | + ], |
| 128 | + toolChoice: { tool: { name: mode.tool.name } }, |
| 129 | + }, |
| 130 | + } satisfies ConverseCommandInput; |
| 131 | + } |
| 132 | + |
| 133 | + case 'object-grammar': { |
| 134 | + throw new UnsupportedFunctionalityError({ |
| 135 | + functionality: 'grammar-mode object generation', |
| 136 | + }); |
| 137 | + } |
| 138 | + |
| 139 | + default: { |
| 140 | + const _exhaustiveCheck: never = type; |
| 141 | + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); |
| 142 | + } |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + async doGenerate( |
| 147 | + options: Parameters<LanguageModelV1['doGenerate']>[0], |
| 148 | + ): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>> { |
| 149 | + const args = await this.getArgs(options); |
| 150 | + |
| 151 | + const response = await this.config.client.send(new ConverseCommand(args)); |
| 152 | + |
| 153 | + const { messages: rawPrompt, ...rawSettings } = args; |
| 154 | + |
| 155 | + return { |
| 156 | + text: |
| 157 | + response.output?.message?.content |
| 158 | + ?.map(part => part.text ?? '') |
| 159 | + .join('') ?? undefined, |
| 160 | + toolCalls: response.output?.message?.content |
| 161 | + ?.filter(part => !!part.toolUse) |
| 162 | + ?.map(part => ({ |
| 163 | + toolCallType: 'function', |
| 164 | + toolCallId: part.toolUse?.toolUseId ?? this.config.generateId(), |
| 165 | + toolName: part.toolUse?.name ?? `tool-${this.config.generateId()}`, |
| 166 | + args: JSON.stringify(part.toolUse?.input ?? ''), |
| 167 | + })), |
| 168 | + finishReason: mapBedrockFinishReason(response.stopReason), |
| 169 | + usage: { |
| 170 | + promptTokens: response.usage?.inputTokens ?? Number.NaN, |
| 171 | + completionTokens: response.usage?.outputTokens ?? Number.NaN, |
| 172 | + }, |
| 173 | + rawCall: { rawPrompt, rawSettings }, |
| 174 | + warnings: [], |
| 175 | + }; |
| 176 | + } |
| 177 | + |
| 178 | + async doStream( |
| 179 | + options: Parameters<LanguageModelV1['doStream']>[0], |
| 180 | + ): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>> { |
| 181 | + const args = await this.getArgs(options); |
| 182 | + |
| 183 | + const response = await this.config.client.send( |
| 184 | + new ConverseStreamCommand({ ...args }), |
| 185 | + ); |
| 186 | + |
| 187 | + const { messages: rawPrompt, ...rawSettings } = args; |
| 188 | + |
| 189 | + let finishReason: LanguageModelV1FinishReason = 'other'; |
| 190 | + let usage: { promptTokens: number; completionTokens: number } = { |
| 191 | + promptTokens: Number.NaN, |
| 192 | + completionTokens: Number.NaN, |
| 193 | + }; |
| 194 | + |
| 195 | + if (!response.stream) { |
| 196 | + throw new Error('No stream found'); |
| 197 | + } |
| 198 | + |
| 199 | + const stream = new ReadableStream<any>({ |
| 200 | + async start(controller) { |
| 201 | + for await (const chunk of response.stream!) { |
| 202 | + controller.enqueue({ success: true, value: chunk }); |
| 203 | + } |
| 204 | + controller.close(); |
| 205 | + }, |
| 206 | + }); |
| 207 | + |
| 208 | + let toolName = ''; |
| 209 | + let toolCallId = ''; |
| 210 | + let toolCallArgs = ''; |
| 211 | + |
| 212 | + return { |
| 213 | + stream: stream.pipeThrough( |
| 214 | + new TransformStream< |
| 215 | + ParseResult<ConverseStreamOutput>, |
| 216 | + LanguageModelV1StreamPart |
| 217 | + >({ |
| 218 | + transform(chunk, controller) { |
| 219 | + function enqueueError(error: Error) { |
| 220 | + finishReason = 'error'; |
| 221 | + controller.enqueue({ type: 'error', error }); |
| 222 | + } |
| 223 | + |
| 224 | + // handle failed chunk parsing / validation: |
| 225 | + if (!chunk.success) { |
| 226 | + enqueueError(chunk.error); |
| 227 | + return; |
| 228 | + } |
| 229 | + |
| 230 | + const value = chunk.value; |
| 231 | + |
| 232 | + // handle errors: |
| 233 | + if (value.internalServerException) { |
| 234 | + enqueueError(value.internalServerException); |
| 235 | + return; |
| 236 | + } |
| 237 | + if (value.modelStreamErrorException) { |
| 238 | + enqueueError(value.modelStreamErrorException); |
| 239 | + return; |
| 240 | + } |
| 241 | + if (value.throttlingException) { |
| 242 | + enqueueError(value.throttlingException); |
| 243 | + return; |
| 244 | + } |
| 245 | + if (value.validationException) { |
| 246 | + enqueueError(value.validationException); |
| 247 | + return; |
| 248 | + } |
| 249 | + |
| 250 | + if (value.messageStop) { |
| 251 | + finishReason = mapBedrockFinishReason( |
| 252 | + value.messageStop.stopReason, |
| 253 | + ); |
| 254 | + } |
| 255 | + |
| 256 | + if (value.metadata) { |
| 257 | + usage = { |
| 258 | + promptTokens: value.metadata.usage?.inputTokens ?? Number.NaN, |
| 259 | + completionTokens: |
| 260 | + value.metadata.usage?.outputTokens ?? Number.NaN, |
| 261 | + }; |
| 262 | + } |
| 263 | + |
| 264 | + if (value.contentBlockDelta?.delta?.text) { |
| 265 | + controller.enqueue({ |
| 266 | + type: 'text-delta', |
| 267 | + textDelta: value.contentBlockDelta.delta.text, |
| 268 | + }); |
| 269 | + } |
| 270 | + |
| 271 | + if (value.contentBlockStart?.start?.toolUse) { |
| 272 | + // store the tool name and id for the next chunk |
| 273 | + const toolUse = value.contentBlockStart.start.toolUse; |
| 274 | + toolName = toolUse.name ?? ''; |
| 275 | + toolCallId = toolUse.toolUseId ?? ''; |
| 276 | + } |
| 277 | + |
| 278 | + if (value.contentBlockDelta?.delta?.toolUse) { |
| 279 | + // continue to get the chunks of the tool call args |
| 280 | + toolCallArgs += value.contentBlockDelta.delta.toolUse.input ?? ''; |
| 281 | + |
| 282 | + controller.enqueue({ |
| 283 | + type: 'tool-call-delta', |
| 284 | + toolCallType: 'function', |
| 285 | + toolCallId, |
| 286 | + toolName, |
| 287 | + argsTextDelta: |
| 288 | + value.contentBlockDelta.delta.toolUse.input ?? '', |
| 289 | + }); |
| 290 | + } |
| 291 | + |
| 292 | + // if the content is done and a tool call was made, send it |
| 293 | + if (value.contentBlockStop && toolCallArgs.length > 0) { |
| 294 | + controller.enqueue({ |
| 295 | + type: 'tool-call', |
| 296 | + toolCallType: 'function', |
| 297 | + toolCallId, |
| 298 | + toolName, |
| 299 | + args: toolCallArgs, |
| 300 | + }); |
| 301 | + } |
| 302 | + }, |
| 303 | + |
| 304 | + flush(controller) { |
| 305 | + controller.enqueue({ |
| 306 | + type: 'finish', |
| 307 | + finishReason, |
| 308 | + usage, |
| 309 | + }); |
| 310 | + }, |
| 311 | + }), |
| 312 | + ), |
| 313 | + rawCall: { rawPrompt, rawSettings }, |
| 314 | + warnings: [], |
| 315 | + }; |
| 316 | + } |
| 317 | +} |
| 318 | + |
| 319 | +function prepareToolsAndToolChoice( |
| 320 | + mode: Parameters<LanguageModelV1['doGenerate']>[0]['mode'] & { |
| 321 | + type: 'regular'; |
| 322 | + }, |
| 323 | +): ToolConfiguration { |
| 324 | + // when the tools array is empty, change it to undefined to prevent errors: |
| 325 | + const tools = mode.tools?.length ? mode.tools : undefined; |
| 326 | + |
| 327 | + if (tools == null) { |
| 328 | + return { tools: undefined, toolChoice: undefined }; |
| 329 | + } |
| 330 | + |
| 331 | + const mappedTools: Tool[] = tools.map(tool => ({ |
| 332 | + toolSpec: { |
| 333 | + name: tool.name, |
| 334 | + description: tool.description, |
| 335 | + inputSchema: { |
| 336 | + json: tool.parameters as any, |
| 337 | + }, |
| 338 | + }, |
| 339 | + })); |
| 340 | + |
| 341 | + const toolChoice = mode.toolChoice; |
| 342 | + |
| 343 | + if (toolChoice == null) { |
| 344 | + return { tools: mappedTools, toolChoice: undefined }; |
| 345 | + } |
| 346 | + |
| 347 | + const type = toolChoice.type; |
| 348 | + |
| 349 | + switch (type) { |
| 350 | + case 'auto': |
| 351 | + return { tools: mappedTools, toolChoice: { auto: {} } }; |
| 352 | + case 'required': |
| 353 | + return { tools: mappedTools, toolChoice: { any: {} } }; |
| 354 | + case 'none': |
| 355 | + // Bedrock does not support 'none' tool choice, so we remove the tools: |
| 356 | + return { tools: undefined, toolChoice: undefined }; |
| 357 | + case 'tool': |
| 358 | + return { |
| 359 | + tools: mappedTools, |
| 360 | + toolChoice: { tool: { name: toolChoice.toolName } }, |
| 361 | + }; |
| 362 | + default: { |
| 363 | + const _exhaustiveCheck: never = type; |
| 364 | + throw new Error(`Unsupported tool choice type: ${_exhaustiveCheck}`); |
| 365 | + } |
| 366 | + } |
| 367 | +} |
0 commit comments