Created
May 12, 2023 08:06
-
-
Save nestoru/857d54a123f52b73fe7e3283a149f258 to your computer and use it in GitHub Desktop.
A CLI script to interact with ChatGPT via API
This file contains 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/env python3 | |
# | |
# clichatgpt.py | |
# | |
# A CLI script to interact with ChatGPT via API | |
# | |
# Nestor Urquiza 20230512 | |
# | |
import sys | |
import openai | |
import os | |
from sty import fg, rs | |
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY') | |
if OPENAI_API_KEY is None: | |
print(fg.red + 'ERROR: You must set the OPENAI_API_KEY environment variable.' + fg.rs) | |
exit(1) | |
openai.api_key = OPENAI_API_KEY | |
one_line_content = '' | |
msgs = [] | |
try: | |
print(fg.blue + 'Type a session prompt or press enter to skip (will be sent with your next prompts)' + fg.rs) | |
session_prompt = input() | |
print(fg.blue + 'Type your prompt and press enter on an empty line to get the response from ChatGPT:' + fg.rs) | |
for line in sys.stdin: | |
one_line_content += line | |
if line == '\n': | |
if session_prompt != '': | |
msgs.append({"role": "user", "content": session_prompt}) | |
msgs.append({"role": "user", "content": one_line_content}) | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages = msgs | |
) | |
print(response.choices[0].message.content + '\n') | |
one_line_content = '' | |
msgs = [] | |
except KeyboardInterrupt: | |
print('\n') | |
exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment