mcpField
S
Spring Boot AI

Spring Boot AI

本地服务
dev.to开发工具119 周前更新

关于 Spring Boot AI

Spring Boot AI 是一个基于 Spring AI 的住宿预订 Agent 示例,面向学习 MCP、RAG 和模型评估测试的开发者。示例整合本地天气工具、远程预订工具、向量检索与多种模型配置。

主要功能

  1. 01住宿预订对话 Agent
  2. 02本地天气与远程预订工具
  3. 03PGVector 支持的 RAG
  4. 04聊天记忆与日志 Advisor
  5. 05Ollama、Gemini 和 Bedrock 配置

适用场景

  1. 01构建旅游住宿预订聊天应用
  2. 02测试本地与远程 MCP 工具调用
  3. 03用向量检索补充城市信息
  4. 04评估不同模型配置下的应用

MCP 相关

应用通过 MCP 客户端连接远程 Booking MCP 服务,并将本地 Weather 工具提供给 Agent。示例还包含实现 Booking 工具的 MCP 服务端。

配置

本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。

mcp.json · 通用配置
{
"mcpServers": {
"spring-boot-ai": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"compose"
]
}
}
}
启动命令docker run -i --rm compose

本地服务需要在你的电脑上安装运行环境(如 Node.js 18+)。各客户端的配置文件位置不同,请参考客户端文档。

安装包
ocicompose

工具

还没有获取到工具列表

本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。

详细介绍

mcp-server chat-server Java Kotlin SpringBoot SpringAI

Gemini Bedrock Ollama

Spring Boot AI

在本示例中,我们受到 Building Agents with AWS: Complete Tutorial 的启发,将使用 Spring AI 构建一个简单的 AI Agent 应用,并展示以下关键功能:

此项目已由 MCP Review 编入索引并获得认证。

原始示例使用 AWS Bedrock,但 Spring AI 的一大优势是,只需稍作配置调整,同一份代码即可用于任何其他受支持的模型。此项目支持三种配置: Ollama(本地)、Google Gemini 和 AWS Bedrock。

该应用包含一个 AI Agent,可帮助用户预订旅游目的地的住宿。

借助 MCP,Agent 可以使用以下工具:

  • 天气工具:获取指定城市和日期的天气信息。
  • 预订工具:预订指定城市和日期的住宿。

天气工具将使用 MCP 在本地实现,而预订工具则由远程 MCP 服务提供。当前日期通过系统提示词提供。城市的其他信息将通过 RAG 从向量存储中检索。

图示

实现

MCP 服务

与 Spring Boot 中的许多情况一样,实现 MCP 服务 相当简单。按照 MCP Server Boot Starter 指南,你只需要:

  1. 添加 spring-ai-starter-mcp-server-webflux 或 spring-ai-starter-mcp-server-webmvc 依赖

  2. 创建一个实例,并使用 @Tool 和 @ToolParam 注解:

@Service // or @Bean / @Component
class BookingTool(private val bookingService: BookingService) {
  @Tool(
    description = "make a reservation for accommodation for a given city and date",
  )
  fun book(
    @ToolParam(description = "the city to make the reservation for")
    city: String,
    @ToolParam(description = "the check-in date, when the reservation begins")
    checkinDate: LocalDate,
    @ToolParam(description = "the check-out date, when the reservation ends")
    checkoutDate: LocalDate
  ): String = bookingService.book(city, checkinDate, checkoutDate) // Delegate to a service
}
  1. 将其注册为 MethodToolCallbackProvider:
@Configuration
class BookingToolConfiguration {
  @Bean
  fun bookingToolCallbackProvider(bookingTool: BookingTool) = 
    MethodToolCallbackProvider.builder()
      .toolObjects(bookingTool)
      .build()
}
聊天服务

聊天服务 是一个使用以下依赖构建的 Spring Boot 应用:

  • spring-boot-starter-web 或 -webflux - 用于为聊天界面提供 REST API
  • spring-ai-starter-mcp-client - 用于使用 MCP
  • spring-ai-starter-vector-store-pgvector 和 spring-ai-advisors-vector-store - 用于通过 PGVector 启用 RAG
  • spring-ai-starter-model-ollama - 用于使用 Ollama 模型
  • spring-ai-starter-model-google-genai 和 spring-ai-starter-model-google-genai-embedding - 用于使用 Google Gemini 模型
  • spring-ai-starter-model-bedrock 和 spring-ai-starter-model-bedrock-converse - 用于使用 AWS Bedrock 模型
