Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(gemini): sanitize enum/required from non-compliant types in tool schema (#14740)

Arvin Xu4ea80c29158d
diff --git a/packages/model-runtime/src/core/contextBuilders/google.ts b/packages/model-runtime/src/core/contextBuilders/google.ts
index 0a8d418dc11..a997c83e7cd 100644
--- a/packages/model-runtime/src/core/contextBuilders/google.ts
+++ b/packages/model-runtime/src/core/contextBuilders/google.ts
@@ -283,6 +283,86 @@ export const buildGoogleMessages = async (messages: OpenAIChatMessage[]): Promis
return filteredContents;
};
+/**
+ * Recursively sanitize a JSON Schema to comply with Gemini proto constraints:
+ * - `enum` is only allowed on STRING type fields
+ * - `required` is only allowed on OBJECT type fields
+ *
+ * This handles the OpenAI→Gemini schema bridge where the upstream
+ * schema may place `enum` on non-STRING types (e.g. number, boolean)
+ * or `required` on non-OBJECT types.
+ *
+ * @see https://linear.app/lobehub/issue/LOBE-8661
+ */
+export const sanitizeGeminiSchema = (schema: any): any => {
+ if (!schema || typeof schema !== 'object') return schema;
+
+ const sanitized = { ...schema };
+
+ // Determine if the schema type is (or includes) STRING / OBJECT.
+ // Handles both `type: 'string'` and nullable `type: ['string', 'null']`.
+ const isStringType = (t: unknown): boolean =>
+ typeof t === 'string' ? t === 'string' : Array.isArray(t) && t.includes('string');
+ const isObjectType = (t: unknown): boolean =>
+ typeof t === 'string' ? t === 'object' : Array.isArray(t) && t.includes('object');
+
+ // Strip enum from non-STRING types and empty enums
+ // Gemini proto: "enum: only allowed for STRING type"
+ if (sanitized.enum !== undefined) {
+ if (!isStringType(sanitized.type) || !Array.isArray(sanitized.enum) || sanitized.enum.length === 0) {
+ console.warn(
+ '[google] sanitizeGeminiSchema stripped enum — not allowed for non-STRING type or empty',
+ { type: sanitized.type, enumLength: sanitized.enum?.length },
+ );
+ delete sanitized.enum;
+ }
+ }
+
+ // Strip required from non-OBJECT types and empty required arrays
+ // Gemini proto: "required: only allowed for OBJECT type"
+ if (sanitized.required !== undefined) {
+ if (!isObjectType(sanitized.type) || !Array.isArray(sanitized.required) || sanitized.required.length === 0) {
+ console.warn(
+ '[google] sanitizeGeminiSchema stripped required — not allowed for non-OBJECT type or empty',
+ { type: sanitized.type, requiredLength: sanitized.required?.length },
+ );
+ delete sanitized.required;
+ }
+ }
+
+ // Recursively sanitize properties
+ if (sanitized.properties && typeof sanitized.properties === 'object') {
+ for (const key of Object.keys(sanitized.properties)) {
+ sanitized.properties[key] = sanitizeGeminiSchema(sanitized.properties[key]);
+ }
+ }
+
+ // Recursively sanitize items (for array types)
+ if (sanitized.items) {
+ sanitized.items = sanitizeGeminiSchema(sanitized.items);
+ }
+
+ // Recursively sanitize anyOf/oneOf/allOf combinators
+ for (const key of ['anyOf', 'oneOf', 'allOf']) {
+ if (Array.isArray(sanitized[key])) {
+ sanitized[key] = sanitized[key].map(sanitizeGeminiSchema);
+ }
+ }
+
+ // Recursively sanitize definitions/$defs — when a tool schema stores
+ // non-compliant constraints inside a referenced sub-schema the walker
+ // must reach into the definitions map as well.
+ for (const key of ['definitions', '$defs']) {
+ if (sanitized[key] && typeof sanitized[key] === 'object') {
+ for (const defKey of Object.keys(sanitized[key])) {
+ sanitized[key][defKey] = sanitizeGeminiSchema(sanitized[key][defKey]);
+ }
+ }
+ }
+
+ return sanitized;
+};
+
/**
* Convert ChatCompletionTool to Google FunctionDeclaration.
* Uses `parametersJsonSchema` to pass standard JSON Schema directly,
@@ -296,7 +376,7 @@ export const buildGoogleTool = (tool: ChatCompletionTool): FunctionDeclaration =
const hasProperties = parameters?.properties && Object.keys(parameters.properties).length > 0;
const jsonSchema = hasProperties
- ? parameters
+ ? sanitizeGeminiSchema(parameters)
: { type: 'object', properties: { dummy: { type: 'string' } } };
return {
diff --git a/packages/model-runtime/src/providers/google/generateObject.test.ts b/packages/model-runtime/src/providers/google/generateObject.test.ts
index 2471e005fb3..8ba67c435df 100644
--- a/packages/model-runtime/src/providers/google/generateObject.test.ts
+++ b/packages/model-runtime/src/providers/google/generateObject.test.ts
@@ -2,6 +2,7 @@
import { Type as SchemaType } from '@google/genai';
import { describe, expect, it, vi } from 'vitest';
+import { buildGoogleTool, sanitizeGeminiSchema } from '../../core/contextBuilders/google';
import {
convertOpenAISchemaToGoogleSchema,
createGoogleGenerateObject,
@@ -178,6 +179,356 @@ describe('Google generateObject', () => {
type: SchemaType.STRING,
});
});
+
+ // LOBE-8661: enum should only be copied for STRING type properties
+ it('should strip enum from non-STRING types', () => {
+ const openAISchema = {
+ name: 'test',
+ schema: {
+ properties: {
+ priority: { enum: ['low', 'medium', 'high'], type: 'number' },
+ status: { enum: ['active', 'inactive'], type: 'string' },
+ visible: { enum: ['true'], type: 'boolean' },
+ },
+ type: 'object' as const,
+ },
+ };
+
+ const result = convertOpenAISchemaToGoogleSchema(openAISchema);
+
+ // enum should be stripped from number and boolean types
+ expect(result).toEqual({
+ properties: {
+ priority: { type: SchemaType.NUMBER },
+ status: { enum: ['active', 'inactive'], type: SchemaType.STRING },
+ visible: { type: SchemaType.BOOLEAN },
+ },
+ type: SchemaType.OBJECT,
+ });
+ });
+
+ // LOBE-8661: enum with empty array should be stripped even for STRING type
+ it('should strip empty enum arrays', () => {
+ const openAISchema = {
+ name: 'test',
+ schema: {
+ properties: {
+ status: { enum: [], type: 'string' },
+ },
+ type: 'object' as const,
+ },
+ };
+
+ const result = convertOpenAISchemaToGoogleSchema(openAISchema);
+
+ expect(result).toEqual({
+ properties: {
+ status: { type: SchemaType.STRING },
+ },
+ type: SchemaType.OBJECT,
+ });
+ });
+
+ // LOBE-8661: required should only be copied for OBJECT types
+ it('should strip required from non-OBJECT types', () => {
+ const openAISchema = {
+ name: 'test',
+ schema: {
+ properties: {
+ nested: {
+ properties: { name: { type: 'string' } },
+ required: ['name'],
+ type: 'object',
+ },
+ },
+ required: ['nested'],
+ type: 'object' as const,
+ },
+ } as any;
+
+ const result = convertOpenAISchemaToGoogleSchema(openAISchema);
+
+ // required should be preserved for OBJECT types (both root and nested)
+ expect(result).toEqual({
+ properties: {
+ nested: {
+ properties: {
+ name: { type: SchemaType.STRING },
+ },
+ required: ['name'],
+ type: SchemaType.OBJECT,
+ },
+ },
+ required: ['nested'],
+ type: SchemaType.OBJECT,
+ });
+ });
+ });
+
+ describe('sanitizeGeminiSchema', () => {
+ it('should strip enum from non-STRING types', () => {
+ const schema = {
+ properties: {
+ priority: { enum: [1, 2, 3], type: 'integer' },
+ status: { enum: ['active'], type: 'string' },
+ },
+ type: 'object',
+ };
+
+ const result = sanitizeGeminiSchema(schema);
+
+ expect(result).toEqual({
+ properties: {
+ priority: { type: 'integer' },
+ status: { enum: ['active'], type: 'string' },
+ },
+ type: 'object',
+ });
+ });
+
+ it('should strip required from non-OBJECT types', () => {
+ const schema = {
+ properties: {
+ name: { required: ['firstName'], type: 'string' },
+ user: {
+ properties: { name: { type: 'string' } },
+ required: ['name'],
+ type: 'object',
+ },
+ },
+ type: 'object',
+ };
+
+ const result = sanitizeGeminiSchema(schema);
+
+ expect(result).toEqual({
+ properties: {
+ name: { type: 'string' },
+ user: {
+ properties: { name: { type: 'string' } },
+ required: ['name'],
+ type: 'object',
+ },
+ },
+ type: 'object',
+ });
+ });
+
+ it('should recursively sanitize nested properties', () => {
+ const schema = {
+ properties: {
+ dashboard: {
+ properties: {
+ widgets: {
+ items: {
+ properties: {
+ color: { enum: ['red'], type: 'string' },
+ priority: { enum: [1, 2], type: 'number' },
+ visible: { enum: ['true'], type: 'boolean' },
+ },
+ type: 'object',
+ },
+ type: 'array',
+ },
+ },
+ type: 'object',
+ },
+ },
+ type: 'object',
+ };
+
+ const result = sanitizeGeminiSchema(schema);
+
+ expect(result).toEqual({
+ properties: {
+ dashboard: {
+ properties: {
+ widgets: {
+ items: {
+ properties: {
+ color: { enum: ['red'], type: 'string' },
+ priority: { type: 'number' },
+ visible: { type: 'boolean' },
+ },
+ type: 'object',
+ },
+ type: 'array',
+ },
+ },
+ type: 'object',
+ },
+ },
+ type: 'object',
+ });
+ });
+
+ it('should handle empty enum arrays', () => {
+ const schema = {
+ properties: {
+ status: { enum: [], type: 'string' },
+ },
+ type: 'object',
+ };
+
+ const result = sanitizeGeminiSchema(schema);
+
+ expect(result).toEqual({
+ properties: {
+ status: { type: 'string' },
+ },
+ type: 'object',
+ });
+ });
+
+ it('should handle anyOf/oneOf/allOf combinators', () => {
+ const schema = {
+ anyOf: [
+ { enum: [1, 2], type: 'number' },
+ { enum: ['low'], type: 'string' },
+ ],
+ };
+
+ const result = sanitizeGeminiSchema(schema);
+
+ expect(result).toEqual({
+ anyOf: [{ type: 'number' }, { enum: ['low'], type: 'string' }],
+ });
+ });
+
+ it('should handle null/undefined gracefully', () => {
+ expect(sanitizeGeminiSchema(null)).toBeNull();
+ expect(sanitizeGeminiSchema(undefined)).toBeUndefined();
+ });
+
+ // LOBE-8661: nullable string enums should be preserved
+ it('should preserve enum on nullable STRING types (type: array with string)', () => {
+ const schema = {
+ properties: {
+ status: {
+ enum: ['active', 'inactive', null],
+ type: ['string', 'null'],
+ },
+ },
+ type: 'object',
+ };
+
+ const result = sanitizeGeminiSchema(schema);
+
+ expect(result).toEqual({
+ properties: {
+ status: {
+ enum: ['active', 'inactive', null],
+ type: ['string', 'null'],
+ },
+ },
+ type: 'object',
+ });
+ });
+
+ // LOBE-8661: nullable object required should be preserved
+ it('should preserve required on nullable OBJECT types (type: array with object)', () => {
+ const schema = {
+ properties: {
+ config: {
+ properties: { key: { type: 'string' } },
+ required: ['key'],
+ type: ['object', 'null'],
+ },
+ },
+ type: 'object',
+ };
+
+ const result = sanitizeGeminiSchema(schema);
+
+ expect(result).toEqual({
+ properties: {
+ config: {
+ properties: { key: { type: 'string' } },
+ required: ['key'],
+ type: ['object', 'null'],
+ },
+ },
+ type: 'object',
+ });
+ });
+
+ // LOBE-8661: should strip enum from nullable non-STRING types
+ it('should strip enum from nullable non-STRING types (type: array without string)', () => {
+ const schema = {
+ properties: {
+ count: {
+ enum: [1, 2, 3],
+ type: ['integer', 'null'],
+ },
+ },
+ type: 'object',
+ };
+
+ const result = sanitizeGeminiSchema(schema);
+
+ expect(result).toEqual({
+ properties: {
+ count: {
+ type: ['integer', 'null'],
+ },
+ },
+ type: 'object',
+ });
+ });
+
+ // LOBE-8661: recurse into definitions/$defs
+ it('should sanitize schemas under definitions', () => {
+ const schema = {
+ definitions: {
+ Priority: { enum: [1, 2, 3], type: 'number' },
+ Status: { enum: ['active', 'inactive'], type: 'string' },
+ },
+ properties: {
+ priority: { $ref: '#/definitions/Priority' },
+ status: { $ref: '#/definitions/Status' },
+ },
+ type: 'object',
+ };
+
+ const result = sanitizeGeminiSchema(schema);
+
+ expect(result).toEqual({
+ definitions: {
+ Priority: { type: 'number' },
+ Status: { enum: ['active', 'inactive'], type: 'string' },
+ },
+ properties: {
+ priority: { $ref: '#/definitions/Priority' },
+ status: { $ref: '#/definitions/Status' },
+ },
+ type: 'object',
+ });
+ });
+
+ // LOBE-8661: recurse into $defs
+ it('should sanitize schemas under $defs', () => {
+ const schema = {
+ $defs: {
+ Shape: { enum: ['circle', 'square'], required: ['radius'], type: 'string' },
+ },
+ properties: {
+ shape: { $ref: '#/$defs/Shape' },
+ },
+ type: 'object',
+ };
+
+ const result = sanitizeGeminiSchema(schema);
+
+ expect(result).toEqual({
+ $defs: {
+ Shape: { enum: ['circle', 'square'], type: 'string' },
+ },
+ properties: {
+ shape: { $ref: '#/$defs/Shape' },
+ },
+ type: 'object',
+ });
+ });
});
describe('createGoogleGenerateObject', () => {
@@ -963,5 +1314,123 @@ describe('Google generateObject', () => {
expect(result).toEqual([{ arguments: {}, name: 'simple_function' }]);
});
+
+ // LOBE-8661: buildGoogleTool should sanitize schema to strip enum from non-STRING types
+ it('should sanitize enum from non-STRING types in tool parameters', () => {
+ const tool: any = {
+ function: {
+ description: 'Update status',
+ name: 'update_status',
+ parameters: {
+ properties: {
+ priority: { enum: [1, 2, 3], type: 'integer' },
+ status: { enum: ['active', 'inactive'], type: 'string' },
+ },
+ required: ['status'],
+ type: 'object',
+ },
+ },
+ type: 'function',
+ };
+
+ // Suppress console.warn from sanitizer
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const result = buildGoogleTool(tool);
+
+ expect(result.parametersJsonSchema).toEqual({
+ properties: {
+ priority: { type: 'integer' },
+ status: { enum: ['active', 'inactive'], type: 'string' },
+ },
+ required: ['status'],
+ type: 'object',
+ });
+
+ warnSpy.mockRestore();
+ });
+
+ // LOBE-8661: buildGoogleTool should sanitize nested tool parameters
+ it('should sanitize nested enum/required in tool parameters', () => {
+ const tool: any = {
+ function: {
+ description: 'Complex operation',
+ name: 'complex_op',
+ parameters: {
+ properties: {
+ config: {
+ properties: {
+ color: { enum: ['red'], type: 'string' },
+ level: { enum: [1, 2, 3], type: 'number' },
+ },
+ required: ['color'],
+ type: 'object',
+ },
+ role: { required: ['admin'], type: 'string' },
+ },
+ type: 'object',
+ },
+ },
+ type: 'function',
+ };
+
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const result = buildGoogleTool(tool);
+
+ expect(result.parametersJsonSchema).toEqual({
+ properties: {
+ config: {
+ properties: {
+ color: { enum: ['red'], type: 'string' },
+ level: { type: 'number' },
+ },
+ required: ['color'],
+ type: 'object',
+ },
+ role: { type: 'string' },
+ },
+ type: 'object',
+ });
+
+ warnSpy.mockRestore();
+ });
+
+ // LOBE-8661: buildGoogleTool should preserve nullable string enum
+ it('should preserve enum on nullable STRING type in tool parameters', () => {
+ const tool: any = {
+ function: {
+ description: 'A tool with nullable enum',
+ name: 'nullableTool',
+ parameters: {
+ properties: {
+ status: {
+ enum: ['active', 'inactive', null],
+ type: ['string', 'null'],
+ },
+ },
+ type: 'object',
+ },
+ },
+ type: 'function',
+ };
+
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const result = buildGoogleTool(tool);
+
+ // nullable types and null enum values should be passed through as-is
+ expect(result.parametersJsonSchema).toEqual({
+ properties: {
+ status: {
+ enum: ['active', 'inactive', null],
+ type: ['string', 'null'],
+ },
+ },
+ type: 'object',
+ });
+
+ warnSpy.mockRestore();
+ });
});
});
diff --git a/packages/model-runtime/src/providers/google/generateObject.ts b/packages/model-runtime/src/providers/google/generateObject.ts
index e9e4c04901e..ccea9c1acb4 100644
--- a/packages/model-runtime/src/providers/google/generateObject.ts
+++ b/packages/model-runtime/src/providers/google/generateObject.ts
@@ -59,18 +59,31 @@ const convertType = (type: string): SchemaType => {
* Convert OpenAI JSON schema to Google Gemini schema format
*/
export const convertOpenAISchemaToGoogleSchema = (openAISchema: GenerateObjectSchema): any => {
- const convertSchema = (schema: any): any => {
+ // Check whether a schema type is (or includes) STRING / OBJECT.
+// Handles both `type: 'string'` and nullable `type: ['string', 'null']`.
+const isStringType = (t: unknown): boolean =>
+ typeof t === 'string' ? t === 'string' : Array.isArray(t) && t.includes('string');
+const isObjectType = (t: unknown): boolean =>
+ typeof t === 'string' ? t === 'object' : Array.isArray(t) && t.includes('object');
+
+const convertSchema = (schema: any): any => {
if (!schema) return schema;
+ // convertType handles single string types; for array types (nullable)
+ // default to STRING which is safe for Gemini Schema proto.
+ const typeArg: string = Array.isArray(schema.type) ? 'string' : schema.type;
const converted: any = {
- type: convertType(schema.type),
+ type: convertType(typeArg),
};
if (schema.description) {
converted.description = schema.description;
}
- if (schema.enum) {
+ // Only include enum if type is STRING and enum is non-empty.
+ // Gemini proto: enum is only allowed for STRING type.
+ // @see https://linear.app/lobehub/issue/LOBE-8661
+ if (schema.enum && schema.enum.length > 0 && isStringType(schema.type)) {
converted.enum = schema.enum;
}
@@ -85,7 +98,10 @@ export const convertOpenAISchemaToGoogleSchema = (openAISchema: GenerateObjectSc
converted.items = convertSchema(schema.items);
}
- if (schema.required) {
+ // Only include required if type is OBJECT and required is non-empty.
+ // Gemini proto: required is only allowed for OBJECT type.
+ // @see https://linear.app/lobehub/issue/LOBE-8661
+ if (schema.required && schema.required.length > 0 && isObjectType(schema.type)) {
converted.required = schema.required;
}