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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
|
#!/bin/env python3
import sys
import openai
import pickle
from collections import defaultdict
from dataclasses import dataclass
from typing import Tuple
from .openai_wrappers import (
create_chat_completion,
list_models,
OpenAIChatResponse,
OpenAIChatResponseStream,
FinishReason,
)
from .argparsing import (
parse_args,
Arguments,
DisplayArguments,
CompletionArguments,
DebugArguments,
)
from .version import VERSION
from .color import get_color_codes
###########################
#### SAVE / REPLAY ####
###########################
def create_chat_completion_from_args(args : CompletionArguments) \
-> OpenAIChatResponseStream:
return create_chat_completion(
model=args.model,
messages=[{ "role": "user", "content": args.message }],
n=args.n_completions,
temperature=args.temperature,
presence_penalty=args.presence_penalty,
frequency_penalty=args.frequency_penalty,
max_tokens=args.max_tokens,
top_p=args.top_p,
stream=True
)
def save_response_and_arguments(args : Arguments) -> None:
completion = create_chat_completion_from_args(args.completion_args)
completion = list(completion)
filename = args.debug_args.save_response_to_file
with open(filename, 'wb') as f:
pickle.dump((args.completion_args, completion,), f)
def load_response_and_arguments(args : Arguments) \
-> Tuple[CompletionArguments, OpenAIChatResponseStream]:
filename = args.debug_args.load_response_from_file
with open(filename, 'rb') as f:
args, completion = pickle.load(f)
return (args, completion)
#########################
#### PRETTY PRINTING ####
#########################
@dataclass
class CumulativeResponse:
content: str = ""
finish_reason: FinishReason = FinishReason.NONE
def take_content(self : "CumulativeResponse"):
chunk = self.content
self.content = ""
return chunk
def print_streamed_response(
display_args : DisplayArguments,
completion : OpenAIChatResponseStream,
n_completions : int
) -> None:
"""
Print the response in real time by printing the deltas as they occur. If multiple responses
are requested, print the first in real-time, accumulating the others in the background. One the
first response completes, move on to the second response printing the deltas in real time. Continue
on until all responses have been printed.
"""
COLOR_CODE = get_color_codes(no_color = not display_args.color)
adornments = display_args.adornments
cumu_responses = defaultdict(CumulativeResponse)
display_idx = 0
prompt_printed = False
for update in completion:
for choice in update.choices:
delta = choice.delta
if delta.content:
cumu_responses[choice.index].content += delta.content
if choice.finish_reason is not FinishReason.NONE:
cumu_responses[choice.index].finish_reason = choice.finish_reason
display_response = cumu_responses[display_idx]
if not prompt_printed and adornments:
res_indicator = '' if n_completions == 1 else \
f' {display_idx + 1}/{n_completions}'
PROMPT = f'[{COLOR_CODE.GREEN}{update.model}{COLOR_CODE.RESET}{COLOR_CODE.RED}{res_indicator}{COLOR_CODE.RESET}]'
prompt_printed = True
print(PROMPT, end=' ', flush=True)
content = display_response.take_content()
print(f'{COLOR_CODE.WHITE}{content}{COLOR_CODE.RESET}',
sep='', end='', flush=True)
if display_response.finish_reason is not FinishReason.NONE:
if display_idx < n_completions:
display_idx += 1
prompt_printed = False
if adornments:
print(end='\n\n', flush=True)
else:
print(end='\n', flush=True)
def main():
args = parse_args()
if args.version:
print(f'version {VERSION}')
sys.exit(0)
if args.list_models:
for model in list_models():
print(model)
sys.exit(0)
completion_args = args.completion_args
COLOR_CODE = get_color_codes(no_color = not args.display_args.color)
debug_args : DebugArguments = args.debug_args
if debug_args.save_response_to_file:
save_response_and_arguments(args)
return
elif debug_args.load_response_from_file:
completion_args, completion = load_response_and_arguments(args)
else:
if args.completion_args.message is None:
if sys.stdin.isatty():
print(f'GPT Chat CLI {VERSION}')
print(f'[{COLOR_CODE.WHITE}#{COLOR_CODE.RESET}]', end=' ', flush=True)
completion_args.message = sys.stdin.read()
completion = create_chat_completion_from_args(completion_args)
print_streamed_response(
args.display_args,
completion,
completion_args.n_completions
)
if __name__ == "__main__":
main()
|