liusuyi
2026-05-30 f4f4fc53260eb67483dce406a963628273786a61
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.ard.agent.tool;
 
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;
 
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * 知识库工具
 *
 * @author lsy
 * @date 2026/5/11
 */
 
@Component
@Slf4j
public class KnowledgeTools {
    
    @Resource
    private VectorStore vectorStore;  // 你的向量数据库
    
    @Tool(description = """
        从内部知识库中检索相关文档。当你需要查询公司政策、技术文档、产品说明等静态知识时,
        应该优先调用此工具。此工具适用于非实时、非动态的数据查询。
        """)
    public String searchKnowledgeBase(
            @ToolParam(description = "搜索关键词或问题") String query) {
        log.info("AI调用searchKnowledgeBase工具,参数: query={}", query);
        // 执行向量检索
        List<Document> results = vectorStore.similaritySearch(
            SearchRequest.builder().query(query) .topK(3)
                    .build()
        );
 
        if (results.isEmpty()) {
            return "未找到相关知识";
        }
        
        return results.stream()
            .map(Document::getText)
            .collect(Collectors.joining("\n---\n"));
    }
}