ASAmol Shukla
Projects
Courses
Prompts
Skills
Contact
Resume
Course Outline
Syllabus Overview

AI Tools: LLM & Prompt Engineering Mastery

Courses/AI Tools: LLM & Prompt Engineering Mastery/Lesson 11: Tools & Function Calling
60 mins lesson duration•11 mins read

Lesson 11: Tools & Function Calling

Tools are how agents touch the world. Learn function calling, tool schemas, and the ReAct pattern with a real example.

What Is a Tool?

A tool is a function you expose to the model. The model can request to call it with specific arguments; your code executes it and returns the result.

LLM ──▶ "call get_weather(city='Delhi')" ──▶ YOUR CODE runs the real API
YOUR CODE ──▶ "32°C, sunny" ──▶ LLM reads it and continues

The LLM doesn't run the tool — your application does. The model only proposes the call.

Function Calling / Tool Use

Modern APIs (OpenAI, Anthropic, Gemini) support function calling natively: you declare tools with a schema (name, description, parameters), and the API returns a structured tool call instead of free text.

tools = [
  {
    "type": "function",
    "function": {
      "name": "get_weather",
      "description": "Get current weather for a city",
      "parameters": {
        "type": "object",
        "properties": {
          "city": {"type": "string", "description": "City name"}
        },
        "required": ["city"]
      }
    }
  }
]

The description field is a prompt for the tool — write it like one ("Use this when the user asks about weather"), because the model reads it to decide when to call.

The ReAct Pattern

ReAct = Reason + Act. The canonical agent prompt structure:

Section Purpose
System prompt Role, available tools, rules
Thought Model's reasoning about the next step
Action Tool name + arguments (or FINAL ANSWER)
Observation Tool output, fed back
…repeat Until FINAL ANSWER

Many frameworks encode ReAct for you, but understanding it matters: the quality of your tool descriptions determines whether the model picks the right tool.

Design Rules for Good Tools

  1. One tool = one job. Don't make a mega-tool with ten parameters.
  2. Descriptions are prompts. "Use when the user asks for the price of a stock" beats "gets prices".
  3. Validate arguments in your code — models sometimes hallucinate values.
  4. Return structured, plain results — JSON or short text, not HTML.
  5. Handle errors inside tools — return "No data for X" instead of crashing.
  6. Sandbox anything dangerous (file writes, shell commands, network).

Safety First

Tools that write files, run code, send emails, or spend money are capability + risk. Apply: allowlists, read-only defaults, human approval for irreversible actions, and audit logs.


Key Takeaways

  • Tools = functions your app runs; the model proposes calls, your code executes them.
  • Tool descriptions act as prompts — invest in them.
  • ReAct = Thought / Action / Observation loops until a final answer.
  • Validate and sandbox tool calls; errors are expected, handle them gracefully.

Next up: Building a simple agent end-to-end.

Interactive Lesson Code Snippet
# ReAct in action: the LLM decides which tool to call, your code runs it
def get_weather(city):
    weather = {"Delhi": "32C, sunny", "Mumbai": "28C, humid", "Bengaluru": "24C, cloudy"}
    return weather.get(city, "No data for that city.")

def calculator(expression):
    try:
        return str(eval(expression))
    except Exception as e:
        return f"Error: {e}"

tools = {"get_weather": get_weather, "calculator": calculator}

def react_agent(prompt):
    print(f"User: {prompt}\n")
    if "weather" in prompt.lower():
        city = prompt.split("in ")[-1].strip("?")
        print("Thought: The user wants weather. I will call get_weather.")
        print(f"Action: get_weather('{city}')")
        result = tools["get_weather"](city)
        print(f"Observation: {result}")
        print(f"Final Answer: The weather in {city} is {result}.")
    elif any(op in prompt for op in ["+", "-", "*", "/"]):
        print("Thought: This is a math expression. I will call calculator.")
        print(f"Action: calculator('{prompt}')")
        result = tools["calculator"](prompt)
        print(f"Observation: {result}")
        print(f"Final Answer: {prompt} = {result}")

react_agent("What is the weather in Delhi?")
print()
react_agent("12 * 8")
Language: python

Lesson Code (Python)

# ReAct in action: the LLM decides which tool to call, your code runs it
def get_weather(city):
    weather = {"Delhi": "32C, sunny", "Mumbai": "28C, humid", "Bengaluru": "24C, cloudy"}
    return weather.get(city, "No data for that city.")

def calculator(expression):
    try:
        return str(eval(expression))
    except Exception as e:
        return f"Error: {e}"

tools = {"get_weather": get_weather, "calculator": calculator}

def react_agent(prompt):
    print(f"User: {prompt}\n")
    if "weather" in prompt.lower():
        city = prompt.split("in ")[-1].strip("?")
        print("Thought: The user wants weather. I will call get_weather.")
        print(f"Action: get_weather('{city}')")
        result = tools["get_weather"](city)
        print(f"Observation: {result}")
        print(f"Final Answer: The weather in {city} is {result}.")
    elif any(op in prompt for op in ["+", "-", "*", "/"]):
        print("Thought: This is a math expression. I will call calculator.")
        print(f"Action: calculator('{prompt}')")
        result = tools["calculator"](prompt)
        print(f"Observation: {result}")
        print(f"Final Answer: {prompt} = {result}")

react_agent("What is the weather in Delhi?")
print()
react_agent("12 * 8")

Console Output

User: What is the weather in Delhi?

Thought: The user wants weather. I will call get_weather.
Action: get_weather('Delhi')
Observation: 32C, sunny
Final Answer: The weather in Delhi is 32C, sunny.

User: 12 * 8

Thought: This is a math expression. I will call calculator.
Action: calculator('12 * 8')
Observation: 96
Final Answer: 12 * 8 = 96

Code Visualization Tips

  • 🧠Draw the tool round-trip: LLM proposes → your code runs → result returns — label who does what.
  • 🧠Annotate a ReAct transcript with colors: Thought=blue, Action=green, Observation=orange.
  • 🧠Sketch a tool schema as a form the model 'fills in' — description, name, required fields.

Professional Tips & Tricks

  • ⚡Write tool descriptions from the model's perspective: 'Call this when…' beats vague labels.
  • ⚡Return JSON from tools — models parse structured data far more reliably than prose.
  • ⚡Never trust tool arguments blindly: validate types and ranges in your code.

Python Code Judge & Practice Arena

LeetCode Style

Run real Python 3.12 WebAssembly code directly in your browser against automated test suites.

Solved:0 / 1
0 / 20 XP
Challenges:
Problem 1 of 1

Design a Tool Schema

Medium+20 XP
Design the function-calling schema for a 'send_email' tool: name, description, and JSON parameters. Include validation considerations.
main.pyPython 3.12 (WASM)
1
2
3
4
5
6
7
8
9
10
11
12
Press Run Code to test or Submit to verify test cases

Up next · Continue learning

Building a Simple Agent

Hands-on: assemble a minimal agent with tools, memory, and stop conditions — then meet the frameworks that do it for you.

12 mins read75 mins
Start next lesson
Previous: What Is an Agentic Loop?Next: Building a Simple Agent
Made withbyAmol Shukla·amolshukla.online
ASAmol Shukla

AI Developer, Trainer & Agentic AI Expert building practical learning systems and real-world AI applications.

Explore

  • Projects
  • Courses
  • Prompts
  • Skills
  • Contact
  • Experience
  • Blogs

Connect

  • Resume
  • Contact
© 2026 Amol Shukla·Created withbyamolshukla.online
Back to top