How to access the RunnableConfig from a tool
This guide assumes familiarity with the following concepts:
Tools are runnables, and you can treat them the same way as any other
runnable at the interface level - you can call invoke()
, batch()
,
and stream()
on them as normal. However, when writing custom tools,
you may want to invoke other runnables like chat models or retrievers.
In order to properly trace and configure those sub-invocations, youโll
need to manually access and pass in the toolโs current
RunnableConfig
object.
This guide covers how to do this for custom tools created in different ways.
From the tool
methodโ
Accessing the RunnableConfig
object for a custom tool created with the
tool
helper method is simple - itโs always the second parameter passed into
your custom function. Hereโs an example:
import { z } from "zod";
import { tool } from "@langchain/core/tools";
import type { RunnableConfig } from "@langchain/core/runnables";
const reverseTool = tool(
async (input: { text: string }, config?: RunnableConfig) => {
const originalString =
input.text + (config?.configurable?.additional_field ?? "");
return originalString.split("").reverse().join("");
},
{
name: "reverse",
description:
"A test tool that combines input text with a configurable parameter.",
schema: z.object({
text: z.string(),
}),
}
);
Then, if we invoke the tool with a config
containing a configurable
field, we can see that additional_field
is passed through correctly:
await reverseTool.invoke(
{ text: "abc" },
{ configurable: { additional_field: "123" } }
);
321cba
Next stepsโ
Youโve now seen how to configure and stream events from within a tool. Next, check out the following guides for more on using tools:
- Pass tool results back to a model
- Building tool-using chains and agents
- Getting structured outputs from models