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();
    }
}
相关推荐
nice_lcj52011 小时前
【从零理解计算机网络 · 03】IP 与端口:数据怎么找到机器,又怎么找到进程
后端·网络协议·计算机网络·面试·ip地址·端口·127.0.0.1
Java展博12 小时前
[Go 后端转场] 从 try-catch 到 if err != nil:写惯 Java 的人第一次上手最别扭的 4 件事
java·开发语言·golang
starzy199012 小时前
Hadoop介绍总结:一张图理清组件、生态与版本
java·hadoop
yyuuuzz12 小时前
nginx 502 排查,先看上游超时那一行
android·java·运维·nginx·502
Java后端的Ai之路12 小时前
Java并发编程25-集合的线程安全
java·安全·面试
雪芽蓝域zzs12 小时前
第 3 章:完成 User 完整 CRUD(新增、根据 id 查询、修改、删除、查询全部)
spring boot
一条Go12 小时前
Pod 终端与日志:为什么浏览器建连要先换一张 60 秒的票
后端·架构·github
CoderYanger12 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第一弹)
java·数据库·spring·面试·java-ee·tomcat·mybatis
码云社区13 小时前
Java租房平台源码方案:Vue 3房源审核、UniApp预约看房与房东管理
java·vue.js
考虑考虑14 小时前
zookeeper认证
后端·zookeeper