跳到主要内容

2 篇博文 含有标签「AI」

查看所有标签

使用Spring AI与Pinecone实现RAG:实践指南

· 阅读需 5 分钟
Kinser
Software Engineer

引言

检索增强生成(RAG)已成为构建结合信息检索与生成式语言模型的AI应用的强大技术。本指南演示如何利用Spring AI和Pinecone向量数据库实现RAG系统,特别适用于创建文档问答机器人。

什么是RAG?

RAG包含两个核心组件:

  1. 检索:通过语义搜索从知识库中查找相关信息
  2. 生成:基于检索结果使用语言模型生成上下文响应

系统架构

[文档网站] → [爬虫] → [分块处理] → [Pinecone向量数据库]

[用户提问] → [Spring AI] → [语义搜索] → [LLM生成] → [响应]

前置条件

  • Pinecone账号(提供免费版)
  • Spring Boot应用(推荐3.x版本)
  • 向量数据库基础知识

实现步骤

1. Pinecone集成配置

Gradle依赖

implementation "org.springframework.ai:spring-ai-pinecone-store-spring-boot-starter"

配置文件(application.yml)

spring:
ai:
vectorstore:
pinecone:
apiKey: ${PINECONE_API_KEY}
environment: ${PINECONE_ENV}
index-name: ${PINECONE_INDEX}
project-id: ${PINECONE_PROJECT_ID}

2. 文档处理流水线

网页爬虫实现

public class DocumentationScraper {
private final Set<String> visitedUrls = new HashSet<>();
private final String baseDomain;

public DocumentationScraper(String baseUrl) {
this.baseDomain = extractDomain(baseUrl);
}

public List<Document> scrape(String startUrl) {
List<Document> documents = new ArrayList<>();
scrapeRecursive(startUrl, documents);
return documents;
}
// 包含URL标准化、同域名检查、内容提取等完整实现
...
}

文档分块服务

@Service
public class DocumentationService {
private final VectorStore vectorStore;
private final TokenTextSplitter textSplitter;

public DocumentationService(VectorStore vectorStore) {
this.vectorStore = vectorStore;
this.textSplitter = new TokenTextSplitter(
2000, // 技术文档的理想分块大小
300, // 最小分块尺寸
100, // 上下文保留的重叠区域
15, // 每页最大分块数
true // 保持文档结构
);
}

public List<Document> processDocument(String content, Map<String, Object> metadata) {
Document originalDoc = new Document(content, metadata);
List<Document> chunks = textSplitter.split(originalDoc);

// 增强元数据以优化检索
for (int i = 0; i < chunks.size(); i++) {
chunks.get(i).getMetadata()
.put("chunk_number", i)
.put("total_chunks", chunks.size());
}
return chunks;
}
}

3. 知识库初始化

数据加载REST端点

@RestController
@RequestMapping("/document")
@Tag(name = "AI模块API")
public class DocumentController {

private final DocumentationService documentationService;

@PostMapping("/load-data")
public ResponseEntity<String> loadDocumentation() {
documentationService.scrapeAndStoreDocumentation("https://docs.openwes.top");
return ResponseEntity.ok("文档加载成功");
}
}

4. 在对话补全中实现RAG

@Service
public class ChatService {

private final ChatModel chatModel;
private final VectorStore vectorStore;

public String generateResponse(String query) {
SearchRequest searchRequest = SearchRequest.defaults()
.withTopK(5) // 检索5个最相关分块
.withSimilarityThreshold(0.7);

return ChatClient.create(chatModel)
.prompt()
.advisors(new QuestionAnswerAdvisor(vectorStore, searchRequest))
.call()
.content();
}
}

最佳实践

  1. 优化分块策略

    • 技术文档:1500-2500 tokens
    • 叙述性内容:500-1000 tokens
    • 保留100-200 tokens重叠区域维持上下文
  2. 增强元数据

metadata.put("document_type", "API参考");
metadata.put("last_updated", "2024-03-01");
metadata.put("relevance_score", 0.95);
  1. 混合搜索
SearchRequest hybridRequest = SearchRequest.defaults()
.withTopK(5)
.withHybridSearch(true)
.withKeywordWeight(0.3);
  1. 提示词工程
PromptTemplate template = new PromptTemplate("""
根据以下上下文回答问题:
{context}

问题:{question}

如果不知道答案,请回答"我不知道"。
""");

性能优化

  • 缓存:对高频查询使用Redis缓存
  • 异步处理:使用@Async处理文档摄入
  • 批量处理:按50-100的批次处理文档

评估指标

指标目标值测量方法
检索准确率>85%人工评估
响应延迟<2秒性能测试
用户满意度>4/5分反馈问卷

结论

本实现展示了如何构建生产级RAG系统,主要优势包括:

  1. 针对文档查询提供精准的上下文感知响应
  2. 可扩展的向量搜索能力
  3. 与现有Spring应用的轻松集成

后续计划

  1. 实现用户反馈机制:
