• About Us
  • Disclaimer
  • Contact Us
  • Privacy Policy
Thursday, January 22, 2026
mGrowTech
No Result
View All Result
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions
No Result
View All Result
mGrowTech
No Result
View All Result
Home Al, Analytics and Automation

How to Design Transactional Agentic AI Systems with LangGraph Using Two-Phase Commit, Human Interrupts, and Safe Rollbacks

Josh by Josh
December 31, 2025
in Al, Analytics and Automation
0
How to Design Transactional Agentic AI Systems with LangGraph Using Two-Phase Commit, Human Interrupts, and Safe Rollbacks
0
SHARES
1
VIEWS
Share on FacebookShare on Twitter


In this tutorial, we implement an agentic AI pattern using LangGraph that treats reasoning and action as a transactional workflow rather than a single-shot decision. We model a two-phase commit system in which an agent stages reversible changes, validates strict invariants, pauses for human approval via graph interrupts, and commits or rolls back only then. With this, we demonstrate how agentic systems can be designed with safety, auditability, and controllability at their core, moving beyond reactive chat agents toward structured, governance-aware AI workflows that run reliably in Google Colab using OpenAI models. Check out the Full Codes here.

!pip -q install -U langgraph langchain-openai


import os, json, uuid, copy, math, re, operator
from typing import Any, Dict, List, Optional
from typing_extensions import TypedDict, Annotated


from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage, AnyMessage
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import interrupt, Command


def _set_env_openai():
   if os.environ.get("OPENAI_API_KEY"):
       return
   try:
       from google.colab import userdata
       k = userdata.get("OPENAI_API_KEY")
       if k:
           os.environ["OPENAI_API_KEY"] = k
           return
   except Exception:
       pass
   import getpass
   os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter OPENAI_API_KEY: ")


_set_env_openai()


MODEL = os.environ.get("OPENAI_MODEL", "gpt-4o-mini")
llm = ChatOpenAI(model=MODEL, temperature=0)

We set up the execution environment by installing LangGraph and initializing the OpenAI model. We securely load the API key and configure a deterministic LLM, ensuring that all downstream agent behavior remains reproducible and controlled. Check out the Full Codes here.

READ ALSO

Slow Down the Machines? Wall Street and Silicon Valley at Odds Over A.I.’s Nearest Future

Inworld AI Releases TTS-1.5 For Realtime, Production Grade Voice Agents

SAMPLE_LEDGER = [
   {"txn_id": "T001", "name": "Asha", "email": "[email protected]", "amount": "1,250.50", "date": "12/01/2025", "note": "Membership renewal"},
   {"txn_id": "T002", "name": "Ravi", "email": "[email protected]", "amount": "-500", "date": "2025-12-02", "note": "Chargeback?"},
   {"txn_id": "T003", "name": "Sara", "email": "[email protected]", "amount": "700", "date": "02-12-2025", "note": "Late fee waived"},
   {"txn_id": "T003", "name": "Sara", "email": "[email protected]", "amount": "700", "date": "02-12-2025", "note": "Duplicate row"},
   {"txn_id": "T004", "name": "Lee", "email": "[email protected]", "amount": "NaN", "date": "2025/12/03", "note": "Bad amount"},
]


ALLOWED_OPS = {"replace", "remove", "add"}


def _parse_amount(x):
   if isinstance(x, (int, float)):
       return float(x)
   if isinstance(x, str):
       try:
           return float(x.replace(",", ""))
       except:
           return None
   return None


def _iso_date(d):
   if not isinstance(d, str):
       return None
   d = d.replace("/", "-")
   p = d.split("-")
   if len(p) == 3 and len(p[0]) == 4:
       return d
   if len(p) == 3 and len(p[2]) == 4:
       return f"{p[2]}-{p[1]}-{p[0]}"
   return None


def profile_ledger(rows):
   seen, anomalies = {}, []
   for i, r in enumerate(rows):
       if _parse_amount(r.get("amount")) is None:
           anomalies.append(i)
       if r.get("txn_id") in seen:
           anomalies.append(i)
       seen[r.get("txn_id")] = i
   return {"rows": len(rows), "anomalies": anomalies}


def apply_patch(rows, patch):
   out = copy.deepcopy(rows)
   for op in sorted([p for p in patch if p["op"] == "remove"], key=lambda x: x["idx"], reverse=True):
       out.pop(op["idx"])
   for op in patch:
       if op["op"] in {"add", "replace"}:
           out[op["idx"]][op["field"]] = op["value"]
   return out


