Python Fundamentals for AI Engineering
Master Python essentials needed for AI Engineering. Learn syntax, data structures, APIs, and libraries used in AI development.
Topics Covered:
Prerequisites:
- Basic programming concepts (any language)
Overview
Python is the most important language for AI Engineering. While you don't need to be a Python expert, understanding core concepts is essential. This tutorial covers Python fundamentals specifically relevant to AI Engineering, including working with APIs, handling data, and using AI libraries.
Python Basics for AI Work
Python's simplicity makes it perfect for AI Engineering. Here are the essentials you need. Variables and Types: • Python is dynamically typed (no type declarations needed) • Common types: str, int, float, bool, list, dict • Use type hints for better code (optional but recommended) Functions: • Define with def keyword • Can return multiple values • Support default arguments and keyword arguments Working with Data: • Lists: ordered, mutable collections • Dictionaries: key-value pairs (very common in AI work) • Tuples: immutable sequences • Sets: unique collections
# Variables and types
name = "Alice" # string
age = 30 # integer
price = 19.99 # float
is_active = True # boolean
# Lists
items = ["apple", "banana", "orange"]
items.append("grape") # Add item
# Dictionaries (very common in AI APIs)
user = {
"name": "Alice",
"age": 30,
"email": "alice@example.com"
}
print(user["name"]) # Access value
# Functions
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
result = greet("Alice") # "Hello, Alice!"
result = greet("Bob", "Hi") # "Hi, Bob!"These are the Python basics you'll use constantly in AI Engineering. Dictionaries are especially important as API responses are often JSON (which maps to Python dictionaries).
Working with APIs
AI Engineering is all about working with APIs. Understanding how to make API calls is crucial. HTTP Requests: • Use requests library for HTTP calls • GET: retrieve data • POST: send data (most AI APIs use this) • Headers: authentication and content type • JSON: most APIs use JSON format API Patterns: • Authentication (API keys, tokens) • Error handling (network issues, API errors) • Rate limiting (API usage limits) • Response parsing (extracting data from responses)
import requests
import os
# Set API key (use environment variables in production!)
api_key = os.getenv("OPENAI_API_KEY")
# Making an API call
def call_openai_api(prompt):
url = "https://api.openai.com/v1/chat/completions"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
data = {
"model": "gpt-3.5-turbo",
"messages": [
{"role": "user", "content": prompt}
]
}
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status() # Raises error for bad status codes
return response.json()
except requests.exceptions.RequestException as e:
print(f"API Error: {e}")
return None
# Usage
result = call_openai_api("Hello, AI!")
if result:
message = result["choices"][0]["message"]["content"]
print(message)This is the pattern you'll use for all AI API calls. Notice error handling, JSON formatting, and response parsing. This is core AI Engineering work.
Essential Python Libraries
Certain Python libraries are essential for AI Engineering. requests: • Making HTTP API calls • Most important library for AI Engineers json: • Parsing JSON responses • Converting Python objects to JSON os and dotenv: • Managing environment variables • Keeping API keys secure pandas (optional but useful): • Data manipulation • Working with datasets • Data analysis numpy (for advanced work): • Numerical computing • Working with arrays
# Using requests library
import requests
response = requests.get("https://api.example.com/data")
data = response.json()
# Using json library
import json
# Convert Python dict to JSON string
data = {"name": "Alice", "age": 30}
json_string = json.dumps(data)
# Parse JSON string to Python dict
parsed = json.loads(json_string)
# Using environment variables
import os
from dotenv import load_dotenv
load_dotenv() # Load .env file
api_key = os.getenv("OPENAI_API_KEY") # Secure way to store keys
# Using pandas for data
import pandas as pd
df = pd.read_csv("data.csv")
filtered = df[df["age"] > 25] # Filter dataThese libraries form the foundation of AI Engineering work. Start with requests and json - you'll use them constantly.
Error Handling and Best Practices
Production AI applications need robust error handling. Common Errors: • Network errors (API unavailable) • API errors (invalid requests, rate limits) • Data errors (malformed responses) • Authentication errors (invalid keys) Best Practices: • Always handle exceptions • Use try/except blocks • Log errors for debugging • Provide user-friendly error messages • Implement retries for transient errors
import requests
import time
from typing import Optional
def call_api_with_retry(url: str, max_retries: int = 3) -> Optional[dict]:
"""Call API with automatic retry on failure."""
for attempt in range(max_retries):
try:
response = requests.post(url, timeout=10)
response.raise_for_status()
return response.json()
except requests.exceptions.Timeout:
print(f"Timeout on attempt {attempt + 1}")
if attempt < max_retries - 1:
time.sleep(2 ** attempt) # Exponential backoff
except requests.exceptions.HTTPError as e:
if e.response.status_code == 429: # Rate limit
print("Rate limited, waiting...")
time.sleep(60)
continue
else:
print(f"HTTP Error: {e}")
return None
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
return None
return None # All retries failed
# Usage
result = call_api_with_retry("https://api.example.com/endpoint")
if result:
print("Success!")
else:
print("Failed after retries")Robust error handling is essential for production AI applications. This pattern handles network issues, rate limits, and other common problems.
Conclusion
Python is the foundation of AI Engineering. Focus on mastering API calls, working with JSON data, and error handling. You don't need to be a Python expert - just comfortable enough to integrate AI APIs and build applications. Practice by building small projects that use AI APIs. The more you code, the more comfortable you'll become.