首頁  >  文章  >  web前端  >  如何將 ChatGPT API 與 Node.js 集成

如何將 ChatGPT API 與 Node.js 集成

王林
王林原創
2024-08-13 06:41:41298瀏覽

Como Integrar a API do ChatGPT com Node.js

將 ChatGPT API 與 Node.js 整合是向應用程式添加自然語言處理功能的強大方法。在這篇文章中,我們將探討如何設定集成,從安裝必要的函式庫到實作 ChatGPT API 呼叫。

1. 先決條件

  • Node.js 安裝在您的電腦上。
  • 一個 OpenAI 帳戶和一個有效的 API 金鑰。
  • 基本上熟悉 JavaScript 和 Node.js。

2. 安裝依賴

首先,建立一個新的 Node.js 專案並安裝必要的依賴項。我們將使用 axios 發出 HTTP 請求,並使用 dotenv 來管理環境變數。

mkdir chatgpt-nodejs
cd chatgpt-nodejs
npm init -y
npm install axios dotenv

3. 配置項目

在您的專案目錄中,建立一個 .env 檔案來儲存您的 OpenAI API 金鑰:

OPENAI_API_KEY=your-api-key-here

現在,建立一個index.js檔案並加入基本程式碼來設定dotenv和axios的使用:

require('dotenv').config();
const axios = require('axios');

const apiKey = process.env.OPENAI_API_KEY;
const apiUrl = 'https://api.openai.com/v1/chat/completions';

async function getChatGPTResponse(prompt) {
    try {
        const response = await axios.post(apiUrl, {
            model: "gpt-4",
            messages: [{ role: "user", content: prompt }],
            max_tokens: 150,
        }, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        const reply = response.data.choices[0].message.content;
        console.log('ChatGPT:', reply);
    } catch (error) {
        console.error('Error fetching response:', error.response ? error.response.data : error.message);
    }
}

getChatGPTResponse('Olá, como você está?');

4. 理解程式碼

  • dotenv:從 .env 檔案載入環境變數。
  • axios:對 ChatGPT API 進行 POST 呼叫。
  • apiKey:儲存請求中使用的 API 金鑰。
  • apiUrl:ChatGPT API URL。
  • getChatGPTResponse:非同步函數,將提示傳送到 ChatGPT 並顯示回應。

5. 運行程式碼

要執行程式碼,請執行指令:

node index.js

如果一切配置正確,您將在控制台中看到 ChatGPT 回應。

6. 自訂整合

您可以調整 API 呼叫中的多個參數,例如模型、回應令牌的數量 (max_tokens),甚至可以在訊息清單中包含上下文訊息。例如:

const conversation = [
    { role: "system", content: "Você é um assistente útil." },
    { role: "user", content: "Me explique o que é uma API." }
];

async function getChatGPTResponse(messages) {
    try {
        const response = await axios.post(apiUrl, {
            model: "gpt-4",
            messages: messages,
            max_tokens: 150,
        }, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        const reply = response.data.choices[0].message.content;
        console.log('ChatGPT:', reply);
    } catch (error) {
        console.error('Error fetching response:', error.response ? error.response.data : error.message);
    }
}

getChatGPTResponse(conversation);

7. 結論

將 ChatGPT API 與 Node.js 整合是一項相對簡單的任務,可以為您的應用程式添加高級 AI 功能。借助 API 的靈活性,您可以創建從會話助手到複雜的自然語言處理系統的所有內容。

嘗試不同的提示和設置,看看 ChatGPT 如何適應您的特定需求!


這是開始整合的基本範例。隨著您對 API 越來越熟悉,您可以探索更高級的功能,例如微調模型和使用更複雜的對話上下文。

以上是如何將 ChatGPT API 與 Node.js 集成的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn