Tools and Tool Calling
A tool is a typed, documented function the model can ask you to run. The model never executes anything: it returns structured requests in `AIMessage.tool_calls`, and your code (or `create_agent`) runs each tool and answers with a `ToolMessage` linked by `tool_call_id`. Know how schemas are built, how to control tool choice, how errors and hidden arguments work, and how to write the loop by hand.
Key points
- 1
@toolturns a function into aStructuredTool. Name: the function name unless you pass one (@tool("web_search")). Description:description=, else the docstring, else theargs_schemadocstring; with none of these the decorator raisesValueError. Type hints are required and become the argument schema. - 2
The model sees only name, description and argument JSON schema (inspect with
tool.args,tool.tool_call_schemaorconvert_to_openai_tool(tool)). Defaults show asdefaultand drop out ofrequired;Annotated[str, "text"]adds a description;Literal[...]becomes anenum. The body and return type are never sent. - 3
parse_docstring=Truereads a Google-styleArgs:section into per-argument descriptions and keeps only the summary as the description; without it the whole docstring is the description. For constraints, pass a Pydanticargs_schema(Field(ge=1, description=...)), which is both shown to the model and enforced on invoke. Validation is Pydantic lax mode, so"3"is coerced to3. - 4
Other ways to build tools:
StructuredTool.from_function(func, coroutine=..., name=..., description=..., args_schema=...), aBaseToolsubclass implementing_run(and optionally_arun), or a toolkit'sget_tools(). Without a native async implementation,ainvokeruns the sync function in a thread executor. - 5
llm = model.bind_tools(tools)returns a new Runnable; the original model is unchanged.tool_choice="any"forces some tool call,tool_choice="<name>"forces that tool, andparallel_tool_calls=Falseasks supported providers (for example OpenAI, Anthropic) for at most one call per turn. - 6
AIMessage.tool_callsis a list of{name, args (dict), id, type: "tool_call"}; it is empty when the model answers directly. Unparseable calls go toinvalid_tool_calls(name, rawargsstring,id,error). Streamed calls arrive astool_call_chunksthat merge byindexwhen you add chunks together. - 7
tool.invoke(args_dict)returns the raw result;tool.invoke(tool_call)(the dict must includetype: "tool_call") returns aToolMessagewith stringified content, the toolnameand the matchingtool_call_id. Dict and list returns are serialised to JSON text. - 8
Manual loop: invoke the bound model, append the
AIMessage, run every tool call and append oneToolMessageper call (each with its own id), invoke again, and stop when there are no tool calls. Add an iteration cap, handle unknown tool names andinvalid_tool_calls, and usebatch(..., return_exceptions=True)to run parallel calls concurrently without losing results. - 9
response_format="content_and_artifact": the tool returns(content, artifact); the model seescontent, andToolMessage.artifactkeeps raw data (rows, document ids) for your code only. Returning anything other than a two-tuple raisesValueError. - 10
Errors: raise
ToolExceptionfor expected failures.handle_tool_error(Falsere-raises,Truereturns the message, a string returns that string, a callable builds the output) applies only toToolException;handle_validation_errordoes the same for bad arguments. Handled results invoked via a tool call becomeToolMessage(status="error"). Increate_agent, broader handling lives in tool middleware. - 11
Hidden arguments:
runtime: ToolRuntime(1.x recommendation) gives agent toolsstate,context,store,stream_writer,configandtool_call_id. Older markers areInjectedToolArg(your code supplies the value),InjectedToolCallId,InjectedStateandInjectedStore. All are excluded from the model's schema;configandruntimeare reserved parameter names. - 12
MCP standardises how servers expose tools and context. LangChain adapts MCP tools into ordinary tools (
langchain.mcp.MCPAdapterwithawait adapter.list_tools()in langchain 1.4+, beta;langchain-mcp-adaptersbefore that), and the model still invokes them through tool calls.
Common traps
Calling
model.bind_tools(...)without using its return value: the tools are never sent.Building
ToolMessage(tool_call_id="1")by hand: the id must match the request, so pass the tool call totool.invokeinstead.Answering only some of the parallel tool calls in a turn: every call needs its own
ToolMessagebefore the next model call.Expecting
handle_tool_error=Trueto catch aKeyError: it only handlesToolException.Treating
InjectedToolArgas a security boundary: it hides the argument from the schema, but a model can still put the key inargs, so overwrite injected values in code.Stopping the loop on
not ai.tool_callsalone, which mistakes a malformed call ininvalid_tool_callsfor a final answer, and looping without a step budget.Reading
tool_callson a single streamed chunk: it is a partial parse; accumulate chunks first.
Read the source
Further reading
Suggest a resourceNo extra reading for Tools and Tool Calling yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on Tools and Tool Calling
Ten questions, with the answer and explanation after each one.