当前位置:   article > 正文

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

spring ai stream

效果展示

在这里插入图片描述

什么是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文档

        <dependency>
            <groupId>io.springboot.ai</groupId>
            <artifactId>spring-ai-openai</artifactId>
            <version>1.0.3</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

接口

@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<String> test(@RequestBody List<ChatCompletionMessage> 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("完成"));
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

前端

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

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Page</title>
</head>
<body>
    <input type="text" id="inputData">
    <button onclick="sendRequest()">发送</button>
    <div id="output"></div>
    <script>
        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();
        }
    </script>
</body>

</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/758002
推荐阅读
相关标签
  

闽ICP备14008679号