【LangChain4J】Tools (Function Calling)工具调用

git地址

Tools官网介绍

https://docs.langchain4j.dev/tutorials/tools

底层API使用ToolSpecification

@Bean
    public FunctionAssistant functionAssistant(ChatModel chatModel){
        ToolSpecification specification = ToolSpecification.builder()
                .name("开具发票助手")
                .description("根据用户提供的开票信息,开具发票")
                .parameters(JsonObjectSchema.builder()
                        .addStringProperty("name", "公司名称")
                        .addStringProperty("dutyNumber", "税号序列")
                        .addStringProperty("amount", "开票金额,保留2位有效数字")
                        .build())
                .build();
        ToolExecutor toolExecutor = (toolExecutionRequest,memoryId) -> {
            log.info("执行工具ID:{}",toolExecutionRequest.id());
            log.info("执行工具Name:{}",toolExecutionRequest.name());
            log.info("工具参数:{}",toolExecutionRequest.arguments());
            return "开具成功";
        };
        return AiServices.builder(FunctionAssistant.class)
                .chatModel(chatModel)
                .tools(Map.of(specification,toolExecutor))
                .build();

    }

高阶Api 实现访问互联网天气接口

 @Bean
    public WeatherAssistant weatherAssistant(ChatModel chatModel){
        return AiServices.builder(WeatherAssistant.class)
                .chatModel(chatModel)
                .tools(new WeatherTool())
                .build();
    }

public interface WeatherAssistant {
    @SystemMessage("你是一个天气查询小助手,根据用户输入的天气问题,调用对应的function回答用户所问题天气,注意:你只回答天气相关的问题,其他问题直接回答'我只回答天气相关问题’")
    Result<String> ask(String question);
}

public class WeatherTool {
    private static final String API_KEY = System.getenv("weather_api");
    private static final String BASE_URL = "https://nf2k5nq7wu.re.qweatherapi.com";

    @Tool(name = "实时天气", value = "获取中国3000+市县区和海外20万个城市实时天气数据,包括实时温度、体感温度、风力风向、相对湿度、大气压强、降水量、能见度、露点温度、云量等。")
    public JsonNode getWeatherV2(@P(value ="需要查询地区的LocationID或以英文逗号分隔的经度,纬度坐标(十进制,最多支持小数点后两位),LocationID可通过 城市搜索function获取。例如 location=101010100 或 location=116.41,39.92") String location) throws Exception {
        //1 传入调用地址url 和apikey
        String url = String.format(BASE_URL+"/v7/weather/now?location=%s&key=%s", location, API_KEY);

        //2 使用默认配置创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //3 创建请求工厂并将其设置给RestTemplate,开启微服务调用和风天气开发服务
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        //4 RestTemplate微服务调用
        String response = new RestTemplate(factory).getForObject(url, String.class);

        //5 解析JSON响应获得第3方和风天气返回的天气预报信息
        JsonNode jsonNode = new ObjectMapper().readTree(response);

        //6 想知道具体信息和结果请查看https://dev.qweather.com/docs/api/weather/weather-now/#response

        return jsonNode;
    }
}

posted @ 2025-12-22 23:01  爱吃鱼的大灰狼  阅读(3)  评论(0)    收藏  举报