0

0

使用 Vercel AI SDK 实现多个并行 AI 流

WBOY

WBOY

发布时间:2024-07-11 19:19:29

|

861人浏览过

|

来源于dev.to

转载

使用 vercel ai sdk 实现多个并行 ai 流

vercel ai sdk 可以轻松与 openai、anthropic 等 llm api 进行交互,并传输数据,以便在加载时快速显示在您的 web 应用程序中。在本文中,我们将学习如何同时运行多个提示并并行查看它们的结果。

tl;dr:github 存储库在这里。

我为什么要这样做?

在 web 应用程序中同时运行多个数据获取请求并不罕见。例如,在假设的博客系统中,当仪表板界面加载时,我们可能希望同时获取用户的个人资料数据、他们创建的帖子以及他们喜欢的其他用户的帖子。

如果同一个仪表板同时向 openai 发出请求,我们可能希望同时向 openai 询问有关改善用户个人资料的提示,并同时分析他们的最新帖子。理论上,如果我们愿意的话,我们可以并行使用数十个人工智能请求(即使来自完全不同的平台和模型),并分析信息、生成内容并同时执行所有类型的其他任务。

安装与设置

您可以在此处克隆包含最终结果的 github 存储库。

从头开始设置:

  1. 遵循 next.js app router 快速入门。 只是基础知识;生成应用程序、安装依赖项并添加您的 openai api 密钥。
  2. 安装并设置 shadcn/ui。

设置基本 ui

完成所有工作的主要组件将包含一个表单和一些用于输出的容器。使用一些基本的 shadcn-ui 组件,表单将如下所示:

LongShot
LongShot

LongShot 是一款 AI 写作助手,可帮助您生成针对搜索引擎优化的内容博客。

下载
export function generationform() {
    // state and other info will be defined here...

        return (
        
{isgenerating ? (
) : null}

historical weather

{weather ? weather : null}

historical news

{news ? news : null}
) }

你可以看到我们这里有一些东西:

  • 表格
  • 加载动画(以及用于显示/隐藏它的 isgenerate 标志)
  • 用于渲染天气内容的容器
  • 用于渲染新闻内容的容器

现在您可以对这些值进行硬编码;它们都会从我们的信息流中删除。

设置 react 服务器组件 (rsc)

streamanswer 服务器操作将完成创建和更新我们的流的工作。

动作的结构是这样的:

export async function streamanswer(question: string) {
    // booleans for indicating whether each stream is currently streaming
  const isgeneratingstream1 = createstreamablevalue(true);
  const isgeneratingstream2 = createstreamablevalue(true);

  // the current stream values
  const weatherstream = createstreamablevalue("");
  const newsstream = createstreamablevalue("");

    // create the first stream. notice that we don't use await here, so that we
    //  don't block the rest of this function from running.
    streamtext({
        // ... params, including the llm prompt
  }).then(async (result) => {
          // read from the async iterator. set the stream value to each new word
          //  received.
      for await (const value of result.textstream) {
        weatherstream.update(value || "");
      }
    } finally {
        // set isgenerating to false, and close that stream.
      isgeneratingstream1.update(false);
      isgeneratingstream1.done();

      // close the given stream so the request doesn't hang.
      weatherstream.done();
    }
  });

  // same thing for the second stream.
    streamtext({
        // ... params
  }).then(async (result) => {
      // ...
  })

  // return any streams we want to read on the client.
  return {
    isgeneratingstream1: isgeneratingstream1.value,
    isgeneratingstream2: isgeneratingstream2.value,
    weatherstream: weatherstream.value,
    newsstream: newsstream.value,
  };
}

编写客户端代码

表单的 onsubmit 处理程序将完成这里的所有工作。以下是其工作原理的详细说明:

"use client";

import { SyntheticEvent, useState } from "react";
import { Button } from "./ui/button";
import { readStreamableValue, useUIState } from "ai/rsc";
import { streamAnswer } from "@/app/actions";
import { Spinner } from "./svgs/Spinner";

