大语言模型(LLM)与reactor响应式编程整合

准备环境

jdk 17 https://www.oracle.com/cn/java/technologies/downloads/#java17-windows
olloma https://ollama.com/download
idea 2024.3 https://www.jetbrains.com.cn/en-us/idea/download/?section=windows

核心依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
            <version>1.0.0-M5</version>
        </dependency>

yml配置

spring:
  ai:
    ollama:
      base-url: http://127.0.0.1:11434
      chat:
        options:
          model: qwen:0.5b
          temperature: 0.8

统一请求参数实体类

public class UserSendParams {
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public UserSendPojo toPojo() {
        UserSendPojo userSendPojo = new UserSendPojo();
        BeanUtils.copyProperties(this, userSendPojo);
        return userSendPojo;
    }

}

controller

@RestController
@RequestMapping("/ollama")
public class OllamaController {

    @Autowired
    private OllamaService ollamaService;

    @PostMapping(value = "/sendStreamReactor", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> sendStreamReactor(@RequestBody UserSendParams params) {
        return ollamaService.sendStreamReactor(params.toPojo());
    }
}

service

public interface OllamaService {
    Flux<String> sendStreamReactor(UserSendPojo userSendPojo);
}

service实现

public class OllamaServiceImpl implements OllamaService {
    private final Logger log = LoggerFactory.getLogger(OllamaServiceImpl.class);

    @Autowired
    private OllamaChatModel ollamaChatModel;

    @Override
    public Flux<String> sendStreamReactor(UserSendPojo userSendPojo) {
        log.info("sendStreamReactor ollama 调用参数 =>{}", userSendPojo.getMessage());
        Prompt prompt = new Prompt(userSendPojo.getMessage());
        long startTime = System.currentTimeMillis();
        try {
            Flux<ChatResponse> fluxResponse = ollamaChatModel.stream(prompt);
            return fluxResponse.map(chatResponse ->
                    chatResponse.getResult().getOutput().getText());
        } catch (Exception e) {
            log.error("sendStreamReactor ollama 流式调用异常 userSendPojo =>{} error =>",
                    userSendPojo, e);
        } finally {
            log.info("sendStreamReactor ollama 调用返回 =>耗时 {}ms",
                    System.currentTimeMillis() - startTime);
        }
        return Flux.empty();
    }

}

简易效果页面

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .chat {
            display: block;
            margin-left: auto;
            margin-right: auto;
            width: 700px;
            border:1px solid #000;
        }
    </style>
</head>

<body>
    <input id="message1" class="message1"></input>
    <button onclick="fetchFunction()">发送文本</button>
</br>
        <label>选择文件上传:</label>
        <input type="file" id="imageUpload" name="imageUpload" accept="image/*">
        <br>
        <button onclick="fetchImageFunction()">发送文本和文件</button>

      <p id="chat" class="chat"></p>
    <script>

    async function fetchFunction(){
    let messageVlue = document.getElementById("message1").value;
    
    if(messageVlue == "" || messageVlue == undefined || messageVlue == null){
        console.log("无输入 =>"+messageVlue);
        return;
    } 
    
    const url = "http://localhost:8080/ollama/sendStreamReactor";
    const textArea = document.getElementById("chat");
    const res = await fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
    "message": messageVlue
})

    });
    console.time("fetch流式耗时");
    const reader = res.body.getReader();
    // 需要将字节数组解码成文字
    const decoder = new TextDecoder();
    textArea.innerText="";
    // 不断循环解析块内容,并且设置进内容区
    while (true) {
        // done代表是否读完,布尔值 value代表当前读到哪一块,是一个字节数组
        const { done, value } = await reader.read();
        // console.log(`当前块的大小: ${value.byteLength}`);
        if (done === true) {
            // 完成全量响应解析,中断解析
            break;
        }
        let decodeText = decoder.decode(value);
        console.log(decodeText)
        decodeText= decodeText.replaceAll("data:","");
        decodeText= decodeText.replaceAll("\n\n","");
        textArea.innerText += decodeText;
    }
    console.timeEnd("fetch流式耗时"); 
}
           
document.getElementById("message1").addEventListener("keydown", function(event) {
  if (event.key === "Enter") {
    fetchFunction();
  }
}); 

async function fetchImageFunction(){
    let messageVlue = document.getElementById("message1").value;
    let imageValue = document.getElementById("imageUpload").value;
    
    if(messageVlue == "" || messageVlue == undefined || messageVlue == null){
        console.log("无输入 =>"+messageVlue);
        return;
    } 
    const formData = new FormData()
    if(imageValue != "" && imageValue != undefined && imageValue != null){
        console.log("有图片 =>"+imageValue);
        let imageFile = document.getElementById("imageUpload").files[0];
        formData.append('imageFile', imageFile);
    } 
    formData.append('message', messageVlue);
    console.log(formData);
    
    const url = "http://localhost:8080/ollama/sendImageAdvisor";
    const textArea = document.getElementById("chat");
    const res = await fetch(url, {
        method: "POST",
        headers: {
            
        },
        body: formData
    });
    console.time("fetch流式耗时");
    const reader = res.body.getReader();
    // 需要将字节数组解码成文字
    const decoder = new TextDecoder();
    textArea.innerText="";
    // 不断循环解析块内容,并且设置进内容区
    while (true) {
        // done代表是否读完,布尔值 value代表当前读到哪一块,是一个字节数组
        const { done, value } = await reader.read();
        // console.log(`当前块的大小: ${value.byteLength}`);
        if (done === true) {
            // 完成全量响应解析,中断解析
            break;
        }
        let decodeText = decoder.decode(value);
        console.log(decodeText)
        decodeText= decodeText.replaceAll("data:","");
        decodeText= decodeText.replaceAll("\n\n","");
        textArea.innerText += decodeText;
    }
    console.timeEnd("fetch流式耗时"); 
}

    </script>
</body>

</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 225,271评论 6 524
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 96,533评论 3 405
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 172,580评论 0 370
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 61,203评论 1 303
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 70,204评论 6 401
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 53,664评论 1 316
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 42,014评论 3 431
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 40,991评论 0 280
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 47,536评论 1 326
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 39,558评论 3 347
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 41,678评论 1 355
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 37,267评论 5 351
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,997评论 3 341
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 33,429评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 34,580评论 1 277
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 50,259评论 3 382
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 46,744评论 2 366

推荐阅读更多精彩内容