A simple “agent”: a program that picks a tool
An agent is a program that splits a task into steps and, when needed, uses tools (a calculator, search, a file). A typical loop: the model looks at the task and decides which tool to call and with which arguments (often as JSON); the program runs the tool and returns the result to the model; the model builds its answer from that result.
In this lesson there is no model itself: a ready-made “call” dictionary stands in for it, and we write the program part: running the matching function according to the tool name in the call. This is a simplified example; real agents also have error handling, several steps, permissions and more.
def kvadrat(son):
return son * son
VOSITALAR = {"kvadrat": kvadrat}
def agent(chaqiriq):
nom = chaqiriq["vosita"]
if nom in VOSITALAR:
return VOSITALAR[nom](chaqiriq["son"])
return "vosita topilmadi"
print(agent({"vosita": "kvadrat", "son": 7}))
print(agent({"vosita": "qidiruv", "son": 7}))Output49
vosita topilmadiA safety rule: give an agent only the tools it needs and check the results. An unknown or wrong call must not crash the program: the “vosita topilmadi” case above is an example.
Remember
- Agent = model + tools + a program that runs the tools.
- The tool name and arguments are passed as a dictionary (JSON).
- Handle an unknown call without crashing.
Exercise
Who performs exact arithmetic in an agent system?
Answer and explanation
- A tool (function) in the program: the model calls it and gets the result back. (correct answer)that way the calculation is done exactly by checkable code.
- Only the model, by generating text.that raises the chance of errors in long calculations.
- The user, by hand.the point of an agent is to automate exactly this kind of work.
Code exercises
- Write the function
kalkulyator(a, b, amal): ifamalis+,-,*or/, it returns the matching result.
Hint: For each operation write a condition likeif amal == "+":andreturn. - Write the function
agent(chaqiriq): if the value ofvositaiskalkulyator, call the calculator witha,b,amaland return the result; for any other tool return the textvosita topilmadi.
Hint: Checkchaqiriq["vosita"]; give the calculatorchaqiriq["a"],chaqiriq["b"]andchaqiriq["amal"].
Do the exercise in the app.
Practical task
Add a divide-by-zero case to the kalkulyator function: instead of an error it should return a clear message.
- I wrote the divide-by-zero condition
- I tested it with the
/operation
Glossary
Interactive mode: search, progress and Python exercises.
