This repository was archived by the owner on Jan 6, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathOpenAiComposer.ts
366 lines (354 loc) · 12.7 KB
/
OpenAiComposer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import {
IMigrateDocument,
IMigrateRoute,
OpenApi,
OpenApiV3,
OpenApiV3_1,
SwaggerV2,
} from "@samchon/openapi";
import { OpenApiTypeChecker } from "@samchon/openapi/lib/internal/OpenApiTypeChecker";
import { OpenApiV3Downgrader } from "@samchon/openapi/lib/internal/OpenApiV3Downgrader";
import typia from "typia";
import { OpenAiSchemaSeparator } from "./internal/OpenAiSchemaSeparator";
import { IOpenAiSchema, ISwaggerOperation, OpenAiTypeChecker } from "./module";
import { IOpenAiDocument } from "./structures/IOpenAiDocument";
import { IOpenAiFunction } from "./structures/IOpenAiFunction";
import { ISwagger } from "./structures/ISwagger";
import { ISwaggerMigrate } from "./structures/ISwaggerMigrate";
/**
* OpenAI Document Composer.
*
* `OpenAiComposer` is a module for composing OpenAI function call schemas from
* Swagger (OpenAPI) document. The composed OpenAI document can be utilized for
* executing the actual function call with {@link OpenAiFetcher}.
*
* Also, if you've configured the {@link IOpenAiDocument.IOptions.separate}
* option, then the function call schemas would be separated into two parts;
* LLM (Large Language Model) and human. In that case, you can combine both
* LLM and human composed arguments into one by utilizing
* {@link OpenAiDataCombiner.parameters} function.
*
* Additionall, if you've configured the {@link IOpenAiDocument.IOptions.keyword}
* option, then the number of parameters in every function schemas would be only
* one, by wrapping all parameters into a single object. However, do not worry.
* {@link OpenAiFetcher} will automatically unwrap the object and pass the
* parameters to the actual function call.
*
* @author Samchon
*/
export namespace OpenAiComposer {
/**
* Properties of {@link document} function.
*/
export interface IProps {
/**
* Input Swagger (OpenAPI) document.
*
* No matter how the version of OpenAPI is, `OpenAiComposer` supports
* every versions of the OpenAPI (Swagger) document.
*/
swagger:
| ISwagger
| SwaggerV2.IDocument
| OpenApiV3.IDocument
| OpenApiV3_1.IDocument;
/**
* Options for composing the OpenAI function call schema document.
*/
options?: Partial<IOpenAiDocument.IOptions>;
/**
* Migrate document from Swagger.
*
* If you've already migrated from the Swagger document, you can re-use it.
*/
migrate?: ISwaggerMigrate;
}
/**
* Compose OpenAI document of function call schemas.
*
* Composes {@link IOpenAiDocument} from OpenAPI (or Swagger) document. In
* the composed OpenAI document, you can find the function call schemas
* which can be utilized for executing the actual function call with
* {@link OpenAiFetcher}.
*
* Also, if you've configured the {@link IOpenAiDocument.IOptions.separate}
* option, then the function call schemas would be separated into two parts;
* LLM (Large Language Model) and human. In that case, you can combine both
* LLM and human composed arguments into one by utilizing
* {@link OpenAiDataCombiner.parameters} function.
*
* Additionall, if you've configured the {@link IOpenAiDocument.IOptions.keyword}
* option, then the number of parameters in every function schemas would be only
* one, by wrapping all parameters into a single object. However, do not worry.
* {@link OpenAiFetcher} will automatically unwrap the object and pass the
* parameters to the actual function call.
*
* @param props Properties for composing the OpenAI document.
* @returns Composed OpenAI document.
*/
export const document = (props: IProps): IOpenAiDocument => {
// LIST UP ARGUMENTS
typia.assert(props);
const swagger: ISwagger = OpenApi.convert(props.swagger);
const options: IOpenAiDocument.IOptions = {
keyword: props.options?.keyword ?? false,
separate: props.options?.separate ?? null,
};
// MIGRATE FROM SWAGGER
const migrate: IMigrateDocument = props.migrate
? props.migrate
: OpenApi.migrate(swagger);
// COMPOSE FUNCTIONS
const errors: IOpenAiDocument.IError[] = migrate.errors.map((e) => ({
method: e.method,
path: e.path,
messages: e.messages,
operation: () => e.operation(),
route: () => undefined,
}));
const functions: IOpenAiFunction[] = migrate.routes
.map((route) => {
if (route.method === "head") return null;
const func: IOpenAiFunction | null = composeFunction(options)(
swagger.components,
)(route);
if (func === null)
errors.push({
method: route.method,
path: route.path,
messages: ["Failed to escape $ref"],
operation: () => route.operation(),
route: () => route,
});
return func;
})
.filter((v): v is IOpenAiFunction => v !== null);
return {
openapi: "3.0.3",
version: swagger.info?.version,
functions,
errors,
options,
};
};
/**
* Convert JSON schema to OpenAI schema.
*
* Converts JSON schema to OpenAI schema, which escapes `$ref` and downgrades
* the schema to the OpenAPI v3 specification. The reason why of escaping `$ref`
* and downgrading the OpenAPI version is that, OpenAI cannot understand both
* `$ref` and OpenAPI v3.1 specification.
*
* For reference, if your Swagger document containg the JSON schema is not the
* spec of OpenAPI v3. emended1, you can pre-convert it to OpenAPI v3.1 emended
* by utilizing the {@link OpenApi.convert} function.
*
* @param components Reusable components of Swagger document
* @param schema JSON schema to be converted
* @returns OpenAI schema if succeeded, otherwise `null`
*/
export const schema = (
components: OpenApi.IComponents,
schema: OpenApi.IJsonSchema,
): IOpenAiSchema | null => {
const escaped: OpenApi.IJsonSchema | null = escapeReference(components)(
new Set(),
)(schema);
if (escaped === null) return null;
const downgraded: IOpenAiSchema = OpenApiV3Downgrader.downgradeSchema({
original: {},
downgraded: {},
})(escaped) as IOpenAiSchema;
OpenAiTypeChecker.visit(downgraded, (schema) => {
if (
OpenAiTypeChecker.isOneOf(schema) &&
(schema as any).discriminator !== undefined
)
delete (schema as any).discriminator;
});
return downgraded;
};
const composeFunction =
(options: IOpenAiDocument.IOptions) =>
(components: OpenApi.IComponents) =>
(route: IMigrateRoute): IOpenAiFunction | null => {
// CAST SCHEMA TYPES
const cast = (s: OpenApi.IJsonSchema) => schema(components, s);
const output: IOpenAiSchema | null | undefined =
route.success && route.success ? cast(route.success.schema) : undefined;
if (output === null) return null;
const properties: [string, IOpenAiSchema | null][] = [
...route.parameters.map((p) => ({
key: p.key,
schema: {
...p.schema,
title: p.parameter().title ?? p.schema.title,
description: p.parameter().description ?? p.schema.description,
},
})),
...(route.query
? [
{
key: route.query.key,
schema: {
...route.query.schema,
title: route.query.title() ?? route.query.schema.title,
description:
route.query.description() ?? route.query.schema.description,
},
},
]
: []),
...(route.body
? [
{
key: route.body.key,
schema: {
...route.body.schema,
description:
route.body.description() ?? route.body.schema.description,
},
},
]
: []),
].map((o) => [o.key, cast(o.schema)]);
if (properties.some(([_k, v]) => v === null)) return null;
// COMPOSE PARAMETERS
const parameters: IOpenAiSchema[] = options.keyword
? [
{
type: "object",
properties: Object.fromEntries(
properties as [string, IOpenAiSchema][],
),
},
]
: properties.map(([_k, v]) => v!);
const operation: ISwaggerOperation = route.operation();
// FINALIZATION
return {
method: route.method as "get",
path: route.path,
name: route.accessor.join("_"),
strict: true,
parameters,
separated: options.separate
? OpenAiSchemaSeparator.parameters({
parameters,
predicator: options.separate,
})
: undefined,
output: output
? (OpenApiV3Downgrader.downgradeSchema({
original: {},
downgraded: {},
})(output) as IOpenAiSchema)
: undefined,
description: (() => {
if (operation.summary && operation.description) {
return operation.description.startsWith(operation.summary)
? operation.description
: [
operation.summary,
operation.summary.endsWith(".") ? "" : ".",
"\n\n",
operation.description,
].join("");
}
return operation.description ?? operation.summary;
})(),
route: () => route,
operation: () => operation,
};
};
const escapeReference =
(components: OpenApi.IComponents) =>
(visited: Set<string>) =>
(input: OpenApi.IJsonSchema): OpenApi.IJsonSchema | null => {
if (OpenApiTypeChecker.isReference(input)) {
// REFERENCE
const name: string = input.$ref.split("#/components/schemas/")[1];
const target: OpenApi.IJsonSchema | undefined =
components.schemas?.[name];
if (!target) return null;
else if (visited.has(name)) return null;
return escapeReference(components)(new Set([...visited, name]))(target);
} else if (OpenApiTypeChecker.isOneOf(input)) {
// ONE-OF
const oneOf: Array<OpenApi.IJsonSchema | null> = input.oneOf.map(
(schema) => escapeReference(components)(visited)(schema)!,
);
if (oneOf.some((v) => v === null)) return null;
return {
...input,
oneOf: oneOf as OpenApi.IJsonSchema[],
};
} else if (OpenApiTypeChecker.isObject(input)) {
// OBJECT
const properties:
| Array<[string, OpenApi.IJsonSchema | null]>
| undefined = input.properties
? Object.entries(input.properties).map(
([key, value]) =>
[key, escapeReference(components)(visited)(value)] as const,
)
: undefined;
const additionalProperties:
| OpenApi.IJsonSchema
| null
| boolean
| undefined = input.additionalProperties
? typeof input.additionalProperties === "object" &&
input.additionalProperties !== null
? escapeReference(components)(visited)(input.additionalProperties)
: input.additionalProperties
: undefined;
if (properties && properties.some(([_k, v]) => v === null)) return null;
else if (additionalProperties === null) return null;
return {
...input,
properties: properties
? Object.fromEntries(
properties.filter(([_k, v]) => !!v) as Array<
[string, OpenApi.IJsonSchema]
>,
)
: undefined,
additionalProperties,
};
} else if (OpenApiTypeChecker.isTuple(input)) {
// TUPLE
const prefixItems: Array<OpenApi.IJsonSchema | null> =
input.prefixItems.map((schema) =>
escapeReference(components)(visited)(schema),
);
const additionalItems:
| OpenApi.IJsonSchema
| null
| boolean
| undefined =
typeof input.additionalItems === "object" &&
input.additionalItems !== null
? escapeReference(components)(visited)(input.additionalItems)
: input.additionalItems;
if (prefixItems.some((v) => v === null)) return null;
else if (additionalItems === null) return null;
return {
...input,
prefixItems: prefixItems as OpenApi.IJsonSchema[],
additionalItems,
};
} else if (OpenApiTypeChecker.isArray(input)) {
// ARRAY
const items: OpenApi.IJsonSchema | null = escapeReference(components)(
visited,
)(input.items);
if (items === null) return null;
return {
...input,
items,
};
}
return input;
};
}