← SDK docs

VENZX + LangGraph

Put a check in front of every tool a LangGraph agent calls. Allowed calls run, blocked calls do not, and calls that need a person wait for one.

Tested with langgraph 1.2.22 and langchain-core 1.8.1. The code on this page is the file our tests run.

5-minute quick start

  1. 1.Install

    pip install venzx langgraph langchain-openai
  2. 2.Set your keys

    Create a VENZX key in your dashboard. The example uses an OpenAI model, so it needs that key too.

    export VENZX_API_KEY="pai-..."
    export OPENAI_API_KEY="sk-..."
  3. 3.Save agent.py

    Save this as agent.py.
    """LangGraph + VENZX: check every tool call before the tool runs.
    
    The one integration point is ``ToolNode(tools, wrap_tool_call=...)``. LangGraph
    calls the wrapper once per tool call, with the call the model asked for and a
    function that executes it. The wrapper asks VENZX first:
    
        allow         -> execute the tool
        block         -> do not execute; the model gets the reason as the tool result
        needs_review  -> do not execute; the model is told it is held for a person
                         (or, with APPROVAL_WAIT_SECONDS set, wait for them and then run)
    
    Tested with langgraph 1.2.22 and langchain-core 1.8.1.
    
    Run it:
        pip install venzx langgraph langchain-openai
        export VENZX_API_KEY="pai-..."  OPENAI_API_KEY="sk-..."
        python agent.py
    """
    from __future__ import annotations
    
    import os
    
    from langchain_core.messages import ToolMessage
    from langchain_core.tools import tool
    from langgraph.graph import END, START, MessagesState, StateGraph
    from langgraph.prebuilt import ToolNode, tools_condition
    
    from venzx import ApprovalRequired, Blocked, Guard, Policy, Venzx
    
    # What this agent may do. Sent with every check, so it applies even if the
    # account's own policy is empty.
    POLICY = (
        Policy()
        .allow_tools("lookup_order", "refund")     # anything else is blocked
        .require_approval("refund")                # a person must say yes
    )
    
    # Stand-in for your systems, so you can see what actually ran.
    ACTIONS: list = []
    
    
    @tool
    def lookup_order(order_id: str) -> str:
        """Look up the status of an order."""
        ACTIONS.append(("lookup_order", order_id))
        return f"Order {order_id}: delivered, total $40.00"
    
    
    @tool
    def refund(order_id: str, amount: float) -> str:
        """Refund an order."""
        ACTIONS.append(("refund", order_id, amount))
        return f"Refunded ${amount:.2f} on order {order_id}"
    
    
    @tool
    def delete_customer(customer_id: str) -> str:
        """Delete a customer and all their data."""
        ACTIONS.append(("delete_customer", customer_id))
        return f"Deleted customer {customer_id}"
    
    
    TOOLS = [lookup_order, refund, delete_customer]
    
    
    # ── the VENZX check (identical in every framework example) ───────────────
    # Seconds to wait for a person when an action is held. 0 (the default) does
    # not wait: the model is told the action is held and carries on.
    APPROVAL_WAIT_SECONDS = float(os.environ.get("APPROVAL_WAIT_SECONDS", "0"))
    
    
    def venzx_refusal(guard: Guard, name: str, args: dict,
                      wait_seconds: float = APPROVAL_WAIT_SECONDS) -> str | None:
        """Ask VENZX about one tool call, before it runs.
    
        Returns None if the tool may run. Otherwise returns the sentence to give
        the model in place of the tool's result. Never raises: anything that goes
        wrong is a refusal, so a tool cannot run unchecked."""
        try:
            guard.tool_call(name, args)
            return None                                   # allowed
        except ApprovalRequired as e:
            approval_id = e.result.approval_id            # held for a person
        except Blocked as e:
            return f"BLOCKED: {e.result.reason}. It has NOT run."
        except Exception as e:  # noqa: BLE001
            return f"BLOCKED: the action could not be checked ({e}). It has NOT run."
    
        status = "pending"
        if wait_seconds > 0:
            try:
                status = guard.client.wait_for_approval(
                    approval_id, timeout=wait_seconds).get("status", "pending")
                # Reading "approved" is not permission. Claiming it is, and the
                # claim names this exact call, so it cannot be spent on another.
                guard.client.consume_approval(
                    approval_id, action={"name": name, "args": dict(args)})
                return None                               # a person said yes
            except Exception:  # noqa: BLE001
                pass                                      # rejected, expired or still pending
        if status == "rejected":
            return f"REJECTED: a person declined '{name}'. It has NOT run."
        return (f"HELD: '{name}' needs a person to approve it "
                f"(approval id {approval_id}). It has NOT run.")
    # ── end of the VENZX check ───────────────────────────────────────────────
    
    
    def venzx_tool_guard(guard: Guard):
        """A ``wrap_tool_call`` function for ``ToolNode`` that checks with VENZX."""
    
        def wrap(request, execute):
            call = request.tool_call                      # {"name", "args", "id"}
            refusal = venzx_refusal(guard, call["name"], call["args"])
            if refusal is None:
                return execute(request)                   # run the tool
            return ToolMessage(content=refusal, tool_call_id=call["id"],
                               name=call["name"], status="error")
    
        return wrap
    
    
    def build_graph(model, guard: Guard | None = None):
        """The standard agent loop: model -> tools -> model, until no tool call."""
        guard = guard or Guard(Venzx(), policy=POLICY)
        llm = model.bind_tools(TOOLS)
    
        def agent(state: MessagesState):
            return {"messages": [llm.invoke(state["messages"])]}
    
        graph = StateGraph(MessagesState)
        graph.add_node("agent", agent)
        graph.add_node("tools", ToolNode(TOOLS, wrap_tool_call=venzx_tool_guard(guard)))
        graph.add_edge(START, "agent")
        graph.add_conditional_edges("agent", tools_condition)   # -> "tools" or END
        graph.add_edge("tools", "agent")
        return graph.compile()
    
    
    def main() -> None:
        from langchain_openai import ChatOpenAI
    
        app = build_graph(ChatOpenAI(model="gpt-4o-mini"))
        result = app.invoke({"messages": [(
            "user",
            "Order A-1001 arrived broken. Look it up, refund it in full, "
            "then delete customer C-77.")]})
        print(result["messages"][-1].content)
        print("\nWhat actually ran:", ACTIONS)
    
    
    if __name__ == "__main__":
        main()
    
  4. 4.Run it

    python agent.py

    The example is a support agent with three tools. Its policy lets lookup_order run, holds refund for a person, and has no entry for delete_customer.

    The model’s wording varies from run to run. The last line is what matters: it lists what actually ran, and it should hold lookup_order only.

    The refund did not run. It is waiting as an approval email at the address on your VENZX account. delete_customer did not run and never will under this policy.

  5. 5.Approve the refund

    Open the approval email and press Approve. By default the example does not wait for you: it tells the model the refund is held and moves on. To have the tool call wait for your decision and then run, set a wait before you start it:

    APPROVAL_WAIT_SECONDS=600 python agent.py

