从零开始,国内实现调用Open Ai

前言:

这是一个简单的思路,部分参考来自GPT-4。

实际可以直接参考本人主页的另一篇

《宝塔快速反代openai官方的API接口,实现国内直接使用GPT》。

目录:

目录


一:获取API。

这里就不细说,不会的看这篇《申请普通GPT-4账号等待GPT-4 API开放的过程》或者私信我。

二:网页制作

  1. 设计一个网页界面:为了让用户能够与GPT交互,你需要创建一个简单的网页界面,包括一个输入框(用于用户输入问题)和一个显示区域(用于展示ChatGPT的回答)。

        创建一个基本的HTML文件,添加输入框、按钮和显示结果的区域。

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ChatGPT示例</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h1>ChatGPT 示例</h1>
        <textarea id="input-text" placeholder="请输入您的问题..."></textarea>
        <button id="submit-button">发送</button>
        <div id="output-text"></div>
    </div>
    <script src="script.js"></script>
</body>
</html>

         创建一个CSS文件(例如:styles.css)来美化你的网页。

body {
    font-family: Arial, sans-serif;
    background-color: #f2f2f2;
}

.container {
    width: 80%;
    margin: 0 auto;
    text-align: center;
    background-color: #ffffff;
    padding: 20px;
    border-radius: 10px;
}

textarea {
    width: 100%;
    height: 100px;
    padding: 10px;
    resize: none;
    margin-bottom: 10px;
}

button {
    padding: 10px 20px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

#output-text {
    margin-top: 20px;
    text-align: left;
}

三.安装必要的库:确保已安装axios库,用于在JavaScript中发起HTTP请求。你可以通过npm或者在HTML文件中引入CDN链接来安装。

        如果你使用npm:

npm install axios

        如果你在HTML文件中引入CDN链接:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

四 创建一个JavaScript文件(例如:script.js)来处理与 GPT-API的交互。

document.getElementById("submit-button").addEventListener("click", async () => {
    const inputText = document.getElementById("input-text").value;
    const outputText = document.getElementById("output-text");

    if (inputText) {
        const response = await fetchChatGPTResponse(inputText);
        outputText.innerHTML = response;
    } else {
        outputText.innerHTML = "请输入问题。";
    }
});

async function fetchChatGPTResponse(inputText) {
    const api_key = "your_api_key_here";
    const api_url = "https://api.openai.com/v1/engines/davinci-codex/completions";
    const prompt = `请回答以下问题:\n问题:${inputText}\n回答:`;

    const response = await fetch(api_url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${api_key}`
        },
        body: JSON.stringify({
            prompt: prompt,
            max_tokens: 100,
            n: 1,
            stop: null,
            temperature: 1,
        }),
    });

    const data = await response.json();
    return data.choices[0].text.trim();
}

 注意:记得用你自己的API密钥替换your_api_key_here

五 ,因为在国内是无法直接调用的,你需要使用代理服务器来实现调用API。

在这里,我将向你展示如何搭建一个基于Node.js的简单代理服务器,并提供一个使用第三方代理服务的示例。

1.搭建一个基于Node.js的简单代理服务器:

首先,确保你已经安装了Node.js。接下来,按照以下步骤创建一个代理服务器:

a. 创建一个新的文件夹,例如命名为proxy-server,然后在文件夹中运行npm init,按照提示创建一个package.json文件。

b. 安装所需的依赖项:expresshttp-proxy-middleware。运行以下命令:

npm install express http-proxy-middleware
c. 在proxy-server文件夹中创建一个名为app.js的文件,并添加以下代码:
const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");

const app = express();
const port = process.env.PORT || 3000;

app.use(express.json());

app.post("/", (req, res) => {
  const targetURL = req.headers["target-url"];

  if (!targetURL) {
    res.status(400).send("Target-URL header is missing.");
    return;
  }

  delete req.headers["target-url"];

  app.use(
    "/",
    createProxyMiddleware({
      target: targetURL,
      changeOrigin: true,
      pathRewrite: { "^/": "" },
      onProxyReq: (proxyReq, req) => {
        Object.assign(proxyReq.headers, req.headers);
      },
    })
  );

  res.sendStatus(200);
});

app.listen(port, () => {
  console.log(`Proxy server is running at http://localhost:${port}`);
});

d. 保存文件并在proxy-server文件夹中运行node app.js。现在你的代理服务器已经在本地运行了。

你可以将此代理服务器部署到云服务提供商,如腾讯云、阿里云或其他类似的服务。

2.使用第三方代理服务:

这里以ProxyCrawl作为示例,

ProxyCrawl是一个提供代理服务的第三方公司。你可以在它们的官方网站上注册并获取API密钥。

在注册并获取API密钥后,你可以修改你的script.js文件,使用ProxyCrawl服务。将fetchChatGPTResponse函数修改为:

async function fetchChatGPTResponse(inputText) {
    const api_key = "your_chatgpt_api_key_here";
    const api_url = "https://api.openai.com/v1/engines/davinci-codex/completions";
    const apify_proxy_username = "auto";
    const apify_proxy_password = "your_apify_api_key_here";
    const proxy_url = "http://proxy.apify.com:8000";
    const prompt = `请回答以下问题:\n问题:${inputText}\n回答:`;

    const response = await fetch(proxy_url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${api_key}`,
            "Proxy-Authorization": `Basic ${btoa(`${apify_proxy_username}:${apify_proxy_password}`)}`
        },
        body: JSON.stringify({
            prompt: prompt,
            max_tokens: 100,
            n: 1,
            stop: null,
            temperature: 1,
        }),
    });

    const data = await response.json();
    return data.choices[0].text.trim();
}

请确保将your_chatgpt_api_key_here替换为你的GPT API密钥,将your_apify_api_key_here替换为你的Apify API密钥。

现在,你已经修改了script.js文件,可以使用Apify代理服务访问GPT API。

示例二:

这里以使用第三方代理服务”Apify”为例。首先,你需要访问Apify官网(https://apify.com/)在注册并获取API密钥后,修改script.js文件中的fetchChatGPTResponse函数,使用Apify代理服务:

在注册并获取API密钥后,修改script.js文件中的fetchChatGPTResponse函数,使用Apify代理服务:

async function fetchChatGPTResponse(inputText) {
    const api_key = "your_chatgpt_api_key_here";
    const api_url = "https://api.openai.com/v1/engines/davinci-codex/completions";
    const apify_proxy_username = "auto";
    const apify_proxy_password = "your_apify_api_key_here";
    const proxy_url = "http://proxy.apify.com:8000";
    const prompt = `请回答以下问题:\n问题:${inputText}\n回答:`;

    const response = await fetch(proxy_url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${api_key}`,
            "Proxy-Authorization": `Basic ${btoa(`${apify_proxy_username}:${apify_proxy_password}`)}`
        },
        body: JSON.stringify({
            prompt: prompt,
            max_tokens: 100,
            n: 1,
            stop: null,
            temperature: 1,
        }),
    });

    const data = await response.json();
    return data.choices[0].text.trim();
}

请确保将your_chatgpt_api_key_here替换为你的ChatGPT API密钥,将your_apify_api_key_here替换为你的Apify API密钥。

现在,你已经修改了script.js文件,可以使用Apify代理服务访问ChatGPT API。

注意:在使用Apify或其他第三方代理服务时,请注意了解其服务条款、隐私政策以及可能产生的费用。

 结尾:

这只是一个简单的思路,具体问题具体分析,88~

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年5月8日
下一篇 2023年5月8日

相关推荐