Propose shared policy updates from LangGraph
A LangGraph workflow reads the team’s refund policy, reports any returned records that need review, and stages a proposed follow-up rule on a branch. The final node opens a Proposal and returns its ChangeSet IDs for a reviewer.
Use Python 3.10 or newer in a virtual environment. Use a scratch Nicia
space with the default schema, an accepted record about refunds, and a
space key with read and
write. The accepted record gives the space a main head to fork. The graph
uses a supplied draft and needs no model provider key.
python -m venv .venvsource .venv/bin/activatepython -m pip install 'langgraph>=1,<2' 'nicia-ai>=0.1,<1'Save this as workflow.py. The SDK handles the read, fork, compare, and
Proposal. The record write uses the branch’s preview HTTP endpoint.
import argparseimport jsonimport osfrom typing import TypedDictfrom urllib.parse import quote
import httpxfrom langgraph.graph import END, START, StateGraphfrom nicia import NiciaSpaceClientfrom nicia.models import ContextRecordItem
class PolicyUpdate(TypedDict): question: str record_id: str label: str body: str run_id: str
class RunState(PolicyUpdate, total=False): main_receipt: str needs_review: list[str] branch_id: str proposal_id: str change_ids: list[str]
def build_graph(space: NiciaSpaceClient, http: httpx.Client, handle: str): def read_main(state: RunState) -> dict[str, object]: context = space.context(state["question"], max_tokens=2000, format="items") return { "main_receipt": context.receipt, "needs_review": [ item.id for item in context.items or [] if isinstance(item, ContextRecordItem) and item.validity and item.validity.state == "needs_review" ], }
def draft_on_branch(state: RunState) -> dict[str, str]: run_id = state["run_id"] branch = space.create_branch(idempotency_key=f"{run_id}:fork").branch record_id = state["record_id"] path = f"/v1/brains/{quote(handle, safe='')}/branches" # The Python SDK has no branch record writer. Use the preview HTTP route. response = http.post( f"{path}/{quote(branch.branch_id, safe='')}/records", headers={"Idempotency-Key": f"{run_id}:write"}, json={ "nodes": [ { "id": record_id, "kind": "rule", "properties": { "slug": record_id, "label": state["label"], "status": "active", "body": state["body"], }, } ] }, ) response.raise_for_status() return {"branch_id": branch.branch_id}
def open_proposal(state: RunState) -> dict[str, object]: branch_id = state["branch_id"] comparison = space.compare_branch(branch_id) if ( comparison.summary.conflicts or comparison.diff.documents or [record.id for record in comparison.diff.records] != [state["record_id"]] ): raise RuntimeError("Expected only the new rule in a conflict-free diff") proposal = space.create_proposal(branch_id, intent=state["label"]) return { "proposal_id": proposal.proposal.id, "change_ids": proposal.revision.change_ids, }
graph = StateGraph(RunState, input_schema=PolicyUpdate) graph.add_node("read_main", read_main) graph.add_node("draft_on_branch", draft_on_branch) graph.add_node("open_proposal", open_proposal) graph.add_edge(START, "read_main") graph.add_edge("read_main", "draft_on_branch") graph.add_edge("draft_on_branch", "open_proposal") graph.add_edge("open_proposal", END) return graph.compile()
def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("question") parser.add_argument("record_id") parser.add_argument("label") parser.add_argument("body") parser.add_argument("--run-id", required=True) args = parser.parse_args() handle = os.environ["NICIA_SPACE"] key = os.environ["NICIA_SPACE_KEY"] url = os.getenv("NICIA_API_URL", "https://api.nicia.ai") with ( NiciaSpaceClient(handle, api_key=key, base_url=url) as space, httpx.Client(base_url=url, headers={"Authorization": f"Bearer {key}"}) as http, ): result = build_graph(space, http, handle).invoke(vars(args)) print(json.dumps(result, indent=2))
if __name__ == "__main__": main()Run the graph and hand off to Review
Section titled “Run the graph and hand off to Review”Choose a new rule ID and a run ID for this draft. Keep the same run ID if you retry the same fork or branch write after a transient error. If the Proposal request’s outcome is uncertain, check Review for the branch’s Proposal before opening another.
export NICIA_SPACE='your-scratch-space-handle'read -rsp 'Nicia space key: ' NICIA_SPACE_KEYexport NICIA_SPACE_KEYprintf '\n'python workflow.py \ 'What must support check before approving a refund?' \ refund-amount 'Confirm the refund amount' \ 'Support must confirm the refund amount before approval.' \ --run-id refund-001The result contains the receipt for the main read, any needs_review
record IDs seen in that context, and the new Proposal and ChangeSet IDs.
A record appears in needs_review when its returned validity has that
state. Try this with a rule whose cited passage disappeared to see the
list populated. The Markdown migration tutorial
shows how to produce that state.
Hand the Proposal and ChangeSet IDs to a reviewer. They can inspect and apply the draft in Review. The workflow only writes to the fork, and main serves the new rule after the approved change is applied.
Run python -m pytest examples/langgraph-python from the repository root
after installing the example’s requirements.txt. The smoke test runs
the actual graph with the SDK’s HTTP requests mocked.