Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,108 @@ describe('inferenceEndpointAdapter', () => {
);
});

it('sanitizes tool schemas when the provider is googlevertexai', () => {
executorMock.invoke.mockResolvedValue(
observableIntoEventSourceStream(of(createOpenAIChunk({ delta: { content: '' } })), logger)
);

const tools = {
myTool: {
description: 'my tool',
schema: {
type: 'object' as const,
properties: {
// shape emitted by zod v4 for `z.record(z.string(), z.string())`
someRecord: {
type: 'object',
propertyNames: { type: 'string' },
additionalProperties: { type: 'string' },
},
} as Record<string, any>,
},
},
};

inferenceEndpointAdapter
.chatComplete({
...defaultArgs,
provider: 'googlevertexai',
messages: [{ role: MessageRole.User, content: 'question' }],
tools,
})
.subscribe(noop);

expect(executorMock.invoke).toHaveBeenCalledWith(
expect.objectContaining({
body: expect.objectContaining({
tools: [
{
type: 'function',
function: {
name: 'myTool',
description: 'my tool',
parameters: {
type: 'object',
properties: {
someRecord: {
type: 'object',
additionalProperties: { type: 'string' },
},
},
},
},
},
],
}),
})
);
});

it('leaves tool schemas untouched for other providers', () => {
executorMock.invoke.mockResolvedValue(
observableIntoEventSourceStream(of(createOpenAIChunk({ delta: { content: '' } })), logger)
);

const schema = {
type: 'object' as const,
properties: {
someRecord: {
type: 'object',
propertyNames: { type: 'string' },
additionalProperties: { type: 'string' },
},
} as Record<string, any>,
};

inferenceEndpointAdapter
.chatComplete({
...defaultArgs,
provider: 'amazonbedrock',
messages: [{ role: MessageRole.User, content: 'question' }],
tools: {
myTool: { description: 'my tool', schema },
},
})
.subscribe(noop);

expect(executorMock.invoke).toHaveBeenCalledWith(
expect.objectContaining({
body: expect.objectContaining({
tools: [
{
type: 'function',
function: {
name: 'myTool',
description: 'my tool',
parameters: schema,
},
},
],
}),
})
);
});

