原标题: ChatGPT可以通过使用HTTP或WebSocket协议与互联网进行连接。以下是一些示例代码,展示了如何在Python中使用这两种方法之一。
导读:
1. 使用HTTP连接:```pythonimport requestsdef chat_with_chatgpt(message):url = ""hea...
1. 使用HTTP连接:
```python
import requests
def chat_with_chatgpt(message):
url = ""
headers = {
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
}
payload = {
"model": "gpt-3.5-turbo",
"messages": [{"role": "system", "content": message}]
response = requests.post(url, headers=headers, json=payload)
if response.status_code == 200:
data = response.json()
return data["choices"][0]["message"]["content"]
# 处理错误情况
```
2. 使用WebSocket连接:
import websocket
import json
def on_message(ws, message):
data=json.loads(message)
if 'text' in data['data'][0]['interpretations'][0]['expression']:
print(data['data'][0]['interpretations'][0]['expression']['text'])
ws=websocket.WebSocketApp("wss://chat.openai.com/api/v1/alpha/you/models/davinci/unstable/chats")
ws.on_open=lambda ws: ws.send('{"botid":"YOU_BOT_ID","type":"Listen"}')
ws.on_message=on_message
ws.run_forever()