Generative AIby Dhruv Narang

1. Make a Tool

Put @tool above a normal function. The docstring tells the LLM when to use it, and the type hints tell it what to send.

What does @tool do? It turns a normal function into a tool object. Your code inside the function does not change. LangChain wraps it and fills in the rest from your function.
The tool hasIt comes from
.namethe function name, like multiply
.descriptionthe docstring
.argsthe type hints, a: int, b: int
.invoke({...})the way to run it: the arguments go in a dictionary
If you print a tool, you see name, description, args_schema and func. The args_schema holds the arguments. .args is made from it. func is your own function, kept inside the tool.
It is not a plain function any more. multiply(45, 12) gives an error. Run it with multiply.invoke({'a': 45, 'b': 12}), and you get 540.
Why does this matter? The model needs a name, a description and the arguments to choose a tool. @tool makes all three for you.
from langchain_core.tools import tool

@tool
def add(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

@tool
def multiply(a: int, b: int) -> int:
    """Multiply two numbers together."""
    return a * b

2. Attach the Tools: bind_tools

The model has to know which tools you have. You give them with bind_tools. After that, the model can ask for any of them.

Give the tools to the model. bind_tools attaches the tools to the model. Every call now carries the tools with it. llm itself does not change.
tools = [add, multiply]
llm_with_tools = llm.bind_tools(tools)
What the model gets. Not the Python code. It gets a short description of each tool, made from your function. This is all the model knows about the tool.
The model getsIt comes from
namethe function name, multiply
descriptionthe docstring, """Multiply two numbers together."""
argumentsthe type hints, a: int, b: int
Why the docstring matters. It is how the model knows what the tool does. Without a docstring, @tool gives an error. With a vague name and no description, the model does not use the tool at all. You do not write the tools into the system prompt. bind_tools does that part.
The model decides. It asks for a tool only when it needs one.
You askThe model answers
What is 45 multiplied by 12?a tool call: multiply with a=45, b=12. No text yet.
Say hello in one word.Hello. No tool call.
Example answers. Yours will be different.
The model only asks. It never runs the tool. We run it, and we send the result back. Then the model writes the answer.
flowchart LR
  Q(["Question"]) --> M1["Model<br/>asks for a tool"] --> T["We run<br/>the tool"] --> M2["Model<br/>reads the result"] --> A(["Final answer"])
  class Q,A term
  class M1,M2 step
  class T fn
classDef term fill:#0e3b3a,stroke:#0e3b3a,color:#ffffff,font-weight:bold
classDef step fill:#d4ecea,stroke:#2a7a79,color:#0e3b3a
classDef fn fill:#fbe5dc,stroke:#c9583a,color:#7a2e1a
Keep the order of the messages. Question, then the model's tool call, then the tool result, then the final answer. Add the model's tool call to the list before the tool result.
Why tool_call_id? The model can ask for more than one tool in one answer. The id tells which result belongs to which call. It is a name of ToolMessage, and you must give it. The value comes from the model: use tool_call["id"].

3. One Tool: Call It Directly

The LLM answers with a tool call: the tool name and the arguments. If you have one tool, you do not need to look anything up. Call the tool yourself with those arguments.

tool_call = ai_message.tool_calls[0]
tool_output = multiply.invoke(tool_call["args"])
The LLM sends
[{'name': 'multiply', 'args': {'a': 45, 'b': 12}, 'id': '…'}]
We call
multiply.invoke({'a': 45, 'b': 12})
The tool returns
540
Example values. This is a short version of the loop in your file, for one tool. Your file works for many tools, as you see next.

4. Many Tools: A Dictionary

With many tools, the LLM can ask for any of them, and it only sends the name as a string. So we keep our tools in a dictionary: the name is the key, the tool is the value.

tools_by_name = {}
for t in tools:
    tools_by_name[t.name] = t
What it does
For every tool t in the list, it saves the tool under its own name.
The result
{'add': add, 'multiply': multiply} the key is the tool name, the value is the tool itself.
Why? So that when the LLM gives us the string 'multiply', we can get the multiply tool with tools_by_name['multiply'].
A shorter way
tools_by_name = {t.name: t for t in tools}
Does the same thing in one line. This is the line in your file.

5. Many Tools: Find the Tool by Name

We use the name the LLM sent to find the tool in the dictionary, then run it. The LLM can ask for more than one tool call in one answer, so we loop over them.

tools_by_name = {t.name: t for t in tools}

for tool_call in ai_message.tool_calls:
    tool_name = tool_call["name"]
    selected_tool = tools_by_name[tool_name]
    argument = tool_call["args"]
    tool_output = selected_tool.invoke(argument)

    messages.append(ToolMessage(
        content=str(tool_output),
        tool_call_id=tool_call["id"]
    ))
The LLM sends
The tool name, as a string: tool_name is 'multiply'
We find the tool
tools_by_name[tool_name] gives the multiply tool. The tool name and the function name are the same, so the lookup just works.
Example values. After the lookup we run the tool. argument is what the LLM sent, like {'a': 45, 'b': 12}. selected_tool.invoke(argument) runs the tool and gives tool_output.
Code
Tool calling with your own tools01_tool_calling.py · 48 linesShow code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from dotenv import load_dotenv
load_dotenv()

from langchain.chat_models import init_chat_model
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, ToolMessage

@tool
def add(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

@tool
def multiply(a: int, b: int) -> int:
    """Multiply two numbers together."""
    return a * b

tools = [add, multiply]
tools_by_name = {t.name: t for t in tools}

llm = init_chat_model("groq:openai/gpt-oss-20b")
llm_with_tools = llm.bind_tools(tools)

query = "What is 45 multiplied by 12?"
messages = [HumanMessage(content=query)]

ai_message = llm_with_tools.invoke(messages)
messages.append(ai_message)

print("Tool Requested by LLM:", ai_message.tool_calls)

for tool_call in ai_message.tool_calls:
    selected_tool = tools_by_name[tool_call["name"]]

    tool_output = selected_tool.invoke(tool_call["args"])

    messages.append(ToolMessage(
        content=str(tool_output),
        tool_call_id=tool_call["id"]
    ))

print("Tool Output:", tool_output)

final_response = llm_with_tools.invoke(messages)

print("\nFinal Answer:")
print(final_response.content)
Tool calling chatbot with history01_tool_calling_chatbot.py · 48 linesShow code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from dotenv import load_dotenv
load_dotenv()

from langchain.chat_models import init_chat_model
from langchain.tools import tool
from langchain.messages import HumanMessage, ToolMessage, SystemMessage

model = init_chat_model("groq:openai/gpt-oss-20b")

@tool
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b

@tool
def multiply(a: int, b: int) -> int:
    """Multiply two numbers"""
    return a * b

tools = [add, multiply]
model_with_tools = model.bind_tools(tools)
tools_by_name = {t.name: t for t in tools}

messages = [SystemMessage("use add and multiply tool for adding and multiplication")]

while True:
    prompt = input("human : (enter exit to leave)")
    if prompt == "exit":
        break
    messages.append(HumanMessage(content=prompt))

    ai_message = model_with_tools.invoke(messages)
    messages.append(ai_message)

    if ai_message.tool_calls:
        for tool_call in ai_message.tool_calls:
            tool_name = tool_call["name"]
            selected_tool = tools_by_name[tool_name]
            argument = tool_call["args"]
            tool_output = selected_tool.invoke(argument)
            messages.append(ToolMessage(content=str(tool_output), tool_call_id=tool_call["id"]))
            print("Tool Output:", tool_output)

        ai_message = model.invoke(messages)
        messages.append(ai_message)

    print(f"ai: {ai_message.content}")