Skip to main content

How to access the RunnableConfig object within a custom tool

Prerequisites

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:


Was this page helpful?


You can also leave detailed feedback on GitHub.