# Write your code here
import os
from openai import OpenAI
# 1. Initialize the client.
# It automatically looks for an environment variable named 'OPENAI_API_KEY'
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY")
)
# 2. Call the Chat Completions API
response = client.chat.completions.create(
model="gpt-4o", # You can also use "gpt-3.5-turbo" or "gpt-4"
messages=[
{"role": "system", "content": "You are a helpful coding assistant."},
{"role": "user", "content": "Write a quick Python function to reverse a string."}
],
temperature=0.7 # Controls randomness (0.0 is deterministic, 1.0 is creative)
)
# 3. Print the text response from the AI
print(response.choices[0].message.content)
Use code with caution.Interactive Console ChatbotIf you want to create a continuous, loop-based chatbot in your terminal that remembers previous messages, use this framework:pythonimport os
from openai import OpenAI
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
# Initialize conversation history with a persona
messages = [
{"role": "system", "content": "You are a witty, helpful AI chatbot."}
]
print("AI Chatbot Initialized! Type 'quit' or 'exit' to stop.\n")
while True:
user_input = input("me: ")
# Check for exit commands
if user_input.lower() in ['quit', 'exit']:
print("Goodbye!")
break
if not user_input.strip():
continue
# Append user message to history
messages.append({"role": "user", "content": user_input})
try:
# Request completion with full history
response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
# Extract and print reply
ai_reply = response.choices[0].message.content
print(f"\nAI: {ai_reply}\n")
# Append AI reply to history so it retains context
messages.append({"role": "assistant", "content": ai_reply})
except Exception as e:
print(f"An error occurred: {e}")
Use code with caution.