Spring AI调用OpenAI 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>

接口

@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("完成"));
    }

}

前端

简单实现,纯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>
  • 28
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值