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();
    }
}
相关推荐
Gust of wind7 小时前
串与KMP模式匹配:存储结构、基本操作、next数组手算
c语言·数据结构·后端·算法
endswel7 小时前
Spring bean 注册多种方式
java·后端·spring
铁皮饭盒7 小时前
还是网页端, 46mb模型, 抠图功能升级了, 抠任意主体, 还是不要显卡, 不要python, 满意吗?
前端·javascript·后端
小林coding7 小时前
Flash模型又添一员大将:实测MiniMax M3.1
后端
鬼手点金7 小时前
opencode-性能优化建议
java·人工智能·git·自动化·nanogpt
聪明蛋子哟7 小时前
Python与Java双栈实战:手撸一个支持RAG与Tool Calling的高性能Agent框架
java·开发语言·python
xuxigifxfh8 小时前
HJ4 字符串分隔
java·开发语言·华为机考
写后端的胖头鱼8 小时前
Java 反射详解 + 场景示例
java·反射
零基础1238 小时前
PDF 处理工具全攻略:pdf24、PDFgear、Adobe Acrobat DC 与 Stirling-PDF 深度对比
java·开发语言·pdf
颜进强8 小时前
25 · NestJs DurableProviders 持久化 Provider:把 ContextId 当缓存键
前端·后端·ai编程