GifproGifpro

Vercel AI SDK Streaming Chat App — Next.js Prompt Example

CODE PREVIEW

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

Prompt

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ファイルで、どんなプロジェクトにも組み込めます。ストリーミング、自動スクロール、ローディング状態、エラーハンドリングを示しています。

Prompt Overview

This is a complete streaming chat application using the Vercel AI SDK. The frontend is styled with Tailwind CSS and handles streaming fetch with plain JavaScript. AI-generated messages are displayed in real-time, providing a smooth user experience.

Backend (Next.js API Route):

// 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: `You are a helpful assistant. The user says: ${message}`,
  });
  return result.toDataStreamResponse();
}

Install dependencies: npm install ai @ai-sdk/openai. Set your OpenAI API key (OPENAI_API_KEY) in environment variables.

The frontend code above is a single HTML file that can be embedded into any project. It demonstrates streaming, auto-scroll, loading states, and error handling.

Was this prompt helpful?

Comments

Comments appear after moderation

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

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

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

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

見る
Homeヘルプ