Skip to main content

如何创建新的插件

本文档介绍如何在 langchat-plugin-tools 模块中创建一个新的插件工具。

1. 架构说明

为了简化管理,所有的通用插件工具都集中在 langchat-plugin/langchat-plugin-tools 模块中。每个插件作为一个独立的包存在。

2. 开发步骤

2.1 创建包

langchat-plugin-tools/src/main/java/cn/langchat/plugin/tool/ 目录下创建一个新的包,建议以插件名称命名。 例如:cn.langchat.plugin.tool.weather

2.2 创建 Maven 依赖 (可选)

如果您的插件需要引入新的第三方库,请在 langchat-plugin-tools/pom.xml 中添加依赖。已有依赖包括:
  • langchat-common-core
  • langchat-common-ai
  • spring-boot-starter-webflux (网络请求)
  • jsoup (HTML解析)
  • langchat-common-oss (文件存储)

2.3 创建 Tool 类

在新建的包下创建工具类,需要满足以下条件:
  1. 添加 @Component 注解交给 Spring 管理。
  2. 实现 cn.langchat.plugin.tool.BaseTool 接口。
  3. 在提供给 AI 调用的方法上添加 @Tool 注解,并写明详细的英文描述。
示例代码:
package cn.langchat.plugin.tool.weather;

import cn.langchat.plugin.tool.BaseTool;
import dev.langchain4j.agent.tool.Tool;
import org.springframework.stereotype.Component;

/**
 * 天气查询工具
 */
@Component
public class WeatherTool implements BaseTool {

    @Tool("Get current weather information for a specific city")
    public String getWeather(String city) {
        // 实现具体的业务逻辑
        return "The weather in " + city + " is Sunny.";
    }

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public String getLabel() {
        return "天气插件";
    }

    @Override
    public String getDescription() {
        return "获取某个城市的天气信息";
    }
}

3. Tool 方法参数说明

@Tool 标注的方法支持多种参数形式,AI 会自动提取参数并调用该方法。
  • 简单参数: 如 String city, int days 等。
  • 对象参数: 可以定义一个 Request 对象包含多个字段,适合复杂的参数结构。

4. 验证

启动项目后,系统会自动扫描实现了 BaseTool 接口的 Bean 并注册到 AI 工具列表中。无需额外配置。