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();
    }
}
相关推荐
sjh21002 小时前
STM32的计数模式和pwm模式
java·stm32·算法
草药味儿の岁月3 小时前
系统测试讲解 - Java使用selenium实现滑块验证的处理详解
java·python·selenium
uzong8 小时前
认知破局:在信息茧房时代重构后端工程师的思维思维
后端
Lisonseekpan8 小时前
MVCC的底层实现原理是什么?
java·数据库·后端·mysql
灰原喜欢柯南9 小时前
实战:MyBatis 中 db.properties 的正确配置与最佳实践
java·数据库·mybatis
中东大鹅9 小时前
SpringBoot实现文件上传
java·spring boot·后端
牛马程序员‍10 小时前
Day116 若依融合mqtt
java·mqtt·若依·mqttx
David爱编程10 小时前
Java中main 方法为何必须是static?
java·后端
追梦人物10 小时前
Uniswap 手续费和协议费机制剖析
前端·后端·区块链
小沈同学呀10 小时前
阿里巴巴高级Java工程师面试算法真题解析:LRU Cache实现
java·算法·面试