OpenAI API (ChatGPT) Interaction
This guide demonstrates how to interact with the OpenAI API to use models like GPT-3.5 and GPT-4. It covers setting up the client, sending chat completion requests, and building a simple CLI chatbot.
Modules Used:
openai: The official Python library for the OpenAI API.- python-dotenv: To securely manage the API key.
- argparse: To handle command-line arguments.
Prerequisites
- OpenAI Account: Sign up at platform.openai.com.
- API Key: Create a new secret key in the API keys section.
- Credit Balance: Ensure your account has credits (OpenAI API is not free, though new accounts often get trial credits).
Installation
pip install openai python-dotenv
Setup
Create a .env file in your project directory:
OPENAI_API_KEY=sk-your-actual-api-key-here
The Code
Save this as chatgpt_tool.py.
import os
import argparse
from openai import OpenAI
from dotenv import load_dotenv
# 1. Configuration
load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def single_query(model, prompt):
"""Send a single prompt and print the response."""
try:
response = client.chat.completions.create(
model=model,
messages=[
{"role": "user", "content": prompt}
]
)
print(response.choices[0].message.content)
except Exception as e:
print(f"Error: {e}")
def chat_mode(model):
"""Interactive chat session with history."""
print(f"--- Chatting with {model} (Type 'quit' to exit) ---")
# Initialize history with a system message
history = [
{"role": "system", "content": "You are a helpful assistant."}
]
while True:
user_input = input("\nYou: ")
if user_input.lower() in ['quit', 'exit']:
break
if not user_input.strip():
continue
# Add user message to history
history.append({"role": "user", "content": user_input})
try:
# Stream response for better UX
stream = client.chat.completions.create(
model=model,
messages=history,
stream=True,
)
print("ChatGPT: ", end="", flush=True)
collected_response = ""
for chunk in stream:
if chunk.choices[0].delta.content is not None:
content = chunk.choices[0].delta.content
print(content, end="", flush=True)
collected_response += content
print() # Newline
# Add assistant response to history
history.append({"role": "assistant", "content": collected_response})
except Exception as e:
print(f"\nError: {e}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="OpenAI GPT CLI Tool")
parser.add_argument("prompt", nargs="?", help="The prompt to send (leave empty for chat mode)")
parser.add_argument("--model", default="gpt-3.5-turbo", help="Model to use (default: gpt-3.5-turbo)")
args = parser.parse_args()
if not os.getenv("OPENAI_API_KEY"):
print("Error: OPENAI_API_KEY not found in .env file.")
else:
if args.prompt:
single_query(args.model, args.prompt)
else:
chat_mode(args.model)
Usage
-
Interactive Chat:
python chatgpt_tool.py -
Single Prompt:
python chatgpt_tool.py "Write a haiku about Python." -
Use GPT-4:
python chatgpt_tool.py --model gpt-4