AI Hints
Home›LangChain Tutorial›Tool Calls by Hand
LangChain · Lesson 42 of 120

Running Tools Yourself

ToolMessage.

⏱ 2 min read▶ Video at 45:54🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

The model has asked for a tool. Now our code runs it, and sends the result back, as a tool message. Then the model can write its final answer.

Running Tools Yourself
From the video: Running Tools Yourself
  • Run the tool
  • Send a ToolMessage
  • Get the final answer

The full round trip

Here's the full loop, by hand. We keep a message list. The model replies with tool calls, and we add that reply to the list. For each call, we run the tool, and add a tool message with the result and the matching ID. Then we call the model again. Run it. The final answer uses the real stock numbers.

round_trip.pypython
from langchain.tools import tool
from langchain.messages import ToolMessage
from langchain.chat_models import init_chat_model

@tool
def check_stock(title: str) -> int:
    """Return how many copies of a book Riverside Books has in stock."""
    return {"Dune": 3, "Circe": 0}.get(title, 0)

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
llm = model.bind_tools([check_stock])

messages = [{"role": "user", "content": "Do you have Dune and Circe? One sentence."}]
reply = llm.invoke(messages)
messages.append(reply)
for call in reply.tool_calls:
    result = check_stock.invoke(call["args"])
    messages.append(ToolMessage(str(result), tool_call_id=call["id"]))
print(llm.invoke(messages).text)
Output
We currently have *Dune* in stock, but unfortunately, we are out of stock for *Circe*.

Why this matters

Doing this by hand once shows exactly what agents do. Every agent, however fancy, runs this loop. Ask the model, run any tools it requests, send the results back, and repeat, until it answers without asking for a tool.

keyvalue
1ask the model
2run requested tools
3send ToolMessages back
4repeat until no tool calls

Summary

Run each requested tool, send results back as tool messages with matching IDs, and call the model again. That loop is the heart of every agent. Next, the agent loop itself.

Key takeaways
  • Append the AI reply
  • ToolMessage per call
  • Call again
Next up: The Agent Loop — think, act, observe