@PostMapping("/feedback")
public void logFeedback(@RequestBody FeedbackDTO feedback) {
// 存储反馈用于持续改进
}
  1. 添加查询模式分析仪表盘
  2. 实现定期文档自动更新

项目参考:完整实现已发布在GitHubmodule-ai包中,欢迎贡献代码和反馈意见!

用模型上下文协议(MCP)和 Spring AI 构建智能应用

· 阅读需 4 分钟
Kinser
Software Engineer

用模型上下文协议(MCP)和 Spring AI 构建智能应用

1. MCP 架构介绍

MCP(模型上下文协议)标准化了人工智能应用与外部数据源之间的交互,使得像数据库、API 和搜索引擎等工具能够无缝集成。其客户端 - 服务器架构包括:

  • MCP 主机:用户与之交互的人工智能应用层(例如 Claude 聊天机器人)。
  • MCP 客户端:处理主机与服务器之间的通信,将请求格式化为外部系统可识别的格式。 img.png
  • MCP 服务器:连接到外部资源(例如 PostgreSQL、Google Drive)并执行操作的中间件。 img_1.png

2. 安装 MySQL MCP 服务器

第一步:您可以查看这个 GitHub 仓库: ** GitHub 手动安装

pip install mysql-mcp-server

第二步:由于我们将使用 uv 工具,因此需要安装它
请参考这篇文章:UV Installation 安装 uv 工具

3. 使用 Spring AI 进行项目设置

第一步:添加依赖项
build.gradle 中包含 Spring AI MCP 库:

implementation 'org.springframework.ai:spring-ai-mcp-client-spring-boot-starter'
implementation 'org.springframework.ai:spring-ai-mcp-client-webflux-spring-boot-starter' // 用于 SSE 传输

4. 客户端集成

第一步:在 application.yml 中配置 Spring AI 配置

spring:
ai:
mcp:
client:
enabled: true
name: mysqlMCP # MCP 服务器名称
version: 1.0.0
type: SYNC
request-timeout: 20s
stdio:
root-change-notification: true
servers-configuration: classpath:mcp-servers-config.json # 与 Claude 桌面配置相同的 MCP 服务器配置。

第二步:添加 mcp-servers-config.json

{
"mcpServers": {
"mysql": {
"command": "C:\\Users\\xxx\\.local\\bin\\uv.exe",
"args": [
"--directory",
"C:\\Users\\xxx\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\mysql_mcp_server",
"run",
"mysql_mcp_server"
],
"env": {
"MYSQL_HOST": "localhost",
"MYSQL_PORT": "3306",
"MYSQL_USER": "root",
"MYSQL_PASSWORD": "root",
"MYSQL_DATABASE": "test"
}
}
}
}

需要检查 uv.exe 和 mysql_mcp_server 的目录,并检查所有 MySQL 配置。


5. 简单示例

示例将使用 MCP 与 MySQL 数据库进行交互。


@SpringBootApplication(scanBasePackages = "org.openwes")
@EnableDiscoveryClient
public class AiApplication {

public static void main(String[] args) {
SpringApplication.run(AiApplication.class, args);
}

private String userInput = "show all tables";

@Bean
public CommandLineRunner predefinedQuestions(ChatClient.Builder chatClientBuilder, ToolCallbackProvider tools,
ConfigurableApplicationContext context) {
return args -> {

var chatClient = chatClientBuilder
.defaultTools(tools)
.build();

System.out.println(">>> 问题: " + userInput);
System.out.println(">>> 回答: " + chatClient.prompt(userInput).call().content());

context.close();
};
}

}

然后我们会看到日志显示它将自然语言“show all tables”转换为 SQL“show all tables”:

received: 2025-03-27 09:21:19,799 - mysql_mcp_server - INFO - Listing tools...

>>> 问题:show all tables

received: 2025-03-27 09:21:20,602 - mysql_mcp_server - INFO - Calling tool: execute_sql with arguments: {'query': 'show all tables'}

>>> 回答:以下是在 MySQL 服务器上执行 `SHOW TABLES` 命令后返回的所有表名:

- a_api
- a_api_config
- a_api_key
- a_api_log
- d_domain_event
- e_container_task
- e_container_task_and_business_task_relation
- e_ems_location_config
- l_change_log
- l_change_log_lock
...

6. Spring AI MCP 的优势

  • 声明式工具注册:通过注解而非手动 SDK 配置简化集成。
  • 统一协议:通过标准化的 MCP 通信消除数据源碎片化。
  • 可扩展性:添加新工具(例如 Meilisearch、Git)而不会干扰现有工作流。

7. 结论

通过结合 Spring AI 的依赖管理与 MCP 的协议标准化,开发人员可以快速构建企业级人工智能应用。对于高级用例,可以探索混合架构,其中 MCP 服务器同时处理实时数据和批处理。


本文综合了最新的 MCP 进展与 Spring AI 的相关内容。完整的代码示例请参考链接中的资源。

代码可在 GitHub 上找到:GitHub - jingsewu/open-wes