make schema openai compatible
This commit is contained in:
parent
1689ac28df
commit
2642558ff0
1 changed files with 51 additions and 3 deletions
|
|
@ -4,6 +4,53 @@
|
|||
|
||||
import type { ChatCompletionCreateParams } from "openai/resources/index.js";
|
||||
|
||||
/**
|
||||
* Recursively transforms schemas to be OpenAI strict mode compatible:
|
||||
* - Adds additionalProperties: false to all object schemas
|
||||
* - Ensures all properties are listed in the required array
|
||||
*/
|
||||
function makeOpenAIStrictCompatible(schema: any): any {
|
||||
if (!schema || typeof schema !== "object") {
|
||||
return schema;
|
||||
}
|
||||
|
||||
const result = { ...schema };
|
||||
|
||||
if (result.type === "object") {
|
||||
result.additionalProperties = false;
|
||||
|
||||
if (result.properties) {
|
||||
const propertyKeys = Object.keys(result.properties);
|
||||
result.required = propertyKeys;
|
||||
|
||||
result.properties = Object.fromEntries(
|
||||
Object.entries(result.properties).map(([key, value]) => [
|
||||
key,
|
||||
makeOpenAIStrictCompatible(value),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (result.items) {
|
||||
result.items = makeOpenAIStrictCompatible(result.items);
|
||||
}
|
||||
|
||||
if (result.anyOf) {
|
||||
result.anyOf = result.anyOf.map(makeOpenAIStrictCompatible);
|
||||
}
|
||||
|
||||
if (result.oneOf) {
|
||||
result.oneOf = result.oneOf.map(makeOpenAIStrictCompatible);
|
||||
}
|
||||
|
||||
if (result.allOf) {
|
||||
result.allOf = result.allOf.map(makeOpenAIStrictCompatible);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts OpenAI tool format to Vercel AI SDK format.
|
||||
*
|
||||
|
|
@ -25,11 +72,12 @@ export async function convertToolsToVercelFormat(
|
|||
const vercelTools: Record<string, any> = {};
|
||||
for (const tool of openaiTools) {
|
||||
if (tool.type === "function") {
|
||||
const parameters = makeOpenAIStrictCompatible(
|
||||
tool.function.parameters ?? { type: "object", properties: {} },
|
||||
);
|
||||
vercelTools[tool.function.name] = {
|
||||
description: tool.function.description,
|
||||
parameters: aiJsonSchema(
|
||||
tool.function.parameters ?? { type: "object", properties: {} },
|
||||
),
|
||||
parameters: aiJsonSchema(parameters),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue