Created
December 18, 2022 17:07
-
-
Save danielgross/214ce155e6553d1a1c67f8b289e36b29 to your computer and use it in GitHub Desktop.
Terminal ChatGPT (with API)
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/env python3 | |
"""Chat with GPT-3 from the Terminal.""" | |
import os | |
import openai | |
if os.path.exists(os.path.expanduser("~/.openai")): | |
openai.api_key = open(os.path.expanduser("~/.openai")).read().strip() | |
else: | |
print("Enter your OpenAI API key: ", end="") | |
openai.api_key = input() | |
starting_prompt = """I am a highly intelligent question answering bot. If you ask me a question that is rooted in truth, I will give you the answer. If you ask me a question that is nonsense, trickery, or has no clear answer, I will respond with \"Unknown\".\n\nQ: What is human life expectancy in the United States?\nA: Human life expectancy in the United States is 78 years.\n\nQ: Who was president of the United States in 1955?\nA: Dwight D. Eisenhower was president of the United States in 1955.\n\nQ: Which party did he belong to?\nA: He belonged to the Republican Party.\n\nQ: What is the square root of banana?\nA: Unknown\n\nQ: How does a telescope work?\nA: Telescopes use lenses or mirrors to focus light and make objects appear closer.\n\nQ: Where were the 1992 Olympics held?\nA: The 1992 Olympics were held in Barcelona, Spain.\n\nQ: How many squigs are in a bonk?\nA: Unknown\n\n""" | |
current_prompt = starting_prompt | |
def gpt3(prompt): | |
response = openai.Completion.create( | |
engine="text-davinci-003", | |
prompt=prompt, | |
temperature=0.9, | |
max_tokens=100, | |
top_p=1, | |
stop=["\n"] | |
) | |
return response["choices"][0]["text"] | |
print("Welcome to GPT-3 Chat! Type 'quit' to exit, 'reset' to reset the conversation.") | |
print(current_prompt) | |
while True: | |
print("Q: ", end="") | |
user_input = input() | |
if user_input == "quit": | |
break | |
if user_input == "reset": | |
current_prompt = starting_prompt | |
# clear screen | |
print("\033c") | |
print(current_prompt) | |
continue | |
current_prompt += f"\nQ: {user_input}\nA:" | |
response = gpt3(current_prompt).strip() | |
# add response without the newline | |
print(f"A: {response}") | |
current_prompt += f" {response}\n" | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment