我正在构建一个 React 应用程序,它与 OpenAI API 集成以生成标签。但是,我经常遇到 429 Too Many Requests 错误。我怎样才能有效地处理这个错误?在前端应用程序中管理 API 速率限制的最佳实践是什么?此外,在 React 应用程序中使用环境变量作为我的 API 密钥时是否存在任何安全问题?任何有关调试策略和减轻这些错误的替代方案的建议也将不胜感激。
const generateTags = async (text) => {
setLoading(true);
setIsOpen(true);
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${import.meta.env.VITE_OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [
{
role: "user",
content: `Generate a list of relevant, SEO-friendly tags from this YouTube video title: "${text}". Make all letters lowercase and separate the tags with commas.`,
},
],
temperature: 0.5,
max_tokens: 60,
frequency_penalty: 0.8,
}),
};
try {
const response = await fetch(
import.meta.env.VITE_OPENAI_API_URL,
options
);
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}
const json = await response.json();
// Check if response has valid choices
if (json.choices && json.choices.length > 0) {
const data = json.choices[0].text.trim();
setTags(data);
} else {
throw new Error("No tags generated.");
}
} catch (error) {
console.error("Error generating tags:", error);
setTags("Failed to generate tags. Please try again.");
} finally {
setLoading(false);
}
};
我尝试在 React 应用程序中使用 OpenAI API 生成 SEO 友好的标签,期望生成的标签能够成功响应。相反,我收到了 429 Too Many Requests 错误,表明超出了 API 速率限制。
如果您收到 429(请求过多)错误状态代码,您可以在延迟一段时间后尝试再次调用 api。我提供了处理这种情况的完整代码。
const generateTags = async (text) => {
setLoading(true);
setIsOpen(true);
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${import.meta.env.VITE_OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [
{
role: "user",
content: `Generate a list of relevant, SEO-friendly tags from this YouTube video title: "${text}". Make all letters lowercase and separate the tags with commas.`,
},
],
temperature: 0.5,
max_tokens: 60,
frequency_penalty: 0.8,
}),
};
try {
const response = await fetch(import.meta.env.VITE_OPENAI_API_URL, options);
// Here, handle 429 status code to call the api after some delay
if (response.status === 429) {
const retryAfter = response.headers.get("Retry-After") || 1;
await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000));
return generateTags(text); // Retry the request after waiting
}
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}
const json = await response.json();
if (json.choices && json.choices.length > 0) {
const data = json.choices[0].text.trim();
setTags(data);
} else {
throw new Error("No tags generated.");
}
} catch (error) {
console.error("Error generating tags:", error);
setTags("Failed to generate tags. Please try again.");
} finally {
setLoading(false);
}
};