export function GenerationForm() {
    // State for loading flags
  const [isGeneratingStream1, setIsGeneratingStream1] = useState(false);
  const [isGeneratingStream2, setIsGeneratingStream2] = useState(false);

  // State for the LLM output streams
  const [weather, setWeather] = useState("");
  const [news, setNews] = useState("");

  // We'll hide the loader when both streams are done.
  const isGenerating = isGeneratingStream1 || isGeneratingStream2;

  async function onSubmit(e: SyntheticEvent) {
    e.preventDefault();

    // Clear previous results.
    setNews("");
    setWeather("");

        // Call the server action. The returned object will have all the streams in it.
    const result = await streamAnswer(question);

    // Translate each stream into an async iterator so we can loop through
    //  the values as they are generated.
    const isGeneratingStream1 = readStreamableValue(result.isGeneratingStream1);
    const isGeneratingStream2 = readStreamableValue(result.isGeneratingStream2);
    const weatherStream = readStreamableValue(result.weatherStream);
    const newsStream = readStreamableValue(result.newsStream);

        // Iterate through each stream, putting its values into state one by one.
        //  Notice the IIFEs again! As on the server, these allow us to prevent blocking
        //   the function, so that we can run these iterators in parallel.
    (async () => {
      for await (const value of isGeneratingStream1) {
        if (value != null) {
          setIsGeneratingStream1(value);
        }
      }
    })();

    (async () => {
      for await (const value of isGeneratingStream2) {
        if (value != null) {
          setIsGeneratingStream2(value);
        }
      }
    })();

    (async () => {
      for await (const value of weatherStream) {
        setWeather((existing) => (existing + value) as string);
      }
    })();

    (async () => {
      for await (const value of newsStream) {
        setNews((existing) => (existing + value) as string);
      }
    })();
  }

  return (
    // ... The form code from before.
  );
}

其他有趣的事情可以尝试

  • 使用streamobject()流式传输结构化json数据而不是文本
  • 并行传输更多内容
  • 同时从不同的 api 进行流式传输
  • 使用相同的提示流式传输不同模型进行比较(例如,cohere、anthropic、gemini 等)
  • 从服务器流式传输 ui(使用 createstreamableui() )

进一步阅读和链接

  • 服务器操作和突变
  • vercel ai sdk
  • streamtext() api 文档
  • next.js 应用路由器快速入门

相关专题

更多
json数据格式
json数据格式

JSON是一种轻量级的数据交换格式。本专题为大家带来json数据格式相关文章,帮助大家解决问题。

403

2023.08.07

json是什么
json是什么

JSON是一种轻量级的数据交换格式,具有简洁、易读、跨平台和语言的特点,JSON数据是通过键值对的方式进行组织,其中键是字符串,值可以是字符串、数值、布尔值、数组、对象或者null,在Web开发、数据交换和配置文件等方面得到广泛应用。本专题为大家提供json相关的文章、下载、课程内容,供大家免费下载体验。

528

2023.08.23

jquery怎么操作json
jquery怎么操作json

操作的方法有:1、“$.parseJSON(jsonString)”2、“$.getJSON(url, data, success)”;3、“$.each(obj, callback)”;4、“$.ajax()”。更多jquery怎么操作json的详细内容,可以访问本专题下面的文章。

307

2023.10.13

go语言处理json数据方法
go语言处理json数据方法

本专题整合了go语言中处理json数据方法,阅读专题下面的文章了解更多详细内容。

74

2025.09.10

js正则表达式
js正则表达式

php中文网为大家提供各种js正则表达式语法大全以及各种js正则表达式使用的方法,还有更多js正则表达式的相关文章、相关下载、相关课程,供大家免费下载体验。

508

2023.06.20

js获取当前时间
js获取当前时间

JS全称JavaScript,是一种具有函数优先的轻量级,解释型或即时编译型的编程语言;它是一种属于网络的高级脚本语言,主要用于Web,常用来为网页添加各式各样的动态功能。js怎么获取当前时间呢?php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

241

2023.07.28

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

249

2023.08.03

js是什么意思
js是什么意思

JS是JavaScript的缩写,它是一种广泛应用于网页开发的脚本语言。JavaScript是一种解释性的、基于对象和事件驱动的编程语言,通常用于为网页增加交互性和动态性。它可以在网页上实现复杂的功能和效果,如表单验证、页面元素操作、动画效果、数据交互等。

5224

2023.08.17

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

74

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Git 教程
Git 教程

共21课时 | 2.3万人学习

Git版本控制工具
Git版本控制工具

共8课时 | 1.5万人学习

Git中文开发手册
Git中文开发手册

共0课时 | 0人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号