组件
  • MCP 工具
    • 天气工具 - 一个本地 MCP 工具,用于查询 WeatherService,获取指定城市在指定日期的天气
    • 预订工具 - 一个远程 MCP 工具,连接到 Booking MCP Server 以预订住宿
  • 聊天
    • 聊天客户端 - 一个 Spring AI ChatClient,配置了:
      • 用于定义 AI Agent 角色和当前日期的系统提示词
      • Spring Boot 根据活动配置文件自动配置的 AI 模型
      • 上述 MCP 工具,作为 AI Agent 工具集的一部分
    • 聊天服务 - 封装 聊天客户端,并添加三个顾问:
      • QuestionAnswerAdvisor - 从向量存储中获取上下文,并扩充用户输入(RAG)
      • MessageChatMemoryAdvisor - 将对话历史添加到用户输入中(聊天记忆)
      • SimpleLoggerAdvisor - 将聊天历史记录到控制台(用于调试)
    • 聊天控制器 - 提供一个简单的 REST POST 端点,接收用户输入,调用 聊天服务,并返回 AI Agent 的响应
  • 向量存储初始化器 - 在启动时向向量存储加载一些示例数据

让我们逐步实现……

天气工具

以下是 天气工具 的实现方式:

  1. 创建一个实例,并使用 @Tool 和 @ToolParam 注解:
@Service // or @Bean / @Component
class WeatherTool(private val weatherService: WeatherService) {
  @Tool(description = "get the weather for a given city and date")
  fun getWeather(
    @ToolParam(description = "the city to get the weather for")
    city: String,
    @ToolParam(description = "the date to get the weather for") 
    date: LocalDate
  ): String = weatherService.getWeather(city, date) // Delegate to a service
}
  1. 将其注册为 MethodToolCallbackProvider:
@Configuration
class WeatherToolConfiguration {
  @Bean
  fun weatherToolCallbackProvider(weatherTool: WeatherTool) =
    MethodToolCallbackProvider.builder()
      .toolObjects(weatherTool)
      .build()
}
预订工具

要将 预订工具 配置为远程 MCP 工具,我们只需在 application.properties 中配置 MCP 客户端的 SSE 连接:

spring.ai.mcp.client.toolcallback.enabled=true
spring.ai.mcp.client.sse.connections.booking-tool.url=http://localhost:8081

你可以在 MCP Client Boot Starter 文档中找到所有其他配置方式。

聊天客户端

我们使用 Spring AI 的 ChatClient.Builder 创建 聊天客户端。它已通过 spring.ai 配置属性自动配置(稍后会在配置一节中介绍),并使用自定义系统提示词和可用的 MCP 工具进行初始化:

@Configuration
class ChatClientConfiguration {
  @Bean
  fun chatClient(
    builder: ChatClient.Builder,
    toolCallbackProviders: List<ToolCallbackProvider>
  ): ChatClient {
    return chatClientBuilder(builder, toolCallbackProviders).build()
  }

  private fun chatClientBuilder(
    builder: ChatClient.Builder,
    toolCallbackProviders: List<ToolCallbackProvider>
  ): ChatClient.Builder {
    val system = """
      You are an AI powered assistant to help people book accommodation in touristic cities around the world.
      If there is no information, then return a polite response suggesting you don't know.
      If the response involves a timestamp, be sure to convert it to something human-readable.
      Do not include any indication of what you're thinking.
      Use the tools available to you to answer the questions.
      Just give the answer.
      When booking accommodation for a weekend, assume check-in on Saturday and check-out on Monday.
      Current date: {currentDate}
      """.trimIndent()
    return builder
      .defaultSystem(system)
      .defaultToolCallbacks(*toolCallbackProviders.toTypedArray())
  }
}
聊天服务

聊天服务提供一个 chat 方法,接收聊天 ID 和用户问题。它会调用 聊天客户端,并将用户问题与一组顾问一同传入,以丰富交互:

  • QuestionAnswerAdvisor - 从向量存储中检索相关上下文,并将其注入上下文(RAG)
  • MessageChatMemoryAdvisor - 将指定聊天 ID 的对话历史添加到用户输入中(聊天记忆)
  • SimpleLoggerAdvisor - 将顾问内部跟踪信息记录到控制台(当 logging.level.org.springframework.ai.chat.client.advisor 设置为 DEBUG 时)

