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;
    }
}