Sythra

Article

Talk to an AI from Python in about 20 lines

Send a prompt to an AI model from Python and print the reply — a short, beginner-friendly walkthrough with almost no setup drama.

vaibhavkothari· Jul 24, 2026· 4 min read
ShareXLinkedIn
Talk to an AI from Python in about 20 lines cover

You do not need a big “AI engineering” course to try this.

In this article you will write a tiny Python program that:

  1. Sends a short question to an AI modelThe specific AI brain you call (for example gpt-4o-mini)
  2. Gets a text answer back
  3. Prints it in your terminal

We keep the language simple. If a word is new, we explain it in one line.

What is an API? (10-second version)

An APIA way for your program to talk to another service on the internet is a way for your program to talk to another service on the internet.

You send a message (your promptThe text instruction or question you send to the AI).
The service sends a message back (the model’s reply).

What you need

  1. Python 3
  2. An API keyA secret password that proves your program is allowed to use the service from a provider that lets you call a chat model
    (OpenAI is common; other hosts work the same idea)
  3. The openai Python package

Install the package with pipPython’s package installer — used to download libraries:

pip install openai

Keep your secret key safe

Your API key is like a password. Do not paste it into GitHub.

Store it as an environment variableA setting your terminal shares with programs — good for secrets. On Windows PowerShell (current window only):

$env:OPENAI_API_KEY = "paste-your-key-here"

On macOS / Linux:

export OPENAI_API_KEY="paste-your-key-here"

The whole program (read it once)

Save as ask_ai.py:

import os
from openai import OpenAI

# 1) Create a client (reads OPENAI_API_KEY from the environment)
client = OpenAI()

# 2) Your question
question = "Explain a Python list in one short paragraph for a beginner."

# 3) Call the model
response = client.chat.completions.create(
    model="gpt-4o-mini",  # a small, cheap chat model — change if your account uses another name
    messages=[
        {
            "role": "system",
            "content": "You explain coding simply. No jargon unless you define it.",
        },
        {
            "role": "user",
            "content": question,
        },
    ],
)

# 4) Pull out the text and print it
answer = response.choices[0].message.content
print(answer)

Run:

python ask_ai.py

You should see a short explanation in plain English.

What each part means

OpenAI()

Builds a clientHelper object that knows how to send API requests for you that knows how to send requests. It looks for OPENAI_API_KEY automatically. The call below is a chat completionAPI request that asks a chat model for a reply.

messages

Chat models work like a short conversation:

  • systemInstructions that set how the AI should behave — rules for how the AI should behave
  • userThe message that holds your actual question — your actual question

You can add more user/assistant turns later. For day one, two messages is enough.

response.choices[0].message.content

The service can return more than one “choice.” We take the first one and read its text.

Make it interactive (still short)

Ask from the keyboard instead of a fixed string — inputBuilt-in command that waits for you to type something pauses for your question:

import os
from openai import OpenAI

client = OpenAI()

question = input("Ask the AI something: ").strip()
if not question:
    print("You typed nothing — exiting.")
    raise SystemExit

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "Reply in clear, simple English."},
        {"role": "user", "content": question},
    ],
)

print("\n--- AI ---")
print(response.choices[0].message.content)

Tiny upgrades you can try

1. Shorter answers

Add max_tokensA cap on how long the reply can be:

max_tokens=120,

inside create(...) so replies stay short.

2. More focused help

Change the system line to:

"You are a patient Python tutor. Use short sentences and one example."

3. Save the answer to a file

from pathlib import Path

Path("answer.txt").write_text(answer or "", encoding="utf-8")
print("Saved to answer.txt")

If something goes wrong

Message / problemLikely fix
Missing API keySet OPENAI_API_KEY in the same terminal, then run again
Model not foundYour account may use a different model name — check the provider docs
Rate limitTemporary block when you send too many requests too fast / quotaWait a minute, or check billing / free-tier limits
Network errorCheck wifi; try again

What you learned

  • How a program calls an AI over the internet
  • How to send a system instruction + user question
  • How to print (or save) the reply

That is the core loop behind chat apps, study tutors, and many “AI features” — including teaching tools like Sythra’s AI tutor idea: the model helps, but you still drive the learning.

Practice idea

Ask the model to:

  1. Explain for loops simply
  2. Then ask it to give a 5-line practice exercise
  3. Solve the exercise yourself in Python — do not paste the answer back until you tried

Want structured labs around Python and ML? Open app.sythra.ai when you are ready for guided practice.

Twenty lines is enough to start. Curiosity does the rest.

Keep reading

Related articles

Newsletter

Get new articles

Free essays on learning, Python, and ML — no account required. We’ll only email when there’s something worth reading.