PHP和GO如何對(duì)接ChatGPT,實(shí)現(xiàn)聊天機(jī)器人效果
PHP部分主要是與ChatGPT API通信
// ChatGPT API Endpoint$apiEndpoint = 'https://api.openai.com/v1/engines/gpt-3.5-turbo/completions';
// ChatGPT API密鑰$apiKey = 'YOUR_API_KEY'; // 替換為你在OpenAI上獲得的API密鑰
// 獲取前端發(fā)送的消息$message = $_POST['prompt'];
// 準(zhǔn)備發(fā)送的數(shù)據(jù)$data = ['prompt' => $message,'max_tokens' => 50,'temperature' => 0.7];
// 構(gòu)建HTTP請(qǐng)求頭$headers = ['Content-Type: application/json','Authorization: Bearer ' . $apiKey,'OpenAI-Organization: org-TBIGMYjFzWqsshWUUQahkUng'];
// 使用cURL發(fā)送HTTP POST請(qǐng)求$ch = curl_init($apiEndpoint);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 執(zhí)行cURL請(qǐng)求$response = curl_exec($ch);
// 關(guān)閉cURL句柄curl_close($ch);
// 處理ChatGPT API的響應(yīng)if ($response !== false) {$responseData = json_decode($response, true);$responseMessage = $responseData['choices'][0]['message']['content'];
// 返回消息逐字輸出for ($i = 0; $i < mb_strlen($responseMessage); $i++) {echo $responseMessage[$i];flush(); // 將輸出立即發(fā)送給瀏覽器usleep(50000); // 等待一段時(shí)間,以實(shí)現(xiàn)逐字輸出的效果}} else {echo 'API請(qǐng)求失敗。';}
在Go語言中,你可以使用 net/http 包來發(fā)送HTTP請(qǐng)求。以下是一個(gè)簡單的示例代碼,演示如何使用Go語言對(duì)接ChatGPT API并實(shí)現(xiàn)逐字輸出:
package main
import ("bytes""encoding/json""fmt""io/ioutil""net/http""os""time")
// ChatGPT API Endpointconst apiEndpoint = "https://api.openai.com/v1/engines/gpt-3.5-turbo/completions"
// ChatGPT API密鑰const apiKey = "YOUR_API_KEY" // 替換為你在OpenAI上獲得的API密鑰
func main() {// 獲取用戶輸入的消息fmt.Print("輸入消息: ")var message stringfmt.Scanln(&message)
// 準(zhǔn)備發(fā)送的數(shù)據(jù)data := map[string]interface{}{"prompt": message,"max_tokens": 50,"temperature": 0.7,}
// 將數(shù)據(jù)轉(zhuǎn)換為JSON格式jsonData, err := json.Marshal(data)if err != nil {fmt.Println("JSON編碼錯(cuò)誤:", err)os.Exit(1)}
// 創(chuàng)建HTTP請(qǐng)求request, err := http.NewRequest("POST", apiEndpoint, bytes.NewBuffer(jsonData))if err != nil {fmt.Println("創(chuàng)建HTTP請(qǐng)求錯(cuò)誤:", err)os.Exit(1)}
// 設(shè)置請(qǐng)求頭request.Header.Set("Content-Type", "application/json")request.Header.Set("Authorization", "Bearer "+apiKey)request.Header.Set("OpenAI-Organization", "org-TBIGMYjFzWqsshWUUQahkUng")
// 發(fā)送HTTP請(qǐng)求client := http.Client{}response, err := client.Do(request)if err != nil {fmt.Println("發(fā)送HTTP請(qǐng)求錯(cuò)誤:", err)os.Exit(1)}defer response.Body.Close()
// 讀取響應(yīng)數(shù)據(jù)responseData, err := ioutil.ReadAll(response.Body)if err != nil {fmt.Println("讀取響應(yīng)數(shù)據(jù)錯(cuò)誤:", err)os.Exit(1)}
// 處理ChatGPT API的響應(yīng)var jsonResponse map[string]interface{}err = json.Unmarshal(responseData, &jsonResponse)if err != nil {fmt.Println("JSON解碼錯(cuò)誤:", err)os.Exit(1)}
// 獲取生成的消息responseMessage := jsonResponse["choices"].([]interface{})[0].(map[string]interface{})["message"].(map[string]interface{})["content"].(string)
// 返回消息逐字輸出for _, char := range responseMessage {fmt.Print(string(char))time.Sleep(100 * time.Millisecond) // 每100毫秒輸出一個(gè)字}}
請(qǐng)注意,這是一個(gè)簡單的示例,你可能需要根據(jù)實(shí)際需求進(jìn)行修改和優(yōu)化。確保將 YOUR_API_KEY 替換為你在OpenAI上獲得的API密鑰。同時(shí),考慮到安全性,你可能需要采取措施來保護(hù)API密鑰,比如在服務(wù)器端進(jìn)行處理,而不是直接在前端處理。
以下是前端請(qǐng)求后端接口效果,示例代碼:
<template><view class="chat-container"><view class="message-list"><!-- 這里是消息列表,用于顯示聊天記錄 --><view v-for="(message, index) in messages" :key="index" class="message-item"><view :class="message.isSender ? 'sender-message' : 'receiver-message'" class="message-bubble">{{ message.content }}</view></view></view>
<view class="input-bar"><!-- 輸入框和發(fā)送按鈕 --><input class="input-box" type="text" v-model="newMessage" placeholder="輸入消息..." /><button @click="sendMessage" class="send-button">發(fā)送</button></view></view></template>
<script>export default {data() {return {messages: [],newMessage: '' // 用于存儲(chǔ)新消息};},methods: {
sendMessage() {if (this.newMessage.trim() !== '') {const message = this.newMessagethis.messages.push({content: this.newMessage,isSender: true});this.newMessage = ''; // 清空輸入框
// 準(zhǔn)備發(fā)送的數(shù)據(jù)const data = {prompt:message,max_tokens:50,temperature:0.7};uni.request({url: '',//后端請(qǐng)求接口method: 'POST',data: data,success: (res) => {console.log('ChatGPT Response:', res.data);
// 返回消息逐字輸出const responseMessage = res.data.message;let index = 0;this.messages.push({content: '',isSender: false});const printMessageInterval = setInterval(() => {const partialMessage = responseMessage.substring(0, index +1); // 獲取部分消息this.messages[this.messages.length - 1].content = partialMessage; // 更新最后一條消息內(nèi)容index++;
// 當(dāng)消息輸出完畢后清除間隔函數(shù)if (index === responseMessage.length) {clearInterval(printMessageInterval);}}, 100); // 每100毫秒輸出一個(gè)字},fail: (err) => {console.error('ChatGPT Error:', err);// 處理錯(cuò)誤}});
}}}};</script>
<style scoped>/* 頁面容器 */.chat-container {display: flex;flex-direction: column;height: 100vh;}
/* 消息列表 */.message-list {flex: 1;overflow-y: scroll;padding: 10px;}
/* 消息項(xiàng)樣式 */.message-item {display: flex;justify-content: flex-start;margin-bottom: 10px;}
.sender-message {align-self: flex-end;background-color: #c3e88d;padding: 8px;border-radius: 8px;margin-left: auto;/* 將發(fā)送者消息框推到右側(cè) */}
.receiver-message {align-self: flex-start;background-color: #f0f0f0;padding: 8px;border-radius: 8px;margin-right: auto;/* 將接收者消息框推到左側(cè) */}
.message-bubble {max-width: 70%;/* 調(diào)整消息框的最大寬度 */}
/* 輸入框和發(fā)送按鈕 */.input-bar {display: flex;align-items: center;justify-content: space-between;padding: 10px;position: fixed;bottom: 0;width: 100%;background-color: #ffffff;}
.input-box {flex: 1;height: 36px;border: 1px solid #ccc;border-radius: 5px;padding: 5px;margin-right: 10px;}
.send-button {background-color: #409eff;color: white;border: none;border-radius: 5px;
}</style>
評(píng)論
圖片
表情
