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();
    }
}
相关推荐
martian6653 分钟前
【Java高级篇】——第16篇:高性能Java应用优化与调优
java·开发语言·jvm
m0_748247554 分钟前
springboot中配置logback-spring.xml
spring boot·spring·logback
m0_748250035 分钟前
springboot使用logback自定义日志
java·spring boot·logback
程序猿熊跃晖9 分钟前
多环境日志管理:使用Logback与Logstash集成实现高效日志处理
spring boot·elk·logback
-优势在我9 分钟前
Android TabLayout 实现随意控制item之间的间距
android·java·ui
Lojarro23 分钟前
JavaEE基础之- Servlet相关
java·servlet·java-ee
KingDol_MIni1 小时前
Spring Boot 集成 T-io 实现客户端服务器通信
java·服务器·spring boot
许苑向上1 小时前
Java八股文(下)
java·开发语言
后端码匠1 小时前
Spring Boot3+Vue2极速整合:10分钟搭建DeepSeek AI对话系统
人工智能·spring boot·后端
逸Y 仙X1 小时前
Git常见命令--助力开发
java·大数据·git·java-ee·github·idea