src/tools/tool.ts
5 KB - 查看原始文件
// A tool is a contract between the model and your code:
// - a name and a description the model reads to decide when to call it,
// - an input schema (Zod) that is sent to the API as JSON Schema AND used to validate the
// input before the tool runs,
// - a run function that returns text (or throws, which becomes an error result).
//
// Lab 01 introduced this file. Lab 04 adds output limits and `summarize` (a one-line description
// of a call, used by approvals and the audit log). Lab 06 adds `definition` for tools that
// Anthropic defines, such as the memory tool.
import { z } from 'zod';
import type { BetaToolUnion } from '../core/model.ts';
export interface ToolContext {
/** IANA time zone of the owner, for tools that deal with dates. */
timezone: string;
/** Clock used by date tools. Tests pass a fixed clock. */
now: () => Date;
/** Longest text a tool may return; longer output is cut with a note (lab 04). */
maxOutputChars?: number;
/** Aborted when the turn is cancelled or the gateway shuts down (lab 12). */
signal?: AbortSignal;
}
export interface Tool<Input = unknown> {
name: string;
description: string;
input: z.ZodType<Input>;
/**
* API definition to send instead of one generated from `input`. Used for Anthropic-defined
* tools (lab 06): the model already knows their schema.
*/
definition?: BetaToolUnion;
/** One line describing a call, for approvals and the audit log. Defaults to the JSON input. */
summarize?(input: Input): string;
/** For program-running tools: the argument vector the policy matches against (lab 05). */
argv?(input: Input): string[];
// Method syntax (not an arrow property) so a Tool<{ date: string }> can sit in a Tool[] list.
run(input: Input, context: ToolContext): Promise<string> | string;
}
/** Helper that infers the input type of `run` from the schema. */
export function defineTool<Input>(tool: Tool<Input>): Tool<Input> {
return tool;
}
/** Converts a tool to the API's tool definition. */
export function toApiTool(tool: Tool): BetaToolUnion {
if (tool.definition) return tool.definition;
// The API wants a plain object schema; drop the "$schema" dialect marker Zod adds.
const schema = { ...(z.toJSONSchema(tool.input) as Record<string, unknown>) };
delete schema.$schema;
return {
name: tool.name,
description: tool.description,
input_schema: { ...schema, type: 'object' },
};
}
export interface ToolOutcome {
content: string;
isError: boolean;
}
export type ParsedCall =
{ ok: true; tool: Tool; input: unknown } | { ok: false; outcome: ToolOutcome };
/** Finds the tool and validates the model's input. */
export function parseCall(tools: readonly Tool[], name: string, rawInput: unknown): ParsedCall {
const tool = tools.find((t) => t.name === name);
if (!tool) return { ok: false, outcome: { content: `Unknown tool: ${name}`, isError: true } };
const parsed = tool.input.safeParse(rawInput);
if (!parsed.success) {
const problems = parsed.error.issues
.map((issue) => `${issue.path.join('.') || 'input'}: ${issue.message}`)
.join('; ');
return {
ok: false,
outcome: { content: `Invalid input for ${name}: ${problems}`, isError: true },
};
}
return { ok: true, tool, input: parsed.data };
}
/** Runs an already-validated call. Never throws. */
export async function execute(
tool: Tool,
input: unknown,
context: ToolContext,
): Promise<ToolOutcome> {
try {
const content = await tool.run(input, context);
return { content: limitOutput(content, context.maxOutputChars), isError: false };
} catch (err) {
return { content: `${tool.name} failed: ${(err as Error).message}`, isError: true };
}
}
/**
* Validates the model's input and runs the tool. Never throws: every failure becomes an error
* result the model can read and react to.
*/
export async function runTool(
tools: readonly Tool[],
name: string,
rawInput: unknown,
context: ToolContext,
): Promise<ToolOutcome> {
const call = parseCall(tools, name, rawInput);
return call.ok ? execute(call.tool, call.input, context) : call.outcome;
}
export function describeCall(tool: Tool, input: unknown): string {
const text = tool.summarize ? tool.summarize(input) : `${tool.name} ${JSON.stringify(input)}`;
return text.length > 200 ? `${text.slice(0, 197)}...` : text;
}
/** Cuts long output and says so. Long tool output costs tokens and can hide injected text. */
export function limitOutput(text: string, maxChars = 12_000): string {
if (text.length <= maxChars) return text;
const hidden = text.length - maxChars;
return `${text.slice(0, maxChars)}\n[output cut: ${hidden} more characters not shown]`;
}