自 2024 年 3 月起,OpenAI 已全面轉向預付款機制。用戶需要預先充值到 OpenAI 帳戶,每次 API 調用會從帳戶餘額中扣除。最低充值金額為 5 美元。
npx create-next-app
創建新專案npm install openai
.env.local
,並加入 OpenAI API key// .env.local
OPENAI_API_KEY=paste_your_api_key
// src/app/api/grammar/route.js
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
export async function POST(request) {
try {
const body = await request.json();
const { sentence } = body;
if (!sentence) {
return new Response(JSON.stringify({ error: "sentence is required" }), {
status: 400,
headers: { "Content-Type": "application/json" },
});
}
const response = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [
{
role: "user",
// 依個別專案需求,創建不同的提示詞(Prompt)
content: `${sentence}\n\n請詳細解釋以上英文句子中的文法`,
},
],
});
return new Response(
JSON.stringify({ result: response.choices[0].message.content }),
{
status: 200,
headers: { "Content-Type": "application/json" },
}
);
} catch (error) {
console.error(error);
return new Response(JSON.stringify({ error: "Something went wrong" }), {
status: 500,
headers: { "Content-Type": "application/json" },
});
}
}
ps. 範例使用 Next.js App Route,如果偏好使用 page route,可參考 reference 中的連結
"use client";
import { useState } from "react";
import styles from "./page.module.css";
export default function Home() {
const [sentence, setSentence] = useState("");
const [isLoading, setLoading] = useState(false);
const [response, setResponse] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
setResponse("");
try {
const res = await fetch("/api/grammar", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sentence }),
});
const data = await res.json();
setResponse(data.result);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
};
return (
<div className={styles.container}>
<h1 className={styles.title}>英文文法解釋器</h1>
<form onSubmit={handleSubmit}>
<textarea
className={styles.input}
value={sentence}
onChange={(e) => setSentence(e.target.value)}
placeholder="貼入句子"
/>
<button type="submit" className={styles.button} disabled={isLoading}>
{isLoading ? "載入中..." : "送出"}
</button>
</form>
{response && (
<p className={styles.result}>
{response.split("\n").map((text, idx) => (<div key={idx}>{text}</div>))}
</p>
)}
</div>
);
}
Error: 403 Country, region, or territory not supported
使用 Vercel edge functions 可以提升 API 效能。由於 Vercel edge functions 離台灣最近的區域是香港,而 OpenAI 無法在香港使用,因此需要設定 regions 來避免錯誤。
App Route:
// src/app/api/grammar/route.js
// 使用 edge function
export const runtime = 'edge';
// 指定區域
const preferredRegion = ['iad1', 'hnd1'];
Page route:
export const config = {
runtime: 'edge',
regions: ['iad1', 'hnd1'],
};
可以設定的區域有:https://vercel.com/docs/edge-network/regions#region-list