π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix: use `parametersJsonSchema` for Google tool schemas (#13656)
Arvin Xu36d2427947f7
diff --git a/packages/model-runtime/src/core/contextBuilders/google.test.ts b/packages/model-runtime/src/core/contextBuilders/google.test.tsindex 564bbfcaf30..0eb25498af1 100644--- a/packages/model-runtime/src/core/contextBuilders/google.test.ts+++ b/packages/model-runtime/src/core/contextBuilders/google.test.ts@@ -1,5 +1,4 @@// @vitest-environment node-import { Type as SchemaType } from '@google/genai';import * as imageToBase64Module from '@lobechat/utils';import { describe, expect, it, vi } from 'vitest';@@ -1081,7 +1080,7 @@ describe('google contextBuilders', () => {});describe('buildGoogleTool', () => {- it('should correctly convert ChatCompletionTool to FunctionDeclaration', () => {+ it('should use parametersJsonSchema to pass standard JSON Schema directly', () => {const tool: ChatCompletionTool = {function: {description: 'A test tool',@@ -1103,19 +1102,20 @@ describe('google contextBuilders', () => {expect(result).toEqual({description: 'A test tool',name: 'testTool',- parameters: {- description: undefined,+ parametersJsonSchema: {properties: {param1: { type: 'string' },param2: { type: 'number' },},required: ['param1'],- type: SchemaType.OBJECT,+ type: 'object',},});+ // Should not have the old parameters field+ expect(result.parameters).toBeUndefined();});- it('should handle tools with empty parameters', () => {+ it('should handle tools with empty parameters using dummy property', () => {const tool: ChatCompletionTool = {function: {description: 'A simple function with no parameters',@@ -1130,248 +1130,14 @@ describe('google contextBuilders', () => {const result = buildGoogleTool(tool);- // Should use dummy property for empty parametersexpect(result).toEqual({description: 'A simple function with no parameters',name: 'simple_function',- parameters: {- description: undefined,- properties: { dummy: { type: 'string' } },- required: undefined,- type: SchemaType.OBJECT,- },+ parametersJsonSchema: { type: 'object', properties: { dummy: { type: 'string' } } },});});- it('should preserve parameter description', () => {- const tool: ChatCompletionTool = {- function: {- description: 'A test tool',- name: 'testTool',- parameters: {- description: 'Test parameters',- properties: {- param1: { type: 'string' },- },- type: 'object',- },- },- type: 'function',- };-- const result = buildGoogleTool(tool);-- expect(result.parameters?.description).toBe('Test parameters');- });-- it('should convert const to enum for Google compatibility', () => {- const tool: ChatCompletionTool = {- function: {- description: 'A tool with const values',- name: 'constTool',- parameters: {- properties: {- action: { const: 'insert', type: 'string' },- nested: {- properties: {- operation: { const: 'create', type: 'string' },- },- type: 'object',- },- },- type: 'object',- },- },- type: 'function',- };-- const result = buildGoogleTool(tool);-- // const should be converted to enum with single value- expect(result.parameters?.properties).toEqual({- action: { enum: ['insert'], type: 'string' },- nested: {- properties: {- operation: { enum: ['create'], type: 'string' },- },- type: 'object',- },- });- });-- it('should handle oneOf with const values (like page-agent modifyNodes)', () => {- const tool: ChatCompletionTool = {- function: {- description: 'Modify nodes operation',- name: 'modifyNodes',- parameters: {- properties: {- operations: {- items: {- oneOf: [- {- properties: {- action: { const: 'insert', type: 'string' },- beforeId: { type: 'string' },- },- type: 'object',- },- {- properties: {- action: { const: 'modify', type: 'string' },- content: { type: 'string' },- },- type: 'object',- },- ],- },- type: 'array',- },- },- type: 'object',- },- },- type: 'function',- };-- const result = buildGoogleTool(tool);-- // All const values in nested oneOf should be converted to enum- const operations = result.parameters?.properties?.operations as any;- expect(operations.items.oneOf[0].properties.action).toEqual({- enum: ['insert'],- type: 'string',- });- expect(operations.items.oneOf[1].properties.action).toEqual({- enum: ['modify'],- type: 'string',- });- });-- it('should filter null values from enum arrays for Google compatibility', () => {- const tool: ChatCompletionTool = {- function: {- description: 'A tool with enum containing null',- name: 'enumTool',- parameters: {- properties: {- memoryType: {- enum: ['short_term', 'long_term', null, 'working'],- type: 'string',- },- nested: {- properties: {- status: {- enum: [null, 'active', 'inactive', null],- type: 'string',- },- },- type: 'object',- },- },- type: 'object',- },- },- type: 'function',- };-- const result = buildGoogleTool(tool);-- // null values should be filtered from enum arrays- expect(result.parameters?.properties).toEqual({- memoryType: {- enum: ['short_term', 'long_term', 'working'],- type: 'string',- },- nested: {- properties: {- status: {- enum: ['active', 'inactive'],- type: 'string',- },- },- type: 'object',- },- });- });-- it('should handle enum with only null values', () => {- const tool: ChatCompletionTool = {- function: {- description: 'A tool with enum containing only null',- name: 'nullEnumTool',- parameters: {- properties: {- value: {- enum: [null],- type: 'string',- },- },- type: 'object',- },- },- type: 'function',- };-- const result = buildGoogleTool(tool);-- // When enum only contains null, the enum property should be removed- expect(result.parameters?.properties?.value).toEqual({- type: 'string',- });- });-- it('should strip unsupported JSON Schema keywords like examples and default', () => {- const tool: ChatCompletionTool = {- function: {- description: 'A tool with unsupported schema keywords',- name: 'mcp_tool',- parameters: {- properties: {- query: {- default: 'hello',- description: 'Search query',- examples: ['weather in London', 'latest news'],- type: 'string',- },- nested: {- properties: {- format: {- $comment: 'internal note',- examples: ['json', 'xml'],- type: 'string',- },- },- type: 'object',- },- },- type: 'object',- },- },- type: 'function',- };-- const result = buildGoogleTool(tool);-- // examples, default should be stripped; $comment is silently ignored by the API- expect(result.parameters?.properties).toEqual({- query: {- description: 'Search query',- type: 'string',- },- nested: {- properties: {- format: {- $comment: 'internal note',- type: 'string',- },- },- type: 'object',- },- });- });-- it('should resolve $ref references from definitions', () => {+ it('should pass through $ref without needing to resolve', () => {const tool: ChatCompletionTool = {function: {description: 'A tool with $ref',@@ -1379,10 +1145,8 @@ describe('google contextBuilders', () => {parameters: {definitions: {timeIntent: {- additionalProperties: false,properties: {selector: { enum: ['today', 'yesterday', 'month'], type: 'string' },- date: { format: 'date-time', type: 'string' },},required: ['selector'],type: 'object',@@ -1390,146 +1154,7 @@ describe('google contextBuilders', () => {},properties: {query: { type: 'string' },- timeIntent: {- allOf: [{ $ref: '#/definitions/timeIntent' }],- },- },- type: 'object',- },- },- type: 'function',- };-- const result = buildGoogleTool(tool);-- // $ref should be resolved and inlined, allOf with single element unwrapped- expect(result.parameters?.properties).toEqual({- query: { type: 'string' },- timeIntent: {- properties: {- selector: { enum: ['today', 'yesterday', 'month'], type: 'string' },- date: { format: 'date-time', type: 'string' },- },- required: ['selector'],- type: 'object',- },- });- });-- it('should resolve nested $ref in oneOf', () => {- const tool: ChatCompletionTool = {- function: {- description: 'A tool with nested $ref in oneOf',- name: 'nestedRefTool',- parameters: {- definitions: {- mySchema: {- properties: { value: { type: 'integer' } },- type: 'object',- },- },- properties: {- anchor: {- oneOf: [- { enum: ['today', 'yesterday'], type: 'string' },- { $ref: '#/definitions/mySchema' },- ],- },- },- type: 'object',- },- },- type: 'function',- };-- const result = buildGoogleTool(tool);-- expect(result.parameters?.properties).toEqual({- anchor: {- oneOf: [- { enum: ['today', 'yesterday'], type: 'string' },- { properties: { value: { type: 'integer' } }, type: 'object' },- ],- },- });- });-- it('should strip definitions from output', () => {- const tool: ChatCompletionTool = {- function: {- description: 'Tool with definitions',- name: 'defTool',- parameters: {- definitions: {- foo: { type: 'string' },- },- properties: {- bar: { type: 'string' },- },- type: 'object',- },- },- type: 'function',- };-- const result = buildGoogleTool(tool);-- // definitions should not appear in the output properties- expect(result.parameters?.properties).toEqual({- bar: { type: 'string' },- });- });-- it('should preserve sibling fields next to $ref', () => {- const tool: ChatCompletionTool = {- function: {- description: 'A tool with $ref siblings',- name: 'siblingTool',- parameters: {- definitions: {- timeIntent: {- properties: {- selector: { type: 'string' },- },- required: ['selector'],- type: 'object',- },- },- properties: {- timeIntent: {- allOf: [{ $ref: '#/definitions/timeIntent' }],- description: 'Calendar-friendly time selector',- },- },- type: 'object',- },- },- type: 'function',- };-- const result = buildGoogleTool(tool);-- // description from sibling should be preserved after $ref resolution- expect(result.parameters?.properties).toEqual({- timeIntent: {- description: 'Calendar-friendly time selector',- properties: {- selector: { type: 'string' },- },- required: ['selector'],- type: 'object',- },- });- });-- it('should handle unknown $ref gracefully by stripping it', () => {- const tool: ChatCompletionTool = {- function: {- description: 'Tool with unknown ref',- name: 'unknownRefTool',- parameters: {- properties: {- field: { $ref: '#/definitions/nonExistent', description: 'some field' },+ timeIntent: { $ref: '#/definitions/timeIntent' },},type: 'object',},@@ -1539,28 +1164,20 @@ describe('google contextBuilders', () => {const result = buildGoogleTool(tool);- // Unknown $ref should be stripped, other properties kept- expect(result.parameters?.properties).toEqual({- field: { description: 'some field' },- });+ // $ref should be passed through as-is via parametersJsonSchema+ expect(result.parametersJsonSchema).toEqual(tool.function.parameters);});- it('should strip additionalProperties from schemas', () => {+ it('should pass through nullable types without sanitization', () => {const tool: ChatCompletionTool = {function: {- description: 'A tool with additionalProperties',- name: 'apTool',+ description: 'A tool with nullable enum',+ name: 'nullableTool',parameters: {properties: {- config: {- additionalProperties: false,- properties: {- nested: {- additionalProperties: { type: 'string' },- type: 'object',- },- },- type: 'object',+ status: {+ enum: ['active', 'inactive', null],+ type: ['string', 'null'],},},type: 'object',@@ -1571,35 +1188,18 @@ describe('google contextBuilders', () => {const result = buildGoogleTool(tool);- expect(result.parameters?.properties).toEqual({- config: {- properties: {- nested: {- type: 'object',- },- },- type: 'object',- },- });+ // nullable types and null enum values should be passed through as-is+ expect(result.parametersJsonSchema).toEqual(tool.function.parameters);});- it('should strip remaining $ref when resolveRefs exceeds depth limit', () => {- // Build a deeply recursive schema that exceeds depth limit of 10+ it('should pass through const values without conversion', () => {const tool: ChatCompletionTool = {function: {- description: 'A tool with deep recursive $ref',- name: 'deepRefTool',+ description: 'A tool with const',+ name: 'constTool',parameters: {- definitions: {- node: {- properties: {- child: { oneOf: [{ type: 'string' }, { $ref: '#/definitions/node' }] },- },- type: 'object',- },- },properties: {- root: { $ref: '#/definitions/node' },+ action: { const: 'insert', type: 'string' },},type: 'object',},@@ -1609,11 +1209,8 @@ describe('google contextBuilders', () => {const result = buildGoogleTool(tool);- // Verify no $ref remains anywhere in the output- const json = JSON.stringify(result);- expect(json).not.toContain('"$ref"');- // Also verify no additionalProperties- expect(json).not.toContain('"additionalProperties"');+ // const should be passed through as-is+ expect(result.parametersJsonSchema).toEqual(tool.function.parameters);});});@@ -1649,14 +1246,13 @@ describe('google contextBuilders', () => {expect(googleTools![0].functionDeclarations![0]).toEqual({description: 'A test tool',name: 'testTool',- parameters: {- description: undefined,+ parametersJsonSchema: {properties: {param1: { type: 'string' },param2: { type: 'number' },},required: ['param1'],- type: SchemaType.OBJECT,+ type: 'object',},});});diff --git a/packages/model-runtime/src/core/contextBuilders/google.ts b/packages/model-runtime/src/core/contextBuilders/google.tsindex 2372adda55c..62261be1488 100644--- a/packages/model-runtime/src/core/contextBuilders/google.ts+++ b/packages/model-runtime/src/core/contextBuilders/google.ts@@ -4,7 +4,6 @@ import type {Part,Tool as GoogleFunctionCallTool,} from '@google/genai';-import { Type as SchemaType } from '@google/genai';import { imageUrlToBase64 } from '@lobechat/utils';import type { ChatCompletionTool, OpenAIChatMessage, UserMessageContentPart } from '../../types';@@ -249,137 +248,25 @@ export const buildGoogleMessages = async (messages: OpenAIChatMessage[]): Promis};/**- * JSON Schema keywords that cause Google GenAI / Vertex AI SDK validation errors.- * Other unsupported keywords are silently ignored by the API, so only strip these.- */-const UNSUPPORTED_SCHEMA_KEYS = new Set(['examples', 'default', 'additionalProperties', '$ref']);--/**- * Resolve all `$ref` pointers in a JSON Schema tree by inlining definitions.- * Only handles internal `#/definitions/β¦` references (the kind produced by our manifests).- * Recursive references are guarded by a depth limit to avoid infinite loops.- */-const resolveRefs = (- node: Record<string, any>,- definitions: Record<string, any>,- depth = 0,-): Record<string, any> => {- if (!node || typeof node !== 'object' || depth > 10) return node;-- if (Array.isArray(node)) {- return node.map((item) => resolveRefs(item, definitions, depth));- }-- // Unwrap single-element allOf (common pattern: allOf: [{ $ref: '...' }])- if (Array.isArray(node.allOf) && node.allOf.length === 1) {- const { allOf, ...rest } = node;- return resolveRefs({ ...rest, ...allOf[0] }, definitions, depth);- }-- // If this node IS a $ref, replace it with the referenced definition- // Preserve sibling fields (e.g. description) that sit next to $ref- if (typeof node.$ref === 'string') {- const { $ref: ref, ...siblings } = node;- const match = ref.match(/^#\/definitions\/(.+)$/);- if (match && definitions[match[1]]) {- return resolveRefs({ ...definitions[match[1]], ...siblings }, definitions, depth + 1);- }- // Unknown $ref β return without it so Google doesn't choke- return siblings;- }-- const result: Record<string, any> = {};- for (const [key, value] of Object.entries(node)) {- // Drop definitions key after resolving β Google doesn't understand it- if (key === 'definitions') continue;-- if (value && typeof value === 'object') {- result[key] = resolveRefs(value, definitions, depth);- } else {- result[key] = value;- }- }- return result;-};--/**- * Sanitize JSON Schema for Google GenAI compatibility- * Google's API doesn't support certain JSON Schema keywords like 'const'- * This function recursively processes the schema and converts unsupported keywords- */-const sanitizeSchemaForGoogle = (- schema: Record<string, any>,- rootDefinitions?: Record<string, any>,-): Record<string, any> => {- if (!schema || typeof schema !== 'object') return schema;-- // Handle arrays- if (Array.isArray(schema)) {- return schema.map((item) => sanitizeSchemaForGoogle(item, rootDefinitions));- }-- const result: Record<string, any> = {};-- for (const [key, value] of Object.entries(schema)) {- // Strip unsupported JSON Schema keywords (e.g. examples, default, $schema)- if (UNSUPPORTED_SCHEMA_KEYS.has(key)) continue;-- // Drop definitions β already resolved by resolveRefs- if (key === 'definitions') continue;-- // Convert 'const' to 'enum' with single value (Google doesn't support 'const')- if (key === 'const') {- result['enum'] = [value];- continue;- }-- // Filter null values from enum arrays (Google doesn't support null in enum)- if (key === 'enum' && Array.isArray(value)) {- const filteredEnum = value.filter((item) => item !== null);- // Only set enum if there are remaining values after filtering- if (filteredEnum.length > 0) {- result[key] = filteredEnum;- }- continue;- }-- // Recursively process nested objects- if (value && typeof value === 'object') {- result[key] = sanitizeSchemaForGoogle(value, rootDefinitions);- } else {- result[key] = value;- }- }-- return result;-};--/**- * Convert ChatCompletionTool to Google FunctionDeclaration+ * Convert ChatCompletionTool to Google FunctionDeclaration.+ * Uses `parametersJsonSchema` to pass standard JSON Schema directly,+ * avoiding Google's restrictive Schema subset (no $ref, nullable, const, etc.).*/export const buildGoogleTool = (tool: ChatCompletionTool): FunctionDeclaration => {const functionDeclaration = tool.function;const parameters = functionDeclaration.parameters;+// refs: https://github.com/lobehub/lobe-chat/pull/5002- const rawProperties =- parameters?.properties && Object.keys(parameters.properties).length > 0- ? parameters.properties- : { dummy: { type: 'string' } }; // dummy property to avoid empty object+ const hasProperties = parameters?.properties && Object.keys(parameters.properties).length > 0;- // Resolve $ref references first, then sanitize for Google compatibility- const definitions = (parameters as any)?.definitions ?? {};- const resolved = resolveRefs(rawProperties, definitions);- const properties = sanitizeSchemaForGoogle(resolved, definitions);+ const jsonSchema = hasProperties+ ? parameters+ : { type: 'object', properties: { dummy: { type: 'string' } } };return {description: functionDeclaration.description,name: functionDeclaration.name,- parameters: {- description: parameters?.description,- properties,- required: parameters?.required,- type: SchemaType.OBJECT,- },+ parametersJsonSchema: jsonSchema,};};diff --git a/packages/model-runtime/src/providers/google/generateObject.test.ts b/packages/model-runtime/src/providers/google/generateObject.test.tsindex 916b8c715ad..2471e005fb3 100644--- a/packages/model-runtime/src/providers/google/generateObject.test.ts+++ b/packages/model-runtime/src/providers/google/generateObject.test.ts@@ -521,14 +521,13 @@ describe('Google generateObject', () => {{description: 'Get weather information',name: 'get_weather',- parameters: {- description: undefined,+ parametersJsonSchema: {properties: {city: { type: 'string' },unit: { type: 'string' },},required: ['city'],- type: SchemaType.OBJECT,+ type: 'object',},},],@@ -950,7 +949,7 @@ describe('Google generateObject', () => {{functionDeclarations: [expect.objectContaining({- parameters: expect.objectContaining({+ parametersJsonSchema: expect.objectContaining({properties: { dummy: { type: 'string' } },}),}),diff --git a/packages/model-runtime/src/providers/google/index.test.ts b/packages/model-runtime/src/providers/google/index.test.tsindex ec3fc80fd4e..83fdabf81ae 100644--- a/packages/model-runtime/src/providers/google/index.test.ts+++ b/packages/model-runtime/src/providers/google/index.test.ts@@ -708,11 +708,9 @@ describe('buildGoogleToolsWithSearch', () => {{name: 'test_tool',description: 'A test tool',- parameters: {- description: undefined,+ parametersJsonSchema: {properties: { dummy: { type: 'string' } },- required: undefined,- type: 'OBJECT',+ type: 'object',},},],