6 篇文章带有标签 “streaming”

Vercel AI SDK 架构设计分析

1. 项目概述

Vercel AI SDK 是一个与提供商无关的 TypeScript 工具包,旨在帮助开发者使用流行的 UI 框架(如 Next.js、React、Svelte、Vue、Angular)和运行时(如 Node.js)构建 AI 驱动的应用程序和智能体。

核心特性

  • 统一提供商架构:支持 OpenAI、Anthropic、Google 等多个模型提供商
  • 多框架支持:React、Svelte、Vue、Angular
  • 多种模型类型:文本生成、嵌入、图像、语音、转录、重排等
  • 智能体框架:ToolLoopAgent 等工具循环代理
  • 流式输出:支持实时流式响应

2. 整体架构

Gradio Chatbot

Gradio Chatbot

DashScope

import os
import pandas as pd
import gradio as gr
from http import HTTPStatus
from dashscope import Generation
from dashscope.api_entities.dashscope_response import Role
from typing import List, Optional, Tuple, Dict, Generator
from urllib.error import HTTPError


DEFAULT_SYSTEM = '您是一个有用的助手。'

History = List[Tuple[str, str]]
Messages = List[Dict[str, str]]

// ...

LangChain ChatTongyi

使用 FastAPI 开发 RESTAPI 服务

创建项目

创建目录

mkdir project
cd project

创建虚拟环境

python -m venv env
source env/bin/activate
# 退出命令 deactivate

创建 requirements.txt 文件

fastapi
python-multipart
aiofiles
uvicorn
gunicorn

安装需要的库

pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/

项目目录结构

project
├── app
│   ├── __init__.py
│   ├── dependencies.py
│   ├── main.py
│   └── routers
│       ├── __init__.py
│       ├── files.py
│       └── users.py
└── requirements.txt

main.py import uvicorn from fastapi import FastAPI from .routers import users from .routers import files app = FastAPI(title='REST API Interface', version='1.

使用 wrk 对 FastAPI 上传和下载文件的基准测试

服务器 CPU 40核,内存 256G,操作系统 Ubuntu 20.04,Python3.9

RESTAPI 基于 FastAPI 实现的文件上传和下载 router = APIRouter(prefix='/file_benchmarking', tags=['Files']) @router.post('/upload/binary/chunk/async_func/async_r_sync_w', tags=['Upload', 'binary']) async def upload_binary_chunk_async_func_async_r_sync_w(request: Request): file_path = get_random_filename() with open(file_path, "wb") as file: async for chunk in request.stream(): file.write(chunk) return {'file_path': file_path} @router.

FastAPI 上传和下载文件的基准测试

使用 FastAPI 实现了文件的上传和下载,部署服务使用了 uvicorn 和 gunicorn+uvicorn 两种方法。

基准测试工具使用的是 wrk

服务器 CPU 40核,内存 256G,操作系统 Ubuntu 20.04,Python3.9

测试流程

使用的测试图片 health.jpg (256kb)

生成测试数据

生成通过 HTTP POST 发送二进制数据的文件。

python make_http_postdata.py make health.jpg postdata
file: /home/wjj/test/postdata
boundary: gouchicao0123456789

创建用于 wrk 的 lua 脚本:postfile.lua

wrk.method = "POST"
local f = io.open("postdata", "rb")
wrk.body   = f:read("*all")
wrk.headers["Content-Type"] = "multipart/form-data; boundary=gouchicao0123456789"

部署 FastAPI 应用 uvicorn uvicorn app.