gpt4 book ai didi

javascript - Nuxt 3 - OpenAi api - 在本地工作但在部署时不工作(在 Vercel 上)

转载 作者:行者123 更新时间:2023-12-02 05:46:26 24 4
gpt4 key购买 nike

我在做什么
一个 Nuxt 3 应用程序,它有一个表单字段,我可以在其中输入提示,这将使用提示调用 OpenAi api,然后显示来自 OpenAi 的结果。 https://zinnetjes-2ertn9n8i-robertbel.vercel.app/

问题
在本地这工作正常,但是当我部署到 Vercel 并提交表单时,我得到了这个响应:{"error": {"code": "500", "message": "服务器发生错误"}}

我的 Nuxt 应用结构是什么样的:
页面/index.vue

<template>
<form @submit.prevent="submitForm">
<input type="text" v-model="sentence" />
<button type="submit">Submit</button>

</form>
<div>
<p class="data">{{ dataFromApi }}</p>
</div>
</template>

<script setup>
import { ref } from 'vue'

const sentence = ref('')
const dataFromApi = ref('')

function submitForm() {
formRequest().then((result) => {
console.log(result)
dataFromApi.value = result
}).catch((error) => {
console.error('Form could not be send', error)
});
}

async function formRequest() {
return await $fetch('/api/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ sentence: sentence.value }),
})
}

</script>

服务器/api/generate.js

import { Configuration, OpenAIApi } from "openai";

export default defineEventHandler(async (event) => {
const body = await readBody(event)
const config = useRuntimeConfig()

const configuration = new Configuration({
apiKey: config.secret,
});
const openai = new OpenAIApi(configuration);

const completion = await openai.createCompletion({
model: "text-davinci-003",
prompt: body.sentence,
temperature: 0.6,
max_tokens: 420,
});

return completion.data.choices[0].text;
})

nuxt.config.ts

export default defineNuxtConfig({
runtimeConfig: {
secret: process.env.OPENAI_API_KEY,
},
nitro: {
preset: 'vercel-edge',
},
});

.环境

OPENAI_API_KEY=XXXXX

在 Vercel 的设置中,我添加了环境变量: enter image description here

我觉得这与 en API key 和环境变量有关,但我很难调试它。

有人知道我如何让它工作吗?

最佳答案

如果您正在使用 nextjs,请在项目的根目录中添加一个 now.json 文件

{
"version": 2,
"builds": [
{
"src": "src/pages/api/**/*.ts",
"use": "@now/node",
"config": {
"timeout": 300000
}
}
]
}

vercel 上的默认超时为 30 秒,这会将其更改为 500 秒。如果您使用复杂的提示,则可能会超时

关于javascript - Nuxt 3 - OpenAi api - 在本地工作但在部署时不工作(在 Vercel 上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74900645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com