Skip to content
Open
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
28 changes: 20 additions & 8 deletions js/ai/src/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,8 @@ async function toolsToActionRefs(

for (const t of toolOpt) {
if (typeof t === 'string') {
tools.push(await resolveFullToolName(registry, t));
const names = await resolveFullToolNames(registry, t);
tools.push(...names);
} else if (isAction(t) || isDynamicTool(t)) {
tools.push(`/${t.__action.metadata?.type}/${t.__action.name}`);
} else if (isExecutablePrompt(t)) {
Expand Down Expand Up @@ -530,17 +531,28 @@ function stripUndefinedOptions(input?: any): any {
return copy;
}

async function resolveFullToolName(
async function resolveFullToolNames(
registry: Registry,
name: string
): Promise<string> {
): Promise<string[]> {
let names: string[];
const parts = name.split(':');
if (parts.length > 1) {
// Dynamic Action Provider
names = await registry.resolveActionNames(
`/dynamic-action-provider/${name}`
);
if (names.length) {
return names;
}
}
if (await registry.lookupAction(`/tool/${name}`)) {
return `/tool/${name}`;
} else if (await registry.lookupAction(`/prompt/${name}`)) {
return `/prompt/${name}`;
} else {
throw new Error(`Unable to determine type of of tool: ${name}`);
return [`/tool/${name}`];
}
if (await registry.lookupAction(`/prompt/${name}`)) {
return [`/prompt/${name}`];
}
throw new Error(`Unable to resolve tool: ${name}`);
}

export type GenerateStreamOptions<
Expand Down
3 changes: 2 additions & 1 deletion js/ai/src/tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,8 @@ export async function lookupToolByName(
const tool =
(await registry.lookupAction(name)) ||
(await registry.lookupAction(`/tool/${name}`)) ||
(await registry.lookupAction(`/prompt/${name}`));
(await registry.lookupAction(`/prompt/${name}`)) ||
(await registry.lookupAction(`/dynamic-action-provider/${name}`));
if (!tool) {
throw new Error(`Tool ${name} not found`);
}
Expand Down
168 changes: 168 additions & 0 deletions js/core/src/dynamic-action-provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/**
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type * as z from 'zod';
import { Action, ActionMetadata, defineAction } from './action.js';
import { ActionType, Registry } from './registry.js';

type DapValue = {
[K in ActionType]?: Action<z.ZodTypeAny, z.ZodTypeAny, z.ZodTypeAny>[];
};

class SimpleCache {
private value: DapValue | undefined;
private expiresAt: number | undefined;
private ttlMillis: number;
private dap: DapAction;
private dapFn: DapFn;

constructor(dap: DapAction, config: DapConfig, dapFn: DapFn) {
this.dap = dap;
this.dapFn = dapFn;
this.ttlMillis = config.cacheConfig?.ttlMillis || 3 * 1000;
}

async getOrFetch(): Promise<DapValue> {
if (
!this.value ||
!this.expiresAt ||
this.ttlMillis < 0 ||
Date.now() > this.expiresAt
) {
// Get a new value
this.value = await this.dapFn(); // this returns the actual actions
this.expiresAt = Date.now() + this.ttlMillis;

// Also run the action
this.dap.run(this.value); // This returns metadata and shows up in dev UI
}
return this.value;
}
}

export interface DynamicRegistry {
__cache: SimpleCache;
getAction(
actionType: string,
actionName: string
): Promise<Action<z.ZodTypeAny, z.ZodTypeAny, z.ZodTypeAny>>;
listActions(
actionType: string,
actionName: string
): Promise<Action<z.ZodTypeAny, z.ZodTypeAny, z.ZodTypeAny>[]>;
}

export type DapAction = Action<z.ZodTypeAny, z.ZodTypeAny, z.ZodTypeAny> &
DynamicRegistry & {
__action: {
metadata: {
type: 'dynamic-action-provider';
};
};
};

export function isDynamicActionProvider(
obj: Action<z.ZodTypeAny, z.ZodTypeAny>
): obj is DapAction {
return obj.__action?.metadata?.type == 'dynamic-action-provider';
}

export interface DapConfig {
name: string;
description?: string;
cacheConfig?: {
// Negative = no caching
// Zero or undefined = default (3000 milliseconds)
// Positive number = how many milliseconds the cache is valid for
ttlMillis: number;
};
metadata?: Record<string, any>;
}

export type DapFn = () => Promise<DapValue>;
export type DapMetadata = {
[K in ActionType]?: ActionMetadata[];
};

function transformDapValue(value: DapValue): DapMetadata {
const metadata: DapMetadata = {};
for (const key of Object.keys(value)) {
metadata[key] = value[key].map((a) => {
return a.__action;
});
}
return metadata;
}

export function defineDynamicActionProvider(
registry: Registry,
config: DapConfig | string,
fn: DapFn
): DapAction {
let cfg: DapConfig;
if (typeof config == 'string') {
cfg = { name: config };
} else {
cfg = { ...config };
}
const a = defineAction(
registry,
{
...cfg,
actionType: 'dynamic-action-provider',
metadata: { ...(cfg.metadata || {}), type: 'dynamic-action-provider' },
},
async (i, _options) => {
// The actions are retrieved and saved in a cache and then passed in here.
// We run this action to return the metadata for the actions only.
// We pass the actions in here to prevent duplicate calls to the mcp
// and also so we are guaranteed the same actions since there is only a
// single call to mcp client/host.
return transformDapValue(i);
}
);
implementDap(a as DapAction, cfg, fn);
return a as DapAction;
}

function implementDap(dap: DapAction, config: DapConfig, dapFn: DapFn) {
dap.__cache = new SimpleCache(dap, config, dapFn);

dap.getAction = async (actionType: string, actionName: string) => {
let result = await dap.__cache.getOrFetch();
if (result[actionType]) {
const action = result[actionType].find(
(t) => t.__action.name == actionName
);
return action;
}
return undefined;
};

dap.listActions = async (actionType: string, actionName: string) => {
let result = await dap.__cache.getOrFetch();
if (result[actionType] && actionName == '*') {
return result[actionType];
}
const action = result[actionType].find(
(t) => t.__action.name == actionName
);
if (action) {
return [action];
}
return [];
};
}
6 changes: 6 additions & 0 deletions js/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ export {
type ContextProvider,
type RequestData,
} from './context.js';
export {
defineDynamicActionProvider,
type DapAction,
type DapConfig,
type DapFn,
} from './dynamic-action-provider.js';
export {
GenkitError,
UnstableApiError,
Expand Down
Loading