AI Ustoz UZ: learn artificial intelligence in Uzbek

Tool calls: the model chooses, the program runs

Advanced level · lesson 2 · about 14 min

In a tool call (function calling) the model, instead of answer text, names a tool and its arguments in a structured form, for example {"vosita": "qosh", "args": [2, 3]}. The program reads this text, runs the matching function and returns the result to the model.

import json

def qosh(a, b):
    return a + b

chaqiriq = json.loads("""{"vosita": "qosh", "args": [2, 3]}""")
print(qosh(*chaqiriq["args"]))
Output5

In the example below json.loads turns the call text into a dictionary, and * passes the values from the list to the function as separate arguments. If the tools are stored in a dictionary, they are easy to find by name.

Safety: run only tools that were registered in advance; reject an unknown name. Never run, without permission, an action that does not belong to the called function (for example, deleting files).

Remember

  • The model names the tool and arguments, the program runs it.
  • json.loads turns the call text into a dictionary; *args unpacks arguments.
  • Run only registered tools.

Exercise

The model named a tool that is not in the list. What should the program do?

Answer and explanation
  1. Reject the call and return a clear message. (correct answer)running an unknown call is dangerous.
  2. Look for a command with that name in the system and run it.that is a security hole.
  3. Stop with a crash.a controlled message is better than a crash.

Code exercises

  1. Write the function bajar(chaqiriq_matn): it reads the JSON text; if the tool is in the list, it calls it with args and returns the result, otherwise it returns vosita topilmadi.
    Hint: Open it with json.loads; check nom not in VOSITALAR; call with VOSITALAR[nom](*d["args"]).
  2. vosita_xabari(nom, natija) should return a dictionary: rol = vosita, vosita = nom, matn = the text form of the result.
    Hint: Turn the number into text with str(natija).

Do the exercise in the app.

Practical task

Add one more tool (for example, multiplying two numbers) and test it with a call text.

  • I added the tool
  • I tested it with a call

Glossary

Interactive mode: search, progress and Python exercises.