14. Tool Calling Basics#
A fast, conceptual revision guide for 14-rag-tool-calling-basics (Module 3). Focused on how LLM tool calling works under the hood — the 4-step message-passing protocol, raw OpenAI SDK wiring vs. LangChain abstractions, multi-tool routing, single-round limits, and tool safety — without boilerplate code clutter.
Why Tool Calling Exists & The 4-Step Execution Flow#
Revision Notes#
Reference files: 1_GIVE_FIRST_Exercise_Questions.html, 2_SHARE_AFTER_Solution_Explainer.html
Concept#
LLMs excel at language, reasoning, and synthesis, but they cannot execute code, query private databases, or perform exact arithmetic reliably (for instance, spotting an off-by-one trap in a 11-digit square). Tool calling solves this by letting the LLM ask your Python application to run a specific function with structured arguments, then fold the returned result into its final answer.
How It Works#
An LLM never executes Python directly; instead, it emits structured tool_calls order slips into a shared messages list, your application runs the allow-listed function locally and appends a matching tool_call_id result, and a second LLM pass writes the grounded reply.
Key Mental Models#
- The LLM never executes your function: Think of the LLM as a restaurant waiter and your Python code as the kitchen. The waiter cannot cook — he reads the menu (tool definitions), writes an order slip with a table number (
tool_call_id), hands it to the kitchen (your runtime), and serves the finished dish (final natural-language answer). - Everything lives in one growing
messageslist: Tool calling is not a separate API endpoint; it is a conversation state machine. The list grows from[user]→[user, assistant(tool_calls)]→[user, assistant(tool_calls), tool(result)]→ final assistant reply. tool_call_idlinks results to requests: Because an LLM can request multiple tools in a single turn, every tool result must echo back the exacttool_call_idfrom the request it answers. The API rejects orphaned or mismatched tool messages.
Tool Calling from Scratch with the OpenAI SDK#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/1_tool_calling_from_scratch.py, 2_SHARE_AFTER_Solution_Code/1_tool_calling_from_scratch.py, .env.example (requires OPENAI_API_KEY)
Concept#
Implementing tool calling with the plain OpenAI SDK strips away framework magic and exposes the exact wire contract between your app and the model. Using a single square_root(number) function, you manually wire the schema, dispatch, and second LLM call.
How It Works#
- Real Python function + dispatch map: Define
square_root(number: float)and map its string name intool_map = {"square_root": square_root}so incoming tool names can be resolved safely. - Hand-written JSON Schema "menu": Describe the tool in OpenAI's
toolslist (type: "function",name,description, and JSON Schemaparameterswithpropertiesandrequired). The LLM never sees your Python code — only this JSON description. - Manual parse, execute, and re-invoke:
- Append the assistant's response (
message) tomessages. - If
message.tool_callsis empty, returnmessage.contentdirectly (e.g., "What is the capital of France?"). - Otherwise, loop over each
tool_call, parsetool_call.function.argumentswithjson.loads(...), executetool_map[fn_name](**fn_args), and append{"role": "tool", "tool_call_id": tool_call.id, "content": str(result)}. - Call
client.chat.completions.create(...)a second time with the fullmessageslist to get the final answer.
- Append the assistant's response (
Trade-Offs & Pitfalls#
- Arguments arrive as a raw JSON string:
tool_call.function.argumentsis a serialized string (not a Pythondict), so forgettingjson.loads(...)breaks unpacking. - Exact parameter name matching: If the JSON Schema declares a parameter name that doesn't match the Python function signature (e.g.,
number),**fn_argsfails with aTypeError. - Strict message ordering: Forgetting
messages.append(message)before appending therole: "tool"result — or sending a wrongtool_call_id— causes an API error complaining that the tool message has no precedingtool_calls. - Empty tool list error: Passing
tools=[]triggers aBadRequestError. - Model-specific
reasoning_effort="none": Forgpt-6-lunain the Chat Completions API, OpenAI requiresreasoning_effort="none"to enable tool calling (and it keeps responses fast and low-cost).
Code Reference#
import json
import math
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv() # reads OPENAI_API_KEY from the .env file
client = OpenAI()
MODEL = "gpt-6-luna"
# ----------------------------------------------------------------------------
# 1) The real Python function (the "tool")
# LLMs predict tokens rather than executing exact arithmetic, so we offload
# deterministic math (like square roots of large numbers) to Python.
# ----------------------------------------------------------------------------
def square_root(number: float) -> float:
if number < 0:
raise ValueError("Cannot compute square root of a negative number.")
return math.sqrt(number)
# Dispatch table mapping the string tool name returned by the LLM -> the Python callable.
# Never use eval() on LLM output; an explicit allow-list prevents arbitrary code execution.
tool_map = {"square_root": square_root}
# ----------------------------------------------------------------------------
# 2) The tool "menu" we show the LLM (JSON Schema)
# The LLM never sees our Python code. It only sees this name, description and parameters,
# so clear descriptions directly determine whether the model picks the right tool.
# ----------------------------------------------------------------------------
# ----- TODO 1: Describe the square_root tool in OpenAI's JSON tool format -----
# Hint: A list with one dict: {"type": "function", "function": {"name": ..., "description": ..., "parameters": {...}}}
# Hint: "parameters" is a JSON Schema: {"type": "object", "properties": {"number": {"type": "number", ...}}, "required": ["number"]}
tools = [] # replace with your code
def chat_with_tools(user_message: str) -> str:
messages = [{"role": "user", "content": user_message}]
# Step 1: ask the LLM, and tell it which tools exist.
# reasoning_effort="none" is required for tool calling with this model in the Chat Completions API.
response = client.chat.completions.create(
model=MODEL,
messages=messages,
tools=tools,
reasoning_effort="none",
)
message = response.choices[0].message
# -> ChatCompletionMessage(content=None, tool_calls=[
# ChatCompletionMessageToolCall(
# id='call_abc123',
# function=Function(name='square_root', arguments='{"number": 15241383937}')
# )
# ]) (once TODO 1 defines `tools`; otherwise tool_calls=None)
# OpenAI requires the assistant message containing tool_calls to remain in `messages`
# before any subsequent `role="tool"` responses, matching each call by `tool_call_id`.
messages.append(message) # keep the assistant's reply (including its tool requests) in the history
# Step 2: did the LLM ask for a tool?
if not message.tool_calls:
return message.content # no tool needed, e.g. "What is the capital of France?"
# Step 3: run every tool the LLM asked for and send the results back
for tool_call in message.tool_calls:
# ----- TODO 2: Run the requested tool and add its result to messages -----
# Hint: The tool name is in tool_call.function.name
# Hint: The arguments are a JSON string in tool_call.function.arguments
# Hint: json.loads(...) turns the arguments into a dict, then call tool_map[name](**args)
# Hint: Append {"role": "tool", "tool_call_id": tool_call.id, "content": str(result)}
# ... (see full file: 1_tool_calling_from_scratch.py)
$ python 1_GIVE_FIRST_Starter_Code/1_tool_calling_from_scratch.py
# Before completing TODOs 1-2 (tools = [] — LLM has no tools registered):
Q: Is 15241383937 the square of 123456?
A: Yes, 123456 squared is 15,241,383,937. # <-- hallucinated! (off by 1 without the tool)
Q: What is the capital of France?
A: The capital of France is Paris.
# After completing TODOs 1-2, the model invokes square_root(15241383937) -> 123456.00000405003
# and correctly reports that 123456^2 = 15241383936 (not 15241383937).
import json
import math
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv() # reads OPENAI_API_KEY from the .env file
client = OpenAI()
MODEL = "gpt-6-luna"
# ----------------------------------------------------------------------------
# 1) The real Python function (the "tool")
# Validates input domain before delegating to math.sqrt for exact floating-point arithmetic.
# ----------------------------------------------------------------------------
def square_root(number: float) -> float:
if number < 0:
raise ValueError("Cannot compute square root of a negative number.")
return math.sqrt(number)
# Allow-listed dispatch table: maps the tool name emitted by the LLM to our local Python function.
tool_map = {"square_root": square_root}
# ----------------------------------------------------------------------------
# 2) The tool "menu" we show the LLM (JSON Schema)
# The LLM never sees our Python code. It only sees this name, description and parameters,
# and uses the JSON Schema to emit valid, typed JSON arguments.
# ----------------------------------------------------------------------------
# ----- TODO 1 (solved): Describe the square_root tool in OpenAI's JSON tool format -----
tools = [
{
"type": "function",
"function": {
"name": "square_root",
"description": "Calculate the square root of a non-negative number.",
"parameters": {
"type": "object",
"properties": {
"number": {
"type": "number",
"description": "The non-negative number to take the square root of.",
}
},
"required": ["number"],
},
},
}
]
def chat_with_tools(user_message: str) -> str:
messages = [{"role": "user", "content": user_message}]
# Step 1: ask the LLM, and tell it which tools exist.
# The model autonomously decides whether to answer directly or emit a tool_calls request.
# reasoning_effort="none" is required for tool calling with this model in the Chat Completions API.
response = client.chat.completions.create(
model=MODEL,
messages=messages,
tools=tools,
# ... (see full file: 1_tool_calling_from_scratch.py)
$ python 2_SHARE_AFTER_Solution_Code/1_tool_calling_from_scratch.py
Q: Is 15241383937 the square of 123456?
[tool] square_root({'number': 15241383937}) -> 123456.00000405003
A: No. The square root of 15,241,383,937 is approximately 123,456.000004, so it is not the exact square of 123,456 (which is 15,241,383,936).
Q: What is the capital of France?
A: The capital of France is Paris.
Q: Can you calculate the square root of 2025 for me?
[tool] square_root({'number': 2025}) -> 45.0
A: The square root of 2025 is 45.
Tool Calling with LangChain#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/2_tool_calling_with_langchain.py, 2_SHARE_AFTER_Solution_Code/2_tool_calling_with_langchain.py
Concept#
LangChain keeps the exact same 4-step protocol as the from-scratch script, but removes the repetitive JSON schema authoring, manual argument parsing, and provider-specific boilerplate.
Key Mental Models#
- From Scratch (3.1) vs. LangChain (3.2) — what the framework automates:
- Describing the tool: Hand-written JSON Schema dict →
@tooldecorator, which auto-generates the schema from three Python elements: the function name, the docstring (description), and the type hints (parameter schema). - Attaching tools: Passing
tools=toolson every API call →llm.bind_tools(tools)once to create a tool-aware runnable. - Reading arguments: Manual
json.loads(tool_call.function.arguments)→tc["args"], already parsed into a Python dict. - Executing & returning results:
tool_map[fn_name](**fn_args)+ raw{"role": "tool", ...}dict →tool_map[tc["name"]].invoke(tc["args"])+ typedToolMessage(content=str(result), tool_call_id=tc["id"]). - Switching LLM providers: Rewriting SDK calls → changing a single line (the chat model class).
- Describing the tool: Hand-written JSON Schema dict →
- Offloading exact math catches subtle traps: On "Is 15241383937 the square of 123456?", the LLM delegates to
square_root, gets123456.00000405003, and correctly spots that the number is off by one (123456² = 15241383936) instead of hallucinating "yes".
Trade-Offs & Pitfalls#
- Use
response.text, notresponse.content: When tools are bound togpt-6-luna, LangChain routes through OpenAI's newer Responses API, whereresponse.contentis a list of structured content blocks ([{'type': 'text', ...}]). Readingresponse.textalways gives clean plain text. - Docstrings are now runtime prompts: Because
@toolturns the docstring into the tool's description, omitting or writing a sloppy docstring directly degrades the model's tool-selection accuracy.
LangChain preserves the exact 4-step message state machine under the hood while automating JSON Schema generation from Python type hints and docstrings, pre-parsing JSON arguments, and normalizing provider response blocks via response.text.
Code Reference#
import math
from dotenv import load_dotenv
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
load_dotenv()
# ----- TODO 1: Turn square_root into a LangChain tool -----
# @tool inspects the function name, type annotations (`number: float`), and docstring
# to auto-generate the exact JSON Schema we wrote by hand in script 1.
# Hint: Put the @tool decorator above the function
# Hint: The docstring becomes the tool description the LLM reads, so keep it clear
def square_root(number: float) -> float:
"""Calculate the square root of a non-negative number."""
return math.sqrt(number) # add the decorator above this function
tools = [square_root]
tool_map = {t.name: t for t in tools} # "square_root" -> the tool object
# bind_tools() attaches the generated JSON schemas to every subsequent LLM invocation.
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
llm_with_tools = llm.bind_tools(tools) # the LLM now knows the tool exists
def chat_with_tools(user_message: str) -> str:
messages = [HumanMessage(content=user_message)]
response = llm_with_tools.invoke(messages) # Step 1: ask
# Preserve the AIMessage (including its tool_calls metadata) before appending ToolMessages.
messages.append(response)
if not response.tool_calls: # Step 2: no tool needed
# .text = the answer as plain text. (With tools bound, LangChain talks to OpenAI's newer
# "Responses API", where .content is a list of blocks; .text joins them for us.)
return response.text
# ----- TODO 2: Run every requested tool and add a ToolMessage with its result -----
# ToolMessage ties each Python return value back to the model's exact request via tool_call_id.
# Hint: Each tool call is a dict with keys "name", "args" and "id"
# Hint: tool_map[tc["name"]].invoke(tc["args"]) runs the tool
# Hint: messages.append(ToolMessage(content=str(result), tool_call_id=tc["id"]))
pass # replace with your code
return llm_with_tools.invoke(messages).text # Step 4: final answer (.text = plain text)
if __name__ == "__main__":
# Peek at the JSON "menu" that @tool generated for us
print("Tool name :", square_root.name)
print("Tool description:", square_root.description)
print("Tool arguments :", square_root.args)
questions = [
"Is 15241383937 the square of 123456?", # a trap: 123456 squared is 15241383936
"What is the capital of France?",
"Can you calculate the square root of 2025 for me?",
]
for q in questions:
print(f"\nQ: {q}")
# ... (see full file: 2_tool_calling_with_langchain.py)
$ python 1_GIVE_FIRST_Starter_Code/2_tool_calling_with_langchain.py
# Before adding @tool in TODO 1:
AttributeError: 'function' object has no attribute 'name'
# Once TODO 1 (@tool) and TODO 2 (tool loop) are completed:
Tool name : square_root
Tool description: Calculate the square root of a non-negative number.
Tool arguments : {'number': {'title': 'Number', 'type': 'number'}}
import math
from dotenv import load_dotenv
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
load_dotenv()
# ----- TODO 1 (solved): Turn square_root into a LangChain tool -----
# @tool converts the function into a StructuredTool whose JSON Schema is derived
# automatically from its name, docstring, and Python type hints.
@tool
def square_root(number: float) -> float:
"""Calculate the square root of a non-negative number."""
if number < 0:
raise ValueError("Cannot compute square root of a negative number.")
return math.sqrt(number)
tools = [square_root]
tool_map = {t.name: t for t in tools} # "square_root" -> the tool object
# -> {'square_root': StructuredTool(name='square_root', args_schema=...)}
# bind_tools() serializes each tool's schema into the API request so the LLM can call it.
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
llm_with_tools = llm.bind_tools(tools) # the LLM now knows the tool exists
def chat_with_tools(user_message: str) -> str:
messages = [HumanMessage(content=user_message)]
response = llm_with_tools.invoke(messages) # Step 1: ask
# -> AIMessage(content='', tool_calls=[
# {'name': 'square_root', 'args': {'number': 15241383937}, 'id': 'call_abc123'}
# ])
# Keep the assistant's AIMessage (with tool_calls) in the conversation history.
messages.append(response)
if not response.tool_calls: # Step 2: no tool needed
# .text = the answer as plain text. (With tools bound, LangChain talks to OpenAI's newer
# "Responses API", where .content is a list of blocks; .text joins them for us.)
return response.text
# ----- TODO 2 (solved): Run every requested tool and add a ToolMessage with its result -----
# Unlike raw OpenAI dicts, LangChain parses tc["args"] from JSON into a Python dict for us.
for tc in response.tool_calls: # Step 3: run the tools
result = tool_map[tc["name"]].invoke(tc["args"])
# -> 123456.00000405003
print(f" [tool] {tc['name']}({tc['args']}) -> {result}")
messages.append(ToolMessage(content=str(result), tool_call_id=tc["id"]))
# -> messages now has 3 items:
# [HumanMessage(...), AIMessage(tool_calls=[...]),
# ToolMessage(content='123456.00000405003', tool_call_id='call_abc123')]
return llm_with_tools.invoke(messages).text # Step 4: final answer (.text = plain text)
if __name__ == "__main__":
# Peek at the JSON "menu" that @tool generated for us
print("Tool name :", square_root.name)
print("Tool description:", square_root.description)
print("Tool arguments :", square_root.args)
questions = [
"Is 15241383937 the square of 123456?", # a trap: 123456 squared is 15241383936
"What is the capital of France?",
"Can you calculate the square root of 2025 for me?",
]
for q in questions:
# ... (see full file: 2_tool_calling_with_langchain.py)
$ python 2_SHARE_AFTER_Solution_Code/2_tool_calling_with_langchain.py
Tool name : square_root
Tool description: Calculate the square root of a non-negative number.
Tool arguments : {'number': {'title': 'Number', 'type': 'number'}}
Q: Is 15241383937 the square of 123456?
[tool] square_root({'number': 15241383937}) -> 123456.00000405003
A: No — the square root of 15,241,383,937 is 123,456.000004, not 123,456 (123,456² = 15,241,383,936).
Q: What is the capital of France?
A: The capital of France is Paris.
Q: Can you calculate the square root of 2025 for me?
[tool] square_root({'number': 2025}) -> 45.0
A: The square root of 2025 is 45.
Multi-Tool Routing & Parameter Extraction (Warehouse Assistant)#
Revision Notes#
Reference files: 1_GIVE_FIRST_Starter_Code/3_inventory_tools_demo.py, 2_SHARE_AFTER_Solution_Code/3_inventory_tools_demo.py
Concept#
Real applications rarely expose just one tool. In the warehouse assistant demo, the LLM is bound to four distinct domain tools over an in-memory INVENTORY and DAILY_DEMAND dataset, and must both choose the right tool and extract typed parameters from plain-English questions:
get_stock_level(sku)— Checks current stock, reorder point, andOK/LOWstatus for a specific SKU.list_low_stock_items()— Takes no arguments; scans all SKUs at or below their reorder point.days_until_stockout(sku)— Estimates runway in days (stock / daily_demand).calculate_reorder_quantity(sku, lead_time_days=7)— Computes a rule-of-thumb order size (lead_time_demand + safety_buffer - stock) and estimated cost.
Key Mental Models#
- Docstrings act as routing rules: Phrases like "List all SKUs that are at or below their reorder point and need restocking" align directly with user intent ("Which items need to be reordered right now?"), enabling reliable single-step routing without brittle
if/elsekeyword matching. - Semantic parameter extraction: From "What quantity of SKU-003 should I order if my supplier takes 10 days to deliver?", the LLM maps
"SKU-003"→skuand"my supplier takes 10 days"→lead_time_days=10by reading parameter names, types (int), and descriptions. - Graceful error strings beat uncaught exceptions: When asked about a nonexistent item (like
SKU-999), returning"SKU SKU-999 not found."lets the LLM explain the problem politely instead of crashing the program. - Parallel tool calls work naturally in one round: Broad prompts (like "Show me everything about SKU-005") can cause the LLM to emit multiple entries in
response.tool_callsat once; thefor tc in response.tool_calls:loop executes all of them and appends aToolMessagefor each before the final synthesis.
Trade-Offs & Pitfalls#
- Overlapping tool descriptions break routing: If two tools share a vague description like "Get info about a SKU", the LLM cannot distinguish them and will pick randomly or call both unnecessarily.
- Registration drift (
KeyError): Defining a@toolfunction without adding it to bothtoolsandtool_mapprevents the LLM from seeing it or crashes dispatch at runtime. - Simplified business logic: The demo's reorder formula (
2 × lead_time_demand - stock) is an intentional rule of thumb for learning tool calling; production systems (and later modules) replace it with proper statistical safety-stock formulas.
Sharp, non-overlapping docstrings and typed signatures let the bound LLM route natural-language warehouse queries to the right domain function—or fan out parallel calls in one turn—while sequential dependencies motivate upgrading to a bounded while-loop.
Code Reference#
from dotenv import load_dotenv
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
load_dotenv()
# ----------------------------------------------------------------------------
# A tiny "database" (a Python dict) of warehouse items. SKU = Stock Keeping Unit = product id.
# reorder_point = when stock falls to this level or below, we should order more.
# ----------------------------------------------------------------------------
INVENTORY = {
"SKU-001": {"name": "Industrial Valve", "stock": 120, "reorder_point": 50, "unit_cost": 7000},
"SKU-002": {"name": "Hydraulic Pump", "stock": 18, "reorder_point": 25, "unit_cost": 35000},
"SKU-003": {"name": "Conveyor Belt", "stock": 5, "reorder_point": 10, "unit_cost": 17500},
"SKU-004": {"name": "Safety Helmet", "stock": 300, "reorder_point": 100, "unit_cost": 1000},
"SKU-005": {"name": "Pressure Gauge", "stock": 42, "reorder_point": 40, "unit_cost": 4500},
}
# How many units of each item we use per day (on average)
DAILY_DEMAND = {"SKU-001": 8, "SKU-002": 3, "SKU-003": 2, "SKU-004": 15, "SKU-005": 6}
# ----------------------------------------------------------------------------
# Tools. The docstring is what the LLM reads to decide WHICH tool to use, so it must be clear.
# Returning descriptive strings (rather than raising exceptions on missing SKUs) lets the LLM
# recover gracefully and explain the issue to the user.
# ----------------------------------------------------------------------------
@tool
def get_stock_level(sku: str) -> str:
"""Return current stock level and reorder point for a given SKU."""
# Normalize case so "sku-002" and "SKU-002" both resolve cleanly
sku = sku.upper()
item = INVENTORY.get(sku)
if not item:
return f"SKU {sku} not found."
status = "LOW" if item["stock"] <= item["reorder_point"] else "OK"
return f"{item['name']} ({sku}): stock={item['stock']}, reorder_point={item['reorder_point']}, status={status}"
@tool
def calculate_reorder_quantity(sku: str, lead_time_days: int = 7) -> str:
"""Calculate recommended reorder quantity for a SKU given supplier lead time in days."""
sku = sku.upper()
item = INVENTORY.get(sku)
if not item:
return f"SKU {sku} not found."
daily = DAILY_DEMAND.get(sku, 1)
# Simple rule of thumb (deterministic math kept in Python, not in the LLM):
# demand during delivery wait = daily demand x lead time
# safety buffer = the same amount again (in case of delays / spikes)
# order = (wait demand + buffer) - what we already have
lead_time_demand = daily * lead_time_days
safety_buffer = lead_time_demand
# Clamp at 0 so overstocked items never produce a negative order quantity
reorder_qty = max(lead_time_demand + safety_buffer - item["stock"], 0)
total_cost = reorder_qty * item["unit_cost"]
return (
f"{item['name']} ({sku}): recommend ordering {reorder_qty} units "
f"(lead_time_demand={lead_time_demand}, safety_buffer={safety_buffer}, "
f"lead_time={lead_time_days}d, estimated_cost=Rs {total_cost:,})"
)
# ... (see full file: 3_inventory_tools_demo.py)
$ python 1_GIVE_FIRST_Starter_Code/3_inventory_tools_demo.py
# Expected multi-tool trace once the starter's agent loop & low-stock tool TODOs are completed:
Q: Check stock for SKU-002 and tell me how many units to reorder if lead time is 7 days.
[tool] get_stock_level({'sku': 'SKU-002'}) -> Hydraulic Pump (SKU-002): stock=18, reorder_point=25, status=LOW
[tool] calculate_reorder_quantity({'sku': 'SKU-002', 'lead_time_days': 7}) -> Hydraulic Pump (SKU-002): recommend ordering 24 units (lead_time_demand=21, safety_buffer=21, lead_time=7d, estimated_cost=Rs 840,000)
A: Hydraulic Pump (SKU-002) is currently LOW (18 units vs. reorder point 25). With a 7-day lead time, order 24 units (estimated cost: Rs 840,000).
from dotenv import load_dotenv
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
load_dotenv()
# ----------------------------------------------------------------------------
# A tiny "database" (a Python dict) of warehouse items. SKU = Stock Keeping Unit = product id.
# reorder_point = when stock falls to this level or below, we should order more.
# ----------------------------------------------------------------------------
INVENTORY = {
"SKU-001": {"name": "Industrial Valve", "stock": 120, "reorder_point": 50, "unit_cost": 7000},
"SKU-002": {"name": "Hydraulic Pump", "stock": 18, "reorder_point": 25, "unit_cost": 35000},
"SKU-003": {"name": "Conveyor Belt", "stock": 5, "reorder_point": 10, "unit_cost": 17500},
"SKU-004": {"name": "Safety Helmet", "stock": 300, "reorder_point": 100, "unit_cost": 1000},
"SKU-005": {"name": "Pressure Gauge", "stock": 42, "reorder_point": 40, "unit_cost": 4500},
}
# How many units of each item we use per day (on average)
DAILY_DEMAND = {"SKU-001": 8, "SKU-002": 3, "SKU-003": 2, "SKU-004": 15, "SKU-005": 6}
# ----------------------------------------------------------------------------
# Tools. The docstring is what the LLM reads to decide WHICH tool to use, so it must be clear.
# Keeping each tool narrowly focused (single responsibility) makes multi-tool routing reliable.
# ----------------------------------------------------------------------------
@tool
def get_stock_level(sku: str) -> str:
"""Return current stock level and reorder point for a given SKU."""
sku = sku.upper()
item = INVENTORY.get(sku)
# -> {'name': 'Hydraulic Pump', 'stock': 18, 'reorder_point': 25, 'unit_cost': 35000}
if not item:
return f"SKU {sku} not found."
status = "LOW" if item["stock"] <= item["reorder_point"] else "OK"
# -> 'LOW' (for SKU-002: 18 <= 25)
return f"{item['name']} ({sku}): stock={item['stock']}, reorder_point={item['reorder_point']}, status={status}"
@tool
def calculate_reorder_quantity(sku: str, lead_time_days: int = 7) -> str:
"""Calculate recommended reorder quantity for a SKU given supplier lead time in days."""
sku = sku.upper()
item = INVENTORY.get(sku)
if not item:
return f"SKU {sku} not found."
daily = DAILY_DEMAND.get(sku, 1)
# Simple rule of thumb (exact arithmetic executed in Python, returned as grounded facts):
# demand during delivery wait = daily demand x lead time
# safety buffer = the same amount again (in case of delays / spikes)
# order = (wait demand + buffer) - what we already have
lead_time_demand = daily * lead_time_days
# -> 21 (for SKU-002: 3 units/day * 7 days)
safety_buffer = lead_time_demand
# Clamp at 0 so well-stocked SKUs never return a negative reorder recommendation
reorder_qty = max(lead_time_demand + safety_buffer - item["stock"], 0)
# -> 24 (max(21 + 21 - 18, 0))
total_cost = reorder_qty * item["unit_cost"]
# -> 840000 (24 * Rs 35,000)
return (
f"{item['name']} ({sku}): recommend ordering {reorder_qty} units "
f"(lead_time_demand={lead_time_demand}, safety_buffer={safety_buffer}, "
f"lead_time={lead_time_days}d, estimated_cost=Rs {total_cost:,})"
)
# ... (see full file: 3_inventory_tools_demo.py)
$ python 2_SHARE_AFTER_Solution_Code/3_inventory_tools_demo.py
Q: Which SKUs are running low and how much should we reorder for each?
[tool] list_low_stock_skus({}) -> Low stock SKUs: SKU-002 (Hydraulic Pump, 18/25), SKU-003 (Conveyor Belt, 5/10)
[tool] calculate_reorder_quantity({'sku': 'SKU-002', 'lead_time_days': 7}) -> Hydraulic Pump (SKU-002): recommend ordering 24 units (lead_time_demand=21, safety_buffer=21, lead_time=7d, estimated_cost=Rs 840,000)
[tool] calculate_reorder_quantity({'sku': 'SKU-003', 'lead_time_days': 7}) -> Conveyor Belt (SKU-003): recommend ordering 23 units (lead_time_demand=14, safety_buffer=14, lead_time=7d, estimated_cost=Rs 402,500)
A: Two SKUs are below their reorder points:
- Hydraulic Pump (SKU-002): 18 in stock (reorder point 25) -> order 24 units (~Rs 840,000).
- Conveyor Belt (SKU-003): 5 in stock (reorder point 10) -> order 23 units (~Rs 402,500).
Single-Round Limits, Multi-Step Loops & Tool Safety#
Revision Notes#
Reference files: 1_GIVE_FIRST_Exercise_Questions.html, 2_SHARE_AFTER_Solution_Explainer.html
Concept#
Exercises 3.1–3.3 intentionally use a single-round pattern (at most two LLM calls: one to request tools, one to write the final answer). Understanding where this breaks — and which tools are safe to expose — bridges basic tool calling to full AI agents.
Key Mental Models#
- Single-round vs. multi-step agent loop:
- Works in 1 round (parallel): Calling multiple independent tools at once (e.g., stock level + days until stockout for
SKU-005), because none of them depend on another tool's output. - Breaks in 1 round (sequential / chained): Questions where Tool B needs Tool A's output (e.g., "Find which items are low in stock, then calculate the reorder quantity for each"). Because the script forces a final text answer after the first tool round, the second step never runs.
- The fix: Replace the two-call structure with a
whileloop that keeps invoking the LLM and executing tools untilresponse.tool_callsis empty (the foundation of an agent loop).
- Works in 1 round (parallel): Calling multiple independent tools at once (e.g., stock level + days until stockout for
- Risk tiers for exposing tools:
- Read-only tools (stock lookup, calculations): Low risk — mistakes only affect the answer, not external state.
- State-changing / side-effect tools (placing purchase orders, transferring money, deleting records, sending emails): High risk — an LLM can misunderstand an instruction or be manipulated by untrusted text (prompt injection).
Trade-Offs & Pitfalls#
- Never expose destructive or financial tools unchecked: Side-effecting tools require strict input validation in code and a human-in-the-loop approval step before execution.
- Unbounded loops need guardrails: Once you upgrade from 1 round to a
whileloop, you also need a max-iteration cap so a confused model cannot loop forever.
How All Building Blocks Connect#
Revision Notes#
This module builds tool calling in three deliberate layers, followed by the bridge to agents:
- Layer 1 — Raw Protocol (
1_tool_calling_from_scratch.py): Proves that tool calling is just a 4-step message-passing contract (JSON Schema menu →tool_callsrequest → local Python execution +role: "tool"withtool_call_id→ final LLM answer). - Layer 2 — Framework Ergonomics (
2_tool_calling_with_langchain.py): Replaces manual JSON schemas,json.loads, and provider lock-in with@tool,llm.bind_tools(tools),tool.invoke(...),ToolMessage, andresponse.text. - Layer 3 — Real-World Routing (
3_inventory_tools_demo.py): Scales the same 4-step pattern to four warehouse tools, showing how clear docstrings and typed parameters drive tool selection and argument extraction from natural language. - Next Step — Agent Loops & Safety: Recognizing that sequential multi-tool questions break a 2-call script motivates the
while-loop agent pattern, while distinguishing read-only vs. write tools establishes the baseline for safe tool design.
Quick Self-Check Questions#
Self-Check Questions#
Does the LLM ever execute your Python tool function directly?
No. The LLM only returns a structured request (name, arguments, id) in tool_calls. Your Python code executes the function and sends the result back in a tool message.
Why must every tool result include a matching tool_call_id?
An LLM can request multiple tools in a single turn. tool_call_id pairs each result with the exact request it answers (like a table number on an order slip), and the API rejects mismatched or missing IDs.
What three parts of a Python function does LangChain's @tool decorator inspect to build the JSON tool schema?
The function name, the docstring (tool description), and the type hints (argument names and types).
Why do Scripts 3.2 and 3.3 read response.text instead of response.content?
With tools bound on gpt-6-luna, LangChain uses OpenAI's Responses API, where response.content is a list of content blocks rather than a plain string. response.text always extracts the clean plain-text answer.
What happens if two tools have nearly identical or vague docstrings?
Because the LLM relies on docstrings to choose tools, overlapping descriptions cause it to pick arbitrarily between them or call both unnecessarily.
What kind of question breaks the 2-call structure used in Scripts 3.1–3.3, and how do you fix it?
A sequential multi-step question where the second tool depends on the first tool's output (e.g., finding low-stock SKUs and then calculating reorder quantities for each). The fix is a loop that keeps calling the LLM until it stops requesting tools.
How should you treat read-only tools differently from state-changing tools (like placing orders or deleting records)?
Read-only tools are low risk, whereas state-changing tools must validate inputs strictly and require a human approval step because LLMs can misunderstand intent or be tricked by untrusted text.