Skip to content
Anlyon
Esc
↑↓navigate↵open⌘Jpreview
On this page

LangGraph: act in your users' accounts

Build a LangGraph agent that calls Anlyon actions as tools for one of your users, pauses the graph while that user approves, and reports the receipt grade.

LangGraph runs your agent’s graph. It does not hold your users’ GitHub or Gmail tokens, count what the agent does per user, or ask the right person before a risky write. A LangGraph interrupt() pauses your graph in your process; it does not stop a request that your tool already sent with a token it holds.

With Anlyon, the graph’s tools call actions by name. Your server binds each graph to one user, Anlyon adds that user’s token at dispatch, checks their limit, parks the call until they approve it in your app, and returns a receipt. The graph never sees a token, and no tool has a user field the model could change.

This guide builds a support agent that opens GitHub issues in each user’s own account:

  1. The model calls the open-issue tool.
  2. Anlyon parks the call for the user’s approval. The graph pauses with interrupt().
  3. The user approves in your app. You resume the graph.
  4. The graph reads the outcome and the model reports the receipt grade.

Before you start

Run the quickstart first, or do its steps 1 and 4 in your environment. You then have:

  • The action open-issue. It opens one issue with the calling user’s own GitHub connection, {{connection:github}}, counts one issues per call and reads the issue back.
  • An approval policy with decidedBy: "end_user": every call waits for the user it acts for.
  • An impact limit of 5 issues a day per user (scope: "end_user").
  • An app key, ANLYON_APP_KEY, from the Standard preset plus end-users:write and end-users:approvals, with Require an end user on.

The graph needs actions:read (to list the action and read results) and actions:invoke. Your server’s approval routes need end-users:approvals, and its connect routes end-users:write. Nothing here needs the GitHub token, approvals:decide or policies:write.

Install the packages. anlyon-langchain turns Anlyon actions into LangChain tools, and LangGraph runs them:

pip install langgraph langchain langchain-openai anlyon-langchain anlyon

Use any chat model that supports tool calling. This guide uses init_chat_model("openai:gpt-5-mini").

Check the key at startup

import os
from anlyon import Client

anlyon = Client(api_key=os.environ["ANLYON_APP_KEY"])

# Fail fast on a wrong key: missing what the app needs, or holding what it must not.
anlyon.auth.require_scopes(
    ["actions:read", "actions:invoke", "end-users:write", "end-users:approvals"],
    forbidden=["approvals:decide", "policies:write", "impact-limits:write", "secrets:write"],
)

require_scopes() raises ScopeCheckError with missing and forbidden. It never changes the key.

Build the graph for one user

The graph is built for one user at a time. anlyon.for_user(end_user_id) binds the client to the user from your session, and everything the graph does happens for that user.

action_tools() reads each action’s name, description and input schema, so the model gets the tool exactly as the action declares it. The tool node calls the action itself, with an idempotency key made from the tool call’s id, so a node that runs twice for one tool call never opens two issues.

# graph.py
import json
import operator
import os
from typing import Annotated, Literal, TypedDict

from anlyon import Client, EndUserConnectionRequiredError
from anlyon.integrations.action_tools import connect_required_result
from anlyon_langchain import action_tools
from langchain.chat_models import init_chat_model
from langchain_core.messages import AnyMessage, SystemMessage, ToolMessage
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import interrupt

anlyon = Client(api_key=os.environ["ANLYON_APP_KEY"])
model = init_chat_model("openai:gpt-5-mini")
checkpointer = InMemorySaver()  # use a durable checkpointer in production

SYSTEM = (
    "You help the user track bugs. To open a GitHub issue, call open-issue once. "
    "If a tool says the user must connect an account, tell them to use the Connect button. "
    "Never call a tool again to get around a decision or an unknown outcome."
)

NOTES = {
    "succeeded": "Done.",
    "pending_approval": "Still waiting for the user's approval. Do not call it again.",
    "running": "Still running. Do not call it again.",
    "unknown": "The outcome is unknown. Do not call it again.",
    "failed": "It did not happen. Tell the user why.",
    "denied": "The user declined. Do not call it again.",
    "expired": "Nobody approved it in time. Do not call it again.",
}


