---
title: "Talk to an AI from Python in about 20 lines"
description: "Send a prompt to an AI model from Python and print the reply — a short, beginner-friendly walkthrough with almost no setup drama."
url: https://articles.sythra.ai/articles/python-talk-to-llm-20-lines
slug: python-talk-to-llm-20-lines
author: "vaibhavkothari"
author_url: https://articles.sythra.ai/writers/vaibhavkothari
date_published: 2026-07-24T17:46:03.878Z
date_modified: 2026-08-29T10:29:25.265Z
topics: ["Python", "Ai"]
reading_time_minutes: 5
publisher: "Sythra"
publisher_url: https://sythra.ai
access: free
language: en
---

# 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.

Source: https://articles.sythra.ai/articles/python-talk-to-llm-20-lines · Author: vaibhavkothari · Published: 2026-07-24 · Reading time: 5 min · Topics: Python, Ai

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 model
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 **API** is a way for your program to talk to another service on the internet.

You send a message (your prompt).  
The service sends a message back (the model’s reply).

## What you need

1. Python 3
2. An API key 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 pip:

```bash
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 variable. On Windows PowerShell (current window only):

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

On macOS / Linux:

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

## The whole program (read it once)

Save as `ask_ai.py`:

```python
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:

```bash
python ask_ai.py
```

You should see a short explanation in plain English.

## What each part means

### `OpenAI()`

Builds a client that knows how to send requests. It looks for `OPENAI_API_KEY` automatically. The call below is a chat completion.

### `messages`

Chat models work like a short conversation:

- **system** — rules for how the AI should behave  
- **user** — 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 — input pauses for your question:

```python
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_tokens:

```python
max_tokens=120,
```

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

**2. More focused help**

Change the system line to:

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

**3. Save the answer to a file**

```python
from pathlib import Path

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

## If something goes wrong

| Message / problem | Likely fix |
|-------------------|------------|
| Missing API key | Set `OPENAI_API_KEY` in the same terminal, then run again |
| Model not found | Your account may use a different model name — check the provider docs |
| Rate limit / quota | Wait a minute, or check billing / free-tier limits |
| Network error | Check 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.

```remember
# Remember this
API key -> lives in an env var, never in the file you commit
`client.messages.create(...)` -> one request, one response
`max_tokens` -> the ceiling on the reply, not a target
---
An API is just a function call that happens over the internet.
```

## 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](https://app.sythra.ai) when you are ready for guided practice.

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

## Glossary (terms defined in this article)
- **model** (basic) — The specific AI brain you call (for example gpt-4o-mini)
- **API** (basic) — A way for your program to talk to another service on the internet
- **prompt** (basic) — The text instruction or question you send to the AI
- **API key** (basic) — A secret password that proves your program is allowed to use the service
- **pip** (basic) — Python’s package installer — used to download libraries
- **environment variable** (medium) — A setting your terminal shares with programs — good for secrets
- **client** (basic) — Helper object that knows how to send API requests for you
- **chat completion** (advanced) — API request that asks a chat model for a reply
- **system** (medium) — Instructions that set how the AI should behave
- **user** (basic) — The message that holds your actual question
- **input** (basic) — Built-in command that waits for you to type something
- **max_tokens** (medium) — A cap on how long the reply can be
- **Rate limit** (medium) — Temporary block when you send too many requests too fast