it('injects a dummy tool when history has tool use and tools are omitted', () => {
executorMock.invoke.mockResolvedValue(
observableIntoEventSourceStream(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type {
ChatCompletionChunkEvent,
ChatCompletionTokenCountEvent,
} from '@kbn/inference-common';
import { InferenceEndpointProvider } from '@kbn/inference-common';
import { eventSourceStreamIntoObservable } from '../../../util/event_source_stream_into_observable';
import {
processOpenAIStream,
Expand All @@ -31,6 +32,7 @@ import {
import { getTemperatureIfValid } from '../../utils/get_temperature';
import type { InferenceEndpointExecutor } from '../../utils/inference_endpoint_executor';
import { ensureToolsWhenHistoryHasToolUse } from '../../utils/ensure_tools_when_history_has_tool_use';
import { sanitizeToolSchemasForVertex } from './sanitize_tool_schemas_for_vertex';
import type { OpenAIRequest } from '../openai/types';

export interface InferenceEndpointAdapterChatCompleteOptions {
Expand All @@ -43,6 +45,7 @@ export interface InferenceEndpointAdapterChatCompleteOptions {
modelName?: string;
// Endpoint model identity is authoritative for parameter support.
endpointModelId?: string;
provider?: string;
abortSignal?: AbortSignal;
metadata?: ChatCompleteMetadata;
stream?: boolean;
Expand All @@ -65,6 +68,7 @@ export const inferenceEndpointAdapter = {
temperature,
modelName,
endpointModelId,
provider,
logger,
abortSignal,
timeout,
Expand All @@ -73,11 +77,16 @@ export const inferenceEndpointAdapter = {

const useSimulatedFunctionCalling = functionCalling === 'simulated';

const sanitizedTools =
provider === InferenceEndpointProvider.GoogleVertexAI
? sanitizeToolSchemasForVertex(tools)
: tools;
Comment on lines +80 to +83

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would move that inside createEndpointRequest, better isolation of concerns ihmo

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simple condition, if it ever expands to more providers, definitely makes sense, gonna merge now to unblock.


const request = createEndpointRequest({
system,
messages,
toolChoice,
tools,
tools: sanitizedTools,
simulatedFunctionCalling: useSimulatedFunctionCalling,
temperature,
modelName,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { pick } from 'lodash';
import { z } from '@kbn/zod/v4';
import type { ToolSchema } from '@kbn/inference-common';
import { sanitizeToolSchemasForVertex } from './sanitize_tool_schemas_for_vertex';

// mirrors how tool schemas are converted before reaching the adapters,
// see `resolveToolSchema` in `@kbn/inference-langchain`
const toToolSchema = (zodSchema: z.ZodType): ToolSchema =>
pick(z.toJSONSchema(zodSchema, { io: 'input' }), [
'type',
'properties',
'required',
]) as ToolSchema;

describe('sanitizeToolSchemasForVertex', () => {
it('rebuilds tool schemas keeping only the fields Vertex AI accepts', () => {
const schema = toToolSchema(
z.object({
size: z.number().positive().lt(100).optional(),
mode: z.literal('fast'),
filter: z.union([z.string(), z.array(z.string())]).optional(),
note: z.string().nullable(),
data: z.record(z.string(), z.string()),
// discriminated unions emit `oneOf` with `const` discriminators inside
operations: z.array(
z.discriminatedUnion('type', [
z.object({ type: z.literal('add'), config: z.record(z.string(), z.string()) }),
z.object({ type: z.literal('remove') }),
])
),
})
);
// zod v4 emits keywords rejected by Vertex: `propertyNames` for records,
// `exclusiveMinimum`/`exclusiveMaximum` for number bounds and `const` for literals
expect(JSON.stringify(schema)).toContain('propertyNames');
expect(JSON.stringify(schema)).toContain('exclusiveMinimum');
expect(JSON.stringify(schema)).toContain('exclusiveMaximum');
expect(JSON.stringify(schema)).toContain('const');

const sanitized = sanitizeToolSchemasForVertex({
myTool: {
description: 'some cool tool',
schema,
},
});

expect(sanitized).toEqual({
myTool: {
description: 'some cool tool',
schema: {
type: 'object',
properties: {
size: {
type: 'number',
},
mode: {
type: 'string',
enum: ['fast'],
},
filter: {
anyOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }],
},
note: {
type: 'string',
nullable: true,
},
data: {
type: 'object',
additionalProperties: { type: 'string' },
},
operations: {
type: 'array',
items: {
anyOf: [
{
type: 'object',
properties: {
type: { type: 'string', enum: ['add'] },
config: {
type: 'object',
additionalProperties: { type: 'string' },
},
},
required: ['type', 'config'],
},
{
type: 'object',
properties: {
type: { type: 'string', enum: ['remove'] },
},
required: ['type'],
},
],
},
},
},
required: ['mode', 'note', 'data', 'operations'],
},
},
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comments in this file are verbose, but considering what it does, I think it's worth keeping them to be explicitly clear about why these functions are needed. Will remove if anyone thinks otherwise.

* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { mapValues } from 'lodash';
import type { ToolOptions, ToolSchemaType } from '@kbn/inference-common';

export const sanitizeToolSchemasForVertex = (tools: ToolOptions['tools']): ToolOptions['tools'] => {
if (!tools) {
return tools;
}

return mapValues(tools, (tool) => ({
...tool,
schema: tool.schema ? toVertexSchema(tool.schema) : undefined,
}));
};

/**
* Fields of Vertex AI's function declaration schema, "a select subset of an
* OpenAPI 3.0 schema object". Any other field is rejected with a 400.
* https://github.com/googleapis/googleapis/blob/master/google/cloud/aiplatform/v1/openapi.proto
*/
const VERTEX_SCHEMA_FIELDS = new Set([
'type',
'format',
'title',
'description',
'nullable',
'default',
'items',
'minItems',
'maxItems',
'enum',
'properties',
'propertyOrdering',
'required',
'minProperties',
'maxProperties',
'minimum',
'maximum',
'minLength',
'maxLength',
'pattern',
'example',
'anyOf',
'additionalProperties',
]);

/**
* `ToolSchemaType` does not model everything zod v4 emits, so the
* conversion operates on this loose representation.
*/
interface SchemaPart {
[key: string]: unknown;
const?: unknown;
type?: string;
nullable?: boolean;
enum?: unknown[];
properties?: Record<string, ToolSchemaType>;
items?: ToolSchemaType;
additionalProperties?: ToolSchemaType | boolean;
anyOf?: ToolSchemaType[];
oneOf?: ToolSchemaType[];
}

/**
* Rebuilds a tool schema keeping only the fields Vertex AI accepts, so that
* JSON Schema keywords zod v4 (or user-provided tool schemas) emit never reach
* Vertex's parser. Conversions preserve the intent of dropped fields:
* `const: 'x'` becomes `enum: ['x']`, `oneOf` branches become `anyOf`, and a
* `null` branch in `anyOf` (zod's representation of nullable values) becomes
* `nullable: true`.
*/
const toVertexSchema = <T extends ToolSchemaType>(schemaPart: T): T => {
Comment on lines +70 to +78

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I really hate that we have to do this, it's crazy that they didn't improve this in 2 years, but I don't see an alternative, so...

const source = schemaPart as SchemaPart;
const schema: SchemaPart = {};

for (const [key, value] of Object.entries(source)) {
if (VERTEX_SCHEMA_FIELDS.has(key)) {
schema[key] = value;
}
}

if (typeof source.const === 'string' && schema.enum === undefined) {
schema.enum = [source.const];
}

if (source.oneOf) {
schema.anyOf = [...(schema.anyOf ?? []), ...source.oneOf];
}

if (schema.properties) {
schema.properties = mapValues(schema.properties, toVertexSchema);
}
if (schema.items) {
schema.items = toVertexSchema(schema.items);
}
if (typeof schema.additionalProperties === 'object') {
schema.additionalProperties = toVertexSchema(schema.additionalProperties);
}
if (schema.anyOf) {
const branches = schema.anyOf.map(toVertexSchema);
const nonNullBranches = branches.filter((branch) => (branch as SchemaPart).type !== 'null');

if (nonNullBranches.length === branches.length) {
schema.anyOf = branches;
} else {
schema.nullable = true;
if (nonNullBranches.length === 1) {
delete schema.anyOf;
Object.assign(schema, nonNullBranches[0]);
} else {
schema.anyOf = nonNullBranches;
}
}
}

return schema as unknown as T;
};
Loading
Loading