Blog › Build
Build a tool-using bot in 30 lines
This walkthrough builds a small agent that can do maths and roll dice. It uses the same pattern as the Tools chapter, and you can build it in Build, save it to your account and share the link.
Step 1: write the tools
A tool is a normal Python function. Give it a clear name, because Pip picks tools by their names.
import pip, json, random
def calculator(a, b, op):
if op == "+":
return a + b
if op == "-":
return a - b
if op == "*":
return a * b
return a / b
def roll_dice(sides):
return random.randint(1, sides)
Step 2: put them in a toolbox
A dictionary maps each tool's name to the function itself, so your code can look the tool up by the name the model gives back.
tools = {"calculator": calculator, "roll_dice": roll_dice}
Step 3: let the model choose
pip.ask_with_tools(question, tools) answers with JSON text. Turn it into a dictionary with json.loads. If reply["tool"] has a name, call that tool with reply["args"]. If it is empty, the model just wants to talk.
while True:
q = input("Ask your bot (or type bye): ")
if q in ("bye", ""):
print("Bye!")
break
reply = json.loads(pip.ask_with_tools(q, tools))
if reply["tool"] is None:
print("Bot:", reply["reply"])
else:
result = tools[reply["tool"]](**reply["args"])
print("Bot used", reply["tool"], "and got", result)
Step 4: try it
Press Run and try "what is 12 plus 30?", then "roll a 20 sided dice", then "tell me a joke". The first two use a tool; the last one does not. Type bye to stop.
Why the two stars in **reply["args"]?
reply["args"] is a dictionary like {"a": 12, "b": 30, "op": "+"}. The two stars unpack it, so Python calls calculator(a=12, b=30, op="+"). That is how one line can call any tool with the right inputs.
Make it yours
- Add a third tool, like a word counter, and give it a name with "define" or "weather" in it to see how Pip picks it.
- Keep a list of every tool your bot used and print it when you say bye.
- Share it on the Show your bot board.
The full version is in the showcase as Tool Bot, by the Questzo team. Press Remix to make your own copy.
Learn it by building it
Questzo teaches Python by building an AI agent, one pixel quest at a time. The first two chapters are free, with no sign-up.
Start the first quest