Python for AI Fundamentals
Learn Python programming essentials for AI development. Build your first AI-powered applications with hands-on coding experience.
Core Skills
Fundamental abilities you'll develop
- Create your first AI-powered Python script
Learning Goals
What you'll understand and learn
- Understand Python basics relevant to AI development
- Learn to work with AI libraries (requests, openai, pandas)
Practical Skills
Hands-on techniques and methods
- Handle API responses and data processing effectively
- Set up a proper development environment for AI projects
Intermediate Content Notice
This lesson builds upon foundational AI concepts. Basic understanding of AI principles and terminology is recommended for optimal learning.
Python for AI Fundamentals
Learn Python programming essentials for AI development. Build your first AI-powered applications with hands-on coding experience.
Tier: Intermediate
Difficulty: Intermediate
Overview
Learn Python programming essentials for AI development. Build your first AI-powered applications with hands-on coding experience.
Learning Objectives
- Understand Python basics relevant to AI development
- Learn to work with AI libraries (requests, openai, pandas)
- Create your first AI-powered Python script
- Handle API responses and data processing effectively
- Set up a proper development environment for AI projects
Prerequisites
- Basic understanding of AI concepts from beginner tier
- Familiarity with using ChatGPT or similar AI tools
- Computer with internet access for coding practice
Introduction to Python for AI
Why Python for AI Development?
Python has become the go-to language for AI development, and for good reason. Let's explore why:
Python's AI Advantages:
- Simple Syntax: Easy to read and write, perfect for beginners
- Rich Libraries: Thousands of AI-focused libraries available
- Community Support: Massive community with tutorials and help
- Industry Standard: Used by Google, OpenAI, and major AI companies
The AI Development Ecosystem
When building AI applications, you'll work with several key components:
Core Libraries:
openai- OpenAI API integrationrequests- HTTP requestspandas- Data manipulationjson- JSON data handling
Development Tools:
pip- Package installervenv- Virtual environmentsVS Code- Code editorTerminal- Command line
What You'll Build Today
By the end of this lesson, you'll create a Python script that:
- ā Connects to the OpenAI API
- ā Processes user input
- ā Generates AI responses
- ā Handles errors gracefully
Python Essentials for AI
Essential Python Concepts
Let's cover the Python fundamentals you'll need for AI development:
1. Variables and Data Types
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Visual Architecture Overview
Interactive visual representation would be displayed here
For Implementation Details:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation: ```python
Variables store data
api_key = "your-api-key-here"
model_name = "gpt-4o-mini"
temperature = 0.7
max_tokens = 150
Common data types for AI
user_message = "Hello, AI!"
String
token_count = 100
Integer
is_streaming = True
Boolean
response_data = {}
Dictionary
### 2. Functions - Your AI Building Blocks
```python
def generate_response(prompt, temperature=0.7):
"""Generate AI response from a prompt"""
try:
# Your AI code here
response = call_openai_api(prompt, temperature)
return response
except Exception as e:
return f"Error: {str(e)}"
# Using the function
result = generate_response("Explain Python in simple terms")
print(result)
3. Error Handling - Essential for AI Apps
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation: ```python
try:
Code that might fail
response = openai.ChatCompletion.create(...)
print(response.choices[0].message.content)
except openai.AuthenticationError:
print("ā Invalid API key")
except openai.RateLimitError:
print("ā³ Rate limit exceeded, please wait")
except Exception as e:
print(f"šØ Unexpected error: {e}")
### Pro Tips for AI Development
- Use descriptive variable names: `user_prompt` instead of `p`
- Add comments: Explain complex AI logic
- Handle errors: AI APIs can fail, be prepared
- Test frequently: Small changes, frequent testing
---
## Working with AI Libraries
### Essential Libraries for AI Development
Let's learn how to work with the key Python libraries for AI projects:
### Installing Libraries with pip
```bash
# Install essential AI libraries
pip install openai requests pandas python-dotenv
# Create a virtual environment (recommended)
python -m venv ai_env
source ai_env/bin/activate
# On Windows: ai_env\Scripts\activate
Importing and Using Libraries
import openai
import requests
import pandas as pd
import json
from dotenv import load_dotenv
import os
# Load environment variables
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
Making HTTP Requests
import requests
# Example: Making a request to any API
headers = {
'Authorization': 'Bearer your-api-key',
'Content-Type': 'application/json'
}
data = {
'model': 'gpt-4o-mini',
'messages': [{'role': 'user', 'content': 'Hello!'}]
}
response = requests.post(
'https://api.openai.com/v1/chat/completions',
headers=headers,
json=data
)
if response.status_code == 200:
result = response.json()
print(result['choices'][0]['message']['content'])
else:
print(f"Error: {response.status_code}")
Working with Data (Pandas)
import pandas as pd
# Create a DataFrame to store AI responses
data = {
'prompt': ['Explain AI', 'Write a poem', 'Solve math problem'],
'response': ['AI is...', 'Roses are red...', '2+2=4'],
'tokens': [50, 30, 10]
}
df = pd.DataFrame(data)
print(df.head())
# Save to CSV for analysis
df.to_csv('ai_responses.csv', index=False)
Common Installation Issues
- Permission errors: Use
pip install --user - Version conflicts: Use virtual environments
- PATH issues: Restart terminal after installation
- Python version: Use Python 3.8+ for AI libraries
Making Your First API Call
Connecting to AI APIs
Let's create your first working AI application by connecting to the OpenAI API:
Setting Up Authentication
First, create a .env file in your project directory:
# .env file
OPENAI_API_KEY=your-actual-api-key-here
Complete Working Example
# ai_assistant.py
import openai
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
def ask_ai(question, temperature=0.7):
"""Ask AI a question and get a response"""
try:
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": question}
],
temperature=temperature,
max_tokens=150
)
return response.choices[0].message.content
except openai.AuthenticationError:
return "ā Authentication failed. Check your API key."
except openai.RateLimitError:
return "ā³ Rate limit exceeded. Please wait a moment."
except Exception as e:
return f"šØ Error: {str(e)}"
# Test the function
if __name__ == "__main__":
user_question = input("Ask me anything: ")
answer = ask_ai(user_question)
print(f"\nAI: {answer}")
Enhanced Version with Features
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation: ```python
def enhanced_ai_chat():
"""Enhanced AI chat with conversation history"""
conversation = [
{"role": "system", "content": "You are a helpful Python programming assistant."}
]
print("š¤ AI Python Assistant (type 'quit' to exit)")
while True:
user_input = input("\nYou: ")
if user_input.lower() == 'quit':
print("Goodbye! š")
break
Add user message to conversation
conversation.append({"role": "user", "content": user_input})
try:
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=conversation,
temperature=0.7,
max_tokens=200
)
ai_response = response.choices[0].message.content
conversation.append({"role": "assistant", "content": ai_response})
print(f"š¤ AI: {ai_response}")
except Exception as e:
print(f"šØ Error: {str(e)}")
Run the enhanced chat
enhanced_ai_chat()
### Try It Yourself!
Copy the code above and:
1. Get your OpenAI API key from [OpenAI Platform](https://platform.openai.com/api-keys)
2. Create a `.env` file with your API key
3. Run the script and start chatting!
4. Try different questions and see how the AI responds
---
## Mastering the OpenAI Library
### Deep Dive into OpenAI Python Library
Now let's explore the powerful features of the OpenAI Python library:
### Understanding Model Parameters
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation: ```python
def create_ai_response(prompt, creativity="balanced"):
"""Create AI response with different creativity levels"""
# Temperature settings for different creativity levels
temperature_settings = {
"conservative": 0.1,
# More focused, deterministic
"balanced": 0.7,
# Good balance
"creative": 1.0
# More random, creative
}
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
temperature=temperature_settings[creativity],
max_tokens=200,
top_p=1.0,
# Controls diversity
presence_penalty=0.0,
# Reduces repetition
frequency_penalty=0.0
# Reduces repetition
)
return response.choices[0].message.content
# Test different creativity levels
prompt = "Write a short story about a robot learning to paint"
print("Conservative:", create_ai_response(prompt, "conservative"))
print("Creative:", create_ai_response(prompt, "creative"))
System Messages for Better Control
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation: ```python
def specialized_ai_assistant(user_question, assistant_type="general"):
"""Create specialized AI assistants with system messages"""
system_messages = {
"python_tutor": "You are a Python programming tutor. Explain concepts clearly with examples.",
"code_reviewer": "You are a code reviewer. Provide constructive feedback and suggestions.",
"creative_writer": "You are a creative writing assistant. Help with storytelling and ideas.",
"general": "You are a helpful and knowledgeable assistant."
}
messages = [
{"role": "system", "content": system_messages[assistant_type]},
{"role": "user", "content": user_question}
]
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=messages,
temperature=0.7
)
return response.choices[0].message.content
Examples of specialized assistants
print("Python Tutor:", specialized_ai_assistant("How do I use loops?quot;, "python_tutor"))
print("Code Reviewer:", specialized_ai_assistant("Review this code: print('hello')", "code_reviewer"))
### Streaming Responses
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation: ```python
def stream_ai_response(prompt):
"""Stream AI response word by word"""
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
stream=True
# Enable streaming
)
print("AI: ", end="")
for chunk in response:
if chunk.choices[0].delta.get("content"):
print(chunk.choices[0].delta.content, end="")
print()
# New line at the end
# Try streaming
stream_ai_response("Explain machine learning in simple terms")
Token Usage Tracking
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation: ```python
def track_token_usage(prompt):
"""Track API usage and costs"""
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
temperature=0.7
)
Extract usage information
usage = response.usage
content = response.choices[0].message.content
print(f"Response: {content}")
print(f"\nš Usage Stats:")
print(f"Prompt tokens: {usage.prompt_tokens}")
print(f"Response tokens: {usage.completion_tokens}")
print(f"Total tokens: {usage.total_tokens}")
Approximate cost calculation (prices may vary)
cost_per_1k_tokens = 0.001
Example rate
estimated_cost = (usage.total_tokens / 1000) * cost_per_1k_tokens
print(f"Estimated cost: {estimated_cost:.4f}")
Track usage
track_token_usage("Explain quantum computing")
### Best Practices Checklist
- ā
Use environment variables for API keys
- ā
Implement proper error handling
- ā
Use appropriate temperature settings
- ā
Track token usage to manage costs
- ā
Use system messages for better control
- ā
Test with small examples first
---
## Building Your First AI Application
### Project: Personal AI Writing Assistant
Let's build a complete AI application that demonstrates everything you've learned:
### Project Overview
We'll create a writing assistant that can:
- ā
Help brainstorm ideas
- ā
Improve existing text
- ā
Check grammar and style
- ā
Save conversation history
- ā
Track usage statistics
### Project Structure
writing_assistant/
āāā .env
API key
āāā main.py
Main application
āāā ai_helper.py
AI functions
āāā utils.py
Utility functions
āāā history.json
Conversation history
### Complete Implementation
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation:
### Conceptual Process
*Visual flowchart/flow diagram would be displayed here*
Technical Implementation: ```python
# ai_helper.py
import openai
import os
from dotenv import load_dotenv
import json
from datetime import datetime
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
class WritingAssistant:
def __init__(self):
self.history = []
self.load_history()
def brainstorm(self, topic):
"""Generate creative ideas for a topic"""
prompt = f"Generate 5 creative ideas for writing about: {topic}"
return self._get_ai_response(prompt, "creative")
def improve_text(self, text):
"""Improve existing text"""
prompt = f"Improve this text while maintaining the original meaning:\n\n{text}"
return self._get_ai_response(prompt, "balanced")
def grammar_check(self, text):
"""Check grammar and style"""
prompt = f"Check grammar and style, provide corrections:\n\n{text}"
return self._get_ai_response(prompt, "conservative")
def _get_ai_response(self, prompt, creativity="balanced"):
"""Get AI response with error handling"""
temperature_map = {
"conservative": 0.2,
"balanced": 0.7,
"creative": 1.0
}
try:
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a professional writing assistant."},
{"role": "user", "content": prompt}
],
temperature=temperature_map[creativity],
max_tokens=300
)
result = response.choices[0].message.content
# Save to history
self.history.append({
"timestamp": datetime.now().isoformat(),
"prompt": prompt,
"response": result,
"tokens": response.usage.total_tokens
})
self.save_history()
return result
except Exception as e:
return f"Error: {str(e)}"
def save_history(self):
"""Save conversation history"""
with open('history.json', 'w') as f:
json.dump(self.history, f, indent=2)
def load_history(self):
"""Load conversation history"""
try:
with open('history.json', 'r') as f:
self.history = json.load(f)
except FileNotFoundError:
self.history = []
def get_stats(self):
"""Get usage statistics"""
total_requests = len(self.history)
total_tokens = sum(item['tokens'] for item in self.history)
return {
"total_requests": total_requests,
"total_tokens": total_tokens,
"estimated_cost": total_tokens * 0.001 / 1000
}
Main Application
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation:
Conceptual Process
Visual flowchart/flow diagram would be displayed here
Technical Implementation: ```python
main.py
from ai_helper import WritingAssistant
def main():
assistant = WritingAssistant()
print("šļø Personal AI Writing Assistant")
print("Commands: brainstorm, improve, grammar, stats, quit")
while True:
print("\n" + "="*50)
command = input("Choose command: ").lower()
if command == 'quit':
print("Goodbye! š")
break
elif command == 'brainstorm':
topic = input("Enter topic: ")
result = assistant.brainstorm(topic)
print(f"\nš” Ideas:\n{result}")
elif command == 'improve':
text = input("Enter text to improve: ")
result = assistant.improve_text(text)
print(f"\n⨠Improved version:\n{result}")
elif command == 'grammar':
text = input("Enter text to check: ")
result = assistant.grammar_check(text)
print(f"\nā
Grammar check:\n{result}")
elif command == 'stats':
stats = assistant.get_stats()
print(f"\nš Usage Statistics:")
print(f"Total requests: {stats['total_requests']}")
print(f"Total tokens: {stats['total_tokens']}")
print(f"Estimated cost: {stats['estimated_cost']:.4f}")
else:
print("Unknown command. Try: brainstorm, improve, grammar, stats, quit")
if name == "main":
main()
### Your Mission
Set up and run this writing assistant:
1. Create the project directory and files
2. Add your OpenAI API key to the .env file
3. Install required libraries: `pip install openai python-dotenv`
4. Run the application: `python main.py`
5. Test all features and see your usage stats!
### Enhancement Ideas
Once you have the basic version working, try adding:
- š± Web interface using Flask or Streamlit
- š¾ Database storage for better history management
- šØ Different writing styles (formal, casual, academic)
- š Better analytics and usage tracking
- š Conversation memory for context
Continue Your AI Journey
Build on your intermediate knowledge with more advanced AI concepts and techniques.