Learning Hub/AI App Development/Session 4

Session 4 of 5 · 60 minutes

Connecting to an AI Service Safely

Learn how apps call AI services: API keys, requests, errors and privacy, with a safe offline mode for practice.

Goals

By the end of this session you can:

  • Explain what an API key is and why it must stay secret
  • Read a key from an environment variable instead of writing it in code
  • Handle errors so the app doesn't crash when a service is slow or down
  • Build a study helper app with a fake model that can be swapped for a real one

Words to know

API key
A secret password that tells an AI service who is making a request.
environment variable
A setting stored outside your code, used to keep secrets out of your files.
JSON
A text format for structured data, which looks like a Python dictionary.
timeout
A limit on how long to wait for a reply before giving up.
rate limit
A cap on how many requests you may send in a period of time.

The lesson

Step 1: How an app asks a model

An AI service lives on someone else’s computer. Your app sends it a request over the internet and gets a response back. The request usually includes:

  1. Who you are: your API key.
  2. What you want: the prompt, plus settings such as how long the answer may be.

The response is usually JSON, text that looks like a Python dictionary. Your code reads the part it needs.

Python
response = {"text": "A volcano is an opening in the Earth where hot rock escapes."}
print(response["text"])
Output
A volcano is an opening in the Earth where hot rock escapes.

Step 2: Keys are secrets

An API key works like a password with a bank card attached: whoever has it can make requests that may cost money or use your quota. So:

  • Never type a key into your code, a document, a chat or a screenshot.
  • Never upload code that contains a key to a public place.
  • Keep it in an environment variable or the secrets setting of your tool, and read it from there.
Python
import os

api_key = os.environ.get("AI_API_KEY")   # reads a secret setting

if api_key is None:
    print("No key found, so the app will use the offline fake model.")
else:
    print("A key is set. The app can use a real service.")
Output
No key found, so the app will use the offline fake model.

If a key leaks: log in to the service and revoke it right away. Then create a new one. Deleting the post is not enough, because someone may already have copied it.

Step 3: When things go wrong

Networks fail. Services get busy. A good app expects that. Python’s try and except let you handle an error instead of crashing.

Python
def ask_service(prompt):
    raise RuntimeError("service is down")

try:
    answer = ask_service("Hello")
    print(answer)
except RuntimeError:
    print("Sorry, the helper is resting. Please try again soon.")
finally:
    print("Done.")
Output
Sorry, the helper is resting. Please try again soon.
Done.

When you call a real service, set a timeout so the app doesn’t wait forever, and handle the error in the except block with a friendly message.

Step 4: The real call (for reference)

Each provider has its own address and field names, so you must follow your provider’s documentation. The general shape looks like this. This code needs a real service and key, so don’t run it in class unless your teacher says so.

Python
import os
import requests

API_URL = os.environ.get("AI_API_URL")
API_KEY = os.environ.get("AI_API_KEY")

def ask_real_model(prompt):
    reply = requests.post(
        API_URL,
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={"prompt": prompt},          # field names vary by provider
        timeout=20,
    )
    reply.raise_for_status()               # raises an error if the service says no
    return reply.json()["text"]            # where the answer lives varies too

Services also have rate limits (a cap on requests) and prices. For a classroom app, that means: ask only when needed, keep prompts short, and never let a loop send requests forever.

Step 5: One door for every model

Remember Session 1: our app calls a single function. Here is the plan that keeps your app flexible and safe.

Python
USE_FAKE = True   # True while practicing. Switch only when your teacher says so.

def fake_model(prompt):
    return "(practice answer) Here is a simple explanation for: " + prompt

def ask_ai(prompt):
    try:
        if USE_FAKE:
            return fake_model(prompt)
        return "A real model would answer here."   # call ask_real_model(prompt)
    except Exception:
        return "Sorry, I couldn't get an answer. Please try again."

def explain_word(word, age):
    prompt = f"You are a kind teacher. Explain the word '{word}' to a {age}-year-old in 2 sentences."
    return ask_ai(prompt)

print(explain_word("gravity", 9))
print("AI-generated. Check important facts.")
Output
(practice answer) Here is a simple explanation for: You are a kind teacher. Explain the word 'gravity' to a 9-year-old in 2 sentences.
AI-generated. Check important facts.

Everything outside ask_ai stays the same whether the answer comes from a fake or a real model. Even with a real one, you must still validate the input and label the output, which is what we do next session.

Exercise

Catch the error

  1. Write a function risky_call() that raises an error on purpose, with raise RuntimeError("service is down").
  2. Call it inside a try block, and in the except block print a friendly message instead of crashing.
  3. Add a finally line that prints Done. no matter what happened.
  4. Change risky_call() so it sometimes succeeds, and test both paths.
Need a hint?

try: then your call, except RuntimeError: then your message.

Small project

Study helper

Build a small app that explains a word in simple language. It works offline with a fake model, and is ready to connect to a real service when your teacher says so.

  1. Write fake_model(prompt) that returns a pretend explanation.
  2. Write ask_ai(prompt) that calls fake_model while USE_FAKE = True, and wraps everything in try/except.
  3. Write explain_word(word, age) that builds a good prompt (Session 2) and returns the answer.
  4. In a loop, ask the user for a word, reject empty input or anything over 40 characters, and print the explanation with a label: AI-generated. Check important facts.
  5. Show your teacher how you would add a real model, without putting a key in the code.

Stretch it: Keep a list of the words the user has asked about and print it when they quit.

Quiz

Check your understanding

Pick one answer for each question. Your score appears right in the page; nothing is sent anywhere.

  1. Question 1Where should you keep an API key?
  2. Question 2You accidentally post your API key online. What should you do?
  3. Question 3What does try / except do?
  4. Question 4Why use a timeout when calling a service?
  5. Question 5Which should you NOT send to an online AI service?