Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fully translate to google schema #161

Merged
merged 2 commits into from
Feb 18, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 47 additions & 39 deletions packages/proxy/src/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1608,55 +1608,63 @@ async function fetchAnthropic(
};
}

async function googleSchemaFromJsonSchemaInternal(
root: any,
schema: any,
): Promise<any> {
if (!schema || typeof schema !== "object") {
return schema;
function convertToNullable(obj: any) {
const anyOf = obj.anyOf;
if (anyOf) {
if (anyOf.length !== 2) {
throw new ProxyBadRequestError(
"Google only supports Optional types for unions",
);
}
const [a, b] = anyOf;
if (a.type === "null") {
Object.assign(obj, b);
} else if (b.type === "null") {
Object.assign(obj, a);
} else {
throw new ProxyBadRequestError(
"Google only supports Optional types for unions",
);
}
delete obj.anyOf;
obj.nullable = true;
}
await $RefParser.dereference(schema);

const allowedFields = [
"type",
"format",
"description",
"nullable",
"items",
"enum",
"properties",
"required",
"example",
];

const result: any = {};

for (const [key, value] of Object.entries(schema)) {
if (!allowedFields.includes(key)) {
continue;
if (obj.properties) {
for (const value of Object.values(obj.properties)) {
convertToNullable(value);
}
}

if (key === "properties") {
result[key] = Object.fromEntries(
await Promise.all(
Object.entries(value as Record<string, any>).map(async ([k, v]) => [
k,
await googleSchemaFromJsonSchemaInternal(root, v),
]),
),
);
} else if (key === "items") {
result[key] = await googleSchemaFromJsonSchemaInternal(root, value);
} else {
result[key] = value;
if (obj.items) {
convertToNullable(obj.items);
}
}

function stripFields(obj: any) {
delete obj.title;
delete obj.additionalProperties;

if (obj.properties) {
for (const value of Object.values(obj.properties)) {
stripFields(value);
}
}

return result;
if (obj.items) {
stripFields(obj.items);
}
}

async function googleSchemaFromJsonSchema(schema: any): Promise<any> {
return await googleSchemaFromJsonSchemaInternal(schema, schema);
if (!schema || typeof schema !== "object") {
return schema;
}
await $RefParser.dereference(schema);
delete schema.$defs;
convertToNullable(schema);
stripFields(schema);
return schema;
}

async function openAIToolsToGoogleTools(params: ChatCompletionCreateParams) {
Expand Down