之前安装了一个ollama,加载了14B的deepseek-R1模型,在此试以下springAI好不好用。

准备大模型

启动ollama服务,运行deepseek模型,打开ollama服务端口11434,由于在windows上面部署的ollama,直接win+R输出wf.msc,新建规则,开放11434端口,以便于springAI连接ollama。

ollama run deepseek-r1:14b

创建应用springBoot的工程

直接创建一个spring工程,引用ollama相关依赖,此处使用的springboot版本3.3.6,JDK17。

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

配置文件

由于使用本地大模型,所以key可以省略。

spring.application.name=spring-ai-chat-ollama
server.port=8081
spring.profiles.active=ollama

# Ollama configuration for Spring AI Chat
# The address of the Ollama service, which defaults to http://localhost:11434.
spring.ai.ollama.base-url=http://192.168.100.105:11434
# The model name which is the one you previously downloaded via the terminal using `ollama pull` or `ollama run`
spring.ai.ollama.chat.model=deepseek-r1:14b
spring.ai.ollama.chat.options.temperature=0.7

配置类

@Configuration
public class OllamaChatClientConfigs {
    /**
     * 1、这里使用的是 Ollama 协议的 ChatModel,因此这里动态注入的 ChatModel 是 OllamaChatModel
     * <p>
     * 2、这里 chatClient 设置了默认的系统提示语,会将所有的聊天请求都带上这个系统提示语,返回的内容均为 JSON 格式
     *
     * @param chatModel
     * @return ChatClient
     */
    @Bean
    public ChatClient chatClient(OllamaChatModel chatModel) {
        return ChatClient.builder(chatModel)
                .defaultSystem("You are a friendly chat bot that answers question with json always")
                .build();
    }
}

创建聊天API


@RestController
@RequestMapping("/api/ollama")
public class ChatController {

    @Autowired
    private ChatClient chatClient;

    /**
     * 普通的聊天接口
     *
     * @param userInput 用户输入
     * @return 返回内容
     */
    @GetMapping("/chat")
    public String prompt(@RequestParam String userInput) {
        return this.chatClient.prompt().user(userInput).call().content();
    }
}

运行springBoot程序,访问聊天API查看集成的结果,响应成功即说明集成成功了。 http://localhost:8081/api/ollama/chat?userInput=%22%E4%BD%A0%E6%98%AF%E8%B0%81%22

总结

这里仅创建了一个聊天API集成ollama,后续还可以创建前端页面,使用流式窗口进行聊天,还可以加上RAG,使响应更加准确,避免知识盲区胡乱回答,还可以使用MCP,使响应更加完美。