AI Development Lesson 7: LLMs & OpenAI API
Large Language Models (GPT-4, Claude, Gemini) are general-purpose AI. Via API, you can add AI capabilities to any app in minutes.
OpenAI API
# pip install openai
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY") # from openai.com
# Basic chat
response = client.chat.completions.create(
model="gpt-4o-mini", # affordable model
messages=[
{"role": "system", "content": "You are a helpful coding tutor."},
{"role": "user", "content": "Explain Python decorators simply."}
]
)
print(response.choices[0].message.content)
# Streaming (response appears word by word)
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role":"user","content":"Write a Python function"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
Structured Output
import json
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{
"role": "user",
"content": "Extract: name, email, phone from: 'John Smith, john@example.com, 555-1234'. Return JSON only."
}],
response_format={"type": "json_object"}
)
data = json.loads(response.choices[0].message.content)
print(data["name"]) # "John Smith"
Groq API (Free & Fast)
# Groq is FREE and 10x faster than OpenAI!
# pip install groq
from groq import Groq
client = Groq(api_key="YOUR_GROQ_API_KEY") # free at console.groq.com
response = client.chat.completions.create(
model="llama-3.1-70b-versatile",
messages=[{"role":"user","content":"Hello!"}]
)
print(response.choices[0].message.content)
🏋️ Practice Task
Build an AI code reviewer. Takes a Python function as input. Calls the API (use Groq for free). Returns: (1) bugs found, (2) performance suggestions, (3) improved version of the code. Build a simple CLI interface.
💡 Hint: System prompt: “You are a senior Python developer reviewing code. Respond with JSON: {bugs:[], suggestions:[], improved_code:””}”