文档

使用 LLM 进行预测

文本嵌入

分词

管理模型

模型信息

API 参考

工具定义

你可以使用 tool() 函数定义工具,并在 operate() 调用中将其传递给模型。

工具的剖析

遵循此标准格式将函数定义为工具

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 调用)

工具也可以具有外部效果,例如创建文件或调用程序甚至 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],
);