📘 CodingMarble Learn

Using AI Tools and Calling an AI API from Python Code

An AI tool is a ready-made app (chat, image, voice, translation) that you use by typing or clicking. An AI API lets your own program ask the same kind of AI service for help. The program sends a request (address, secret key and a question in JSON) and receives a response (status code and an answer in JSON). With Python this takes about six lines using the requests library. Good use means clear prompts, checking answers, protecting your key and respecting cost and limits.

🎬 Step-by-step story

  1. You open a chat AI tool and type a question. The AI sends back an answer. Here a person is the one asking. Watch the orange request go and the green answer return.
  2. Different jobs need different tools: a chat AI for writing, an image AI for pictures, a voice AI for reading aloud, a translate AI for languages. Tap a task and the right tile lights up.
  3. Now your own program wants to ask. Think of a restaurant. Your program is the customer, the API is the waiter who carries the order, and the AI service is the kitchen that makes the dish.
  4. Here are the six lines of code. Run them one phase at a time: get ready, write the question, send it, read the answer. Each phase lights one line.
  5. The key is like a house key: keep it secret. Every call also costs a little and has limits, so test small. The red bar shows how calls pile up.
  6. Free play. Send a request and read the answer, or try a wrong key and see the gate say "no" with a 401 error.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

🤔 Common doubts, cleared

What is the difference between using an AI tool and using its API?

In a tool a person types. In an API a program types for you. Compare the first step (a person) with the program in the restaurant picture.

How do I know which AI tool to use?

Match the job to the tool: text, picture, voice or translation. Tap each task in the 3D and see the tile light up.

Why do we call the API a waiter?

Because you never walk into the kitchen. The API takes your order in an agreed form and brings back the result.

What does each line of the code do?

Run the four phases in the 3D: get ready (lines 1–3), write data (4), send (5), read (6). The highlighted line shows the one running.

Why must I keep the key secret and call carefully?

Anyone with the key can use your account and spend your money. Calls also have limits; the red bar shows them piling up.

What does a 401 mean when I try it?

The gate refused the request because the key was wrong. Press "Try a wrong key" in free play to see it.

AI platforms and tools: what they are

An AI tool is an app that uses a trained AI model to do a job for you. An AI platform is a bigger service where you can use many such models, test them and, if you are a developer, connect them to your own programs.

Using AI tools well

The question you type is called a prompt. Good prompts say: who the AI should act as, what job to do, and in which format (for example, "Explain rain to a Class 6 child in 3 short lines").

  1. Check the answer. AI can sound sure and still be wrong. Compare with a book or a teacher.
  2. Protect private data. Do not paste passwords, ID numbers or other people's private details.
  3. Be honest. If AI helped with homework, say so, and learn from the answer, do not just copy it.
  4. Pick the right tool. A text AI is not a calculator and an image AI is not a fact-checker.

What is an API? The waiter picture

An API (Application Programming Interface) is a set of rules that lets one program ask another program for something. In the restaurant picture: your program = customer, API = waiter, AI service = kitchen. You do not go into the kitchen; you give the waiter an order in the agreed form, and a dish comes back.

Most AI services offer a web API. You send a request to an address (a URL, also called an endpoint) over the internet and get a response. Data usually travels as JSON, a simple text form like {"prompt": "hello"}.

Calling an API in Python

The common Python library is requests. A call has four parts: Key, URL, Data, Send.

import requests
key = "YOUR_SECRET_KEY"
url = "https://api.example.com/v1/chat"   # example address, not real
data = {"prompt": "Explain rain in one line"}
reply = requests.post(url, json=data, headers={"Authorization": "Bearer " + key})
print(reply.json()["answer"])

Real services use their own address and field names; read their documentation and copy the pattern, not the example above.

Keys, errors, cost and limits

Keep the key safe. Never write it in code you share or upload. Store it in an environment variable and read it with os.environ["AI_KEY"].

Handle errors. Networks fail. Use a timeout and check the status:

try:
    reply = requests.post(url, json=data, headers=h, timeout=10)
    reply.raise_for_status()      # stops on 401, 429, 500...
    print(reply.json()["answer"])
except requests.RequestException as e:
    print("Could not reach the AI service:", e)

Cost and limits. Many services charge per request or per amount of text (tokens) and limit how many requests you can send per minute. Test with short prompts and do not call in an endless loop.

Try it

In the 3D free-play step send each of the three requests, then press "Try a wrong key". Predict the status code before you read it. Then write on paper the six lines of code from memory and mark K, U, D, S, R next to the right lines.

At home with a grown-up: try one real AI tool. Write a vague prompt first, then a clear one with who, what and format, and compare the answers.

Key formulas and definitions

Worked examples

1. In the code line reply = requests.post(url, json=data, headers=h), what does each part do?

requests.post sends a POST request; url is the address; json=data sends the question as JSON; headers=h carries the key. reply stores what comes back.

2. A program gets status 401. What is the most likely problem and the fix?

The key is wrong, missing or expired. Check the Authorization header and the key value, then try again.

3. A service allows 60 requests per minute. A loop sends one request every 0.5 seconds. What happens?

One request per 0.5 s means 120 per minute, more than 60. After about 30 seconds the program will start getting 429 errors. Add a wait of at least 1 second between calls.

4. Rewrite the prompt "tell me about rain" as a better prompt.

For example: "You are a Class 6 science teacher. Explain how rain forms in 3 short lines with one everyday example." It says who, what and format.

Common mistakes

Practice quiz

1. In the restaurant picture, the API is the:
2. Status code 401 usually means:
3. Which Python library is commonly used to call web APIs?
4. Where should an API key be stored safely?
5. What does reply.json() do?

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What is the difference between an AI tool and an AI API?

A tool is an app you use by hand (typing, clicking). An API lets your own program use the same kind of AI service automatically, by sending requests and reading responses.

Do I need to know AI to call an AI API?

No. You only need to know how to send a request and read a response: address, key, JSON data and the reply. The AI itself runs on the service.

Is it safe to put my API key in my code?

Not if you share or upload the code. Keep keys in environment variables or a private settings file that you never share.

Where this is taught

China高一Comp.1 Ch.4 Intelligent era

Learn first

Learn next

Related lessons

All Computer Science lessons