You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
As an alternative to `inputs_from_state` and `outputs_to_state`, a tool can declare a parameter annotated as `State` to receive the live `State` object at invocation time.
444
+
This lets the tool read from and write to any number of state keys without declaring mappings upfront.
445
+
446
+
For function-based tools, add a `State` parameter to the function and use the `@tool` decorator:
447
+
448
+
```python
449
+
from typing import Annotated
450
+
451
+
from haystack.components.agents import Agent, State
452
+
from haystack.components.generators.chat import OpenAIChatGenerator
453
+
from haystack.dataclasses import ChatMessage, Document
454
+
from haystack.tools import tool
455
+
456
+
457
+
@tool
458
+
defretrieve_and_store(
459
+
query: Annotated[str, "The search query"],
460
+
state: State,
461
+
) -> str:
462
+
"""Retrieve documents and store them directly in state."""
463
+
documents = [Document(content=f"Result for '{query}'")]
464
+
state.set("documents", documents)
465
+
user_name = state.get("user_name", "unknown")
466
+
returnf"Retrieved {len(documents)} document(s) for {user_name}"
result = agent.run(messages=[ChatMessage.from_user("Find documents about Python")])
521
+
```
522
+
523
+
`ToolInvoker` automatically injects the runtime `State` object and excludes the `State` parameter from the LLM-facing schema, so the model is never asked to supply it.
524
+
Both `State` and `State | None` annotations are supported.
525
+
441
526
## Complete Example
442
527
443
528
This example shows a multi-tool agent workflow where tools share data through State:
0 commit comments