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(model-runtime): resolve Vertex AI $ref schema error and toolConfig incompatibility (#13524)

Arvin Xuf9f7283fecb5
diff --git a/packages/model-runtime/src/core/contextBuilders/google.test.ts b/packages/model-runtime/src/core/contextBuilders/google.test.ts
index 08a419b0a4f..c3b58fef969 100644
--- a/packages/model-runtime/src/core/contextBuilders/google.test.ts
+++ b/packages/model-runtime/src/core/contextBuilders/google.test.ts
@@ -1370,6 +1370,181 @@ describe('google contextBuilders', () => {
},
});
});
+
+ it('should resolve $ref references from definitions', () => {
+ const tool: ChatCompletionTool = {
+ function: {
+ description: 'A tool with $ref',
+ name: 'refTool',
+ parameters: {
+ definitions: {
+ timeIntent: {
+ additionalProperties: false,
+ properties: {
+ selector: { enum: ['today', 'yesterday', 'month'], type: 'string' },
+ date: { format: 'date-time', type: 'string' },
+ },
+ required: ['selector'],
+ type: 'object',
+ },
+ },
+ 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: {
+ additionalProperties: false,
+ 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' },
+ },
+ type: 'object',
+ },
+ },
+ type: 'function',
+ };
+
+ const result = buildGoogleTool(tool);
+
+ // Unknown $ref should be stripped, other properties kept
+ expect(result.parameters?.properties).toEqual({
+ field: { description: 'some field' },
+ });
+ });
});
describe('buildGoogleTools', () => {
diff --git a/packages/model-runtime/src/core/contextBuilders/google.ts b/packages/model-runtime/src/core/contextBuilders/google.ts
index 109f1e59ba5..b3abd2d9729 100644
--- a/packages/model-runtime/src/core/contextBuilders/google.ts
+++ b/packages/model-runtime/src/core/contextBuilders/google.ts
@@ -254,17 +254,68 @@ export const buildGoogleMessages = async (messages: OpenAIChatMessage[]): Promis
*/
const UNSUPPORTED_SCHEMA_KEYS = new Set(['examples', 'default']);
+/**
+ * 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>): Record<string, any> => {
+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));
+ return schema.map((item) => sanitizeSchemaForGoogle(item, rootDefinitions));
}
const result: Record<string, any> = {};
@@ -273,6 +324,9 @@ const sanitizeSchemaForGoogle = (schema: Record<string, any>): Record<string, an
// 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];
@@ -291,7 +345,7 @@ const sanitizeSchemaForGoogle = (schema: Record<string, any>): Record<string, an
// Recursively process nested objects
if (value && typeof value === 'object') {
- result[key] = sanitizeSchemaForGoogle(value);
+ result[key] = sanitizeSchemaForGoogle(value, rootDefinitions);
} else {
result[key] = value;
}
@@ -312,8 +366,10 @@ export const buildGoogleTool = (tool: ChatCompletionTool): FunctionDeclaration =
? parameters.properties
: { dummy: { type: 'string' } }; // dummy property to avoid empty object
- // Sanitize properties to remove unsupported JSON Schema keywords for Google
- const properties = sanitizeSchemaForGoogle(rawProperties);
+ // 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);
return {
description: functionDeclaration.description,
diff --git a/packages/model-runtime/src/providers/google/index.test.ts b/packages/model-runtime/src/providers/google/index.test.ts
index 3ce60054601..ec3fc80fd4e 100644
--- a/packages/model-runtime/src/providers/google/index.test.ts
+++ b/packages/model-runtime/src/providers/google/index.test.ts
@@ -722,6 +722,43 @@ describe('buildGoogleToolsWithSearch', () => {
expect(config.toolConfig).toEqual({ includeServerSideToolInvocations: true });
});
+ it('should not set includeServerSideToolInvocations for Vertex AI', async () => {
+ const vertexInstance = new LobeGoogleAI({ apiKey: 'test', isVertexAi: true });
+ const mockStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue({
+ text: 'test',
+ candidates: [
+ {
+ content: { parts: [{ text: 'test' }], role: 'model' },
+ finishReason: 'STOP',
+ index: 0,
+ },
+ ],
+ usageMetadata: { promptTokenCount: 1, totalTokenCount: 2 },
+ modelVersion: 'gemini-3.1-pro-preview',
+ });
+ controller.close();
+ },
+ });
+ vi.spyOn(vertexInstance['client'].models, 'generateContentStream').mockResolvedValue(
+ mockStream as any,
+ );
+
+ await vertexInstance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gemini-3.1-pro-preview',
+ temperature: 0,
+ enabledSearch: true,
+ tools: [{ type: 'function', function: { name: 'test_tool', description: 'A test tool' } }],
+ });
+
+ const callArgs = (vertexInstance['client'].models.generateContentStream as any).mock.calls[0];
+ const config = callArgs[0].config as any;
+ // Vertex AI does not support includeServerSideToolInvocations
+ expect(config.toolConfig).toBeUndefined();
+ });
+
it('should not set toolConfig when Gemini 3+ has only search tools without function declarations', async () => {
const mockStream = new ReadableStream({
start(controller) {
diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.ts
index 492b7eec67f..78a88bcdd79 100644
--- a/packages/model-runtime/src/providers/google/index.ts
+++ b/packages/model-runtime/src/providers/google/index.ts
@@ -219,9 +219,11 @@ export class LobeGoogleAI implements LobeRuntimeAI {
? undefined
: thinkingConfig,
// https://ai.google.dev/gemini-api/docs/tool-combination
- toolConfig: this.needsServerSideToolInvocations(payload)
- ? { includeServerSideToolInvocations: true }
- : undefined,
+ // Vertex AI does not support includeServerSideToolInvocations
+ toolConfig:
+ !this.isVertexAi && this.needsServerSideToolInvocations(payload)
+ ? { includeServerSideToolInvocations: true }
+ : undefined,
tools: this.buildGoogleToolsWithSearch(payload.tools, payload),
topP: payload.top_p,
};