CAFECA-IO / BAIFA

https://baifa.vercel.app
GNU General Public License v3.0
0 stars 0 forks source link

查找串接 ChatGPT API Key 文件 #405

Closed godmmt closed 9 months ago

godmmt commented 9 months ago

查找串接 ChatGPT API Key 文件

steps:

godmmt commented 9 months ago

Reference about ChatGPT chatbot for website

References translation ver

godmmt commented 9 months ago

OpenAI docs

( ✍️ Snippet from OpenAI docs, only the part I need )

Introduction

You can interact with the API through HTTP requests from any language, via our official Python bindings, our official Node.js library, or a community-maintained library.

To install the official Node.js library, run the following command in your Node.js project directory:

npm install openai@^4.0.0

Authentication

The OpenAI API uses API keys for authentication. Visit your API Keys page to retrieve the API key you'll use in your requests.

Remember that your API key is a secret! Do not share it with others or expose it in any client-side code (browsers, apps). Production requests must be routed through your own backend server where your API key can be securely loaded from an environment variable or key management service.

All API requests should include your API key in an Authorization HTTP header as follows:

Authorization: Bearer OPENAI_API_KEY

Making requests

You can paste the command below into your terminal to run your first API request. Make sure to replace $OPENAI_API_KEY with your secret API key.

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
     "model": "gpt-3.5-turbo",
     "messages": [{"role": "user", "content": "Say this is a test!"}],
     "temperature": 0.7
   }'

This request queries the gpt-3.5-turbo model (which under the hood points to the latest gpt-3.5-turbo model variant) to complete the text starting with a prompt of "Say this is a test".

You should get a response back that resembles the following:

{
    "id": "chatcmpl-abc123",
    "object": "chat.completion",
    "created": 1677858242,
    "model": "gpt-3.5-turbo-1106",
    "usage": {
        "prompt_tokens": 13,
        "completion_tokens": 7,
        "total_tokens": 20
    },
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "\n\nThis is a test!"
            },
            "logprobs": null,
            "finish_reason": "stop",
            "index": 0
        }
    ]
}

Now that you've generated your first chat completion, let's break down the response object. We can see the finish_reason is stop which means the API returned the full chat completion generated by the model without running into any limits. In the choices list, we only generated a single message but you can set the n parameter to generate multiple messages choices.

godmmt commented 9 months ago

Terminal shows error :

liz@CAFECAdeMBP:s002->/Users/liz (0) 
> curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer s**********************w" \
  -d '{
     "model": "gpt-3.5-turbo",
     "messages": [{"role": "user", "content": "Say this is a test!"}],
     "temperature": 0.7
   }'
{
    "error": {
        "message": "You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.",
        "type": "insufficient_quota",
        "param": null,
        "code": "insufficient_quota"
    }
}

訊息: 您超出了當前的配額限制,請檢查您的方案和計費詳情。有關此錯誤的更多資訊,請參閱文檔:https://platform.openai.com/docs/guides/error-codes/api-errors

godmmt commented 9 months ago

Resolved Terminal shows error. ✅

截圖 2023-12-20 下午5 35 13

godmmt commented 9 months ago

took 8 hours remains 3 hours

godmmt commented 9 months ago

Test :

Terminal (my first API request):

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
     "model": "gpt-3.5-turbo",
     "messages": [{"role": "user", "content": "Hello? Who are you?"}],
     "temperature": 0.7
   }'

Response :

1703139955229

> curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer s**********************Z" \
  -d '{
     "model": "gpt-3.5-turbo",
     "messages": [{"role": "user", "content": "Hello? Who are you?"}],
     "temperature": 0.7
   }'

{
  "id": "chatcmpl-8Y6R4g0Z9y45l7f3MJQ1WgexS6FVI",
  "object": "chat.completion",
  "created": 1703138582,
  "model": "gpt-3.5-turbo-0613",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! I am an AI language model developed by OpenAI. I don't have a personal identity as I am just a program designed to assist with answering questions and engaging in conversations. How can I help you today?"
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 13,
    "completion_tokens": 44,
    "total_tokens": 57
  },
  "system_fingerprint": null
}
godmmt commented 9 months ago

took 1 hour

remains 2 hours

godmmt commented 9 months ago

How to Integrate ChatGPT on Your Website

We‘ve talked about what ChatGPT is, why it’s valuable, how to prepare for its integration, and where to place it on your site. Now, let's get down to the business of actually integrating this AI powerhouse into your website.

Since all websites are a little different and there are a lot of factors that go into integrating ChatGPT into your website, we'll provide a high-level overview of the steps below.

Step 1: Setup OpenAI's ChatGPT API

With your OpenAI API key in hand, you‘re ready to set up the ChatGPT API. Here's one way to do it using Node.js.

設置ChatGPT API。

以下是使用Node.js的一種方法:

const axios = require("axios");
const OPENAI_API_KEY = "your-api-key-here";
axios
  .post(
    "https://api.openai.com/v1/engines/davinci-codex/completions",
    {
      prompt: 'Translate the following English text to French: "{text}"',
      max_tokens: 60,
    },
    {
      headers: {
        Authorization: `Bearer ${OPENAI_API_KEY}`,
        "Content-Type": "application/json",
      },
    },
  )
  .then((response) => {
    console.log(response.data.choices[0].text.trim());
  })
  .catch((error) => {
    console.error(error);
  });

Step 2: Connect to the API

The next step is to connect to the API. This requires setting up a server-side route that makes the call to the ChatGPT API and returns the response.

設置一個服務器端路由,可以調用ChatGPT API並回傳回應。

Step 3: Add ChatGPT to Your Website's Backend

To add ChatGPT to your website‘s backend, you’ll need to set up a server-side function that makes requests to the API. This function will be responsible for sending user input to ChatGPT and receiving responses.

負責向API發送請求的 server-side 函數。這個函數負責把使用者輸入的訊息,發送到ChatGPT,並接收回應。

Step 4: Create a Frontend for the Chatbot

With the backend setup, you'll need to create a frontend for your chatbot. This includes designing the chat interface and scripting the interactivity. Here, you can use a combination of HTML, CSS, and JavaScript.

Step 5: Test the Integration

godmmt commented 9 months ago

took 0.5 hour

Total time : 9.5 hours

done.