Skip to content

Commit 1f705d5

Browse files
docs: add ToolContext section for advanced tool metadata (#1868)
1 parent 2efaf4a commit 1f705d5

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

docs/context.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,51 @@ if __name__ == "__main__":
6868
4. The context is passed to the `run` function.
6969
5. The agent correctly calls the tool and gets the age.
7070

71+
---
72+
73+
### Advanced: `ToolContext`
74+
75+
In some cases, you might want to access extra metadata about the tool being executed — such as its name, call ID, or raw argument string.
76+
For this, you can use the [`ToolContext`][agents.tool_context.ToolContext] class, which extends `RunContextWrapper`.
77+
78+
```python
79+
from typing import Annotated
80+
from pydantic import BaseModel, Field
81+
from agents import Agent, Runner, function_tool
82+
from agents.tool_context import ToolContext
83+
84+
class WeatherContext(BaseModel):
85+
user_id: str
86+
87+
class Weather(BaseModel):
88+
city: str = Field(description="The city name")
89+
temperature_range: str = Field(description="The temperature range in Celsius")
90+
conditions: str = Field(description="The weather conditions")
91+
92+
@function_tool
93+
def get_weather(ctx: ToolContext[WeatherContext], city: Annotated[str, "The city to get the weather for"]) -> Weather:
94+
print(f"[debug] Tool context: (name: {ctx.tool_name}, call_id: {ctx.tool_call_id}, args: {ctx.tool_arguments})")
95+
return Weather(city=city, temperature_range="14-20C", conditions="Sunny with wind.")
96+
97+
agent = Agent(
98+
name="Weather Agent",
99+
instructions="You are a helpful agent that can tell the weather of a given city.",
100+
tools=[get_weather],
101+
)
102+
```
103+
104+
`ToolContext` provides the same `.context` property as `RunContextWrapper`,
105+
plus additional fields specific to the current tool call:
106+
107+
- `tool_name` – the name of the tool being invoked
108+
- `tool_call_id` – a unique identifier for this tool call
109+
- `tool_arguments` – the raw argument string passed to the tool
110+
111+
Use `ToolContext` when you need tool-level metadata during execution.
112+
For general context sharing between agents and tools, `RunContextWrapper` remains sufficient.
113+
114+
---
115+
71116
## Agent/LLM context
72117

73118
When an LLM is called, the **only** data it can see is from the conversation history. This means that if you want to make some new data available to the LLM, you must do it in a way that makes it available in that history. There are a few ways to do this:

0 commit comments

Comments
 (0)