解锁 SpringAI:开启开发实践之旅!

0 阅读1分钟

欢迎关注公众号:月伴飞鱼,每天分享程序员职场经验!

文章内容收录到个人网站,方便阅读:hardyfish.top/

资料分享

技术之瞳 阿里巴巴技术笔试心得::pan.quark.cn/s/1e9825fc2…

Spring AI是一个专为AI工程设计的Java应用框架。

SpringAI是Spring框架的一个扩展,用于方便开发者集成AI调用AI接口。

官网:spring.io/projects/sp…

Spring AI有以下特点:

在AI的聊天、文生图、嵌入模型等方面提供API级别的支持。

与模型之间支持同步式和流式交互。

多种模型支持。

基本使用

使用:start.spring.io/,构建一个Spring Boot 项目。

点击ADD DEPENDENCIES,搜索Ollama添加依赖。

打开生成的项目,查看pom.xml,可以看到核心依赖:

<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
</dependency>

安装 Ollama:

curl -fsSL https://ollama.com/install.sh | sh

官网:ollama.com/download/

运行 deepseek-r1:

ollama run deepseek-r1:671b

配置Ollama的相关信息:

spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.model=deepseek-r1:1.5b

spring.ai.ollama.base-url: Ollama的API服务地址。

spring.ai.ollama.chat.model: 要调用的模型名称。

调用Ollama中的deepseek-r1模型:

public class TestOllama {
​
    @Autowired
    private OllamaChatModel ollamaChatModel;
​
    @Test
    public void testChatModel() {
        String prompt = "英文就翻译成中文";
        String message = "test";
        String result = ollamaChatModel.call(prompt + ":" + message);
        System.out.println(result);
    }
}

集成 DeepSeek 大模型

Spring AI 集成 DeepSeek的代码示例:github.com/Fj-ivy/spri…

DeepSeek 官方文档:api-docs.deepseek.com/zh-cn/

引入依赖:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>

配置:

spring:
  ai:
    openai:
      api-key: sk-xxx   // 填写自己申请的key
      base-url: https://api.deepseek.com
      chat:
        options:
          model: deepseek-chat

简单示例:

@RestController
public class ChatController {
​
    private final OpenAiChatModel chatModel;
​
    @Autowired
    public ChatController(OpenAiChatModel chatModel) {
        this.chatModel = chatModel;
    }
​
    /**
     * 让用户输入一个prompt,然后返回一个结果
     */
    @GetMapping("/ai/generate")
    public Map<String,String> generate(@RequestParam(value = "message") String message) {
        return Map.of("generation", this.chatModel.call(message));
    }
}