Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(js/ai): Fixes use of namespaced tools in model calls. #1423

Merged
merged 4 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
20 changes: 16 additions & 4 deletions js/ai/src/generate/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/

import {
GenkitError,
getStreamingCallback,
runWithStreamingCallback,
z,
Expand Down Expand Up @@ -116,6 +117,19 @@ async function generate(
const tools = await resolveTools(registry, rawRequest.tools);

const resolvedFormat = await resolveFormat(registry, rawRequest.output);
// Create a lookup of tool names with namespaces stripped to original names
const toolMap = tools.reduce<Record<string, ToolAction>>((acc, tool) => {
const name = tool.__action.name;
const shortName = name.substring(name.lastIndexOf('/') + 1);
if (acc[shortName]) {
throw new GenkitError({
status: 'INVALID_ARGUMENT',
message: `Cannot provide two tools with the same name: '${name}' and '${acc[shortName]}'`,
});
}
acc[shortName] = tool;
return acc;
}, {});

const request = await actionToGenerateRequest(
rawRequest,
Expand Down Expand Up @@ -184,9 +198,7 @@ async function generate(
'Tool request expected but not provided in tool request part'
);
}
const tool = tools?.find(
(tool) => tool.__action.name === part.toolRequest?.name
);
const tool = toolMap[part.toolRequest?.name];
if (!tool) {
throw Error(`Tool ${part.toolRequest?.name} not found`);
}
Expand Down Expand Up @@ -238,7 +250,7 @@ async function actionToGenerateRequest(
messages: options.messages,
config: options.config,
docs: options.docs,
tools: resolvedTools?.map((tool) => toToolDefinition(tool)) || [],
tools: resolvedTools?.map((tool) => toToolDefinition(tool, true)) || [],
output: {
...(resolvedFormat?.config || {}),
schema: toJsonSchema({
Expand Down
10 changes: 8 additions & 2 deletions js/ai/src/tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,16 @@ export async function lookupToolByName(
* Converts a tool action to a definition of the tool to be passed to a model.
*/
export function toToolDefinition(
tool: Action<z.ZodTypeAny, z.ZodTypeAny>
tool: Action<z.ZodTypeAny, z.ZodTypeAny>,
stripNamespace = false
): ToolDefinition {
let name = tool.__action.name;
if (stripNamespace) {
name = name.substring(name.lastIndexOf('/') + 1);
}

return {
name: tool.__action.name,
name,
description: tool.__action.description || '',
outputSchema: toJsonSchema({
schema: tool.__action.outputSchema ?? z.void(),
Expand Down
50 changes: 49 additions & 1 deletion js/ai/tests/generate/generate_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

import { z } from '@genkit-ai/core';
import { PluginProvider, z } from '@genkit-ai/core';
import { Registry } from '@genkit-ai/core/registry';
import assert from 'node:assert';
import { beforeEach, describe, it } from 'node:test';
Expand Down Expand Up @@ -43,6 +43,23 @@ describe('toGenerateRequest', () => {
}
);

const namespacedPlugin: PluginProvider = {
name: 'namespaced',
initializer: async () => {},
};
registry.registerPluginProvider('namespaced', namespacedPlugin);

const namespacedTool = defineTool(
registry,
{
name: 'namespaced/add',
description: 'add two numbers together',
inputSchema: z.object({ a: z.number(), b: z.number() }),
outputSchema: z.number(),
},
async ({ a, b }) => a + b
);

const testCases = [
{
should: 'translate a string prompt correctly',
Expand Down Expand Up @@ -95,6 +112,37 @@ describe('toGenerateRequest', () => {
output: {},
},
},
{
should: 'strip namespaces from tools when passing to the model',
prompt: {
model: 'vertexai/gemini-1.0-pro',
tools: ['namespaced/add'],
prompt: 'Add 10 and 5.',
},
expectedOutput: {
messages: [{ role: 'user', content: [{ text: 'Add 10 and 5.' }] }],
config: undefined,
docs: undefined,
tools: [
{
description: 'add two numbers together',
inputSchema: {
$schema: 'http://json-schema.org/draft-07/schema#',
additionalProperties: true,
properties: { a: { type: 'number' }, b: { type: 'number' } },
required: ['a', 'b'],
type: 'object',
},
name: 'namespaced/add',
mbleigh marked this conversation as resolved.
Show resolved Hide resolved
outputSchema: {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'number',
},
},
],
output: {},
},
},
{
should:
'translate a string prompt correctly with tools referenced by their action',
Expand Down
2 changes: 1 addition & 1 deletion js/genkit/src/genkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,7 @@ export class Genkit {
if (!response.tools && options.tools) {
response.tools = (
await resolveTools(this.registry, options.tools)
).map(toToolDefinition);
).map((t) => toToolDefinition(t));
}
if (!response.output && options.output) {
response.output = {
Expand Down
50 changes: 42 additions & 8 deletions js/testapps/flow-simple-ai/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { initializeApp } from 'firebase-admin/app';
import { getFirestore } from 'firebase-admin/firestore';
import { MessageSchema, genkit, run, z } from 'genkit';
import { logger } from 'genkit/logging';
import { PluginProvider } from 'genkit/plugin';
import { Allow, parse } from 'partial-json';

logger.setLogLevel('debug');
Expand All @@ -53,6 +54,32 @@ const ai = genkit({
plugins: [googleAI(), vertexAI()],
});

const math: PluginProvider = {
name: 'math',
initializer: async () => {
ai.defineTool(
{
name: 'math/add',
description: 'add two numbers',
inputSchema: z.object({ a: z.number(), b: z.number() }),
outputSchema: z.number(),
},
async ({ a, b }) => a + b
);

ai.defineTool(
{
name: 'math/subtract',
description: 'subtract two numbers',
inputSchema: z.object({ a: z.number(), b: z.number() }),
outputSchema: z.number(),
},
async ({ a, b }) => a - b
);
},
};
ai.registry.registerPluginProvider('math', math);

const app = initializeApp();

export const jokeFlow = ai.defineFlow(
Expand Down Expand Up @@ -538,11 +565,18 @@ export const arrayStreamTester = ai.defineStreamingFlow(
}
);

// async function main() {
// const { stream, output } = arrayStreamTester();
// for await (const chunk of stream) {
// console.log(chunk);
// }
// console.log(await output);
// }
// main();
ai.defineFlow(
{
name: 'math',
inputSchema: z.string(),
outputSchema: z.string(),
},
async (query) => {
const { text } = await ai.generate({
model: gemini15Flash,
prompt: query,
tools: ['math/add', 'math/subtract'],
});
return text;
}
);