此外,问题和回答也会记录到控制台。

实现如下:

@Service // or @Bean / @Component
class ChatService(
  vectorStore: VectorStore,
  private val clock: Clock,
  private val chatClient: ChatClient
) {
  private val logger = LoggerFactory.getLogger(ChatService::class.java)
  private val questionAnswerAdvisor = QuestionAnswerAdvisor.builder(vectorStore).build()
  private val simpleLoggerAdvisor = SimpleLoggerAdvisor()
  private val chatMemoryAdvisor = MessageChatMemoryAdvisor.builder(
    MessageWindowChatMemory.builder()
      .chatMemoryRepository(InMemoryChatMemoryRepository())
      .build()
  ).build()

  fun chat(chatId: String, question: String): String {
    return chatClient
      .prompt()
      .system { it.param("currentDate", LocalDate.now(clock)) }
      .user(question)
      .advisors(questionAnswerAdvisor, chatMemoryAdvisor, simpleLoggerAdvisor)
      .advisors { a -> a.param(ChatMemory.CONVERSATION_ID, chatId) }
      .call()
      .content().apply {
        logger.info("Chat #$chatId question: $question")
        logger.info("Chat #$chatId answer: $this")
      }!!
  }
}
聊天控制器

聊天控制器提供一个简单的 REST POST 端点,接收用户输入、调用 聊天服务,并返回 AI Agent 的响应:

@RestController
class ChatController(private val chatService: ChatService) {
  @PostMapping("/{chatId}/chat")
  fun chat(
    @PathVariable chatId: String, 
    @RequestParam question: String
  ): String? {
    return chatService.chat(chatId, question)
  }
}
向量存储初始化器

只需使用 Spring AI 自动配置的 VectorStore 并向其中添加文档即可。这会自动调用嵌入模型生成嵌入向量,并将其存储到向量存储中:

@Bean
fun vectorStoreInitializer(vectorStore: VectorStore) = 
  ApplicationRunner {
    // TODO check if the vector store is empty ...
    // TODO load cities from a JSON file or any other source ...
    cities.forEach { city ->
      val document = Document(
        "name: ${city.name} " +
        "country: ${city.country} " +
        "description: ${city.description}"
      )
      vectorStore.add(listOf(document))
    }
  }

你可以在 ChatServerApplication.kt 中找到完整版本的 vectorStoreInitializer。

配置

我们使用 application.properties,而不是 application.yml,因为 YAML 无法同时包含 spring.ai.model.embedding(标量,供 Bedrock 和 Ollama 使用)和 spring.ai.model.embedding.text(嵌套项,供 Gemini 使用)。也许将来会解决这个问题,但无论如何,这是一个支持多种模型的 PoC——在生产应用中,你很可能只会使用一种模型,因此不会遇到这个问题。

在此文件中,我们定义全局配置值:

  • 默认禁用所有模型自动配置。
  • 配置数据源,连接到支持 PGVector 的 PostgreSQL 数据库。
  • 将服务端口设置为 8080。
  • 配置远程 预订工具 MCP 服务的 URL。
  • 设置聊天顾问调试跟踪信息的日志级别。
spring.application.name=chat-server

spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=password
spring.datasource.driver-class-name=org.postgresql.Driver

spring.ai.model.chat=none
spring.ai.model.embedding=none
spring.ai.model.embedding.text=none

spring.ai.mcp.client.toolcallback.enabled=true
spring.ai.mcp.client.sse.connections.booking-tool.url=http://localhost:8081

server.port=8080

logging.level.org.springframework.ai.chat.client.advisor=INFO

AI 模型通过 Spring 配置文件进行配置。每个配置文件都会设置聊天模型、嵌入模型和向量存储维度。必须在运行时使用 SPRING_PROFILES_ACTIVE 指定活动配置文件。

Ollama 配置文件

