AI Ustoz UZ: learn artificial intelligence in Uzbek

API: a structured request and response

Advanced level · lesson 1 · about 14 min

Artificial intelligence services usually work through an API: the program sends the service a structured request and the service returns a structured response. The request and response are most often in JSON. In this lesson we do not connect to a real service: we only practice the structure of a request and a response.

A request usually consists of a model name and a list of messages; each message has a role (system, user) and text. In a response the result sits nested, so you take it out layer by layer. Field names differ between services: read them in the service’s official documentation.

import json

javob_matn = """{"holat": "ok", "natija": {"matn": "Salom", "tokenlar": 3}}"""
javob = json.loads(javob_matn)
print(javob["holat"])
print(javob["natija"]["matn"])
Outputok
Salom

An important rule: before using a response, check its status (success or error). Do not write secret keys (an API key) into code that is published openly, and do not send them to a chat tool.

Remember

  • A request and response are usually JSON.
  • Take the value you need out of the response layer by layer.
  • Check the status first; keep the API key secret.

Exercise

What is sensible to check before taking the text out of a response?

Answer and explanation
  1. The response status: whether it is a success or an error. (correct answer)an error response may not have the expected field.
  2. Nothing: the response is always right.the network and the service can return an error.
  3. Only the length of the response.length does not show success.

Code exercises

  1. Create the dictionary payload: key model with the value mini, key messages with a list of one message; in the message rol = user and matn = the value of savol.
    Hint: Inside the messages list there is a dictionary: [{"rol": "user", "matn": savol}].
  2. Use d: if holat is ok, print the text first and then the number of tokens; otherwise print xato.
    Hint: Check d["holat"] == "ok"; the values are inside d["natija"].

Do the exercise in the app.

Practical task

For an imaginary question-and-answer service, write the request as JSON (a model name, one message). Do not write real keys or data.

  • I wrote the request JSON
  • It has a role and text

Glossary

Interactive mode: search, progress and Python exercises.