> For the complete documentation index, see [llms.txt](https://dnotifier.gitbook.io/product-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/middleware/python.md).

# Python

Register middleware on `define_agent` or `Workflow` with a `middleware` list of dicts. Prefer **snake\_case** hook names (`before_agent`, `before_tool`, …). CamelCase names are also accepted.

## Logging middleware

```python
async def before_agent(ctx):
    print("[agent:start]", getattr(ctx, "agent_name", None), ctx.input)

async def after_agent(ctx, result):
    print("[agent:done]", getattr(ctx, "agent_name", None))
    return result

async def on_agent_error(ctx, err):
    print("[agent:error]", err)
    raise err

async def before_model(ctx, request):
    print("[model]", {"round": request.get("round"), "model": request.get("model")})
    return request

async def before_tool(ctx, call):
    print("[tool:call]", call.get("name"), call.get("arguments"))
    return call

async def after_tool(ctx, call, result):
    print("[tool:result]", call.get("name"), result)
    return result

logging = {
    "name": "logging",
    "before_agent": before_agent,
    "after_agent": after_agent,
    "on_agent_error": on_agent_error,
    "before_model": before_model,
    "before_tool": before_tool,
    "after_tool": after_tool,
}

agent = DNotifier.define_agent(
    name="assistant",
    instructions="Use tools when needed.",
    tools=[search_tool],
    middleware=[logging],
)

await notifier.run_agent(agent, input="Find the refund policy")
```

## Tool access middleware

```python
async def seed_allowlist(ctx):
    ctx.state["allowed_tools"] = (
        ["ops.readMetric", "ops.restartService"]
        if ctx.state.get("role") == "sre"
        else ["ops.readMetric"]
    )

async def before_tool(ctx, call):
    allowed = ctx.state.get("allowed_tools") or []
    name = call.get("name")
    if name not in allowed:
        return {
            **call,
            "skip": True,
            "result": {"error": "tool_not_allowed", "name": name},
        }
    return call

agent = DNotifier.define_agent(
    name="ops",
    tools=[read_metric, restart_service],
    instructions="Help with ops questions.",
    middleware=[
        {"before_agent": seed_allowlist},
        {"name": "tool-allowlist", "before_tool": before_tool},
    ],
)
```

## Workflow access middleware

```python
async def before_workflow(ctx):
    if not ctx.sender_id:
        raise DNotifier.WorkflowError("Authentication required")
    ctx.state["started_at"] = time.time()

async def after_workflow(ctx, result):
    started = ctx.state.get("started_at") or time.time()
    if isinstance(result, dict):
        return {**result, "duration_ms": int((time.time() - started) * 1000)}
    return {"result": result, "duration_ms": int((time.time() - started) * 1000)}

async def on_workflow_complete(ctx, info):
    print("[workflow]", info.get("status"), info.get("error"))

async def entry(ctx):
    return await ctx.run_agent("ops")

workflow = DNotifier.Workflow(
    name="ops-flow",
    middleware=[
        {
            "name": "workflow-access",
            "before_workflow": before_workflow,
            "after_workflow": after_workflow,
            "on_workflow_complete": on_workflow_complete,
        }
    ],
    entry=entry,
).register_agents({"ops": agent})

await notifier.run_workflow(
    workflow=workflow,
    input={"question": "CPU for api-1?"},
    sender_id="user_123",
)
```

## See also

* [**Middleware overview**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/middleware.md)
* [**Define an agent**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/define-agent/python.md)
* [**Build a workflow**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/build-workflow/python.md)