def validate(rows):
   issues = []
   for i, r in enumerate(rows):
       if _parse_amount(r.get("amount")) is None:
           issues.append(i)
       if _iso_date(r.get("date")) is None:
           issues.append(i)
   return {"ok": len(issues) == 0, "issues": issues}

We define the core ledger abstraction along with the patching, normalization, and validation logic. We treat data transformations as reversible operations, allowing the agent to reason about changes safely before committing them. Check out the Full Codes here.

class TxnState(TypedDict):
   messages: Annotated[List[AnyMessage], add_messages]
   raw_rows: List[Dict[str, Any]]
   sandbox_rows: List[Dict[str, Any]]
   patch: List[Dict[str, Any]]
   validation: Dict[str, Any]
   approved: Optional[bool]


def node_profile(state):
   p = profile_ledger(state["raw_rows"])
   return {"messages": [AIMessage(content=json.dumps(p))]}


def node_patch(state):
   sys = SystemMessage(content="Return a JSON patch list fixing amounts, dates, emails, duplicates")
   usr = HumanMessage(content=json.dumps(state["raw_rows"]))
   r = llm.invoke([sys, usr])
   patch = json.loads(re.search(r"\[.*\]", r.content, re.S).group())
   return {"patch": patch, "messages": [AIMessage(content=json.dumps(patch))]}


def node_apply(state):
   return {"sandbox_rows": apply_patch(state["raw_rows"], state["patch"])}


def node_validate(state):
   v = validate(state["sandbox_rows"])
   return {"validation": v, "messages": [AIMessage(content=json.dumps(v))]}


def node_approve(state):
   decision = interrupt({"validation": state["validation"]})
   return {"approved": decision == "approve"}


def node_commit(state):
   return {"messages": [AIMessage(content="COMMITTED")]}


def node_rollback(state):
   return {"messages": [AIMessage(content="ROLLED BACK")]}

We model the agent’s internal state and define each node in the LangGraph workflow. We express agent behavior as discrete, inspectable steps that transform state while preserving message history. Check out the Full Codes here.

builder = StateGraph(TxnState)


builder.add_node("profile", node_profile)
builder.add_node("patch", node_patch)
builder.add_node("apply", node_apply)
builder.add_node("validate", node_validate)
builder.add_node("approve", node_approve)
builder.add_node("commit", node_commit)
builder.add_node("rollback", node_rollback)


builder.add_edge(START, "profile")
builder.add_edge("profile", "patch")
builder.add_edge("patch", "apply")
builder.add_edge("apply", "validate")


builder.add_conditional_edges(
   "validate",
   lambda s: "approve" if s["validation"]["ok"] else "rollback",
   {"approve": "approve", "rollback": "rollback"}
)


builder.add_conditional_edges(
   "approve",
   lambda s: "commit" if s["approved"] else "rollback",
   {"commit": "commit", "rollback": "rollback"}
)


builder.add_edge("commit", END)
builder.add_edge("rollback", END)


app = builder.compile(checkpointer=InMemorySaver())

We construct the LangGraph state machine and explicitly encode the control flow between profiling, patching, validation, approval, and finalization. We use conditional edges to enforce governance rules rather than rely on implicit model decisions. Check out the Full Codes here.

def run():
   state = {
       "messages": [],
       "raw_rows": SAMPLE_LEDGER,
       "sandbox_rows": [],
       "patch": [],
       "validation": {},
       "approved": None,
   }


   cfg = {"configurable": {"thread_id": "txn-demo"}}
   out = app.invoke(state, config=cfg)


   if "__interrupt__" in out:
       print(json.dumps(out["__interrupt__"], indent=2))
       decision = input("approve / reject: ").strip()
       out = app.invoke(Command(resume=decision), config=cfg)


   print(out["messages"][-1].content)


run()

We run the transactional agent and handle human-in-the-loop approval through graph interrupts. We resume execution deterministically, demonstrating how agentic workflows can pause, accept external input, and safely conclude with either a commit or rollback.

In conclusion, we showed how LangGraph enables us to build agents that reason over states, enforce validation gates, and collaborate with humans at precisely defined control points. We treated the agent not as an oracle, but as a transaction coordinator that can stage, inspect, and reverse its own actions while maintaining a full audit trail. This approach highlights how agentic AI can be applied to real-world systems that require trust, compliance, and recoverability, and it provides a practical foundation for building production-grade autonomous workflows that remain safe, transparent, and human-supervised.


