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

amazon-bedrock.ts

139 lines4.9 KB

1/**
2 * Amazon Bedrock — first-party only (issue #153). Models come from the user
3 * guide's model cards; the runtime schema (Converse, ConverseStream,
4 * InvokeModel, InvokeModelWithResponseStream) is generated from the AWS
5 * SDK's Bedrock Runtime service model. Neither needs AWS credentials
6 * (ListFoundationModels does), and no aggregator is read.
7 */
8import type { Activity } from '#/db/schema.ts'
9​
10import { BEDROCK_CARDS_URL, bedrockCardListing } from '../bedrock-cards.ts'
11import {
12 BEDROCK_RUNTIME_PATHS,
13 BEDROCK_SDK_MODEL_URL,
14 bedrockConverseSpec,
15} from '../bedrock-sdk-spec.ts'
16import type { BedrockServiceModel } from '../bedrock-sdk-spec.ts'
17import { loadBedrockConverseWireMaps } from '../bedrock-converse-facts.ts'
18import { loadBedrockThinkingGuides } from '../bedrock-thinking-guides.ts'
19import { docsRun, docsReport } from '../model-facts.ts'
20import { fetchText, sha256Text } from '../types.ts'
21import type {
22 ListModelsResult,
23 ProviderConfig,
24 ProviderSecrets,
25 SpecFetchResult,
26 UpstreamModelIdentity,
27} from '../types.ts'
28​
29/** The geography a card's inference-profile id starts with (`us.`, `global.`). */
30const PROFILE_GEO = /^(?:us|us-gov|eu|apac|au|ca|jp|in|global)\./
31/**
32 * Bedrock's own version on a model id: `-v1:0`, `-v1`, `-1:0`, then any
33 * remaining `:N`. Only version 1 is read as Bedrock's: a maker's own
34 * `-v4` (`cohere.embed-v4:0`) or `-v2` (`luma.ray-v2:0`) stays in the id.
35 */
36const BEDROCK_VERSION = /(?:-v1(?::\d+)?|-1:\d+|:\d+)$/
37​
38/**
39 * `us.anthropic.claude-opus-4-5-20251101-v1:0` → anthropic /
40 * `claude-opus-4-5-20251101`. The card's model id names the maker before
41 * the first dot; a profile id is that model id behind a geography. An
42 * `amazon.` id is Bedrock's own model (Nova, Titan): no other host to name.
43 */
44function bedrockUpstreamIdentity(rawId: string): UpstreamModelIdentity | null {
45 const match = rawId.replace(PROFILE_GEO, '').match(/^([a-z0-9-]+)\.(.+)$/)
46 if (!match?.[1] || !match[2] || match[1] === 'amazon') return null
47 // A model part that still opens with `maker.` means the first segment was a
48 // geography this rule does not know (`me.anthropic.…`): state nothing.
49 // Every dot inside a listed model name is followed by a digit (`grok-4.7`).
50 if (/^[a-z][a-z0-9-]*\.[a-z]/.test(match[2])) return null
51 const upstreamId = match[2].replace(BEDROCK_VERSION, '')
52 return upstreamId
53 ? {
54 providerNamespace: match[1],
55 rawId: upstreamId,
56 source: {
57 derivation: 'docs-derived',
58 sourceUrl: BEDROCK_CARDS_URL,
59 path: 'Programmatic Access: Model ID',
60 },
61 }
62 : null
64​
65async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
66 const text = await fetchText(BEDROCK_SDK_MODEL_URL)
67 const hash = await sha256Text(text)
68 return {
69 specs: [bedrockConverseSpec(JSON.parse(text) as BedrockServiceModel)],
70 sources: [{ url: BEDROCK_SDK_MODEL_URL, hash }],
71 outputStrategy: 'post-200',
72 specRevision: hash,
73 }
75​
76async function listModels(
77 _env: ProviderSecrets,
78 kv?: KVNamespace,
79): Promise<ListModelsResult> {
80 const catalog = await bedrockCardListing(kv)
81 const run = docsRun()
82 const thinking = await loadBedrockThinkingGuides(
83 catalog.models,
84 catalog.groups,
85 run,
86 kv,
87 )
88 const models = await loadBedrockConverseWireMaps(thinking, run, kv)
89 return { models, docsFailures: docsReport(run) }
91​
92export const provider: ProviderConfig = {
93 id: 'amazon-bedrock',
94 // LLM Gateway route name (providers[].providerId).
95 modelNamespaces: ['aws-bedrock'],
96 upstreamModelIdentity: bedrockUpstreamIdentity,
97 displayName: 'Amazon Bedrock',
98 specSourceUrl: BEDROCK_SDK_MODEL_URL,
99 modelsEndpoint: BEDROCK_CARDS_URL,
100 defaultDerivation: 'generated',
101 // Converse is an AWS API: requests are SigV4-signed (service `bedrock`).
102 // A Bedrock API key (`AWS_BEARER_TOKEN_BEDROCK`) is the stated alternative.
103 connect: {
104 servers: [
105 {
106 url: 'https://bedrock-runtime.{region}.amazonaws.com',
107 variables: {
108 region: {
109 default: 'us-east-1',
110 description: 'The AWS Region you call.',
111 },
112 },
113 },
114 ],
115 securitySchemes: {
116 sigv4: {
117 type: 'apiKey',
118 in: 'header',
119 name: 'Authorization',
120 'x-amazon-apigateway-authtype': 'awsSigv4',
121 description:
122 'AWS Signature Version 4 with service `bedrock` and the Region in the URL; a generated HTTP client cannot sign this itself, so route through an AWS SDK or a SigV4 signer.',
123 },
124 bearerAuth: {
125 type: 'http',
126 scheme: 'bearer',
127 description:
128 'A Bedrock API key (`AWS_BEARER_TOKEN_BEDROCK`) as `Authorization: Bearer <key>`.',
129 },
130 },
131 security: [{ sigv4: [] }, { bearerAuth: [] }],
132 },
133 fetchSpec,
134 listModels,
135 classify: (path): Activity | null =>
136 (BEDROCK_RUNTIME_PATHS as ReadonlyArray<string>).includes(path)
137 ? 'chat'
138 : null,