How it plugs in

The integration point is ToolNode(tools, wrap_tool_call=...), which LangGraph provides for exactly this.

LangGraph’s ToolNode takes a wrap_tool_call function. It is called once for each tool call the model makes, with the request (the tool’s name, arguments and call id) and a function that runs the tool.

The example’s wrapper asks VENZX about the name and arguments first, and calls that function only when the answer is allow. That one argument to ToolNode is the whole integration.

When a call is refused. The wrapper returns a ToolMessage with status "error" whose content is the reason. The model reads it as the tool’s result, so the graph carries on and the model can tell the user what happened.

The check itself

venzx_refusal in the file above is the same in every framework example. It returns nothing when the tool may run, and otherwise the sentence to give the model:

  • Allowed: the tool runs.
  • Blocked: the tool does not run, and the model is told why.
  • Held for a person: the tool does not run. With APPROVAL_WAIT_SECONDS set, it waits for the decision and then claims the approval for that exact tool and those exact arguments before running. An approval cannot be spent on a different call.
  • Anything goes wrong, including VENZX being unreachable: the tool does not run.

The policy at the top of the file travels with every check. Change it there, or delete it to use the policy saved on your account. See Policy and the human-approval gate.

Using create_agent instead of your own graph

LangChain’s create_agent builds the loop for you, so there is no ToolNode to configure. Its equivalent is a middleware with a wrap_tool_call method, which receives the same request and the same function. This file reuses the guard from agent.py unchanged. Tested with langchain 1.5.0.

Save this as with_create_agent.py, next to agent.py.
"""The same VENZX check with LangChain's ``create_agent``.

``create_agent`` builds the agent loop for you, so there is no ToolNode to
pass ``wrap_tool_call`` to. The equivalent hook is a middleware: its
``wrap_tool_call`` method receives the same request and the same "run it"
function, so it can reuse the guard from agent.py unchanged.

Tested with langchain 1.5.0 and langgraph 1.2.22.

Run it (from this folder, next to agent.py):
    pip install venzx langchain langchain-openai
    export VENZX_API_KEY="pai-..."  OPENAI_API_KEY="sk-..."
    python with_create_agent.py
"""
from __future__ import annotations

from langchain.agents import create_agent
from langchain.agents.middleware import AgentMiddleware

from agent import ACTIONS, POLICY, TOOLS, venzx_tool_guard
from venzx import Guard, Venzx


class VenzxMiddleware(AgentMiddleware):
    """Checks every tool call with VENZX before it runs."""

    def __init__(self, guard: Guard) -> None:
        super().__init__()
        self._check = venzx_tool_guard(guard)

    def wrap_tool_call(self, request, handler):
        return self._check(request, handler)


def build_agent(model, guard: Guard | None = None):
    guard = guard or Guard(Venzx(), policy=POLICY)
    return create_agent(model, TOOLS, middleware=[VenzxMiddleware(guard)])


def main() -> None:
    from langchain_openai import ChatOpenAI

    result = build_agent(ChatOpenAI(model="gpt-4o-mini")).invoke({"messages": [(
        "user",
        "Order A-1001 arrived broken. Look it up, refund it in full, "
        "then delete customer C-77.")]})
    print(result["messages"][-1].content)
    print("\nWhat actually ran:", ACTIONS)


if __name__ == "__main__":
    main()

Run it with: pip install langchain, then python with_create_agent.py

What this does not cover

  • Only tools run by that ToolNode are checked. A tool you call yourself from another node is not.
  • When the model asks for several tools in one turn, LangGraph runs them in parallel. Each is checked on its own, so one being held does not stop the others.
  • The check runs in your process. Code that calls a tool function directly, without going through the graph, bypasses it.

VENZX answers before your tool runs and never sees it execute. The general limits are in What VENZX does NOT do.

Other frameworks

CrewAI · OpenAI Agents SDK · MCP · SDK docs

The example, its pinned requirements.txt and its test are in examples/langgraph/ of the SDK repository.