API: a structured request and response
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
SalomAn 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
- The response status: whether it is a success or an error. (correct answer)an error response may not have the expected field.
- Nothing: the response is always right.the network and the service can return an error.
- Only the length of the response.length does not show success.
Code exercises
- Create the dictionary
payload: keymodelwith the valuemini, keymessageswith a list of one message; in the messagerol=userandmatn= the value ofsavol.
Hint: Inside themessageslist there is a dictionary:[{"rol": "user", "matn": savol}]. - Use
d: ifholatisok, print the text first and then the number of tokens; otherwise printxato.
Hint: Checkd["holat"] == "ok"; the values are insided["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.
