工具
您可以注册工具(也称为函数),LLM在构建答案时可能会决定调用这些工具。 参见OpenAI函数、Ollama工具或Anthropic工具使用。
并非所有LLM模型都支持工具功能,在这些情况下,GenAIScript也支持通过系统提示实现工具调用的回退机制(参见Fallback Tools)。
defTool
defTool
用于定义一个可供大语言模型调用的工具。
它接收一个JSON模式来定义输入,并期望输出字符串。
参数使用parameters schema进行定义。
LLM决定自行调用此工具!
defTool( "current_weather", "get the current weather", { city: "", }, (args) => { const { location } = args if (location === "Brussels") return "sunny" else return "variable" })
在上面的示例中,我们定义了一个名为current_weather
的工具,它接收位置作为输入并返回天气信息。
天气工具示例
这个例子使用current_weather
工具来获取布鲁塞尔的天气。
script({ model: "small", title: "Weather as function", description: "Query the weather for each city using a dummy weather function", temperature: 0.5, files: "src/cities.md", tests: { files: "src/cities.md", keywords: "Brussels", },})
$`Query the weather for each listed city and return the results as a table.`
def("CITIES", env.files)
defTool( "get_current_weather", "get the current weather", { type: "object", properties: { location: { type: "string", description: "The city and state, e.g. San Francisco, CA", }, }, required: ["location"], }, (args) => { const { context, location } = args const { trace } = context
trace.log(`Getting weather for ${location}...`)
let content = "variable" if (location === "Brussels") content = "sunny"
return content })
数学工具示例
这个示例使用数学表达式求值器来评估一个数学表达式。
script({ title: "math-agent", model: "small", description: "A port of https://ts.llamaindex.ai/examples/agent", parameters: { question: { type: "string", default: "How much is 11 + 4? then divide by 3?", }, }, tests: { description: "Testing the default prompt", keywords: "5", },})
defTool( "sum", "Use this function to sum two numbers", { a: 1, b: 2 }, ({ a, b }) => { console.log(`${a} + ${b}`) return `${a + b}` })
defTool( "divide", "Use this function to divide two numbers", { type: "object", properties: { a: { type: "number", description: "The first number", }, b: { type: "number", description: "The second number", }, }, required: ["a", "b"], }, ({ a, b }) => { console.log(`${a} / ${b}`) return `${a / b}` })
$`Answer the following arithmetic question:
${env.vars.question}`
在系统脚本中复用工具
您可以在系统脚本中定义工具,并将它们像其他系统脚本或工具一样包含到您的主脚本中。
system({ description: "Random tools" })
export default function (ctx: ChatGenerationContext) { const { defTool } = ctx defTool("random", "Generate a random number", {}, () => Math.random())}
- 确保在系统脚本中使用
system
而不是script
。
script({ title: "Random number", tools: ["random"],})$`Generate a random number.
同一系统脚本的多个实例
您可以在脚本中多次包含相同的系统脚本,只需使用不同的参数即可。
script({ system: [ "system.agent_git", // git operations on current repository { id: "system.agent_git", // same system script parameters: { repo: "microsoft/genaiscript" } // but with new parameters variant: "genaiscript" // appened to the identifier to keep tool identifiers unique } ]})
模型上下文协议工具
Model Context Provider (MCP) 是一个开放协议,可实现LLM应用程序与外部数据源和工具之间的无缝集成。
您可以利用MCP服务器为您的LLM提供工具。
defTool({ memory: { command: "npx", args: ["-y", "@modelcontextprotocol/server-memory"], },})
更多信息请参见Model Context Protocol Tools。
代理工具
Agentic 是一个标准化的AI函数/工具库,专为常规TS使用和基于LLM的使用场景进行了优化。您可以在脚本中使用defTool
来注册任何agentic工具。
import { calculator } from "@agentic/calculator"defTool(calculator)
查看Agentic tools获取更多信息。
回退工具支持
部分LLM模型没有内置工具支持。 对于这些模型,可以通过系统提示启用工具支持。性能可能低于内置工具,但仍然可以使用工具功能。
工具支持是通过system.tool_calls实现的,它会"教导"大语言模型如何调用工具。当启用此模式时,您将看到大语言模型返回的工具调用令牌。
GenAIScript维护了一个不支持工具的知名模型列表,因此对于这些模型会自动处理。
要启用此模式,您可以
- 在脚本中添加
fallbackTools
选项
script({ fallbackTools: true,})
- 或者在CLI中添加
--fallack-tools
标志
npx genaiscript run ... --fallback-tools
打包为系统脚本
要选择哪些工具包含在脚本中,您可以将它们分组到系统脚本中。例如,current_weather
工具可以包含在system.current_weather.genai.mjs
脚本中。
script({ title: "Get the current weather",})defTool("current_weather", ...)
然后在tools
字段中使用工具ID。
script({ ..., tools: ["current_weather"],})
示例
让我们通过一个问答脚本来说明工具如何协同工作。
在下面的脚本中,我们添加了retrieval_web_search
工具。这个工具
会在需要时调用retrieval.webSearch
。
script({ title: "Answer questions", tool: ["retrieval_web_search"]})
def("FILES", env.files)
$`Answer the questions in FILES using a web search.
- List a summary of the answers and the sources used to create the answers.
然后我们可以将这个脚本应用到下面的questions.md
文件。
- What is the weather in Seattle?- What laws were voted in the USA congress last week?
在第一个请求之后,LLM会要求为每个问题调用web_search
。
网络搜索结果随后会被添加到LLM的消息历史中,并再次发出请求。
第二次请求会产生包含网络搜索结果的最终结果。