-
Notifications
You must be signed in to change notification settings - Fork 0
/
sample.py
76 lines (61 loc) · 2.02 KB
/
sample.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import sys
import time
import math
import datetime
import ChatAIStream as cas
# print sentence by a character incrementally.
def print_incremental(st, interval_sec):
for i in range(len(st)):
if not running:
break
print(f"{st[i]}", end='')
sys.stdout.flush()
interruptible_sleep(interval_sec)
# Customized sleep for making available of running flag interruption.
def interruptible_sleep(time_sec):
counter = math.floor(time_sec / 0.10)
frac = time_sec - (counter * 0.10)
for i in range(counter):
if not running:
break
time.sleep(0.10)
if not running:
return
time.sleep(frac)
# callback for getting answer of ChatGPT
def answer_cb(user_message, completion):
print(f"\n[{user_message.extern.author.name} {user_message.extern.datetime}] {user_message.message}\n")
interruptible_sleep(3)
time_str = datetime.datetime.now().strftime ('%H:%M:%S')
message = completion.choices[0]["message"]["content"]
print(f"[ChatGPT {time_str}] ", end='')
print_incremental(message, 0.05)
print("\n")
interruptible_sleep(5)
running = False
# YouTube Video ID and ChatGPT API Key is given from command line in this example.
if len(sys.argv) <= 2:
exit(0)
# Set params of getting messages from stream source.
stream_params=cas.streamParams(video_id=sys.argv[1])
# Set params of Chat AI.
ai_params=cas.aiParams(
api_key = sys.argv[2],
system_role = "You are a cheerful assistant who speek English and can get conversation exciting with user.",
answer_cb = answer_cb
)
# Create ChatAIStream instance.
ai_stream = cas.ChatAIStream(cas.params(stream_params=stream_params, ai_params=ai_params))
running = True
# Wake up internal thread to get chat messages from stream and ChatGPT answers.
ai_stream.start()
# Wait any key inputted from keyboad.
input()
# Turn off runnging flag in order to finish printing messages and answers by the sample.
running=False
# Finish getting ChatGPT answers.
# Internal thread will stop soon.
ai_stream.disconnect()
# terminating internal thread.
ai_stream.join()
del ai_stream