# Automate Tasks with ChatGPT: A Practical Guide
Stop wasting hours on repetitive tasks that a language model could handle in seconds. In this guide, I’ll show you how to integrate ChatGPT into your development workflow using its API—not the web interface, but actual code that runs autonomously.
You’ll learn to build scripts that handle text processing, generate code, summarize logs, and automate documentation. No hype, just working examples you can copy-paste into your projects.
## Prerequisites
Before writing any code, you need:
1. **OpenAI API key** – Get it from [platform.openai.com](https://platform.openai.com). You’ll need to add billing—API calls aren’t free, but they’re cheap for personal automation.
2. **Python 3.10+** – The examples below use Python, but the API works with any HTTP client.
3. **openai library** – Install it:
“`bash
pip install openai python-dotenv
“`
Create a `.env` file in your project root:
“`
OPENAI_API_KEY=sk-your-key-here
“`
## Your First Automated Task
Here’s a script that takes a messy Git commit history and summarizes it into readable changelog entries. This is the kind of task I actually run weekly:
“`python
from openai import OpenAI
import os
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(api_key=os.getenv(“OPENAI_API_KEY”))
def summarize_commits(commit_messages: list[str]) -> str:
“””Turn a list of git commit messages into a clean changelog.”””
commits_text = “\n”.join(f”- {msg}” for msg in commit_messages)
response = client.chat.completions.create(
model=”gpt-4o-mini”, # Cheap and fast for this task
messages=[
{
“role”: “system”,
“content”: “You are a technical writer. Convert these git commits into a clean, user-facing changelog. Group by feature, bug fix, or refactor. Use past tense.”
},
{
“role”: “user”,
“content”: f”Commits:\n{commits_text}”
}
],
temperature=0.3 # Low randomness for consistent output
)
return response.choices[0].message.content
# Example usage
commits = [
“fix: null pointer in user auth”,
“feat: add dark mode toggle”,
“refactor: simplify database queries”,
“docs: update API endpoint examples”,
“fix: memory leak in websocket handler”
]
changelog = summarize_commits(commits)
print(changelog)
“`
Run this and you’ll get output like:
“`
## Features
– Added dark mode toggle
## Bug Fixes
– Fixed null pointer in user authentication
– Fixed memory leak in websocket handler
## Refactoring
– Simplified database queries
## Documentation
– Updated API endpoint examples
“`
This costs roughly $0.002 per run. That’s less than a cent.
## Handling API Responses Properly
The previous example works, but production scripts need error handling. The API can fail—rate limits, network issues, invalid keys. Here’s a robust wrapper:
“`python
from openai import OpenAI, RateLimitError, APIConnectionError
import time
def chat_with_retry(prompt: str, max_retries: int = 3, delay: float = 2.0) -> str:
“””Call the API with exponential backoff on failure.”””
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model=”gpt-4o-mini”,
messages=[{“role”: “user”, “content”: prompt}]
)
return response.choices[0].message.content
except RateLimitError:
print(f”Rate limited. Waiting {delay}s before retry…”)
time.sleep(delay)
delay *= 2 # Exponential backoff
except APIConnectionError as e:
print(f”Connection error: {e}”)
if attempt == max_retries – 1:
raise
time.sleep(delay)
raise Exception(“Max retries exceeded”)
“`
This handles the two most common failures. Add your own logging or alerting here if needed.
## Automating Code Reviews
Here’s a more complex example—automating code review comments. This scans a diff and outputs actionable feedback:
“`python
def review_code(diff: str) -> dict:
“””Analyze a code diff and return structured review comments.”””
prompt = f”””Analyze this git diff and return a JSON object with:
– “severity”: “critical”, “major”, or “minor”
– “issue”: brief description of the problem
– “suggestion”: how to fix it
Only flag actual bugs, security issues, or significant code smells.
Ignore style issues.
Diff:
{diff}
Return ONLY valid JSON, no other text.”””
response = client.chat.completions.create(
model=”gpt-4o”,
messages=[{“role”: “user”, “content”: prompt}],
temperature=0.2,
response_format={“type”: “json_object”}
)
import json
return json.loads(response.choices[0].message.content)
# Example diff
sample_diff = “””@@ -12,7 +12,7 @@ def process_user_data(user):
– query = f”SELECT * FROM users WHERE id = ”
+ query = f”SELECT * FROM users WHERE id = ” # SQL injection risk
cursor.execute(query)”””
review = review_code(sample_diff)
print(review)
“`
The `response_format={“type”: “json_object”}` parameter (available in recent API versions) forces valid JSON output—no more parsing “Here is the JSON:” wrapper text.
## Building Reusable Workflows
For tasks you run repeatedly, create a modular structure:
“`python
# gpt_tasks.py
from openai import OpenAI
from abc import ABC, abstractmethod
class GPTTask(ABC):
def __init__(self, model: str = “gpt-4o-mini”):
self.client = OpenClient()
self.model = model
@abstractmethod
def build_prompt(self, input_data) -> list[dict]:
pass
def run(self, input_data) -> str:
messages = self.build_prompt(input_data)
response = self.client.chat.completions.create(
model=self.model,
messages=messages
)
return response.choices[0].message.content
class SummarizeLogs(GPTTask):
def build_prompt(self, logs: str) -> list[dict]:
return [
{“role”: “system”, “content”: “Extract errors and warnings from logs. Group by type.”},
{“role”: “user”, “content”: logs}
]
class ExplainError(GPTTask):
def build_prompt(self, error: str) -> list[dict]:
return [
{“role”: “system”, “content”: “Explain this error in plain English. Suggest likely causes.”},
{“role”: “user”, “content”: error}
]
# Usage
logs_task = SummarizeLogs(model=”gpt-4o-mini”)
summary = logs_task.run(open(“app.log”).read())
“`
This pattern lets you swap models, add logging, or integrate with other tools without rewriting the API calls.
## What the API Can’t Do
Be realistic about limitations:
– **Latency** – API calls take 1-3 seconds. Not suitable for real-time user interfaces.
– **Cost at scale** – Processing millions of tokens adds up. Monitor your usage at platform.openai.com.
– **Hallucinations** – The model can confidently output wrong facts. Always validate critical outputs.
– **No memory between calls** – Each API call is stateless. For conversation history, you must pass the full context every time.
– **Rate limits** – Free tier has strict limits. Paid tiers still have caps (500 RPM for pay-as-you-go).
## Key Takeaways
– The ChatGPT API costs roughly $0.001-0.01 per task—cheap for automation, expensive at scale
– Use `gpt-4o-mini` for simple tasks, `gpt-4o` for complex reasoning
– Always implement retry logic with exponential backoff
– Use `response_format={“type”: “json_object”}` for structured outputs
– Keep prompts in system messages for consistent behavior across calls
## Next Steps
1. **Pick one repetitive task** from your current workload—a report, a summary, a code transformation
2. **Write a script** using the patterns above. Start with the simple version, add error handling later
3. **Set up usage alerts** in your OpenAI dashboard so you don’t get surprised by costs
4. **Consider the CLI** – If you prefer shell commands, check out the `openai` CLI tool: `openai api chat.completions.create -m gpt-4o-mini`
The goal isn’t to automate everything—it’s to offload the tasks that eat your time but don’t need your creativity. Start small, measure the time you save, and expand from there.



