Created
June 19, 2023 07:08
-
-
Save allanrbo/eca306b6e50f6f9f933fec2a0c28b902 to your computer and use it in GitHub Desktop.
ChatGPT from your command line, without any library dependencies (API key required)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
# Quick and dirty ChatGPT from your command line, without any library dependencies (API key required) | |
# End your input with a line consisting of just --- | |
# Stop generating with ctrl-c | |
from urllib.request import Request, urlopen | |
import json | |
messages = [] | |
while True: | |
query = "" | |
while True: | |
try: | |
line = input() | |
if line == "---": | |
break | |
query += line + "\n" | |
except KeyboardInterrupt: | |
exit() | |
messages.append({"role": "user", "content": query}) | |
d = { | |
#"model": "gpt-4", | |
"model": "gpt-3.5-turbo", | |
"stream": True, | |
"messages": messages | |
} | |
req = Request("https://api.openai.com/v1/chat/completions", data=json.dumps(d).encode("utf-8")) | |
req.get_method = lambda: "POST" | |
req.add_header("Content-Type", "application/json") | |
req.add_header("Accept", "text/event-stream") | |
req.add_header("Authorization", "Bearer <<<<<<<<<<<your-api-key>>>>>>>>>>>>>") | |
stream = urlopen(req) | |
buf = b"" | |
done = False | |
ans = "" | |
try: | |
while not done: | |
r = stream.read(100) | |
if not r: | |
done = True | |
else: | |
buf += r | |
breaks_pos = buf.find(b"\n\n") | |
if breaks_pos == -1: | |
continue | |
cur = buf[:breaks_pos] | |
buf = buf[breaks_pos + 2:] | |
line = cur.decode("utf-8") | |
if not line.startswith("data: "): | |
print(buf) | |
raise(Exception("unexpected response format")) | |
line = line[len("data: "):] | |
if line == "[DONE]": | |
continue | |
j = json.loads(line) | |
delta = j["choices"][0]["delta"] | |
if "content" in delta: | |
print(delta["content"], end="", flush=True) | |
ans += delta["content"] | |
if ans[-1] != "\n": | |
print() | |
print("---") | |
messages.append({"role": "assistant", "content": ans}) | |
except KeyboardInterrupt: | |
stream.close() | |
print("") | |
print("---") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment