许多 AI 应用程序通过自然语言与用户交互。然而,有些用例需要模型使用结构化输入直接与外部系统(如 API、数据库或文件系统)进行接口。工具是代理调用的组件,用于执行操作。它们通过让模型通过定义良好的输入和输出来与世界交互,从而扩展了模型的功能。工具封装了一个可调用函数及其输入模式。这些可以传递给兼容的聊天模型,允许模型决定是否调用工具以及使用哪些参数。在这些场景中,工具调用使模型能够生成符合指定输入模式的请求。
import * as z from "zod"import { tool } from "langchain"const searchDatabase = tool( ({ query, limit }) => `Found ${limit} results for '${query}'`, { name: "search_database", description: "Search the customer database for records matching the query.", schema: z.object({ query: z.string().describe("Search terms to look for"), limit: z.number().describe("Maximum number of results to return"), }), });
import * as z from "zod";import { tool } from "langchain";const getWeather = tool( ({ city }, config) => { const writer = config.streamWriter; // Stream custom updates as the tool executes writer(`Looking up data for city: ${city}`); writer(`Acquired data for city: ${city}`); return `It's always sunny in ${city}!`; }, { name: "get_weather", description: "Get weather for a given city.", schema: z.object({ city: z.string(), }), });