Your First AI Call: Talk to a Language Model from Python
Hands-on lab · IDE in your browser

Your First AI Call: Talk to a Language Model from Python

Send your first prompt to a real language model from Python, then learn the five things every AI feature is built on: reading the reply, reading the token receipt and the time it took, what temperature does to the answers, giving the model a role with a system message, and keeping your program alive when the call fails.

Time
40 min
Checked steps
5
Level
Beginner
Setup
None
Read step 1

Hands-on labs require Pro · $29.99/mo · cancel anytime

Lab cockpit40 min · 5 stepsSession running
4 / 5 steps passingWhen it fails: keep the program alive · step 5 of 5
ai.py▶ Run✓ Check
FALLBACK = "Sorry, the assistant is unavailable right now. Please try again in a minute."  def safe_ask(prompt, client=None, model=None):    """Like ask(), but a failed call returns FALLBACK instead of crashing."""    client = client or CLIENT         
TerminalOutput

The job

Brightline Books is a small shop that wants an assistant on its website. Before anyone designs that assistant, someone has to make one call to a language model work from code and understand what comes back. That is your job today. You write five short Python functions in ai.py, one per step, and run each one against a real hosted model. Every check tries your function twice: once against a stand-in model that records exactly what you sent, and once against the real one.

5 steps, each checked when you finish it

A check runs your work at the end of every step. Hints and the full solution are there if you get stuck.

  1. 1

    Say hello: send a prompt, get a reply

    A language model answers messages.

    You writeask()
  2. 2

    Read the receipt: tokens and time

    Every reply comes with a receipt.

    You writeask_with_stats()
  3. 3

    Temperature: why the same question gets different answers

    You saw in Step 1 that the same question can get a different answer each time.

    You writesample()
  4. 4

    Give it a role: the system message

    So far you have sent one message, from the user.

    You writeask_with_role()
  5. 5

    When it fails: keep the program alive

    A model call goes over the network to someone else's service, so sometimes it fails: the network drops, the service is overloaded, the key is wrong, or the request names a model that does not exist.

    You writesafe_ask()

Step 1 as it appears in the lab

The lab’s own text. The hint and the solution stay inside the lab.

Step 1: Say hello: send a prompt, get a reply

A language model answers messages. Your program sends it a list of messages; the model sends back one new message. That round trip is the whole interface, and every AI feature you will ever build starts with it.

Open ai.py. The top of the file is already done:

  • from openai import OpenAI loads the client library. Most hosted models, not only OpenAI's, accept requests in this format.
  • CLIENT = OpenAI() creates the connection. The lab already holds the address and the key, so it needs no arguments here.
  • MODEL is the name of the model you will talk to: Llama 3.1 8B, a small open model.

Each function takes client=None and starts with client = client or CLIENT. That line means "use the real connection unless someone hands me another one". The checker hands in a stand-in that records what you sent, so it can tell you exactly what was wrong.

Do this

1. Write ask(prompt). Replace the TODO with two statements:

response = client.chat.completions.create(
    model=MODEL,
    messages=[{"role": "user", "content": prompt}],
)
return response.choices[0].message.content

messages is a Python list (square brackets) holding one dictionary (curly braces). The dictionary says who is speaking ("user", that is, you) and what they said. The reply comes back inside response: a list called choices (you asked for one answer, so take the first, [0]), its message, and that message's content.

2. Click Run. It calls ask() with a real question and prints the answer. Run it twice. The wording will probably change.

3. Click Check. The checker sends ask() a question it can verify: it asks the real model a question with one right answer.

ai.py, the file you edit50 lines
"""Your first AI calls, from Python.

The lab's environment already knows where the model lives and holds the key,
so `OpenAI()` needs no arguments here. On your own machine you would set
OPENAI_API_KEY (and OPENAI_BASE_URL for a non-OpenAI provider) first.
"""
import time

import openai
from openai import OpenAI

CLIENT = OpenAI()
MODEL = "meta/llama-3.1-8b-instruct"


def ask(prompt, client=None):
    """Send one question to the model and return its reply as a string."""
    client = client or CLIENT
    # TODO (Step 1): ask the model and return its reply text.
    #   1. response = client.chat.completions.create(model=MODEL, messages=[...])
    #      messages is a list with ONE dict: {"role": "user", "content": prompt}
    #   2. return response.choices[0].message.content
    raise NotImplementedError("Step 1: write ask()")


def ask_with_stats(prompt, client=None):
    """Ask, and also report what the call cost in tokens and time."""
    client = client or CLIENT
    raise NotImplementedError("ask_with_stats() arrives in Step 2")


def sample(prompt, temperature, n=5, client=None):
    """Ask the same question n times at one temperature; return the n replies."""
    client = client or CLIENT
    raise NotImplementedError("sample() arrives in Step 3")


def ask_with_role(system, prompt, client=None):
    """Give the model standing instructions (a system message), then ask."""
    client = client or CLIENT
    raise NotImplementedError("ask_with_role() arrives in Step 4")


FALLBACK = "Sorry, the assistant is unavailable right now. Please try again in a minute."


def safe_ask(prompt, client=None, model=None):
    """Like ask(), but a failed call returns FALLBACK instead of crashing."""
    client = client or CLIENT
    raise NotImplementedError("safe_ask() arrives in Step 5")
Provided for you:try_it.py

Frequently asked questions

Do I need to know Python for this lab?

No. Each step shows the exact lines you need and explains them. You write about 40 lines in total, and the checker tells you what to fix when something is off.

Do I need my own API key?

No. The lab environment is already connected to a hosted model. The first lines of ai.py explain which two settings you would add on your own computer.

Which model does the lab use?

Llama 3.1 8B Instruct, a small open model, through an OpenAI-compatible endpoint. The same code works with other providers by changing the model name and the base URL.

What is temperature?

A setting that controls how much the model varies its word choices. At 0 it picks the most likely words and repeats itself; at higher values it samples more freely. Step 3 measures the difference on a real prompt.

What happens when a program talks to a language model

A chat assistant on a website is a program that sends text to a language model over the internet and shows what comes back. The request is a list of messages, each with a role and some text. The response carries the reply, a count of the tokens that were read and written, and the name of the model that answered. Everything larger, from a support bot to an agent, is built on that one exchange. This lab makes that exchange concrete in Python with the OpenAI client library, which most hosted models accept. You send a prompt and read the reply, read the token counts that decide the bill, time the call, run the same prompt at two temperatures to see why answers vary, add a system message that changes how the model behaves, and catch the errors a real service throws so your program shows a friendly message instead of a crash.