How to pass run time values to tools
Source: langchain

# How to pass run time values to toolsimport Prerequisites from "@theme/Prerequisites";import Compatibility from "@theme/Compatibility";<Prerequisites titlesAndLinks={[  ["Chat models", "/docs/concepts/#chat-models"],  ["LangChain Tools", "/docs/concepts/#tools"],  ["How to create tools", "/docs/how_to/custom_tools"],  ["How to use a model to call tools", "/docs/how_to/tool_calling"],]} /><Compatibility packagesAndVersions={[  ["langchain-core", "0.2.21"],]} />You may need to bind values to a tool that are only known at runtime. For example, the tool logic may require using the ID of the user who made the request.Most of the time, such values should not be controlled by the LLM. In fact, allowing the LLM to control the user ID may lead to a security risk.Instead, the LLM should only control the parameters of the tool that are meant to be controlled by the LLM, while other parameters (such as user ID) should be fixed by the application logic.This how-to guide shows you how to prevent the model from generating certain tool arguments and injecting them in directly at runtime.:::info Using with LangGraphIf you're using LangGraph, please refer to [this how-to guide](https://langchain-ai.github.io/langgraph/how-tos/pass-run-time-values-to-tools/)which shows how to create an agent that keeps track of a given user's favorite pets.:::We can bind them to chat models as follows:```{=mdx}import ChatModelTabs from "@theme/ChatModelTabs";<ChatModelTabs  customVarName="llm"  fireworksParams={`model="accounts/fireworks/models/firefunction-v1", temperature=0`}/>``````python# | output: false# | echo: false# %pip install -qU langchain langchain_openaiimport osfrom getpass import getpassfrom langchain_openai import ChatOpenAIif "OPENAI_API_KEY" not in os.environ:    os.environ["OPENAI_API_KEY"] = getpass()llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)```## Hiding arguments from the modelWe can use the InjectedToolArg annotation to mark certain parameters of our Tool, like `user_id` as being injected at runtime, meaning they shouldn't be generated by the model```pythonfrom typing import Listfrom langchain_core.tools import InjectedToolArg, toolfrom typing_extensions import Annotateduser_to_pets = {}@tool(parse_docstring=True)def update_favorite_pets(    pets: List[str], user_id: Annotated[str, InjectedToolArg]) -> None:    """Add the list of favorite pets.    Args:        pets: List of favorite pets to set.        user_id: User's ID.    """    user_to_pets[user_id] = pets@tool(parse_docstring=True)def delete_favorite_pets(user_id: Annotated[str, InjectedToolArg]) -> None:    """Delete the list of favorite pets.    Args:        user_id: User's ID.    """    if user_id in user_to_pets:        del user_to_pets[user_id]@tool(parse_docstring=True)def list_favorite_pets(user_id: Annotated[str, InjectedToolArg]) -> None:    """List favorite pets if any.    Args:        user_id: User's ID.    """    return user_to_pets.get(user_id, [])```If we look at the input schemas for these tools, we'll see that user_id is still listed:```pythonupdate_favorite_pets.get_input_schema().schema()```    {'title': 'update_favorite_petsSchema',     'description': 'Add the list of favorite pets.',     'type': 'object',     'properties': {'pets': {'title': 'Pets',       'description': 'List of favorite pets to set.',       'type': 'array',       'items': {'type': 'string'}},      'user_id': {'title': 'User Id',       'description': "User's ID.",       'type': 'string'}},     'required': ['pets', 'user_id']}But if we look at the tool call schema, which is what is passed to the model for tool-calling, user_id has been removed:```pythonupdate_favorite_pets.tool_call_schema.schema()```    {'title': 'update_favorite_pets',     'description': 'Add the list of favorite pets.',     'type': 'object',     'properties': {'pets': {'title': 'Pets',       'description': 'List of favorite pets to set.',       'type': 'array',       'items': {'type': 'string'}}},     'required': ['pets']}So when we invoke our tool, we need to pass in user_id:```pythonuser_id = "123"update_favorite_pets.invoke({"pets": ["lizard", "dog"], "user_id": user_id})print(user_to_pets)print(list_favorite_pets.invoke({"user_id": user_id}))```    {'123': ['lizard', 'dog']}    ['lizard', 'dog']But when the model calls the tool, no user_id argument will be generated:```pythontools = [    update_favorite_pets,    delete_favorite_pets,    list_favorite_pets,]llm_with_tools = llm.bind_tools(tools)ai_msg = llm_with_tools.invoke("my favorite animals are cats and parrots")ai_msg.tool_calls```    [{'name': 'update_favorite_pets',      'args': {'pets': ['cats', 'parrots']},      'id': 'call_W3cn4lZmJlyk8PCrKN4PRwqB',      'type': 'tool_call'}]## Injecting arguments at runtimeIf we want to actually execute our tools using the model-generated tool call, we'll need to inject the user_id ourselves:```pythonfrom copy import deepcopyfrom langchain_core.runnables import chain@chaindef inject_user_id(ai_msg):    tool_calls = []    for tool_call in ai_msg.tool_calls:        tool_call_copy = deepcopy(tool_call)        tool_call_copy["args"]["user_id"] = user_id        tool_calls.append(tool_call_copy)    return tool_callsinject_user_id.invoke(ai_msg)```    [{'name': 'update_favorite_pets',      'args': {'pets': ['cats', 'parrots'], 'user_id': '123'},      'id': 'call_W3cn4lZmJlyk8PCrKN4PRwqB',      'type': 'tool_call'}]And now we can chain together our model, injection code, and the actual tools to create a tool-executing chain:```pythontool_map = {tool.name: tool for tool in tools}@chaindef tool_router(tool_call):    return tool_map[tool_call["name"]]chain = llm_with_tools | inject_user_id | tool_router.map()chain.invoke("my favorite animals are cats and parrots")```    [ToolMessage(content='null', name='update_favorite_pets', tool_call_id='call_HUyF6AihqANzEYxQnTUKxkXj')]Looking at the user_to_pets dict, we can see that it's been updated to include cats and parrots:```pythonuser_to_pets```    {'123': ['cats', 'parrots']}## Other ways of annotating argsHere are a few other ways of annotating our tool args:```pythonfrom langchain_core.pydantic_v1 import BaseModel, Fieldfrom langchain_core.tools import BaseToolclass UpdateFavoritePetsSchema(BaseModel):    """Update list of favorite pets"""    pets: List[str] = Field(..., description="List of favorite pets to set.")    user_id: Annotated[str, InjectedToolArg] = Field(..., description="User's ID.")@tool(args_schema=UpdateFavoritePetsSchema)def update_favorite_pets(pets, user_id):    user_to_pets[user_id] = petsupdate_favorite_pets.get_input_schema().schema()```    {'title': 'UpdateFavoritePetsSchema',     'description': 'Update list of favorite pets',     'type': 'object',     'properties': {'pets': {'title': 'Pets',       'description': 'List of favorite pets to set.',       'type': 'array',       'items': {'type': 'string'}},      'user_id': {'title': 'User Id',       'description': "User's ID.",       'type': 'string'}},     'required': ['pets', 'user_id']}```pythonupdate_favorite_pets.tool_call_schema.schema()```    {'title': 'update_favorite_pets',     'description': 'Update list of favorite pets',     'type': 'object',     'properties': {'pets': {'title': 'Pets',       'description': 'List of favorite pets to set.',       'type': 'array',       'items': {'type': 'string'}}},     'required': ['pets']}```pythonfrom typing import Optional, Typeclass UpdateFavoritePets(BaseTool):    name: str = "update_favorite_pets"    description: str = "Update list of favorite pets"    args_schema: Optional[Type[BaseModel]] = UpdateFavoritePetsSchema    def _run(self, pets, user_id):        user_to_pets[user_id] = petsUpdateFavoritePets().get_input_schema().schema()```    {'title': 'UpdateFavoritePetsSchema',     'description': 'Update list of favorite pets',     'type': 'object',     'properties': {'pets': {'title': 'Pets',       'description': 'List of favorite pets to set.',       'type': 'array',       'items': {'type': 'string'}},      'user_id': {'title': 'User Id',       'description': "User's ID.",       'type': 'string'}},     'required': ['pets', 'user_id']}```pythonUpdateFavoritePets().tool_call_schema.schema()```    {'title': 'update_favorite_pets',     'description': 'Update list of favorite pets',     'type': 'object',     'properties': {'pets': {'title': 'Pets',       'description': 'List of favorite pets to set.',       'type': 'array',       'items': {'type': 'string'}}},     'required': ['pets']}```pythonclass UpdateFavoritePets2(BaseTool):    name: str = "update_favorite_pets"    description: str = "Update list of favorite pets"    def _run(self, pets: List[str], user_id: Annotated[str, InjectedToolArg]) -> None:        user_to_pets[user_id] = petsUpdateFavoritePets2().get_input_schema().schema()```    {'title': 'update_favorite_petsSchema',     'description': 'Use the tool.\n\nAdd run_manager: Optional[CallbackManagerForToolRun] = None\nto child implementations to enable tracing.',     'type': 'object',     'properties': {'pets': {'title': 'Pets',       'type': 'array',       'items': {'type': 'string'}},      'user_id': {'title': 'User Id', 'type': 'string'}},     'required': ['pets', 'user_id']}```pythonUpdateFavoritePets2().tool_call_schema.schema()```    {'title': 'update_favorite_pets',     'description': 'Update list of favorite pets',     'type': 'object',     'properties': {'pets': {'title': 'Pets',       'type': 'array',       'items': {'type': 'string'}}},     'required': ['pets']}