| 56 | * @since 4.0.0 |
| 57 | */ |
| 58 | export function toCodecOpenAI<T, E, RD, RE>( |
| 59 | schema: Schema.ConstraintCodec<T, E, RD, RE> |
| 60 | ): { |
| 61 | codec: Schema.ConstraintCodec<T, unknown, RD, RE> |
| 62 | jsonSchema: JsonSchema.JsonSchema |
| 63 | } { |
| 64 | const codec = InternalStructuredOutput.toCodec(schema) |
| 65 | const document = JsonSchema.resolveTopLevel$ref( |
| 66 | Schema.toJsonSchemaDocument(codec, { generateDescriptions: true }) |
| 67 | ) |
| 68 | const jsonSchema = rewriteOpenAI(document.schema) |
| 69 | if (jsonSchema.type !== "object" || jsonSchema.anyOf !== undefined) { |
| 70 | throw new Error( |
| 71 | `OpenAiStructuredOutput: Root JSON Schema must have type "object" and must not use "anyOf"` |
| 72 | ) |
| 73 | } |
| 74 | if (Object.keys(document.definitions).length > 0) { |
| 75 | jsonSchema.$defs = Rec.map(document.definitions, rewriteOpenAI) |
| 76 | } |
| 77 | return { codec, jsonSchema } |
| 78 | } |
| 79 | |
| 80 | function rewriteOpenAI(schema: JsonSchema.JsonSchema): JsonSchema.JsonSchema { |
| 81 | return InternalStructuredOutput.walkJsonSchema(schema, (schema) => { |