How to automate tasks with AI in python
Quick answer
Use the
OpenAI Python SDK to automate tasks by sending prompts to AI models like gpt-4o. Write Python scripts that call client.chat.completions.create() with task instructions, then process the AI's response to perform automation.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official openai Python package and set your API key as an environment variable for secure access.
pip install openai>=1.0 Step by step
This example shows how to automate a simple task: generating a daily summary email draft using AI. The script sends a prompt to gpt-4o and prints the AI-generated text.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
prompt = (
"You are an assistant that writes a professional daily summary email. "
"Summarize the key points from today's meetings and tasks."
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
print("Generated email draft:\n", response.choices[0].message.content) output
Generated email draft: Dear Team, Here is the summary of today's meetings and tasks: - Discussed project milestones and deadlines. - Assigned action items to team members. - Reviewed client feedback and planned next steps. Best regards, Your AI Assistant
Common variations
- Use asynchronous calls with
asynciofor non-blocking automation. - Switch models to
gpt-4o-minifor faster, cheaper responses. - Stream responses for real-time output during long tasks.
import os
import asyncio
from openai import OpenAI
async def async_automation():
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
prompt = "Generate a to-do list for tomorrow based on today's tasks."
response = await client.chat.completions.acreate(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}]
)
print("Async to-do list:\n", response.choices[0].message.content)
asyncio.run(async_automation()) output
Async to-do list: - Follow up on project milestones - Prepare presentation slides - Schedule client meeting - Review code submissions
Troubleshooting
- If you get authentication errors, verify your
OPENAI_API_KEYenvironment variable is set correctly. - For rate limit errors, reduce request frequency or switch to a smaller model.
- If responses are incomplete, increase
max_tokensin the API call.
Key Takeaways
- Use the OpenAI Python SDK with environment-stored API keys for secure automation.
- Write clear prompts to instruct AI models for specific task automation.
- Leverage async and streaming features for efficient, real-time automation workflows.