<p id="m2nkj"><option id="m2nkj"><big id="m2nkj"></big></option></p>
    <strong id="m2nkj"></strong>
    <ruby id="m2nkj"></ruby>

    <var id="m2nkj"></var>
  • PHP和GO如何對(duì)接ChatGPT,實(shí)現(xiàn)聊天機(jī)器人效果

    共 14381字,需瀏覽 29分鐘

     ·

    2024-03-22 03:30

    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語言中,你可以使用 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 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è)簡單的示例,你可能需要根據(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.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> /* 頁面容器 */ .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>


    瀏覽 91
    點(diǎn)贊
    評(píng)論
    收藏
    分享

    手機(jī)掃一掃分享

    分享
    舉報(bào)
    評(píng)論
    圖片
    表情
    推薦
    點(diǎn)贊
    評(píng)論
    收藏
    分享

    手機(jī)掃一掃分享

    分享
    舉報(bào)
    <p id="m2nkj"><option id="m2nkj"><big id="m2nkj"></big></option></p>
    <strong id="m2nkj"></strong>
    <ruby id="m2nkj"></ruby>

    <var id="m2nkj"></var>
  • 亚洲黄色视频免费看 | 黄片无码免费看 | 日韩最新高清无码 | 特级毛片内射 | 操碰97人人操 | 中文字幕久久青青 | 美女福利在线 | 超碰97人人艹 | 天天操天天摸天天碰 | 亚洲无码av在线观看 |