Last active
July 25, 2023 07:05
-
-
Save jatinkrmalik/3c80fd5c50d3df706e5c0f86902ad7cb to your computer and use it in GitHub Desktop.
ChatGPT CLI [Python App]
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
""" | |
Author: @jatinkrmalik | |
This script creates a chat interface between the user and OpenAI's GPT model. | |
Instructions to run the program: | |
1. Set your OpenAI API key as an environment variable in your terminal session. You can do this by running the following command: | |
export OPENAI_API_KEY='your-api-key-here' | |
Remember to replace 'your-api-key-here' with your actual OpenAI API key. | |
2. After setting the API key, you can run the script with the following command: | |
python gpt_cli.py | |
3. Once the script is running, you can start typing your messages into the terminal. The model's responses will be printed out. You can keep the conversation going for as long as you like. | |
4. If you wish to stop the program, simply type 'quit' or 'exit'. | |
""" | |
import argparse | |
import openai | |
import os | |
# Fetch the OpenAI API key from the environment variables | |
openai_api_key = os.getenv('OPENAI_API_KEY') | |
if openai_api_key is None: | |
raise ValueError("The environment variable OPENAI_API_KEY is not set. Please set this variable with your OpenAI API key.") | |
# Set the OpenAI API key | |
openai.api_key = openai_api_key | |
# Initialize conversation with a system message | |
conversation = [ | |
{ | |
"role": "system", | |
"content": "You are a helpful assistant." | |
} | |
] | |
def chat_with_model(message): | |
conversation.append({ | |
"role": "user", | |
"content": message | |
}) | |
response = openai.ChatCompletion.create( | |
model="gpt-4-0613", # update this to newer model if it's available, such as gpt-3.5-turbo-16k | |
messages=conversation | |
) | |
conversation.append({ | |
"role": "assistant", | |
"content": response['choices'][0]['message']['content'] | |
}) | |
return response['choices'][0]['message']['content'] | |
# Interactive conversation loop | |
print("You are now chatting with OpenAI gpt-4-0613 model. Type 'quit' or 'exit' to end the program.") | |
print() | |
while True: | |
user_message = input("👨 User: ") | |
if user_message.lower() in ['quit', 'exit']: | |
break | |
else: | |
print("🤖 Assistant: ", chat_with_model(user_message)) | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a preview: