AI工具集成框架

基于Spring AI的工具集成框架,提供AI模型调用、工具方法注解和实时事件推送功能,适用于智能提案生成和上下文感知应用开发。

  • by lucasdengcn
  • Java
  • 云端部署
  • 更新于
在 GitHub 查看 lucasdengcn/spring-ai-example

使用说明

Spring AI示例

项目概述

这个项目演示了使用Spring AI工具的各种实现模式和最佳实践。它由两个主要模块组成:

  • mcp服务器:实现同时支持WebFlux和WebVC SSE的模型上下文协议(MCP)服务器
  • 提案代理人:实现MCP客户端,用于提出基于人工智能的提案

项目结构

.
├── mcp-server/           # MCP Server implementation
│   ├── src/             # Server source code
│   └── README.md        # Server documentation
├── proposal-agent/      # MCP Client implementation
│   ├── src/             # Client source code
│   └── README.md        # Client documentation
└── src/                 # Common source code

工具实现模式

方法即工具

Spring AI支持将方法作为工具,并为其添加注释 @Tool示例来自 DateTimeTools:

@Tool(name = "getCurrentDateTime", description = "Get the current date and time")
public String getCurrentDateTime() {
    return LocalDateTime.now().atZone(LocaleContextHolder.getTimeZone().toZoneId()).toString();
}

工具结果转换器

可以实现自定义结果转换器来控制工具结果的格式。示例来自 CustomToolCallResultConverter:

@Tool(name = "getCustomer",
      description = "Retrieve customer information",
      resultConverter = CustomToolCallResultConverter.class)
public Customer getCustomer(String name, ToolContext context) {
    return new Customer(name, "example@email.com");
}

工具上下文

Spring AI提供了一个 ToolContext 可以注入到工具方法中以访问上下文信息的参数:

public Customer getCustomerByEmail(String email, ToolContext context) {
    log.info("Context: {}", context);
    return new Customer("Demo", email);
}

刀具参数

工具参数可以用以下方式注释 @ToolParam 提供描述:

@Tool(name = "setAlarm")
public void setAlarm(@ToolParam(description = "Time in ISO-8601 format") String time) {
    // Implementation
}

配置

该项目使用具有以下关键配置的Spring Boot:

  • Ollama AI模型集成
  • 使用PGVector的矢量存储
  • H2数据库开发
  • web访问的CORS配置
  • MCP服务器实现
  • MCP客户端实现
  • SSE实施

SSE实施

用于实时更新的SSE(服务器发送事件)的实现。这是通过使用 SseEmitter 类。

技术栈

  • Spring Boot
  • 春季AI
  • Olama人工智能模型
  • PGVector矢量存储
  • H2数据库
  • CORS配置
  • SSE(服务器发送事件)用于实时更新