Tool calls: the model chooses, the program runs
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"]))Output5In 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.loadsturns the call text into a dictionary;*argsunpacks 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
- Reject the call and return a clear message. (correct answer)running an unknown call is dangerous.
- Look for a command with that name in the system and run it.that is a security hole.
- Stop with a crash.a controlled message is better than a crash.
Code exercises
- Write the function
bajar(chaqiriq_matn): it reads the JSON text; if the tool is in the list, it calls it withargsand returns the result, otherwise it returnsvosita topilmadi.
Hint: Open it withjson.loads; checknom not in VOSITALAR; call withVOSITALAR[nom](*d["args"]). 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 withstr(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.