在 application-ollama.yml 中,我们配置 Spring AI 使用 Ollama 模型:

  • 将 Ollama 服务的基础 URL 设置为 http://localhost:11434。
  • 将聊天模型设置为 llama3.1:8b(必须是启用了 工具 的模型)。
  • 将嵌入模型设置为 nomic-embed-text。
  • 使用 pull-model-strategy: when_missing,仅在模型本地不可用时拉取模型。
  • 将 PGVector 配置为向量存储,维度为 768(与嵌入模型大小匹配)。
spring:
  ai:
    model:
      embedding: "ollama"
      chat: "ollama"
    ollama:
      base-url: "http://localhost:11434"
      init:
        pull-model-strategy: "when_missing"
      chat:
        options:
          model: "llama3.1:8b"
      embedding:
        options:
          model: "nomic-embed-text"
    vectorstore:
      pgvector:
        table-name: "vector_store_ollama"
        dimensions: 768
        initialize-schema: true
Gemini 配置文件

在 application-gemini.yml 中,我们配置 Spring AI 使用 Google Gemini 模型:

  • 从 GOOGLE_API_KEY 环境变量中读取 Google API 密钥。
  • 将聊天模型设置为 gemini-2.5-flash。
  • 将嵌入模型设置为 gemini-embedding-001,维度为 768。
  • 将 PGVector 配置为向量存储,维度为 768。
spring:
  ai:
    model:
      chat: "google-genai"
      embedding:
        text: "google-genai"
    google:
      genai:
        api-key: "${GOOGLE_API_KEY}"
        chat:
          options:
            model: "gemini-2.5-flash"
            temperature: 0.7
        embedding:
          api-key: "${GOOGLE_API_KEY}"
          text:
            options:
              model: "gemini-embedding-001"
              dimensions: 768
    vectorstore:
      pgvector:
        table-name: "vector_store_gemini"
        dimensions: 768
        initialize-schema: true
Bedrock 配置文件

在 application-bedrock.yml 中,我们配置 Spring AI 使用 AWS Bedrock 模型:

  • 从环境变量中读取 AWS 凭证和区域。
  • 使用 Bedrock Converse API 设置聊天模型。
  • 使用 Bedrock Cohere 设置嵌入模型。
  • 将 PGVector 配置为向量存储,维度为 1024(与 Cohere 嵌入模型大小匹配)。
spring:
  ai:
    model:
      embedding: "bedrock-cohere"
      chat: "bedrock-converse"
    bedrock:
      aws:
        access-key: "${AWS_ACCESS_KEY_ID}"
        secret-key: "${AWS_SECRET_ACCESS_KEY}"
        region: "${AWS_REGION:eu-central-1}"
      converse:
        chat:
          options:
            model: "${AWS_BEDROCK_CHAT_MODEL}"
            max-tokens: 2048
      cohere:
        embedding:
          model: "${AWS_BEDROCK_EMBEDDING_MODEL}"
    vectorstore:
      pgvector:
        table-name: "vector_store_bedrock"
        dimensions: 1024
        initialize-schema: true

测试

测试 MCP 服务

要测试 MCP 服务,我们将使用 McpClient 调用 预订工具的 book 方法,并模拟下游的 BookingService:

MCP 服务测试

请参阅下面的简化测试实现。完整实现(包括验证可用工具列表的测试)请参阅 McpServerApplicationTest.kt。

@SpringBootTest(webEnvironment = RANDOM_PORT)
class McpServerApplicationTest {

  // 1. Inject the server port (it is random)
  @LocalServerPort
  val port: Int = 0

  // 2. Mock the BookingService instance
  @MockitoBean
  lateinit var bookingService: BookingService

