Skip to main content

middleware

AI Agent Middleware System for PraisonAI Agents. Provides wrap_model_call and wrap_tool_call patterns for intercepting and modifying agent behavior at model/tool call boundaries. Zero Performance Impact:
  • All middleware is optional
  • Empty middleware chain is O(1) fast path
  • No overhead when middleware not registered
Usage: from praisonaiagents.hooks import before_model, wrap_model_call, wrap_tool_call @before_model def add_context(request): request.messages.append({“role”: “system”, “content”: “Extra”}) return request @wrap_model_call def retry_on_error(request, call_next): for _ in range(3): try: return call_next(request) except Exception: pass raise RuntimeError(“All retries failed”) agent = Agent(name=“Test”, hooks=[add_context, retry_on_error])

Import

from praisonaiagents.hooks import middleware

Classes

InvocationContext

Context passed through middleware chain.

ModelRequest

Request data for model calls.

ModelResponse

Response data from model calls.

ToolRequest

Request data for tool calls.

ToolResponse

Response data from tool calls.

MiddlewareChain

Synchronous middleware chain executor.

AsyncMiddlewareChain

Asynchronous middleware chain executor.

MiddlewareManager

Manages middleware for an agent.

Functions

before_model()

Decorator to mark a function as a before_model hook.

after_model()

Decorator to mark a function as an after_model hook.

wrap_model_call()

Decorator to mark a function as a wrap_model_call middleware.

before_tool()

Decorator to mark a function as a before_tool hook.

after_tool()

Decorator to mark a function as an after_tool hook.

wrap_tool_call()

Decorator to mark a function as a wrap_tool_call middleware.

get_hook_type()

Get the hook type of a decorated function.

is_middleware()

Check if a function is a middleware (wrap_* type).

categorize_hooks()

Categorize hooks by their type.

Constants

NameValue
TTypeVar('T')

Middleware Feature