SpringAI与DeepSeek大模型应用开发其四:对话机器人初涉

4 SpringAI入门:对话机器人

4.1 快速上手

4.1.1 创建项目
  • 新建一个SpringBoot项目,勾选Web、MySQL驱动、Ollama:
此处插入图片描述SpringAI与DeepSeek大模型应用开发其四:对话机器人初涉

" /> 此处插入图片描述SpringAI与DeepSeek大模型应用开发其四:对话机器人初涉

" />
  • 项目结构:

    • application.properties更改为application.yaml
    • 后续把chatrobot文件夹重命名为ai
此处插入图片描述SpringAI与DeepSeek大模型应用开发其四:对话机器人初涉

" />
  • 初始pom.xml内容:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.4.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.shisan</groupId>
    <artifactId>chat-robot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>chat-robot</name>
    <description>chat-robot</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
        <spring-ai.version>1.0.0-M6</spring-ai.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>${spring-ai.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
4.1.2 引入依赖
  • SpringAI很好地适配了SpringBoot的自动装配机制,并且为不同的大模型提供了对应的starter,例如:

    • Anthropic:
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-anthropic-spring-boot-starter</artifactId>
</dependency>
* Azure OpenAI:
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-azure-openai-spring-boot-starter</artifactId>
</dependency>
* DeepSeek:
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
* Hugging Face:
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-huggingface-spring-boot-starter</artifactId>
</dependency>
* Ollama:
<dependency>
   <groupId>org.springframework.ai</groupId>
   <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
</dependency>
* OpenAI:
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
  • 可根据所选平台选择引入相应依赖,此处以Ollama为例;

    • 因4.1.1创建项目时已勾选依赖,后续步骤可略过;
    • 在项目pom.xml中添加spring-ai版本信息:
<spring-ai.version>1.0.0-M6</spring-ai.version>
  • 接着添加spring-ai的依赖管理项:
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-bom</artifactId>
            <version>${spring-ai.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
  • 最后引入spring-ai-ollama的依赖:
<dependency>
   <groupId>org.springframework.ai</groupId>
   <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
</dependency>
  • 为方便后续开发,手动引入Lombok依赖==(此步骤不可省略)==:
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.22</version>
</dependency>
* 注意:切勿使用start.spring.io提供的lombok,存在bug!
  • 完整依赖如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.4.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.shisan</groupId>
    <artifactId>chat-robot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>chat-robot</name>
    <description>chat-robot</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
        <spring-ai.version>1.0.0-M6</spring-ai.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>${spring-ai.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
4.1.3 配置模型信息
  • 在配置文件中配置模型相关参数,以Ollama为例:
spring:
  application:
    name: chart-robot
  ai:
    ollama:
      base-url: http://localhost:11434 # ollama服务地址,默认值如此
      chat:
        model: deepseek-r1:14b # 模型名称
        options:
          temperature: 0.8 # 模型温度,影响生成结果随机性,值越小越稳定
4.1.4 ChatClient
  • ChatClient封装了与AI大模型对话的各类API,支持同步或响应式交互;

  • 使用前需声明ChatClient

  • com.shisan.ai.config包下新建CommonConfiguration类:

此处插入图片描述SpringAI与DeepSeek大模型应用开发其四:对话机器人初涉

" />
  • 代码:
package com.shisan.ai.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CommonConfiguration {

    // 注意参数中的model为使用的模型,此处用Ollama,也可选用OpenAIChatModel
    @Bean
    public ChatClient chatClient(OllamaChatModel model) {
        return ChatClient.builder(model) // 创建ChatClient工厂
                .build(); // 构建ChatClient实例
    }
}
* `ChatClient.builder`:获取`ChatClient.Builder`工厂对象,可自由选择模型并添加自定义配置;
* `OllamaChatModel`:引入ollama starter后可自动注入,同理OpenAI也可如此使用。
4.1.5 同步调用
  • 定义Controller,接收用户提示词,发送给大模型并返回结果;
此处插入图片描述SpringAI与DeepSeek大模型应用开发其四:对话机器人初涉

" />
  • 代码:
package com.shisan.ai.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {

    private final ChatClient chatClient;
    // 请求方式和路径勿改,后续需与前端联调
    @RequestMapping("/chat")
    public String chat(@RequestParam String prompt) {
        return chatClient
                .prompt(prompt) // 传入用户提示词
                .call() // 同步请求,待AI全部输出后返回结果
                .content(); // 返回响应内容
    }
}
* 基于`call()`方法的调用为同步调用,需所有响应结果返回后才返回前端;
  • 启动项目,浏览器访问:http://localhost:8080/ai/chat?prompt=你好
此处插入图片描述SpringAI与DeepSeek大模型应用开发其四:对话机器人初涉

" />
4.1.6 流式调用
  • 同步调用需长时间等待页面才见结果,用户体验差。可改进为流式调用;

    • SpringAI用WebFlux技术实现流式调用;
    • 修改ChatController中的chat方法:
// 注意返回值为Flux<String>,即流式结果,需设定响应类型和编码,否则前端乱码
@RequestMapping(value = "/chat", produces = "text/html;charset=UTF-8")
public Flux<String> chat(@RequestParam String prompt) {
    return chatClient
            .prompt(prompt)
            .stream() // 流式调用
            .content();
}
  • 重启测试,再次访问:
此处插入图片描述SpringAI与DeepSeek大模型应用开发其四:对话机器人初涉

" />
4.17 System设定
  • 询问AI你是谁时,它会回答是DeepSeek-R1,这是大模型底层设定。若要让AI按新设定工作,需设置System背景信息;

  • SpringAI中设置System信息简便,创建ChatClient时指定即可;

  • 修改CommonConfiguration中代码,给ChatClient设定默认System信息:

@Bean
public ChatClient chatClient(OllamaChatModel model) {
    return ChatClient
            .builder(model) // 创建ChatClient工厂实例
            .defaultSystem("你是邓超,请以邓超的口吻回答用户的问题。")
            .defaultAdvisors(new SimpleLoggerAdvisor())
            .build(); // 构建ChatClient实例

}
  • 再次询问“你是谁?”
此处插入图片描述SpringAI与DeepSeek大模型应用开发其四:对话机器人初涉

" />
* 以上回答由DeepSeek的**深度思考** 内+最终回答组成。

4.2 日志功能

  • 默认情况下,AI交互不记录日志,不便调试。
4.2.1 Advisor
  • SpringAI基于AOP机制实现与大模型对话过程的增强、拦截、修改等功能,所有增强通知需实现Advisor接口;
此处插入图片描述SpringAI与DeepSeek大模型应用开发其四:对话机器人初涉

" />
  • Spring提供一些Advisor默认实现,实现基本增强功能:
此处插入图片描述SpringAI与DeepSeek大模型应用开发其四:对话机器人初涉

" />
* `SimpleLoggerAdvisor`:日志记录Advisor;
* `MessageChatMemoryAdvisor`:会话记忆Advisor;
* `QuestionAnswerAdvisor`:实现RAG的Advisor;
4.2.2 添加日志Advisor
  • 修改CommonConfiguration,给ChatClient添加日志Advisor:
@Bean
public ChatClient chatClient(OllamaChatModel model) {
    return ChatClient
        .builder(model) // 创建ChatClient工厂实例
        .defaultSystem("你是邓超,请以邓超的口吻回答用户的问题。")
        .defaultAdvisors(new SimpleLoggerAdvisor()) // 添加默认Advisor,记录日志
        .build(); // 构建ChatClient实例
}
4.2.3 修改日志级别
  • application.yaml中添加日志配置,修改日志级别:
logging:
  level:
    org.springframework.ai.chat.client.advisor: debug # AI对话日志级别
    com.shisan.ai: debug # 本项目日志级别
  • 重启项目,再次聊天可在IDEA运行控制台看到AI对话日志信息;
此处插入图片描述SpringAI与DeepSeek大模型应用开发其四:对话机器人初涉

" />

4.3 对接前端

*

相关文章

暂无评论

暂无评论...