springboot 对接 ollama

spring ai 对接 ollama

引入依赖

xml 复制代码
<dependency>
    <groupId>io.springboot.ai</groupId>
    <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</dependency>

这里因为使用的是快照版本所以需要配置 spring repository 的快照的仓库

xml 复制代码
<repositories>
    <repository>
        <name>spring-milestones</name>
        <id>spring-milestones</id>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

配置文件

yaml 复制代码
spring:
  application:
    name: study-spring-ai
  ai:
    ollama:
      # 这里填写 ollama 对应的地址信息就行
      base-url: http://192.168.4.11:11434
      chat:
        options:
          model: qwen2:0.5b

编码实现

编码是相对比较简单的,我们这里提供一个实例

java 复制代码
package org.study.ai.controller;

import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xl-9527
 * @since 2024/10/25
 **/
@RestController
@RequestMapping("ai/chat-models")
public class AiRequestController {

    private final OllamaChatClient ollamaChatClient;

    public AiRequestController(final OllamaChatClient ollamaChatClient) {
        this.ollamaChatClient = ollamaChatClient;
    }

    @GetMapping("ollama/dialogue")
    public Object dialogue(@RequestParam(name = "msg") String msg) {
        UserMessage userMessage = new UserMessage(msg);
        ChatResponse callResponse = ollamaChatClient.call(
                new Prompt(
                        userMessage,
                        OllamaOptions.create()
                                .withModel("qwen2:0.5b")
                )
        );
        Generation result = callResponse.getResult();
        return result.getOutput().getContent();
    }
}
相关推荐
boring_1113 分钟前
全局id生成器生产方案
大数据·分布式·后端
heyCHEEMS4 分钟前
[USACO09OCT] Bessie‘s Weight Problem G Java
java·开发语言·算法
兔子蟹子41 分钟前
JAVA中Spring全局异常处理@ControllerAdvice解析
java·spring
prinrf('千寻)44 分钟前
项目右键没有add as maven project选项
java·maven
工业互联网专业1 小时前
基于springboot+vue的健康健身追踪系统
java·vue.js·spring boot·毕业设计·源码·课程设计·健康健身追踪系统
王有品1 小时前
Spring、Spring MVC 与 Spring Boot 的关系与核心用途
spring boot·spring·mvc
杰仔正在努力1 小时前
Java + Seleium4.X + TestNG自动化技术
java·开发语言·自动化
brave_zhao1 小时前
使用Spring Boot实现WebSocket广播
spring boot·后端·websocket
lynn-661 小时前
JAVA-使用Apache POI导出数据到Excel,并把每条数据的图片打包成zip附件项
java·apache·excel
JiaHao汤2 小时前
基于 SpringBoot 与 Redis 的缓存预热案例
spring boot·redis·缓存