PHP和GO如何对接ChatGPT,实现聊天机器人效果

php学习交流吧

共 14381字,需浏览 29分钟

 · 2024-03-22

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密钥
// 获取前端发送的消息 $message = $_POST['prompt'];
// 准备发送的数据 $data = [ 'prompt' => $message, 'max_tokens' => 50, 'temperature' => 0.7 ];
// 构建HTTP请求头 $headers = [ 'Content-Type: application/json', 'Authorization: Bearer ' . $apiKey, 'OpenAI-Organization: org-TBIGMYjFzWqsshWUUQahkUng' ];
// 使用cURL发送HTTP POST请求 $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);
// 执行cURL请求 $response = curl_exec($ch);
// 关闭cURL句柄 curl_close($ch);
// 处理ChatGPT API的响应 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(); // 将输出立即发送给浏览器 usleep(50000); // 等待一段时间,以实现逐字输出的效果 } } else { echo 'API请求失败。'; }
?>


在Go语言中,你可以使用 net/http 包来发送HTTP请求。以下是一个简单的示例代码,演示如何使用Go语言对接ChatGPT API并实现逐字输出:

      
        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)
// 准备发送的数据 data := map[string]interface{}{ "prompt": message, "max_tokens": 50, "temperature": 0.7, }
// 将数据转换为JSON格式 jsonData, err := json.Marshal(data) if err != nil { fmt.Println("JSON编码错误:", err) os.Exit(1) }
// 创建HTTP请求 request, err := http.NewRequest("POST", apiEndpoint, bytes.NewBuffer(jsonData)) if err != nil { fmt.Println("创建HTTP请求错误:", err) os.Exit(1) }
// 设置请求头 request.Header.Set("Content-Type", "application/json") request.Header.Set("Authorization", "Bearer "+apiKey) request.Header.Set("OpenAI-Organization", "org-TBIGMYjFzWqsshWUUQahkUng")
// 发送HTTP请求 client := http.Client{} response, err := client.Do(request) if err != nil { fmt.Println("发送HTTP请求错误:", err) os.Exit(1) } defer response.Body.Close()
// 读取响应数据 responseData, err := ioutil.ReadAll(response.Body) if err != nil { fmt.Println("读取响应数据错误:", err) os.Exit(1) }
// 处理ChatGPT API的响应 var jsonResponse map[string]interface{} err = json.Unmarshal(responseData, &jsonResponse) if err != nil { fmt.Println("JSON解码错误:", 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毫秒输出一个字 } }

请注意,这是一个简单的示例,你可能需要根据实际需求进行修改和优化。确保将 YOUR_API_KEY 替换为你在OpenAI上获得的API密钥。同时,考虑到安全性,你可能需要采取措施来保护API密钥,比如在服务器端进行处理,而不是直接在前端处理。

以下是前端请求后端接口效果,示例代码:

      
        
          <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"> <!-- 输入框和发送按钮 --> <input class="input-box" type="text" v-model="newMessage" placeholder="输入消息..." /> <button @click="sendMessage" class="send-button">发送</button> </view> </view> </template>
<script> export default { data() { return { messages: [], newMessage: '' // 用于存储新消息 }; }, methods: {
sendMessage() { if (this.newMessage.trim() !== '') { const message = this.newMessage this.messages.push({ content: this.newMessage, isSender: true }); this.newMessage = ''; // 清空输入框
// 准备发送的数据 const data = { prompt:message, max_tokens:50, temperature:0.7 }; uni.request({ url: '',//后端请求接口 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; // 更新最后一条消息内容 index++;
// 当消息输出完毕后清除间隔函数 if (index === responseMessage.length) { clearInterval(printMessageInterval); } }, 100); // 每100毫秒输出一个字 }, fail: (err) => { console.error('ChatGPT Error:', err); // 处理错误 } });
} } } }; </script>
<style scoped> /* 页面容器 */ .chat-container { display: flex; flex-direction: column; height: 100vh; }
/* 消息列表 */ .message-list { flex: 1; overflow-y: scroll; padding: 10px; }
/* 消息项样式 */ .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; /* 将发送者消息框推到右侧 */ }
.receiver-message { align-self: flex-start; background-color: #f0f0f0; padding: 8px; border-radius: 8px; margin-right: auto; /* 将接收者消息框推到左侧 */ }
.message-bubble { max-width: 70%; /* 调整消息框的最大宽度 */ }
/* 输入框和发送按钮 */ .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>


浏览 21
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报