vue.js 错误429:返回API“请求失败,状态代码为429”

uyto3xhc  于 2023-02-24  发布在  Vue.js
关注(0)|答案(2)|浏览(725)

我正在尝试将OpenAI API连接到我的Vue.js项目。一切正常,但每次我尝试POST请求时,我都会得到一个429状态码(太多请求),但我甚至没有机会做一个。有帮助吗?
回复:

{
    "message": "Request failed with status code 429",
    "name": "Error",
    "stack": "Error: Request failed with status code 429\n    at createError (C:\\Users\\sim\\Documents\\SC\\server\\node_modules\\axios\\lib\\core\\createError.js:16:15)\n    at settle (C:\\Users\\sim\\Documents\\SC\\server\\node_modules\\axios\\lib\\core\\settle.js:17:12)\n    at IncomingMessage.handleStreamEnd (C:\\Users\\sim\\Documents\\SC\\server\\node_modules\\axios\\lib\\adapters\\http.js:322:11)\n    at IncomingMessage.emit (events.js:412:35)\n    at endReadableNT (internal/streams/readable.js:1333:12)\n    at processTicksAndRejections (internal/process/task_queues.js:82:21)",
    "config": {
        "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
        },
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json",
            "User-Agent": "OpenAI/NodeJS/3.1.0",
            "Authorization": "Bearer secret",
            "Content-Length": 137
        },
        "method": "post",
        "data": "{\"model\":\"text-davinci-003\",\"prompt\":\"option-2\",\"temperature\":0,\"max_tokens\":3000,\"top_p\":1,\"frequency_penalty\":0.5,\"presence_penalty\":0}",
        "url": "https://api.openai.com/v1/completions"
    },
    "status": 429
}

我在Vue.js中的方法:

async handleSelect() {
      try {
        const res = await fetch("http://localhost:8000/", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            question: this.selectedOption,
          })
        })

        const data = await res.json();
        console.log(data);
      } catch {
        console.log(data);
      }
    }

在服务器端

app.post("/", async (req, res) => {
  try {
    const question = req.body.question;

    const response = await openai.createCompletion({
      model: "text-davinci-003",
      prompt: `${question}`,
      temperature: 0, // Higher values means the model will take more risks.
      max_tokens: 3000, // The maximum number of tokens to generate in the completion. Most models have a context length of 2048 tokens (except for the newest models, which support 4096).
      top_p: 1, // alternative to sampling with temperature, called nucleus sampling
      frequency_penalty: 0.5, // Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.
      presence_penalty: 0, // Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.
    });
    // console.log(response);
    res.status(200).send({
      bot: response.data.choices[0].text,
    });
  } catch (error) {
    // console.error(error);
    res.status(500).send(error || "Something went wrong");
  }
});
35g0bw71

35g0bw711#

这就是您收到该错误的原因,您的订阅或免费计划已过期
enter image description here

bf1o4zei

bf1o4zei2#

如官方OpenAI article中所述:
此错误消息(即429)表示您已达到为API分配的速率限制。这意味着您在短时间内提交了太多令牌或请求,并且已超过允许的请求数。发生此情况的原因有多种,例如:

  • 您使用的循环或脚本会发出频繁或并发的请求。
  • 您正在与其他用户或应用程序共享API密钥。
  • 您使用的是费率限制较低的免费计划。

下面的代码可以工作。

前端

    • 你好,世界之旅**
<template>
  <div class="hello"></div>

  <select v-model="selected" @change="handleSelect()">
    <option disabled value="">Please select one</option>
    <option>Say this is a test</option>
    <option>Say nothing</option>
  </select>

  <div class="container-selected">Selected: {{ selected }}</div>

  <div class="container-data" v-if="showData">{{ showData.bot }}</div>
</template>

<script>
export default {
  data: function () {
    return {
      selected: "",
      showData: "",
    };
  },
  methods: {
    async handleSelect(data) {
      try {
        const res = await fetch("http://localhost:3000/", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            question: this.selected,
          }),
        });

        const data = await res.json();
        this.showData = data;
        console.log(data);
      } catch {
        console.log(data);
      }
    },
  },
};
</script>

<style lang="scss">
.container-selected {
  margin-top: 12px;
  font-size: 20px;
}

.container-data {
  margin-top: 24px;
  font-size: 20px;
}
</style>
    • 包. json**
{
  "name": "openai",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "register-service-worker": "^1.7.2",
    "vue": "^3.2.13",
    "vue-class-component": "^8.0.0-0",
    "vue-router": "^4.0.3",
    "vuex": "^4.0.0"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^5.4.0",
    "@typescript-eslint/parser": "^5.4.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-plugin-pwa": "~5.0.0",
    "@vue/cli-plugin-router": "~5.0.0",
    "@vue/cli-plugin-typescript": "~5.0.0",
    "@vue/cli-plugin-vuex": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "@vue/eslint-config-typescript": "^9.1.0",
    "eslint": "^7.32.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-vue": "^8.0.3",
    "prettier": "^2.4.1",
    "sass": "^1.32.7",
    "sass-loader": "^12.0.0",
    "typescript": "~4.5.5"
  }
}

后端

    • 索引. js**
const express = require('express');
const app = express();
app.use(express.json());

const cors = require('cors');
app.use(cors());

app.post('/', async(req, res) => {
  try {
    const { Configuration, OpenAIApi } = require('openai');
    const configuration = new Configuration({
        apiKey: 'sk-xxxxxxxxxxxxxxxxxxxx'
    });
    const openai = new OpenAIApi(configuration);

    const question = req.body.question;

    await openai.createCompletion({
      model: 'text-davinci-003',
      prompt: question,
      temperature: 0,
      max_tokens: 7
    })
    .then((response) => {
      console.log(response.data.choices[0].text);
      res.status(200).send({ bot: response.data.choices[0].text });
    })
    .catch((err) => {
      res.status(400).send({ message: err.message });
    })
  } catch (error) {
    res.status(500).send(error || 'Something went wrong');
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
    • 包. json**
{
  "name": "openai-server",
  "version": "1.0.0",
  "description": "Express server",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.18.2",
    "nodemon": "^2.0.20",
    "openai": "^3.1.0"
  }
}

输出

相关问题