Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

text.ts

133 lines4.9 KB

1import OpenAI from 'openai'
2import { OpenAIBaseChatCompletionsTextAdapter } from '@tanstack/openai-base'
3import {
4 isBedrockOpenAIContextOverflow,
5 withBedrockDefaults,
6} from '../utils/client'
7import {
8 BEDROCK_MODEL_INPUT_MODALITIES,
9 BEDROCK_MODEL_REASONING,
10} from '../model-meta'
11import type { Modality } from '@tanstack/ai'
12import type { BedrockClientConfig } from '../utils/client'
13import type { BedrockMessageMetadataByModality } from '../message-types'
14import type {
15 BedrockChatModels,
16 BedrockChatModelToolCapabilitiesByName,
17 BedrockModelReasoningByName,
18 ResolveInputModalities,
19 ResolveProviderOptions,
20} from '../model-meta'
21import type { OpenAIBaseTextAdapterOptions } from '@tanstack/openai-base'
22​
23export interface BedrockTextConfig
24 extends BedrockClientConfig, OpenAIBaseTextAdapterOptions {}
25​
26export type { ExternalTextProviderOptions as BedrockTextProviderOptions } from '../text/text-provider-options'
27​
28/** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */
29type ResolveReasoning<TModel extends string> =
30 TModel extends keyof BedrockModelReasoningByName
31 ? BedrockModelReasoningByName[TModel]
32 : never
33​
34type ResolveToolCapabilities<TModel extends string> =
35 TModel extends keyof BedrockChatModelToolCapabilitiesByName
36 ? NonNullable<BedrockChatModelToolCapabilitiesByName[TModel]>
37 : readonly []
38​
39/**
40 * Bedrock Chat Completions adapter. Drives Bedrock's OpenAI-compatible
41 * `/chat/completions` endpoint via the OpenAI SDK with a baseURL override
42 * (same pattern as ai-groq). Tool conversion, streaming, structured output,
43 * and the agent loop come from the base.
44 */
45export class BedrockTextAdapter<
46 TModel extends BedrockChatModels,
47 // Constraint mirrors ai-groq and the base, which parameterises
48 // `TProviderOptions extends Record<string, any>`. Our default
49 // `ResolveProviderOptions<TModel>` resolves to the `BedrockTextProviderOptions`
50 // interface, which (lacking an implicit index signature) `Record<string,
51 // unknown>` would reject but `Record<string, any>` accepts. This `any` is
52 // confined to the generic constraint (the established ai-groq pattern) — no
53 // value/shape `as` cast is introduced.
54 TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,
55 TInputModalities extends ReadonlyArray<Modality> =
56 ResolveInputModalities<TModel>,
57 TToolCapabilities extends ReadonlyArray<string> =
58 ResolveToolCapabilities<TModel>,
59> extends OpenAIBaseChatCompletionsTextAdapter<
60 TModel,
61 TProviderOptions,
62 TInputModalities,
63 BedrockMessageMetadataByModality,
64 TToolCapabilities,
65 ResolveReasoning<TModel>
66> {
67 override readonly kind = 'text' as const
68 override readonly name = 'bedrock' as const
69 override readonly provider = 'amazon-bedrock'
70 override readonly inputModalities = BEDROCK_MODEL_INPUT_MODALITIES[this.model]
71​
72 constructor(config: BedrockTextConfig, model: TModel) {
73 // No `forced` -> honors config.endpoint ('runtime' default, 'mantle' allowed).
74 const options = withBedrockDefaults(config, undefined, model)
75 super(model, 'bedrock', new OpenAI(options), {
76 ...config,
77 fetch: options.fetch,
78 })
79 }
80​
81 protected override isContextOverflow(error: {
82 message: string
83 code: string | undefined
84 }): boolean {
85 return (
86 super.isContextOverflow(error) || isBedrockOpenAIContextOverflow(error)
87 )
88 }
89​
90 protected override modelReasoning(model: string) {
91 return BEDROCK_MODEL_REASONING[model]
92 }
93​
94 /**
95 * Surface reasoning deltas (gpt-oss / Claude reasoning) the OpenAI-compatible
96 * way. Base types the chunk as `unknown`; narrow with runtime guards — no
97 * `as` casts, no `any`.
98 */
99 protected override extractReasoning(
100 chunk: unknown,
101 ): { text: string } | undefined {
102 return readDeltaReasoning(chunk)
103 }
105​
106/** Cast-free narrowing of a Chat Completions chunk's reasoning delta. */
107function readDeltaReasoning(chunk: unknown): { text: string } | undefined {
108 if (typeof chunk !== 'object' || chunk === null || !('choices' in chunk))
109 return undefined
110 if (!Array.isArray(chunk.choices)) return undefined
111 const choice: unknown = chunk.choices[0]
112 if (typeof choice !== 'object' || choice === null || !('delta' in choice))
113 return undefined
114 const delta = choice.delta
115 if (typeof delta !== 'object' || delta === null) return undefined
116 const raw =
117 'reasoning' in delta && typeof delta.reasoning === 'string'
118 ? delta.reasoning
119 : 'reasoning_content' in delta &&
120 typeof delta.reasoning_content === 'string'
121 ? delta.reasoning_content
122 : undefined
123 return raw && raw.length > 0 ? { text: raw } : undefined
125​
126/** Chat adapter with an explicit API key (low-level; the public branching factory delegates here). */
127export function createBedrockChat<TModel extends BedrockChatModels>(
128 model: TModel,
129 apiKey: string,
130 config?: Omit<BedrockTextConfig, 'apiKey'>,
131): BedrockTextAdapter<TModel> {
132 return new BedrockTextAdapter({ ...config, apiKey }, model)