class State(TypedDict):
    messages: Annotated[list[AnyMessage], operator.add]
    pending: list[dict]  # calls parked for the user's approval


def outcome(invocation: dict) -> str:
    """What the model reads back: status, receipt grade and what to do next."""
    status = invocation["status"]
    return json.dumps({
        "status": status,
        "grade": invocation.get("grade"),
        "invocationId": invocation["id"],
        "error": invocation.get("error"),
        "note": NOTES.get(status, ""),
    })


def build_graph(end_user_id: str):
    user = anlyon.for_user(end_user_id)  # your server binds the user; the model cannot
    tools = action_tools(user, names=["open-issue"])
    model_with_tools = model.bind_tools(tools)

    def llm_call(state: State) -> dict:
        reply = model_with_tools.invoke([SystemMessage(SYSTEM)] + state["messages"])
        return {"messages": [reply]}

    def tool_node(state: State) -> dict:
        messages, pending = [], []
        for call in state["messages"][-1].tool_calls:
            try:
                invocation = user.actions.invoke(
                    call["name"],
                    call["args"],
                    # One tool call, one invocation, even if this node runs again.
                    idempotency_key=f"langgraph:{end_user_id}:{call['id']}",
                ).data
            except EndUserConnectionRequiredError as error:
                # Not connected: nothing was sent. The model relays the message.
                result = connect_required_result(error)
                messages.append(ToolMessage(content=json.dumps(result), tool_call_id=call["id"]))
                continue
            if invocation["pendingApproval"]:
                pending.append({
                    "tool_call_id": call["id"],
                    "invocation_id": invocation["id"],
                    "approval_id": invocation["approvalId"],
                })
            else:
                messages.append(ToolMessage(content=outcome(invocation), tool_call_id=call["id"]))
        return {"messages": messages, "pending": pending}

    def await_approval(state: State) -> dict:
        # Pauses the graph. This node only reads, so running it again on resume is safe.
        interrupt({"approvalIds": [p["approval_id"] for p in state["pending"]]})
        messages = []
        for p in state["pending"]:
            invocation = user.actions.invocation(p["invocation_id"]).data
            messages.append(ToolMessage(content=outcome(invocation), tool_call_id=p["tool_call_id"]))
        return {"messages": messages, "pending": []}

    def after_llm(state: State) -> Literal["tool_node", END]:
        return "tool_node" if state["messages"][-1].tool_calls else END

    def after_tools(state: State) -> Literal["await_approval", "llm_call"]:
        return "await_approval" if state.get("pending") else "llm_call"

    builder = StateGraph(State)
    builder.add_node("llm_call", llm_call)
    builder.add_node("tool_node", tool_node)
    builder.add_node("await_approval", await_approval)
    builder.add_edge(START, "llm_call")
    builder.add_conditional_edges("llm_call", after_llm, ["tool_node", END])
    builder.add_conditional_edges("tool_node", after_tools, ["await_approval", "llm_call"])
    builder.add_edge("await_approval", "llm_call")
    return builder.compile(checkpointer=checkpointer)

Why the write and the pause are in different nodes: when a graph resumes, LangGraph runs the interrupted node again from its first line. If the invoke sat before interrupt() in the same node, every resume would send it again. Here the invoke runs in tool_node, which finished and was checkpointed before the pause, and await_approval only reads.

Run it for a user

Your route takes the user from its own session, never from the request body or the model:

from langchain_core.messages import HumanMessage

from graph import build_graph


def chat(session_user_id: str, thread_id: str, text: str) -> dict:
    graph = build_graph(session_user_id)
    config = {"configurable": {"thread_id": thread_id}}
    graph.invoke({"messages": [HumanMessage(text)]}, config)

    state = graph.get_state(config).values
    if state.get("pending"):
        # Paused: show the user their approval in your app.
        return {"waiting": [p["approval_id"] for p in state["pending"]]}
    return {"reply": state["messages"][-1].content}

When the user asks to open an issue, the graph pauses and the call is parked in Anlyon. Nothing has reached GitHub:

{ "waiting": ["apr_01JABCDEF"] }

Let the user approve, then resume

Show the user their pending approval: the exact title and body the agent wants to send. When they decide, your server relays it and resumes the graph. Approving runs the parked call with the request exactly as the user saw it.

