簡體   English   中英

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

[英]Nuxt 3 - OpenAi api - Works locally but not when deployed (on Vercel)

我在做什么
一個 Nuxt 3 應用程序,它有一個表單字段,我可以在其中輸入提示,這將使用提示調用 OpenAi api,然后顯示來自 OpenAi 的結果。 https://zi.netjes-2ertn9n8i-robertbel.vercel.app/

問題
在本地這工作正常,但是當我部署到 Vercel 並提交表單時,我得到這個響應: {"error": {"code": "500", "message": "A server error has occurred"}}

我的 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',
  },
});

.env

OPENAI_API_KEY=XXXXX

在 Vercel 的設置中,我添加了環境變量: 在此處輸入圖像描述

我覺得這與 en API 密鑰和環境變量有關,但我很難調試它。

有人知道我如何讓它工作嗎?

如果您使用的是 nextjs,請在項目的根目錄中添加一個 now.json 文件

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

Vercel 上的默認超時為 30 秒,這會將其更改為 500 秒。 如果您使用復雜的提示,它可能會超時

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM