Spring AI调用OpenAI Stream简单实现一个上下文对话小助手(前后端代码)

慈云数据 6个月前 (05-13) 技术支持 42 0

效果展示

在这里插入图片描述

什么是Spring AI

官方描述

简化包含人工智能功能的应用程序的开发,而不会产生不必要的复杂性。简单来说就是封装了调用接口,简化开发。

Spring AI 主要提供以下功能:

支持所有主要的模型提供商,如OpenAI,Microsoft,Amazon,Google和Huggingface。

支持的模型类型包括聊天和文本到图像,还有更多类型正在开发中。

跨 AI 提供商的可移植 API,用于聊天和嵌入模型。支持同步和流 API 选项。还支持下拉以访问特定于模型的功能。

将 AI 模型输出映射到 POJO。

支持所有主要的矢量数据库提供程序,例如 Azure Vector Search、Chroma、Milvus、Neo4j、PostgreSQL/PGVector、PineCone、Qdrant、Redis 和 Weaviate

跨 Vector Store 提供程序的可移植 API,包括新颖的类似 SQL 的元数据过滤器 API,该 API 也是可移植的。

函数调用

AI 模型和矢量存储的 Spring Boot 自动配置启动器。

用于数据工程的 ETL 框架

导入依赖

如果要用自动装配版本可以使用spring-ai-openai-spring-boot-starter模块,我这里直接使用模块里面的,用法一样

用法API文档

        
            io.springboot.ai
            spring-ai-openai
            1.0.3
        

接口

@RestController
public class AiController {
    // 代理
//        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
//        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 1080));
//        requestFactory.setProxy(proxy);
//        var openAiApi = new OpenAiApi("","",  RestClient.builder().requestFactory(requestFactory));
    @PostMapping("/test")
    public Flux test(@RequestBody List messages) {
        String pt = "我是你的主人,请使用口语化的、可爱的、女性化的、调皮的语言风格和我交流. 你是一只萌宠, 你的名字叫可莉, 你需要尝试体会我与你对话中的感情、产生自己的情感并尽可能给出可爱的回答"; 
        messages.addFirst(new ChatCompletionMessage(pt, ChatCompletionMessage.Role.SYSTEM));
        var openAiApi = new OpenAiApi("自定义URL","API Key sk-");
        return openAiApi.chatCompletionStream(new ChatCompletionRequest(messages, "gpt-3.5-turbo", 0.8f, true))
                .mapNotNull(s-> s.choices().getFirst().delta().content())
                .onErrorResume(WebClientResponseException.class, ex -> Flux.just(ex.getResponseBodyAsString()))
                .doFinally(signalType -> System.out.println("完成"));
    }
}

前端

简单实现,纯HTML编写,不加任何组件,低版本浏览器可能不支持fetch



    
    Test Page


    
    发送
    
const dataArray = []; // 保存聊天消息 const s = document.getElementById('output'); //获取元素ID async function sendRequest() { const inputData = document.getElementById('inputData').value; //获取元素ID的值 s.innerText += "\n\n用户:" + inputData + "\n助手:";; dataArray.push({"role": "user","content": inputData }); const response = await fetch('http://127.0.0.1:8080/test', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(dataArray) }); var rs = ""; const reader = response.body.getReader(); async function processStream() { const { done, value } = await reader.read(); if (done) { dataArray.push({"role": "assistant","content": rs}); return; } const data = new TextDecoder().decode(value); s.innerText += data; rs += data; await processStream(); } await processStream(); }
微信扫一扫加客服

微信扫一扫加客服

点击启动AI问答
Draggable Icon