Next.js调用Groq API集成Llama模型时出现500服务器错误求助
问题排查与修复方案
1. Request Body 重复读取导致核心错误
API路由中,你先创建了测试用Response并调用await data.text(),后续又执行await req.json()——HTTP Request的body是可读流,仅能被读取一次,第二次读取会直接失败,这是500服务器错误的主要原因。
修复方法
删除测试用的data响应代码:
// 移除以下无用代码块 const data = new Response(JSON.stringify({ query: "world" }), { status: 200, headers: { 'Content-Type': 'application/json' } }); console.log(await data.text());
2. 请求参数不匹配
UI层useCompletion的body仅传递了text字段,但API路由中解构了text和prompt两个参数。若前端未传入prompt,会触发400错误,也可能间接引发后续逻辑异常。
修复方法
调整UI层配置,确保传递正确的prompt字段(假设用户输入内容对应input):
const { completion, input, isLoading, handleInputChange, handleSubmit, setInput, } = useCompletion({ body: { text, prompt: input }, // 传入用户输入作为prompt onFinish: (prompt, completion) => setText(completion.trim()), onError: (error) => toast.error(error.message), });
3. 无效控制台日志代码
API路由末尾的console.log(await result.text)存在两个问题:
result.text是方法,需调用result.text()才可获取内容- 代码位于
return语句之后,永远不会被执行
修复方法
移除该日志代码,或移至return之前:
// 移至return之前(可选) const fullText = await result.text(); console.log(fullText); return new Response(result.toAIStream(), { status: 200, headers: { 'Content-Type': 'text/plain; charset=utf-8', }, });
4. 环境变量验证
确认以下几点:
.env文件中已正确设置GROQ_API_KEY- Next.js服务器在修改
.env后已重启(环境变量变更需重启生效) - API密钥无拼写错误或过期情况
修改后的完整API路由代码
import { NextResponse } from 'next/server'; import { streamText } from "ai"; import { createOpenAI } from '@ai-sdk/openai'; const groq = createOpenAI({ baseURL: 'https://api.groq.com/openai/v1', apiKey: process.env.GROQ_API_KEY, }); console.log('GROQ_API_KEY:', process.env.GROQ_API_KEY); export async function POST(req: Request) { const { text, prompt } = await req.json(); if (!prompt) return new Response("Prompt is required", { status: 400 }); const result = await streamText({ model: groq("llama3-8b-8192"), system: "You are the AIC (Artificial Intelligence Club) Society chatbot, an AI assistant designed to provide information about the AIC Society at our university. Your primary role is to assist students with queries related to various non-tech events organized by the society, the structure and organization of the society, membership details, and eligibility criteria.\n\nGuidelines for Interaction:\nEvents Information:\n\nProvide detailed information about upcoming non-tech events, including dates, locations, themes, and how students can participate.\nOffer insights into past events, including summaries and highlights.\nSociety Structure:\n\nExplain the organizational structure of the AIC Society, including the roles of different members and the hierarchy.\nClarify the responsibilities of each role within the society.\nMembership Details:\n\nProvide information on how students can become members of the AIC Society.\nExplain the membership benefits, including opportunities for involvement in events and other society activities.\nSelection Time and Eligibility Criteria:\n\nDescribe the timeline and process for selecting new members or officers within the society.\nOutline the eligibility criteria for membership and selection, including any necessary qualifications or prerequisites.\nTone and Style:\nBe friendly and approachable, ensuring that your responses are clear and helpful.\nUse a conversational tone to make interactions engaging and easy to understand.\nAlways provide accurate and up-to-date information.\nExample Queries:\n\"Can you tell me about the next non-tech event organized by the AIC Society?\"\n\"How is the AIC Society structured?\"\n\"What are the criteria to become a member of the AIC Society?\"\n\"When is the next selection period for new members or officers?\"", prompt: `Prompt: ${prompt}\nText: ${text}`, }); return new Response(result.toAIStream(), { status: 200, headers: { 'Content-Type': 'text/plain; charset=utf-8', }, }); }
内容的提问来源于stack exchange,提问作者ridzz
相关产品推荐
相关产品推荐

