GifproGifpro

Vercel AI SDK 流式聊天应用示例|Next.js 提示词模板

代码预览

エディタを読み込み中…
P

提示词

Create a full-stack streaming chat application using the Vercel AI SDK. The frontend is a single HTML file with Tailwind CSS (CDN) and modern JavaScript. The chat UI shows streaming text character by character as it arrives from the AI. Include a text input and send button, a message list that scrolls automatically, and a loading indicator while waiting for the response. Use the Vercel AI SDK's useChat hook (or equivalent streaming fetch) to connect to a backend API route at /api/chat. The backend (Node.js with Next.js API route) uses the Vercel AI SDK's streamText function with a simple prompt. The example should demonstrate real-time streaming, error handling, and a clean, responsive design. Provide the complete code for both frontend and backend.

これはVercel AI SDKを使った完全なストリーミングチャットアプリケーションです。フロントエンドはTailwind CSSでスタイリングし、プレーンなJavaScriptでストリーミングfetchを処理します。AIが生成するメッセージがリアルタイムで表示され、スムーズなユーザー体験を提供します。

バックエンド(Next.js APIルート):

// app/api/chat/route.ts
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';

export async function POST(req: Request) {
  const { message } = await req.json();
  const result = streamText({
    model: openai('gpt-4o-mini'),
    prompt: `あなたは親切なアシスタントです。ユーザーが言っています: ${message}`,
  });
  return result.toDataStreamResponse();
}

依存関係をインストール: npm install ai @ai-sdk/openai。環境変数にOpenAI APIキー(OPENAI_API_KEY)を設定してください。

上記のフロントエンドコードは単一のHTMLファイルで、どんなプロジェクトにも組み込めます。ストリーミング、自動スクロール、ローディング状態、エラーハンドリングを示しています。

提示词解读

这是一个使用Vercel AI SDK构建的完整流式聊天应用程序。前端使用Tailwind CSS进行样式设计,并通过纯JavaScript处理流式fetch请求。AI生成的消息会实时显示,提供流畅的用户体验。

后端(Next.js API路由):

// app/api/chat/route.ts
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';

export async function POST(req: Request) {
  const { message } = await req.json();
  const result = streamText({
    model: openai('gpt-4o-mini'),
    prompt: `你是一位友好的助手。用户说: ${message}`,
  });
  return result.toDataStreamResponse();
}

安装依赖: npm install ai @ai-sdk/openai。请在环境变量中设置OpenAI API密钥(OPENAI_API_KEY)。

上述前端代码是一个独立的HTML文件,可以集成到任何项目中。它展示了流式传输、自动滚动、加载状态和错误处理等功能。

这个提示对您有帮助吗?

评论

评论将在审核后显示

この記事が役に立ったら投げ銭で応援

Apple Pay / Google Pay / カード (Visa/Mastercard/JCB/Amex) / Link / Alipay / WeChat Pay 対応 · Stripeで安全に決済

開発者が選ぶ最強ツール集

運営者が毎日使っているツール・ガジェット 6選

見る
首页ヘルプ