from langgraph.types import Command

from graph import anlyon, build_graph


def pending_approvals(session_user_id: str) -> list[dict]:
    # This user's approvals only. Another user's answers 404.
    return anlyon.end_users.approvals.list(session_user_id, status="pending").data


def decide(session_user_id: str, thread_id: str, approval_id: str, approve: bool) -> str:
    anlyon.end_users.approvals.decide(
        session_user_id, approval_id, decision="approve" if approve else "deny"
    )
    graph = build_graph(session_user_id)
    config = {"configurable": {"thread_id": thread_id}}
    graph.invoke(Command(resume=True), config)
    return graph.get_state(config).values["messages"][-1].content

On resume, await_approval reads the invocation and the model replies with the outcome. For open-issue the tool message reads:

{ "status": "succeeded", "grade": "confirmed", "invocationId": "inv_01JABCDEF", "error": null, "note": "Done." }

confirmed means Anlyon read the issue back from GitHub and its title matched.

The approval does not have to be decided while anyone waits. It stays pending for 24 hours by default. The graph stays paused in its checkpoint, and the invocation id stays in the graph’s state, so your app can resume it the next day. To learn about decisions without polling, subscribe to approval events with a webhook.

Connect a user who has not connected GitHub

When the user has no GitHub connection, the action is not sent, and the tool message is:

{
  "status": "connect_required",
  "integration": "github",
  "connectUrl": "https://...",
  "message": "The user has not connected github yet, so nothing was done. Ask them to connect it, then try again."
}

reconnect_required means the provider revoked the connection. Render connectUrl as a Connect GitHub button: it works once, for 10 minutes. It is null when the environment has no default redirect URL; then make a link yourself and confirm the connection in your callback:

from anlyon import parse_connect_redirect

link = anlyon.end_users.create_connect_link(
    end_user_id=session_user_id,
    integration="github",
    redirect_url="https://app.example.com/connections/callback",
).data  # send the browser to link["url"]

# In the callback route, with the user from your session:
result = parse_connect_redirect(callback_url)
if result and result.status == "pending_confirmation" and result.flow_id:
    anlyon.end_users.confirm_connection(session_user_id, result.flow_id)

See Workspace connections and end-user connections.

Read the result

Status Grade What the graph should do
pending_approval pending Stay paused. The user decides in your app.
running pending Read the same invocation later.
succeeded confirmed or acknowledged Report it. confirmed: a read-back matched the request.
failed failed or refused Report error. refused means Anlyon refused it at dispatch, for example on the user’s daily limit. Nothing was sent.
unknown unknown No usable response. Anlyon does not send it again. Do not call the tool again.
denied / expired denied Stop. Do not resubmit to get around the decision.

A resume value such as Command(resume=True) is not an Anlyon decision. It only wakes the graph. The decision is the one the user made through end_users.approvals.decide, bound to the exact request, and nothing the model writes can make it.

Handle errors

Error What it means What to do
EndUserConnectionRequiredError The user has no working connection. Handled in the tool node: the model gets connect_required.
EndUserRequiredError (400 END_USER_REQUIRED) A call was made without for_user(). Always build the graph with build_graph(session_user_id).
ScopeCheckError The key is wrong for the app. Use a key with the scopes above.
AnlyonError with code AUTHORIZATION_ERROR (403) The key lacks a scope a call needs. Add it when you create the key.
RateLimitError, NetworkError, TimeoutError Raised after the SDK’s own retries. Run the graph again from its checkpoint. The idempotency key answers a repeated tool call from the first record.

See the Python SDK for every error.

Use the prebuilt agent instead

When you do not need to pause the graph, LangChain’s create_agent runs the same tools on LangGraph with no graph code:

from anlyon_langchain import action_tools
from langchain.agents import create_agent

assistant = create_agent(
    model="openai:gpt-5-mini",
    tools=action_tools(anlyon.for_user(session_user_id), names=["open-issue"]),
    system_prompt="You help the user track bugs.",
)

Each tool returns the invocation: a gated call comes back with pendingApproval and an approvalId, and a missing connection comes back as connect_required, both as tool results. The SDK generates a fresh idempotency key for each tool call, which covers its own retries but not a whole node running again.

Was this page helpful?