工具调用

This commit is contained in:
huangge1199 2025-07-12 13:53:23 +08:00
parent fada2aab78
commit 47becaa432
3 changed files with 66 additions and 0 deletions

View File

@ -60,6 +60,11 @@
<artifactId>langchain4j-spring-boot-starter</artifactId>
<version>1.1.0-beta7</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.20.1</version>
</dependency>
</dependencies>
<build>

View File

@ -1,6 +1,7 @@
package com.huangge1199.ai.config;
import com.huangge1199.ai.service.LangChainService;
import com.huangge1199.ai.tool.InterviewQuestionTool;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatModel;
@ -33,6 +34,7 @@ public class LangChainConfig {
.chatMemory(chatMemory)
.chatMemoryProvider(memoryId->MessageWindowChatMemory.withMaxMessages(10))
.contentRetriever(contentRetriever)
.tools(new InterviewQuestionTool())
.build();
}
}

View File

@ -0,0 +1,59 @@
package com.huangge1199.ai.tool;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* InterviewQuestionTool
*
* @author huangge1199
* @since 2025/7/12 13:15:28
*/
@Slf4j
public class InterviewQuestionTool {
/**
* 从面试鸭网站获取关键词相关的面试题列表
*
* @param keyword 搜索关键词"redis""java多线程"
* @return 面试题列表若失败则返回错误信息
*/
@Tool(name = "interviewQuestionSearch", value = """
Retrieves relevant interview questions from mianshiya.com based on a keyword.
Use this tool when the user asks for interview questions about specific technologies,
programming concepts, or job-related topics. The input should be a clear search term.
"""
)
public String searchInterviewQuestions(@P(value = "the keyword to search") String keyword) {
List<String> questions = new ArrayList<>();
// 构建搜索URL编码关键词以支持中文
String encodedKeyword = URLEncoder.encode(keyword, StandardCharsets.UTF_8);
String url = "https://www.mianshiya.com/search/all?searchText=" + encodedKeyword;
// 发送请求并解析页面
Document doc;
try {
doc = Jsoup.connect(url)
.userAgent("Mozilla/5.0")
.timeout(5000)
.get();
} catch (IOException e) {
log.error("get web error", e);
return e.getMessage();
}
// 提取面试题
Elements questionElements = doc.select(".ant-table-cell > a");
questionElements.forEach(el -> questions.add(el.text().trim()));
return String.join("\n", questions);
}
}