AI SDK - 代码模式
@ai-sdk/code-mode 让模型写 JavaScript 或调用您的类型脚本
AI SDK工具. 代码在一个孤立的QuickJS 沙盒中运行并返回 a
JSON的系列价值.
设置
npm i ai @ai-sdk/code-mode zod
使用量
import {
DIRECT_TOOL_CALL,
experimental_codeModeTool as codeModeTool,
} from '@ai-sdk/code-mode';
import { generateText, isStepCount, tool } from 'ai';
import { z } from 'zod';
const getInventory = tool({
description: 'Get available inventory for a product.',
inputSchema: z.object({ productId: z.string() }),
outputSchema: z.object({
productId: z.string(),
availableUnits: z.number(),
}),
execute: async ({ productId }) => ({
productId,
availableUnits: 42,
}),
});
const getDemand = tool({
description: 'Get requested units for a product.',
inputSchema: z.object({ productId: z.string() }),
outputSchema: z.object({
productId: z.string(),
requestedUnits: z.number(),
}),
execute: async ({ productId }) => ({
productId,
requestedUnits: 31,
}),
});
const tools = {
code_mode: codeModeTool({
executionPolicy: {
timeoutMs: 30_000,
},
}),
getInventory,
getDemand,
} as const;
const result = await generateText({
model,
tools,
experimental_toolCallers: {
getInventory: ['code_mode', DIRECT_TOOL_CALL],
getDemand: ['code_mode'],
},
stopWhen: isStepCount(10),
prompt: 'Compare inventory and demand for product sku_123.',
});
见 代码模式文档 更多信息.