Skip to content

Commit 8055932

Browse files
committed
fix(ai): preserve Gemini enum schema types
1 parent 51ba2a5 commit 8055932

2 files changed

Lines changed: 63 additions & 145 deletions

File tree

‎packages/ai/src/providers/clean-for-gemini.test.ts‎

Lines changed: 30 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -226,48 +226,34 @@ describe("cleanSchemaForGemini", () => {
226226
expect(cleaned.properties?.agentId?.type).toBe("string");
227227
});
228228

229-
// Gemini Function Calling requires string enum values. Numeric/boolean enums
230-
// (common in tool schemas — priorities, scores, flags) must be coerced to
231-
// strings and the schema retyped as `"string"`, otherwise Gemini rejects the
232-
// request with `TYPE_STRING expected` errors.
233-
it("coerces numeric enum values to strings and retypes as string", () => {
234-
const cleaned = cleanSchemaForGemini({
235-
type: "integer",
236-
enum: [1, 2, 3],
237-
}) as { type?: unknown; enum?: unknown };
238-
239-
expect(cleaned.type).toBe("string");
240-
expect(cleaned.enum).toStrictEqual(["1", "2", "3"]);
241-
});
242-
243-
it("coerces boolean enum values to strings", () => {
244-
const cleaned = cleanSchemaForGemini({
245-
type: "boolean",
246-
enum: [true, false],
247-
}) as { type?: unknown; enum?: unknown };
248-
249-
expect(cleaned.type).toBe("string");
250-
expect(cleaned.enum).toStrictEqual(["true", "false"]);
251-
});
252-
253-
it("preserves already-string enum values without retyping", () => {
254-
const cleaned = cleanSchemaForGemini({
255-
type: "string",
256-
enum: ["a", "b", "c"],
257-
}) as { type?: unknown; enum?: unknown };
258-
259-
expect(cleaned.type).toBe("string");
260-
expect(cleaned.enum).toStrictEqual(["a", "b", "c"]);
261-
});
262-
263-
it("coerces a numeric const to a string enum and retypes as string", () => {
264-
const cleaned = cleanSchemaForGemini({
265-
type: "integer",
266-
const: 42,
267-
}) as { type?: unknown; enum?: unknown };
268-
269-
expect(cleaned.type).toBe("string");
270-
expect(cleaned.enum).toStrictEqual(["42"]);
229+
it.each([
230+
{
231+
name: "integer enum",
232+
schema: { type: "integer", enum: [1, 2, 3] },
233+
expected: { type: "integer", enum: ["1", "2", "3"] },
234+
},
235+
{
236+
name: "integer enum before type",
237+
schema: { enum: [1, 2, 3], type: "integer" },
238+
expected: { enum: ["1", "2", "3"], type: "integer" },
239+
},
240+
{
241+
name: "boolean enum",
242+
schema: { type: "boolean", enum: [true, false] },
243+
expected: { type: "boolean", enum: ["true", "false"] },
244+
},
245+
{
246+
name: "string enum",
247+
schema: { type: "string", enum: ["a", "b", "c"] },
248+
expected: { type: "string", enum: ["a", "b", "c"] },
249+
},
250+
{
251+
name: "integer const before type",
252+
schema: { const: 42, type: "integer" },
253+
expected: { enum: ["42"], type: "integer" },
254+
},
255+
])("stringifies $name values without changing the schema type", ({ schema, expected }) => {
256+
expect(cleanSchemaForGemini(schema)).toStrictEqual(expected);
271257
});
272258

273259
it("drops null/undefined enum entries and de-duplicates", () => {
@@ -279,7 +265,7 @@ describe("cleanSchemaForGemini", () => {
279265
expect(cleaned.enum).toStrictEqual(["1", "2", "3"]);
280266
});
281267

282-
it("coerces numeric enums inside deeply nested tool parameters", () => {
268+
it("stringifies nested numeric enums while preserving their number type", () => {
283269
const cleaned = cleanSchemaForGemini({
284270
type: "object",
285271
properties: {
@@ -300,7 +286,7 @@ describe("cleanSchemaForGemini", () => {
300286
};
301287

302288
const score = cleaned.properties?.outer?.items?.properties?.score;
303-
expect(score?.type).toBe("string");
289+
expect(score?.type).toBe("number");
304290
expect(score?.enum).toStrictEqual(["1", "2", "3", "4", "5"]);
305291
});
306292

@@ -312,48 +298,4 @@ describe("cleanSchemaForGemini", () => {
312298

313299
expect(cleaned.enum).toBeUndefined();
314300
});
315-
316-
// Regression: schema key order is not semantic. `{ enum: [...], type: "..." }`
317-
// must produce the same output as `{ type: "...", enum: [...] }`. If the
318-
// coercion is applied only while visiting `enum`, a later `type` key would
319-
// overwrite `type: "string"` and Gemini would still reject the declaration.
320-
it("coerces numeric enum with enum-before-type ordering (regression: property order independence)", () => {
321-
const cleaned = cleanSchemaForGemini({
322-
enum: [1, 2, 3],
323-
type: "integer",
324-
}) as { type?: unknown; enum?: unknown };
325-
326-
expect(cleaned.type).toBe("string");
327-
expect(cleaned.enum).toStrictEqual(["1", "2", "3"]);
328-
});
329-
330-
it("coerces boolean enum with enum-before-type ordering", () => {
331-
const cleaned = cleanSchemaForGemini({
332-
enum: [true, false],
333-
type: "boolean",
334-
}) as { type?: unknown; enum?: unknown };
335-
336-
expect(cleaned.type).toBe("string");
337-
expect(cleaned.enum).toStrictEqual(["true", "false"]);
338-
});
339-
340-
it("coerces numeric const with const-before-type ordering", () => {
341-
const cleaned = cleanSchemaForGemini({
342-
const: 42,
343-
type: "integer",
344-
}) as { type?: unknown; enum?: unknown };
345-
346-
expect(cleaned.type).toBe("string");
347-
expect(cleaned.enum).toStrictEqual(["42"]);
348-
});
349-
350-
it("leaves type untouched when no enum coercion happened", () => {
351-
// A pure integer schema without enum/const must NOT be retyped as string.
352-
const cleaned = cleanSchemaForGemini({
353-
type: "integer",
354-
description: "a plain integer field",
355-
}) as { type?: unknown };
356-
357-
expect(cleaned.type).toBe("integer");
358-
});
359301
});

‎packages/ai/src/providers/clean-for-gemini.ts‎

Lines changed: 33 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,33 @@ function copySchemaMeta(from: Record<string, unknown>, to: Record<string, unknow
4646
}
4747
}
4848

49+
// Google requires enum entries as strings even when the declared schema type is numeric or
50+
// boolean. Keep the type intact so tool argument generation and runtime validation still agree.
51+
function stringifyGeminiEnumValue(value: unknown): string | undefined {
52+
if (typeof value === "string") {
53+
return value;
54+
}
55+
if (typeof value === "number" && Number.isFinite(value)) {
56+
return String(value);
57+
}
58+
if (typeof value === "boolean") {
59+
return String(value);
60+
}
61+
return undefined;
62+
}
63+
64+
function cleanGeminiEnumValues(value: unknown): string[] | undefined {
65+
if (!Array.isArray(value)) {
66+
return undefined;
67+
}
68+
const values = value.flatMap((entry) => {
69+
const stringified = stringifyGeminiEnumValue(entry);
70+
return stringified === undefined ? [] : [stringified];
71+
});
72+
const unique = [...new Set(values)];
73+
return unique.length > 0 ? unique : undefined;
74+
}
75+
4976
// Check if an anyOf/oneOf array contains only literal values that can be flattened.
5077
// TypeBox Type.Literal generates { const: "value", type: "string" }.
5178
// Some schemas may use { enum: ["value"], type: "string" }.
@@ -317,68 +344,25 @@ function cleanSchemaForGeminiWithDefs(
317344
}
318345
}
319346

320-
// Gemini's Function Calling only accepts STRING values in `enum` (see
321-
// https://ai.google.dev/gemini-api/docs/function-calling). Numeric, boolean,
322-
// and bigint enum values must be coerced to strings, otherwise the API
323-
// rejects the whole request with:
324-
// Invalid value at 'tools[X].function_declarations[Y].parameters...enum[N]'
325-
// (TYPE_STRING), 1
326-
// This applies to both `enum` arrays and single-valued `const` (which is
327-
// rewritten to `enum: [value]` below).
328-
const coerceEnumValue = (v: unknown): string | undefined => {
329-
if (typeof v === "string") {
330-
return v;
331-
}
332-
if (typeof v === "number" && Number.isFinite(v)) {
333-
return String(v);
334-
}
335-
if (typeof v === "boolean") {
336-
return v ? "true" : "false";
337-
}
338-
if (typeof v === "bigint") {
339-
return v.toString();
340-
}
341-
return undefined;
342-
};
343-
const coerceEnumArray = (arr: unknown): string[] | undefined => {
344-
if (!Array.isArray(arr)) {
345-
return undefined;
346-
}
347-
const out: string[] = [];
348-
for (const entry of arr) {
349-
const coerced = coerceEnumValue(entry);
350-
if (coerced !== undefined && !out.includes(coerced)) {
351-
out.push(coerced);
352-
}
353-
}
354-
return out;
355-
};
356-
357347
const cleaned: Record<string, unknown> = {};
358-
// Track whether we produced an enum this pass; the final `type` is forced to
359-
// "string" after the loop so that `type` appearing AFTER `enum` in the input
360-
// schema cannot overwrite the coercion (schema key order is not semantic).
361-
let enumCoercedToString = false;
362348

363349
for (const [key, value] of Object.entries(obj)) {
364350
if (GEMINI_UNSUPPORTED_SCHEMA_KEYWORDS.has(key)) {
365351
continue;
366352
}
367353

368354
if (key === "const") {
369-
const coerced = coerceEnumValue(value);
370-
if (coerced !== undefined) {
371-
cleaned.enum = [coerced];
372-
enumCoercedToString = true;
355+
const enumValues = cleanGeminiEnumValues([value]);
356+
if (enumValues) {
357+
cleaned.enum = enumValues;
373358
}
374359
continue;
375360
}
376361

377362
if (key === "enum") {
378-
const coerced = coerceEnumArray(value);
379-
if (coerced && coerced.length > 0) {
380-
cleaned.enum = coerced;
381-
enumCoercedToString = true;
363+
const enumValues = cleanGeminiEnumValues(value);
364+
if (enumValues) {
365+
cleaned.enum = enumValues;
382366
}
383367
continue;
384368
}
@@ -442,14 +426,6 @@ function cleanSchemaForGeminiWithDefs(
442426
}
443427
}
444428

445-
// Force `type: "string"` when the schema produced a coerced enum, regardless
446-
// of the input schema's property order. Setting this after the loop makes the
447-
// behavior independent of whether `type` appeared before or after `enum` /
448-
// `const` in the input object.
449-
if (enumCoercedToString) {
450-
cleaned.type = "string";
451-
}
452-
453429
// Cloud Code Assist API rejects anyOf/oneOf in nested schemas even after
454430
// simplifyUnionVariants runs above. Flatten remaining unions as a fallback:
455431
// pick the common type or use the first variant's type so the tool

0 commit comments

Comments
 (0)