feat(docs): dynamic model and tool selection in create react agent (#5777)

Document dynamic models and dynamic tools
This commit is contained in:
Eugene Yurtsev
2025-07-31 11:22:30 -04:00
committed by GitHub
parent 18887e9f86
commit 116121eb3a
2 changed files with 146 additions and 0 deletions
+76
View File
@@ -172,6 +172,82 @@ await agent.invoke({
:::
:::python
### Dynamically select tools
Configure tool availability at runtime based on context:
```python
from dataclasses import dataclass
from typing import Literal
from langchain.chat_models import init_chat_model
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agent
from langgraph.prebuilt.chat_agent_executor import AgentState
from langgraph.runtime import Runtime
@dataclass
class CustomContext:
tools: list[Literal["weather", "compass"]]
@tool
def weather() -> str:
"""Returns the current weather conditions."""
return "It's nice and sunny."
@tool
def compass() -> str:
"""Returns the direction the user is facing."""
return "North"
model = init_chat_model("anthropic:claude-sonnet-4-20250514")
# highlight-next-line
def configure_model(state: AgentState, runtime: Runtime[CustomContext]):
"""Configure the model with tools based on runtime context."""
selected_tools = [
tool
for tool in [weather, compass]
if tool.name in runtime.context.tools
]
return model.bind_tools(selected_tools)
agent = create_react_agent(
# Dynamically configure the model with tools based on runtime context
# highlight-next-line
configure_model,
# Initialize with all tools available
# highlight-next-line
tools=[weather, compass]
)
output = agent.invoke(
{
"messages": [
{
"role": "user",
"content": "Who are you and what tools do you have access to?",
}
]
},
# highlight-next-line
context=CustomContext(tools=["weather"]), # Only enable the weather tool
)
print(output["messages"][-1].text())
```
!!! version-added "New in langgraph>=0.6"
:::
## Use in a workflow
If you are writing a custom workflow, you will need to: