Skip to main content
message_history_in_tool_hooks.py
"""
Message History In Tool Hooks
=============================

Access the current run's message history inside tool hooks in a team
via run_context.messages.
"""

from typing import Any, Callable, Dict

from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.run.base import RunContext
from agno.team import Team
from agno.tools import FunctionCall, tool

# ---------------------------------------------------------------------------
# Create Members
# ---------------------------------------------------------------------------


def context_aware_hook(
    run_context: RunContext,
    function_name: str,
    function_call: Callable,
    arguments: Dict[str, Any],
):
    """Log conversation context before executing a member's tool."""
    msgs = run_context.messages
    count = len(msgs) if msgs else 0
    print(f"[hook] {function_name} - {count} messages in run")
    return function_call(**arguments)


def pre_hook(run_context: RunContext, fc: FunctionCall):
    msgs = run_context.messages
    count = len(msgs) if msgs else 0
    print(f"[pre-hook] {fc.function.name} - {count} messages in run")


@tool(pre_hook=pre_hook)
def get_weather(city: str) -> str:
    """Get the current weather for a city."""
    return f"Sunny, 72F in {city}"


weather_agent = Agent(
    name="Weather Agent",
    role="Get weather information for cities",
    model=OpenAIChat(id="gpt-4o-mini"),
    tools=[get_weather],
    tool_hooks=[context_aware_hook],
    instructions=["Use the tools to help the user."],
)

# ---------------------------------------------------------------------------
# Create Team
# ---------------------------------------------------------------------------
team = Team(
    name="Travel Team",
    model=OpenAIChat(id="gpt-4o-mini"),
    members=[weather_agent],
    mode="coordinate",
)

# ---------------------------------------------------------------------------
# Run Team
# ---------------------------------------------------------------------------
if __name__ == "__main__":
    team.print_response("What is the weather in Tokyo?")

Run the Example

1

Set up your virtual environment

uv venv --python 3.12
source .venv/bin/activate
uv venv --python 3.12
.venv\Scripts\activate
2

Install dependencies

uv pip install -U agno openai
3

Export your OpenAI API key

export OPENAI_API_KEY="your_openai_api_key_here"
$Env:OPENAI_API_KEY="your_openai_api_key_here"
4

Run the example

Save the code above as message_history_in_tool_hooks.py, then run:
python message_history_in_tool_hooks.py
Full source: cookbook/03_teams/03_tools/message_history_in_tool_hooks.py