Why Teach Your Python Scripts to "Think"?
Rules-based automation has a ceiling. You can write a script that files every email containing the word "invoice" — but what about "attached is the bill you asked for" or "payment due on Friday"? A rule misses it. A person doesn't.
That's the gap AI fills. You already know how to make Python do boring tasks on a schedule (if you've followed our guides on sending emails with Python or watching website prices, you know the drill). Now you can add the one missing piece: judgment.
Think of it this way:
- A rule is a vending machine: exact input, exact output, zero surprises.
- An AI call is a barista: "make me something with caffeine" — it understands intent, not just keywords.
In this guide you'll write two working scripts: a 15-line "hello world" AI call, and a file summarizer you can point at any text file. No machine-learning degree, no GPU, no math. Just requests — the same Python library you may already use for web scraping.
How AI APIs Work (One Minute Version)
AI models don't live on your computer. They live on a server run by an AI provider, and you talk to them through an API — a web address your script sends messages to.
The whole interaction is two pieces of text:
- Your script sends a JSON request containing the conversation and your question.
- The provider sends back a JSON response containing the AI's answer.
That's it. Here's the request your script will send (don't type this — the Python code in the next section builds it for you):
{
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Write a one-line welcome message for a beginner programmer."}
],
"max_tokens": 100
}
And here's the shape of the answer that comes back (shortened):
{
"choices": [
{
"message": {
"role": "assistant",
"content": "Welcome to programming — every expert was once a beginner!"
}
}
]
}
Your job in Python is simple: send the first JSON, then reach into the second one and pull out the text at choices[0].message.content. Every line of code below is just plumbing around those two steps.
What's an API key? A password that proves it's really you making the request (so the provider can bill you, or count your free usage). Keep it out of your code — we'll use an environment variable instead.
Get Your API Key
You need an account with an AI provider. A few beginner-friendly options:
| Provider | Cost to start | Notes |
|---|---|---|
| OpenAI | Free trial credit | The default choice; gpt-4o-mini is the cheap model |
| Gemini (Google) | Free tier, no card | Generous free quota for learning |
| Groq | Free tier | Very fast, OpenAI-compatible |
| Ollama | $0 forever | Runs a model on your computer — needs 8GB+ RAM |
The scripts in this guide use the OpenAI-compatible format, which is the industry standard: OpenAI, Groq, and dozens of smaller providers all accept the exact same JSON shape. If you pick a different provider, you change one line (the base URL) and nothing else.
After you sign up and get a key, store it where scripts can find it without touching your code:
export MY_API_KEY="your-api-key-here"
Use your real key on the right side. The variable only lives in this terminal session — close the terminal and it's gone, which is exactly what you want for a secret.
Your First AI Call in 15 Lines
Create first_ai_call.py:
import os
import requests
API_KEY = os.environ.get("MY_API_KEY", "your-api-key-here")
BASE_URL = os.environ.get("AI_BASE_URL", "https://api.openai.com/v1")
MODEL = os.environ.get("AI_MODEL", "gpt-4o-mini")
response = requests.post(
f"{BASE_URL}/chat/completions",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"model": MODEL,
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Write a one-line welcome message for a beginner programmer."},
],
"max_tokens": 100,
},
timeout=60,
)
response.raise_for_status()
data = response.json()
print(data["choices"][0]["message"]["content"])
Run it:
python3 first_ai_call.py
A real run from our test machine printed:
Welcome to coding—where every bug is just a hidden lesson in disguise!
What each line does:
os.environ.get(...)reads the key from the environment — never hard-code secrets in a script you might share.requests.post(...)sends the conversation to the provider's server.response.raise_for_status()throws an error if something went wrong, instead of failing silently.data["choices"][0]["message"]["content"]digs the answer out of the JSON — the same path you saw in the response shape above.
If it breaks (and first runs usually do — that's normal):
| Error | Meaning | Fix |
|---|---|---|
401 |
Wrong or missing API key | Check export MY_API_KEY="..." — did you paste your real key? |
429 |
Too many requests | You hit a rate limit. Wait a minute and try again. |
Connection error |
No internet, or wrong base URL | Check your Wi-Fi and AI_BASE_URL. |
Build Something Real: The File Summarizer
One AI call is neat. An AI call inside a script you already know how to write is where automation gets interesting. Let's build a tool that reads any text file and writes a five-point summary next to it.
Create summarize.py:
"""summarize.py — point it at any text file and get an AI summary.
Usage: python3 summarize.py <file.txt>
"""
import os
import sys
import requests
API_KEY = os.environ.get("MY_API_KEY", "your-api-key-here")
BASE_URL = os.environ.get("AI_BASE_URL", "https://api.openai.com/v1")
MODEL = os.environ.get("AI_MODEL", "gpt-4o-mini")
def ask_ai(prompt, max_tokens=500):
"""Send one message to the AI and return its reply as plain text."""
response = requests.post(
f"{BASE_URL}/chat/completions",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"model": MODEL,
"messages": [
{"role": "system", "content": "You are a helpful assistant. Reply with plain text only."},
{"role": "user", "content": prompt},
],
"max_tokens": max_tokens,
},
timeout=60,
)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"].strip()
def main():
if len(sys.argv) < 2:
print("Usage: python3 summarize.py <file.txt>")
sys.exit(1)
# 1. Read the file
with open(sys.argv[1], encoding="utf-8") as f:
text = f.read()
# 2. Ask the AI to summarize it
prompt = (
"Summarize the text below in 5 bullet points. "
"Start each bullet with a bold short phrase.\n\n" + text
)
summary = ask_ai(prompt)
# 3. Save the answer next to the original file
out_path = sys.argv[1] + ".summary.txt"
with open(out_path, "w", encoding="utf-8") as f:
f.write(summary + "\n")
print(f"Saved summary to {out_path}")
if __name__ == "__main__":
main()
Test it on a file of your own — meeting notes, a long article you saved, an old essay:
cat > /tmp/my-notes.txt <<'EOF'
Project Notes — Neighborhood Book Club Website (draft)
Meeting logistics: the club meets every Saturday morning at the local
library, community room 2. We currently have 12 members and the room
fits 20, so membership is open. Books are chosen by vote at the end of
each meeting; we read one book per month, discussed across two
Saturdays. Snacks and drinks are provided by rotating volunteers, one
per week. The website needs a page for the current book, a calendar
for meetings, and a simple member sign-up form. Domain budget: under
$20/year.
EOF
python3 summarize.py /tmp/my-notes.txt
The exact run above produced this on our test machine (real API, real output):
Saved summary to /tmp/my-notes.txt.summary.txt
- **Meeting logistics**: Club meets every Saturday morning at local library, community room 2; currently 12 members, room fits 20, so membership is open.
- **Book selection**: Books chosen by vote at each meeting's end; one book per month, discussed across two Saturdays.
- **Volunteer system**: Snacks and drinks provided by rotating volunteers, one per week.
- **Website needs**: Include a page for current book, a calendar for meetings, and a simple member sign-up form.
- **Budget constraint**: Domain budget is under $20/year.
This is the pattern, and it scales: the same ask_ai() function can summarize a news article, extract action items from meeting notes, or translate a README. You're no longer limited to tasks you can express as rules.
Three More Ideas to Steal
Now that you can call AI from Python, here's where this skill compounds with scripts you may already have:
- Sort your inbox by meaning, not keywords — an AI pass over each email's subject and first line can decide "receipt", "newsletter", or "needs a reply", then file it. Our guide to reading emails with Python fetches the messages; auto-organizing your inbox shows the filing part. AI is the upgrade that makes the filing smart.
- Price drops that write their own alerts — instead of "Price fell below $200", your price tracker can send "The keyboard you saved dropped to $189 — that's the lowest price in 6 months, and the listing says stock is low." Human judgment, automated. Send it through your Telegram bot and it lands on your phone.
- A daily digest that reads for you — our Python news digest scrapes headlines on a schedule; an AI step can rank them by relevance to you and write a two-sentence summary of each. Wake up to a shortlist, not a firehose.
One skill worth pairing with all of this: writing better prompts. Your Python code is only as good as the instructions inside ask_ai(). Our AI prompt templates are copy-paste recipes for exactly that.
How Much Does This Cost?
Less than you'd guess:
- Free tiers: Gemini and Groq both give you enough free usage to learn and run small daily automations without ever entering a card. Ollama is free forever if your computer can run it.
- Paid APIs: a typical short AI call (like the summarizer above) costs a fraction of a cent. OpenAI's
gpt-4o-miniis priced so that summarizing a few dozen documents a day costs cents per month. - The expensive mistake is forgetting: a script stuck in a loop calling the API every second will burn through your quota. Set
max_tokens(as above), and put long-running scripts on a timer with a tool like cron — our cron guide shows how to schedule anything in Linux.
Start on a free tier. Upgrade only when a real automation earns it.
Next Steps
- Make your scripts do the reading for you — read emails with Python and pair it with the AI pass from this guide
- Take AI automation to your daily routine — the Python news digest is the most satisfying 20-minute project we've published
- Write better prompts so the AI side of your scripts gets sharper — 10 AI prompt templates that actually work
You now have the missing ingredient that turns a collection of Python scripts into something that feels like a junior assistant. The first Saved summary to ... message is a genuine "wow" moment — go get yours.
All code in this article was tested and runs successfully on Python 3.8.10 (Ubuntu 20.04) with requests 2.32.4 — verified August 2026 against a real OpenAI-compatible chat API, with the sample inputs and outputs shown above produced by actual runs.