Check out the Full Codes here. Also, feel free to follow us on Twitter and don’t forget to join our 100k+ ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.


Asif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is committed to harnessing the potential of Artificial Intelligence for social good. His most recent endeavor is the launch of an Artificial Intelligence Media Platform, Marktechpost, which stands out for its in-depth coverage of machine learning and deep learning news that is both technically sound and easily understandable by a wide audience. The platform boasts of over 2 million monthly views, illustrating its popularity among audiences.



Source_link

Related Posts

Slow Down the Machines? Wall Street and Silicon Valley at Odds Over A.I.’s Nearest Future
Al, Analytics and Automation

Slow Down the Machines? Wall Street and Silicon Valley at Odds Over A.I.’s Nearest Future

January 22, 2026
Inworld AI Releases TTS-1.5 For Realtime, Production Grade Voice Agents
Al, Analytics and Automation

Inworld AI Releases TTS-1.5 For Realtime, Production Grade Voice Agents

January 22, 2026
FlashLabs Researchers Release Chroma 1.0: A 4B Real Time Speech Dialogue Model With Personalized Voice Cloning
Al, Analytics and Automation

FlashLabs Researchers Release Chroma 1.0: A 4B Real Time Speech Dialogue Model With Personalized Voice Cloning

January 22, 2026
Al, Analytics and Automation

Salesforce AI Introduces FOFPred: A Language-Driven Future Optical Flow Prediction Framework that Enables Improved Robot Control and Video Generation

January 21, 2026
Why it’s critical to move beyond overly aggregated machine-learning metrics | MIT News
Al, Analytics and Automation

Why it’s critical to move beyond overly aggregated machine-learning metrics | MIT News

January 21, 2026
What are Context Graphs? – MarkTechPost
Al, Analytics and Automation

What are Context Graphs? – MarkTechPost

January 21, 2026
Next Post
Factor Meal Delivery Promo: Free $200 Withings Body-Scan Scale

Factor Meal Delivery Promo: Free $200 Withings Body-Scan Scale

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

POPULAR NEWS

Trump ends trade talks with Canada over a digital services tax

Trump ends trade talks with Canada over a digital services tax

June 28, 2025
Communication Effectiveness Skills For Business Leaders

Communication Effectiveness Skills For Business Leaders

June 10, 2025
15 Trending Songs on TikTok in 2025 (+ How to Use Them)

15 Trending Songs on TikTok in 2025 (+ How to Use Them)

June 18, 2025
App Development Cost in Singapore: Pricing Breakdown & Insights

App Development Cost in Singapore: Pricing Breakdown & Insights

June 22, 2025
Google announced the next step in its nuclear energy plans 

Google announced the next step in its nuclear energy plans 

August 20, 2025

EDITOR'S PICK

How to Fix Black Ops 7 Keeps Restarting

How to Fix Black Ops 7 Keeps Restarting

November 17, 2025
Cannes wrap: Creativity is going out of fashion

Cannes wrap: Creativity is going out of fashion

June 26, 2025
A Guide for Writing a Social Media Plan to Market Headstones

A Guide for Writing a Social Media Plan to Market Headstones

July 24, 2025
MetalMakina and Hydraulic & Pneumatic Magazines Strengthen Their Global Presence

MetalMakina and Hydraulic & Pneumatic Magazines Strengthen Their Global Presence

October 31, 2025

About

We bring you the best Premium WordPress Themes that perfect for news, magazine, personal blog, etc. Check our landing page for details.

Follow us

Categories

  • Account Based Marketing
  • Ad Management
  • Al, Analytics and Automation
  • Brand Management
  • Channel Marketing
  • Digital Marketing
  • Direct Marketing
  • Event Management
  • Google Marketing
  • Marketing Attribution and Consulting
  • Marketing Automation
  • Mobile Marketing
  • PR Solutions
  • Social Media Management
  • Technology And Software
  • Uncategorized

Recent Posts

  • Slow Down the Machines? Wall Street and Silicon Valley at Odds Over A.I.’s Nearest Future
  • Women Leaders in Electronics Returns in April 2026
  • Transform Your Fitness Business with AR/VR Integration
  • 10 Best Cvent Alternatives and Competitors in 2026
  • About Us
  • Disclaimer
  • Contact Us
  • Privacy Policy
No Result
View All Result
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?