File size: 1,165 Bytes
842b5ee
42bad84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# coding=utf-8
import websocket
import json
import os

MY_OPENAI_API_KEY = os.environ.get('MY_OPENAI_API_KEY')


def on_message(ws, message):
    response = json.loads(message)
    # 处理来自 ChatGPT 的响应
    print(response['choices'][0]['text'])

    # 根据您的条件判断是否需要关闭连接
    if '完成对话的条件':
        ws.close()


def on_error(ws, error):
    print(error)


def on_close(ws):
    print("连接已关闭")


def on_open(ws):
    # 发送初始消息
    ws.send(json.dumps({
        'type': 'input',
        'message': '你好,ChatGPT!'
    }))

    # 发送后续消息(用于完成)
    ws.send(json.dumps({
        'type': 'input',
        'message': '技术问题是...'
    }))


if __name__ == '__main__':
    # 创建 WebSocket 连接和其他初始化代码
    ws = websocket.WebSocketApp(
        'wss://api.openai.com/v1/streaming_chat_completion',
        on_message=on_message,
        on_error=on_error,
        on_close=on_close,
        header={
            'Authorization': 'Bearer YOUR_API_KEY'
        }
    )

    ws.on_open = on_open

    # 运行 WebSocket 连接
    ws.run_forever()