  @Test
  fun `should book`() {
    // 3. Create a McpClient connected to the server
    val client = McpClient.sync(
      HttpClientSseClientTransport("http://localhost:$port")
    ).build()
    client.initialize()
    client.ping()

    // 4. Mock the bookingService using argument captors
    val bookResult = "Booking is done!"
    val cityCaptor = argumentCaptor<String>()
    val checkinDateCaptor = argumentCaptor<LocalDate>()
    val checkoutDateCaptor = argumentCaptor<LocalDate>()
    doReturn(bookResult)
      .whenever(bookingService)
      .book(
        cityCaptor.capture(),
        checkinDateCaptor.capture(),
        checkoutDateCaptor.capture()
      )

    // 5. Call the tool
    val city = "Barcelona"
    val checkinDate = LocalDate.parse("2025-04-15")
    val checkoutDate = LocalDate.parse("2025-04-18")
    val result = client.callTool(CallToolRequest(
      "book",
      mapOf(
        "city" to city,
        "checkinDate" to checkinDate.toEpochDay(),
        "checkoutDate" to checkoutDate.toEpochDay()
      )
    ))

    // 6. Verify the result
    assertThat(result.isError).isFalse()
    assertThat(result.content).singleElement()
      .isInstanceOfSatisfying(TextContent::class.java) {
        // TODO why is text double quoted?
        assertThat(it.text).isEqualTo("\"$bookResult\"")
      }

    // 7. Verify that the bookingService was called with
    // the correct parameters
    assertThat(cityCaptor.allValues).singleElement()
      .isEqualTo(city)
    assertThat(checkinDateCaptor.allValues).singleElement()
      .isEqualTo(checkinDate)
    assertThat(checkoutDateCaptor.allValues).singleElement()
      .isEqualTo(checkoutDate)

    // 8. Close the client
    client.close()
  }
}

运行 MCP 服务测试:

cd mcp-server
./gradlew test
测试聊天服务

要测试 聊天服务,我们将:

  • 在 application-test.yml 中将默认配置文件切换为 gemini,并禁用 MCP 客户端(可通过 SPRING_PROFILES_ACTIVE 覆盖)。
  • 用本地 预订测试工具 替换远程 预订工具,并保持签名相同。
  • 使用 MockitoBean 模拟下游服务 天气服务 和 预订服务。
  • 在 ClockTestToolConfiguration.kt 中创建固定的 Clock,以控制当前日期。
    • 将其声明为 @Primary @Bean,以覆盖默认的 Clock Bean。
  • 使用 Testcontainers 启动带有 PGVector 的 Docker Compose

聊天服务测试

你可能已经注意到,由于 MCP 客户端已禁用,测试实际上并未检查其 SSE 连接。我尝试使用 McpServerAutoConfiguration 启动 McpServer,几乎成功了。问题是什么?客户端在服务启动之前就尝试连接,导致整个应用在启动时失败。也许这只是顺序问题,希望将来能修复 🤞

接下来是有趣的部分:我们如何测试 AI Agent 的回答?这就要用到评估测试:

评估回答的一种方法是使用 AI 模型本身进行评估。选择最适合评估的 AI 模型,它不一定与用于生成回答的模型相同。

这与 Martin Fowler 的 Evals GenAI 模式中描述的评估技术一致:

  • 自我评估:大模型评估自己的回答,但这可能会强化其自身的错误或偏见。
  • LLM 作为评判者:由另一个模型对输出评分,通过引入第二种意见来减少偏见。
  • 人工评估:由人工审查回答,确保语气和意图恰当。

为简化起见,我们采用自我评估 🤓

每项测试都遵循以下结构:

@Test
fun `should do something`() {
  // 1. Mock downstream service(s)
  // Optionally use argument captors depending on how you plan
  // to verify parameters in step 5
  // Example for BookingService:
  doReturn("Your booking is done!")
    .whenever(bookingTestService).book(any(), any(), any())

  // 2. Call the chat service
  val chatId = UUID.randomUUID().toString()
  val chatResponse = chatService.chat(
    chatId, 
    "Can you book accommodation for Barcelona from 2025-04-15 to 2025-04-18?"
  )
  
  // 3. Evaluate the response using the AI model
  val evaluationResult = TestEvaluator(chatClientBuilder) { evaluationRequest, userSpec ->
    userSpec.text(
      """
      Your task is to evaluate if the answer given by an AI agent to a human user matches the claim.
      Return YES if the answer matches the claim and NO if it does not.
      After returning YES or NO, explain why.
      Assume that today is ${LocalDate.now(clock)}.
      Answer: {answer}
      Claim: {claim}
      """.trimIndent()
    )
      .param("answer", evaluationRequest.responseContent)
      .param("claim", evaluationRequest.userText)
  }.evaluate(EvaluationRequest(
    "Accommodation has been booked Barcelona from 2025-04-15 to 2025-04-18", 
    chatResponse
  ))
  
  // 4. Assert the evaluation result is successful, show feedback if not
  assertThat(evaluationResult.isPass).isTrue
    .withFailMessage { evaluationResult.feedback }
  
  // 5. If applicable, verify the parameters passed to the service
  // You can verify with argument captors or use the `verify` method as in the example below:
  verify(bookingTestService).book(
    eq("Barcelona"), 
    eq(LocalDate.parse("2025-04-15")), 
    eq(LocalDate.parse("2025-04-18"))
  )
}

