Basic Python AI API Example
Here is a complete, working Python example that calls the OpenAI API securely. This is the pattern used in real AI applications.
15 min•By Priygop Team•Updated 2026
Complete Working Example
Complete Working Example
# Complete example: call the OpenAI API from Python
# Install: pip install openai
# Set environment variable: set OPENAI_API_KEY=your-key-here
import os
from openai import OpenAI
def ask_ai(question, system_instruction=None, model="gpt-4o-mini"):
"""
Send a question to the OpenAI API and return the AI's response.
Parameters:
- question: the user's question or prompt
- system_instruction: how the AI should behave
- model: which OpenAI model to use
Returns:
- str: the AI's text response, or an error message
"""
# Load API key from environment variable (NEVER hardcode)
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
return "Error: OPENAI_API_KEY environment variable is not set."
# Create the OpenAI client
client = OpenAI(api_key=api_key)
# Build the messages list
messages = []
if system_instruction:
messages.append({
"role": "system",
"content": system_instruction
})
messages.append({
"role": "user",
"content": question
})
# Send the request to the API
response = client.chat.completions.create(
model=model,
messages=messages,
max_tokens=300,
temperature=0.7
)
# Extract and return the text response
return response.choices[0].message.content
# Example usage
if __name__ == "__main__":
system = "You are a helpful tutor for beginners learning about Generative AI. Explain concepts simply and clearly."
questions = [
"What is a token in the context of AI?",
"What is the difference between training and inference?",
]
for question in questions:
print(f"Question: {question}")
answer = ask_ai(question, system_instruction=system)
print(f"Answer: {answer}")
print()Tip
Tip
gpt-4o-mini is the best starting model for beginners. It is much cheaper than gpt-4o (about 15 times lower cost per token) and handles most learning tasks very well. Switch to gpt-4o only when you need significantly better performance on complex tasks.
Diagram
Loading diagram…
Deep Learning ⊂ Machine Learning ⊂ Artificial Intelligence