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();
    }
}
相关推荐
陈明勇1 小时前
Go 1.26 新特性回顾:语言增强、工具升级与 Green Tea GC 默认启用
后端·go
咖啡八杯11 小时前
GoF设计模式——策略模式
java·后端·spring·设计模式
lizhongxuan12 小时前
AI Agent 上下文压缩利器 Headroom
后端
Csvn14 小时前
SSH 远程管理与安全加固 — 运维的守门之道
后端
IT_陈寒14 小时前
Python搞不定字符串编码?这破玩意坑我两小时!
前端·人工智能·后端
菜鸟谢15 小时前
Rust 智能指针完整详解
后端
java小白小15 小时前
SpringBoot(01): 初识SpringBoot,从Spring的痛点说起
spring boot
菜鸟谢15 小时前
Rust 函数完整知识点详解
后端
爱勇宝16 小时前
淡泊名利之前,先承认我们都很焦虑
前端·后端·程序员
菜鸟谢16 小时前
Rust 闭包(Closure)完整详解
后端