PHP和GO對(duì)接ChatGPT實(shí)現(xiàn)聊天機(jī)器人效果實(shí)例
PHP部分主要是與ChatGPT API通信
<?php // 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語(yǔ)言對(duì)接ChatGPT API并實(shí)現(xiàn)逐字輸出
在Go語(yǔ)言中,你可以使用net/http
包來(lái)發(fā)送HTTP請(qǐng)求。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何使用Go語(yǔ)言對(duì)接ChatGPT API并實(shí)現(xiàn)逐字輸出:
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "os" "time" ) // ChatGPT API Endpoint const 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 string fmt.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è)簡(jiǎn)單的示例,你可能需要根據(jù)實(shí)際需求進(jìn)行修改和優(yōu)化。確保將YOUR_API_KEY
替換為你在OpenAI上獲得的API密鑰。同時(shí),考慮到安全性,你可能需要采取措施來(lái)保護(hù)API密鑰,比如在服務(wù)器端進(jìn)行處理,而不是直接在前端處理
前端請(qǐng)求后端接口效果
以下是前端請(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.newMessage this.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> /* 頁(yè)面容器 */ .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>
以上就是PHP和GO對(duì)接ChatGPT實(shí)現(xiàn)聊天機(jī)器人效果實(shí)例的詳細(xì)內(nèi)容,更多關(guān)于PHP GO對(duì)接ChatGP聊天機(jī)器人的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Golang線上內(nèi)存爆掉問(wèn)題排查(pprof)與解決
這篇文章主要介紹了Golang線上內(nèi)存爆掉問(wèn)題排查(pprof)與解決,涉及到數(shù)據(jù)敏感,文中代碼是我模擬線上故障的一個(gè)情況,好在我們程序都有添加pprof監(jiān)控,于是直接通過(guò)go tool pprof分析,需要的朋友可以參考下2024-04-04Go/C語(yǔ)言LeetCode題解997找到小鎮(zhèn)法官
這篇文章主要為大家介紹了Go語(yǔ)言LeetCode題解997找到小鎮(zhèn)的法官示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12Golang實(shí)現(xiàn)簡(jiǎn)單http服務(wù)器的示例詳解
這篇文章主要為大家詳細(xì)介紹了如何利用Golang實(shí)現(xiàn)簡(jiǎn)單http服務(wù)器,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Golang有一定的幫助,需要的可以參考一下2023-03-03Go中string與[]byte高效互轉(zhuǎn)的方法實(shí)例
string與[]byte經(jīng)常需要互相轉(zhuǎn)化,普通轉(zhuǎn)化會(huì)發(fā)生底層數(shù)據(jù)的復(fù)制,下面這篇文章主要給大家介紹了關(guān)于Go中string與[]byte高效互轉(zhuǎn)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-09-09我為什么喜歡Go語(yǔ)言(簡(jiǎn)潔的Go語(yǔ)言)
從2000年至今,也寫(xiě)了11年代碼了,期間用過(guò)VB、Delphi、C#、C++、Ruby、Python,一直在尋找一門(mén)符合自己心意和理念的語(yǔ)言。我很在意寫(xiě)代碼時(shí)的手感和執(zhí)行的效率,所以在Go出現(xiàn)之前一直沒(méi)有找到2014-10-10