请参阅 ChatServerApplicationTest.kt 中的完整测试实现。

每项评估都会使用针对待测回答定制的提示词。尝试过程中,你会发现一些出人意料的古怪行为。因此,我最终创建了自定义的 TestEvaluator,它基于 Spring AI 的 RelevancyEvaluator 和 FactCheckingEvaluator,不过它们目前可能还无法提供你所需的定制程度。

遇到奇怪的结果后,我不得不调整每个提示词。例如,评估模型以为现在还是 2023 年,不相信 AI Agent 能预测 2025 年的天气。或者,它把回答中的“你”误认为是在指它自己,而不是用户。最离谱的是,有一次评估只回答了“NO”,但解释却说:“嗯,也许我应该回答 YES” 🤣

对于生产系统,你肯定需要大量调整和测试提示词,才能让系统和评估器都达到预期;我想这应该也是使用 GenAI 的“乐趣”之一。

默认情况下,本地和 CI 中的测试都使用 Gemini 配置文件(需要 GOOGLE_API_KEY)。

cd chat-server
./gradlew test

要在本地使用 Ollama 进行测试(需要先运行 Ollama;如果 GPU 硬件不足,结果可能不稳定):

cd chat-server
SPRING_PROFILES_ACTIVE=ollama ./gradlew test

要在本地使用 Bedrock 进行测试(需要 AWS 凭证):

cd chat-server
SPRING_PROFILES_ACTIVE=bedrock ./gradlew test

运行

你可以使用环境变量或根目录中的 system.properties 文件配置应用。Git 会忽略此文件,./gradlew bootRun 和测试都会加载该文件。

system.properties 示例:

# AWS Bedrock
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
AWS_REGION=eu-central-1
AWS_BEDROCK_CHAT_MODEL=...
AWS_BEDROCK_EMBEDDING_MODEL=...

# Google Gemini
GOOGLE_API_KEY=...
运行向量数据库

所有配置都需要 PGVector 作为 RAG 向量数据库:

cd chat-server
docker compose -f docker-compose-vectordb.yml up -d

停止它:

cd chat-server
docker compose -f docker-compose-vectordb.yml down

停止它并移除所有卷(会删除所有向量数据库数据):

cd chat-server
docker compose -f docker-compose-vectordb.yml down -v
在本地运行 Ollama

如果你想使用本地大模型,可以通过 Docker Compose 运行 Ollama,也可以将其作为原生应用运行(更多信息请访问 ollama.com)。

cd chat-server
docker compose -f docker-compose-ollama.yml up -d

停止它:

cd chat-server
docker compose -f docker-compose-ollama.yml down
运行应用
  1. 启动 MCP 服务
cd mcp-server
./gradlew bootRun
  1. 使用以下任一配置启动 Chat Server:

Ollama(需要 Ollama 和向量数据库):

cd chat-server
SPRING_PROFILES_ACTIVE=ollama ./gradlew bootRun

Gemini(需要向量数据库和 GOOGLE_API_KEY):

cd chat-server
SPRING_PROFILES_ACTIVE=gemini ./gradlew bootRun

Bedrock(需要向量数据库和 AWS 凭证):

cd chat-server
SPRING_PROFILES_ACTIVE=bedrock ./gradlew bootRun
  1. 开始聊天

可通过 http://localhost:8080/chat.html 使用简单的聊天 UI(免责声明:此 UI 完全由 AI 生成,因为前端并非本 PoC 的目标)。

你也可以通过 http://localhost:8080/swagger-ui.html 查看 API 端点。

如何使用其他 AI 模型

若要使用 Spring AI 支持的其他任意 AI 模型,请按以下步骤操作:

  • 添加所需依赖
  • 在独立的 application-<model>.yml 文件中配置模型
  • 使用 SPRING_PROFILES_ACTIVE=<model> 激活配置

文档

祝你 GenAI 编码愉快!💙

评论

支持 Markdown

第一次接触 MCP?

从协议是什么,到在客户端里装上第一个服务,这几条回答覆盖了大多数入门问题。

一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。