Open History to see the last commit
1/**
2 * Bedrock Runtime as OpenAPI (issues #153, #619). AWS publishes no OpenAPI
3 * document, so the spec is generated at sync time from the service model the
4 * AWS SDK for Python ships (botocore `service-2.json`): every shape becomes a
5 * component schema. The generation paths are Converse, ConverseStream,
6 * InvokeModel, and InvokeModelWithResponseStream.
7 *
8 * An event stream (`eventstream`) is one event per message: the response
9 * media type is `application/vnd.amazon.eventstream` and the schema allows
10 * exactly one member. InvokeModel's HTTP payload is a blob, which on the
11 * wire is the model's own JSON document, not a base64 structure member.
12 */
13import { BEDROCK_CONVERSE_PATH } from './bedrock-cards.ts'
14import { PROVENANCE_MARKER } from './types.ts'
15import type { OpenApiDocument } from './types.ts'
16
17/** Paths `GET /v1/openapi/amazon-bedrock` must publish. */
18export const BEDROCK_RUNTIME_PATHS = [
19 BEDROCK_CONVERSE_PATH,
20 '/model/{modelId}/converse-stream',
21 '/model/{modelId}/invoke',
22 '/model/{modelId}/invoke-with-response-stream',
23] as const
24
25const EVENT_STREAM = 'application/vnd.amazon.eventstream'
26
27export const BEDROCK_SDK_MODEL_URL =
28 'https://raw.githubusercontent.com/boto/botocore/develop/botocore/data/bedrock-runtime/2023-09-30/service-2.json'
29
30const REF = '#/components/schemas/'
31
32interface Member {
33 shape: string
34 documentation?: string
35 /** `uri` / `header` / `querystring`: not part of the JSON body. */
36 location?: string
37 /** Wire name when it differs from the member name. */
38 locationName?: string
39}
40
41interface Shape {
42 type: string
43 members?: Record<string, Member>
44 required?: Array<string>
45 member?: Member
46 value?: Member
47 enum?: Array<string>
48 min?: number
49 max?: number
50 documentation?: string
51 /** Tagged union: exactly one member is set. */
52 union?: boolean
53 /** Event stream: each message sets exactly one member. */
54 eventstream?: boolean
55 /** HTTP body is this member, not the structure. */
56 payload?: string
57 /** Free-form JSON value. */
58 document?: boolean
59 exception?: boolean
60}
61
62export interface BedrockServiceModel {
63 operations: Record<
64 string,
65 {
66 http: { method: string; requestUri: string }
67 input?: { shape: string }
68 output?: { shape: string }
69 documentation?: string
70 }
71 >
72 shapes: Record<string, Shape>
73}
74
75type Schema = Record<string, unknown>
76
77function prose(html: string | undefined): string | undefined {
78 const text = html
79 ?.replace(/<[^>]+>/g, ' ')
80 .replace(/\s+/g, ' ')
81 .trim()
82 return text === '' ? undefined : text
83}
84
85function described(schema: Schema, html: string | undefined): Schema {
86 const description = prose(html)
87 return description ? { ...schema, description } : schema
88}
89
90const ref = (member: Member): Schema =>
91 described({ $ref: REF + member.shape }, member.documentation)
92
93function range(shape: Shape, min: string, max: string): Schema {
94 return {
95 ...(shape.min !== undefined ? { [min]: shape.min } : {}),
96 ...(shape.max !== undefined ? { [max]: shape.max } : {}),
97 }
98}
99
100function shapeSchema(shape: Shape): Schema {
101 switch (shape.type) {
102 case 'structure': {
103 if (shape.document) return {}
104 const body = Object.entries(shape.members ?? {}).filter(
105 ([, member]) => member.location === undefined,
106 )
107 const required = (shape.required ?? []).filter((name) =>
108 body.some(([key]) => key === name),
109 )
110 return {
111 type: 'object',
112 properties: Object.fromEntries(
113 body.map(([name, member]) => [name, ref(member)]),
114 ),
115 ...(required.length > 0 ? { required } : {}),
116 ...(shape.union || shape.eventstream
117 ? { minProperties: 1, maxProperties: 1 }
118 : {}),
119 }
120 }
121 case 'list':
122 return {
123 type: 'array',
124 ...(shape.member ? { items: ref(shape.member) } : {}),
125 ...range(shape, 'minItems', 'maxItems'),
126 }
127 case 'map':
128 return {
129 type: 'object',
130 ...(shape.value ? { additionalProperties: ref(shape.value) } : {}),
131 }
132 case 'string':
133 // `pattern` is dropped: the SDK's regexes are not all ECMAScript.
134 return {
135 type: 'string',
136 ...(shape.enum ? { enum: shape.enum } : {}),
137 ...range(shape, 'minLength', 'maxLength'),
138 }
139 case 'blob':
140 return { type: 'string', contentEncoding: 'base64' }
141 case 'integer':
142 case 'long':
143 return { type: 'integer', ...range(shape, 'minimum', 'maximum') }
144 case 'float':
145 case 'double':
146 return { type: 'number', ...range(shape, 'minimum', 'maximum') }
147 case 'boolean':
148 return { type: 'boolean' }
149 case 'timestamp':
150 return { type: 'string', format: 'date-time' }
151 default:
152 throw new Error(`amazon-bedrock SDK model: shape type "${shape.type}"`)
153 }
154}
155
156interface HttpBody {
157 schema: Schema
158 mediaType: string
159 required: boolean
160}
161
162function mustShape(model: BedrockServiceModel, name: string): Shape {
163 const shape = model.shapes[name]
164 if (!shape)
165 throw new Error(`amazon-bedrock SDK model: missing shape "${name}"`)
166 return shape
167}
168
169/**
170 * Shapes to publish. Exception shapes stay out unless an emitted shape
171 * points at them (event-stream errors). A missing target throws.
172 */
173function publishedShapes(model: BedrockServiceModel): Set<string> {
174 const seen = new Set<string>()
175 const visit = (name: string) => {
176 if (seen.has(name)) return
177 const shape = mustShape(model, name)
178 seen.add(name)
179 for (const member of Object.values(shape.members ?? {})) visit(member.shape)
180 if (shape.member) visit(shape.member.shape)
181 if (shape.value) visit(shape.value.shape)
182 }
183 for (const [name, shape] of Object.entries(model.shapes)) {
184 if (!shape.exception) visit(name)
185 }
186 return seen
187}
188
189/** Path and header members. The JSON body schema already omits them. */
190function parameters(shape: Shape): Array<Schema> {
191 const params: Array<Schema> = []
192 for (const [name, member] of Object.entries(shape.members ?? {})) {
193 if (member.location !== 'uri' && member.location !== 'header') continue
194 params.push(
195 described(
196 {
197 name: member.locationName ?? name,
198 in: member.location === 'uri' ? 'path' : 'header',
199 required:
200 member.location === 'uri' || (shape.required ?? []).includes(name),
201 schema:
202 member.location === 'uri'
203 ? { type: 'string' }
204 : { $ref: REF + member.shape },
205 },
206 member.location === 'header' ? member.documentation : undefined,
207 ),
208 )
209 }
210 return params
211}
212
213/**
214 * HTTP body for one input or output structure. `@httpPayload` replaces the
215 * structure. A payload blob is the raw JSON document; a payload event
216 * stream is the event union, not `{ stream: ... }`.
217 */
218function httpBody(model: BedrockServiceModel, shapeName: string): HttpBody {
219 const shape = mustShape(model, shapeName)
220 if (shape.type !== 'structure') {
221 throw new Error(
222 `amazon-bedrock SDK model: "${shapeName}" is not a structure`,
223 )
224 }
225 const payloadName = shape.payload
226 if (!payloadName) {
227 const required = (shape.required ?? []).some(
228 (name) => shape.members?.[name]?.location === undefined,
229 )
230 return {
231 schema: { $ref: REF + shapeName },
232 mediaType: 'application/json',
233 required,
234 }
235 }
236 const member = shape.members?.[payloadName]
237 if (!member) {
238 throw new Error(
239 `amazon-bedrock SDK model: "${shapeName}" payload "${payloadName}" is missing`,
240 )
241 }
242 const target = mustShape(model, member.shape)
243 const required = (shape.required ?? []).includes(payloadName)
244 if (target.eventstream) {
245 return {
246 schema: { $ref: REF + member.shape },
247 mediaType: EVENT_STREAM,
248 required,
249 }
250 }
251 if (target.type === 'blob') {
252 return {
253 schema: described({}, member.documentation),
254 mediaType: 'application/json',
255 required,
256 }
257 }
258 return { schema: ref(member), mediaType: 'application/json', required }
259}
260
261/** The SDK service model → an OpenAPI document for the runtime paths. */
262export function bedrockConverseSpec(
263 model: BedrockServiceModel,
264): OpenApiDocument {
265 const published = publishedShapes(model)
266 const paths: NonNullable<OpenApiDocument['paths']> = {}
267 for (const uri of BEDROCK_RUNTIME_PATHS) {
268 const found = Object.entries(model.operations).filter(
269 ([, op]) => op.http.requestUri === uri,
270 )
271 const entry = found[0]
272 if (found.length !== 1 || !entry) {
273 throw new Error(`amazon-bedrock SDK model: no ${uri} operation`)
274 }
275 const [operationId, operation] = entry
276 if (
277 operation.http.method !== 'POST' ||
278 !operation.input ||
279 !operation.output
280 ) {
281 throw new Error(
282 `amazon-bedrock SDK model: ${uri} is not a POST with a body`,
283 )
284 }
285 const inputShape = mustShape(model, operation.input.shape)
286 const input = httpBody(model, operation.input.shape)
287 const output = httpBody(model, operation.output.shape)
288 paths[uri] = {
289 post: {
290 operationId,
291 ...described({}, operation.documentation),
292 [PROVENANCE_MARKER]: { derivation: 'generated' },
293 parameters: parameters(inputShape),
294 requestBody: {
295 required: input.required,
296 content: { [input.mediaType]: { schema: input.schema } },
297 },
298 responses: {
299 '200': {
300 description: 'OK',
301 content: { [output.mediaType]: { schema: output.schema } },
302 },
303 },
304 },
305 }
306 }
307 return {
308 openapi: '3.1.0',
309 info: { title: 'Amazon Bedrock Runtime', version: '2023-09-30' },
310 paths,
311 components: {
312 schemas: Object.fromEntries(
313 Object.entries(model.shapes)
314 .filter(([name]) => published.has(name))
315 .map(([name, shape]) => [
316 name,
317 described(shapeSchema(shape), shape.documentation),
318 ]),
319 ),
320 },
321 }
322}