You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Vercel AI SDK官方Next.js代码运行报错:RetryError问题求助

解决Vercel AI SDK RetryError并实现基础Next.js AI程序

错误核心原因

出现RetryError通常是以下问题导致:

  • 未正确配置AI模型的API密钥
  • 环境变量未在Next.js中加载生效
  • 模型名称与SDK要求不匹配
  • Next.js版本与Vercel AI SDK版本不兼容

可运行的基础实现步骤

1. 初始化项目并安装依赖

创建Pages Router类型的Next.js项目,安装核心依赖:

npx create-next-app@latest ai-basic-demo --typescript --eslint --app=false
cd ai-basic-demo
npm install ai openai

2. 配置环境变量

在项目根目录创建.env.local文件,填入你的OpenAI API密钥:

OPENAI_API_KEY=你的OpenAI API密钥

注意:该文件默认会被Next.js自动加载,且需确保它在.gitignore中,避免密钥泄露。

3. 创建API路由

在pages/api目录下新建chat.ts文件:

import { OpenAIStream, StreamingTextResponse } from 'ai';
import { OpenAI } from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY!,
});

export const config = {
  runtime: 'edge',
};

export default async function handler(req: Request) {
  const { messages } = await req.json();

  const response = await openai.chat.completions.create({
    model: 'gpt-3.5-turbo',
    stream: true,
    messages: messages.map((message: any) => ({
      role: message.role,
      content: message.content,
    })),
  });

  const stream = OpenAIStream(response);
  return new StreamingTextResponse(stream);
}

4. 编写前端页面

替换pages/index.tsx内容:

'use client';

import { useChat } from 'ai/react';

export default function Home() {
  const { messages, input, handleInputChange, handleSubmit } = useChat();

  return (
    <div className="max-w-md mx-auto p-6">
      <h1 className="text-2xl font-bold mb-6">基础AI聊天工具</h1>
      <div className="space-y-3 mb-6">
        {messages.map((m) => (
          <div key={m.id} className={`p-3 rounded-lg ${m.role === 'user' ? 'bg-blue-50' : 'bg-gray-50'}`}>
            <span className="font-semibold">{m.role === 'user' ? '用户' : 'AI'}:</span> {m.content}
          </div>
        ))}
      </div>
      <form onSubmit={handleSubmit} className="flex gap-2">
        <input
          type="text"
          value={input}
          onChange={handleInputChange}
          placeholder="输入问题..."
          className="flex-1 p-2 border border-gray-300 rounded-lg"
        />
        <button type="submit" className="bg-blue-600 text-white px-4 py-2 rounded-lg">发送</button>
      </form>
    </div>
  );
}

5. 启动项目

npm run dev

访问http://localhost:3000即可使用基础AI聊天功能。

额外排查要点

  • 确认API密钥无拼写错误、无多余空格
  • 检查网络可正常访问OpenAI服务(若需代理,需在环境变量中配置OPENAI_BASE_URL)
  • 确保ai和openai为最新稳定版本,可执行npm update ai openai更新

内容的提问来源于stack exchange,提问作者Joe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 00:42:10