文档
工具定义
您可以使用 tool()
函数定义工具,并在 act()
调用中将它们传递给模型。
请遵循此标准格式将函数定义为工具
import { tool } from "@lmstudio/sdk";
import { z } from "zod";
const exampleTool = tool({
// The name of the tool
name: "add",
// A description of the tool
description: "Given two numbers a and b. Returns the sum of them.",
// zod schema of the parameters
parameters: { a: z.number(), b: z.number() },
// The implementation of the tool. Just a regular function.
implementation: ({ a, b }) => a + b,
});
重要提示:工具名称、描述和参数定义都将传递给模型!
这意味着您的措辞将影响生成质量。务必始终提供清晰的工具描述,以便模型知道如何使用它。
工具还可以具有外部效应,例如创建文件或调用程序乃至 API。通过实现具有外部效应的工具,您可以将您的 LLM 基本上转变为可以在本地机器上执行任务的自主代理。
createFileTool
import { tool } from "@lmstudio/sdk";
import { existsSync } from "fs";
import { writeFile } from "fs/promises";
import { z } from "zod";
const createFileTool = tool({
name: "createFile",
description: "Create a file with the given name and content.",
parameters: { name: z.string(), content: z.string() },
implementation: async ({ name, content }) => {
if (existsSync(name)) {
return "Error: File already exists.";
}
await writeFile(name, content, "utf-8");
return "File created.";
},
});
createFile
工具的示例代码:import { LMStudioClient } from "@lmstudio/sdk";
import { createFileTool } from "./createFileTool";
const client = new LMStudioClient();
const model = await client.llm.model("qwen2.5-7b-instruct");
await model.act(
"Please create a file named output.txt with your understanding of the meaning of life.",
[createFileTool],
);
本页内容
工具的构成
具有外部效应的工具(如计算机使用或 API 调用)
示例:createFileTool
工具定义
使用 createFile 工具的示例代码