Book a Meeting

Managing Human Interrupts in LangGraph-Based Transactional AI Systems

Transactional AI
Written By Hadiqa Mazhar

Written By : Hadiqa Mazhar

Senior Content Writer

Facts Checked by M. Akif Malhi

Facts Checked by : M. Akif Malhi

Founder & CEO

Table of Contents

AI systems, especially those handling transactions, need to be designed with reliability in mind. But no system is perfect – human intervention is often needed to keep things running smoothly. That’s where LangGraph comes in.

 With its ability to handle two-phase commit transactions, human interrupts, and safe rollbacks, LangGraph lets you build AI systems that adapt to real-world challenges. In this blog, we’ll look at how these components work together to create a dependable AI system that can handle both machine and human challenges.

Setting Up LangGraph with OpenAI Integration and Environment Configuration

This code sets up a system for using LangGraph and LangChain with OpenAI’s API. Let’s break it down step by step:

Environment Setup for OpenAI API Key

The code first defines a function _set_env_openai() to ensure that the OpenAI API key is available in the environment. It checks if OPENAI_API_KEY is already set in the environment variables. 

If not, it tries to fetch the key using google.colab’s userdata feature (commonly used in Colab notebooks). If that fails, it prompts the user to input their OpenAI API key using getpass.getpass(). This ensures the key is securely retrieved without being exposed in the code.

Loading OpenAI’s Chat API

The code then imports ChatOpenAI from the langchain_openai module, which allows interaction with OpenAI’s models through LangChain.

The MODEL variable is set by looking up an environment variable OPENAI_MODEL or defaults to “gpt-4o-mini”. This model name configures the model variant used to generate responses.

Creating a Language Model Object

The llm object is created using ChatOpenAI, where model=MODEL sets the model to be used (either from the environment variable or the default) and temperature=0 indicates deterministic responses (i.e., no randomness in the generated output).

LangGraph Integration

The code imports StateGraph, START, END, and other necessary components from the langgraph.graph module. LangGraph is a library used for designing agentic AI systems by creating state-based graphs that can handle tasks, manage interruptions, and control flows through states.

  • The add_messages function is imported to facilitate the addition of messages into the graph state, which allows the AI to respond based on prior context.
  • The InMemorySaver is used to store and manage the state during the conversation, ensuring that the state of the AI’s progress is saved in memory.
  • The interrupt and Command components from LangGraph handle potential human interruptions and AI commands to modify the execution flow.

Understanding and Managing the Transactional Ledger with Validation, Anomaly Detection, and Patching

This code is designed to handle a ledger of financial transactions, applying various operations such as adding, removing, and replacing entries. Here’s a breakdown of how the code works:

Transaction Data (SAMPLE_LEDGER)

SAMPLE_LEDGER contains a list of transaction records, each represented as a dictionary. Each transaction has several fields: txn_id, name, email, amount, date, and note. Some records contain anomalies such as invalid amounts or duplicate entries.

Allowed Operations (ALLOWED_OPS)

The ALLOWED_OPS dictionary defines the permitted operations that can be applied to the ledger records. These operations are “replace”, “remove”, and “add”. These are used in the apply_patch function to modify the ledger.

Parsing the Amount (_parse_amount)

The function _parse_amount(x) converts the amount field (which may be a string or a number) into a float. If the amount is formatted with commas (e.g., “1,250.50”), it removes the commas before converting it to a float. If the conversion fails, it returns None.

Parsing the Date (_iso_date)

The function _iso_date(d) normalizes dates to the ISO 8601 format (YYYY-MM-DD). It handles different date formats, such as 12/01/2025 and 2025-12-02, and converts them to a standard format. If the date cannot be parsed, it returns None.

Profile Ledger (profile_ledger)

This function processes the ledger rows to detect anomalies. It identifies rows where the amount is invalid (i.e., cannot be parsed into a float) or where duplicate txn_id values are present. It returns the number of rows and a list of indices where anomalies were detected.

Building Transactional AI States with LangGraph

This code is part of an agentic AI system built using LangGraph, with several nodes designed to manage the state of a transaction ledger. The nodes represent distinct stages of transaction processing, including validation, patching, applying patches, and approval. Let’s go through each node and its function:

TxnState Class

The TxnState class is a TypedDict, defining the structure of the state that will be passed between the nodes. It contains:

  • messages: A list of messages (annotated to include AI-generated responses).
  • raw_rows: The raw data of transactions.
  • sandbox_rows: A copy of the raw_rows that can be modified without affecting the original data.
  • patch: A list of patch operations that will be applied to the ledger.
  • validation: A dictionary that holds the validation results.
  • approved: An optional boolean flag indicating whether the transaction has been approved.

Node Profile (node_profile)

This node calls the profile_ledger function, which processes the ledger and identifies anomalies like invalid amounts or duplicate entries.

It returns a message (in the form of an AIMessage) containing a JSON object with the results of the profiling, providing insight into the number of rows and detected anomalies.

Node Patch (node_patch)

This node generates a patch for fixing issues in the raw transaction data. It uses a SystemMessage to ask the AI to return a patch that fixes issues like incorrect amounts, dates, and duplicates.

The raw transaction data (raw_rows) is passed as a HumanMessage, and the AI then returns a patch list in JSON format. This patch is then returned, along with a message containing the patch details.

Node Apply (node_apply)

This node applies the generated patch to the raw_rows, modifying the rows based on the patch operations (add, replace, remove).

It uses the apply_patch function to modify the raw_rows and then returns the updated sandbox_rows. The sandbox_rows are a safe copy of the data that can be further manipulated or validated without altering the original rows.

Node Validate (node_validate)

After applying the patch, this node validates the modified sandbox_rows by calling the validate function.

It checks for any issues in the rows (invalid amounts, incorrect dates, etc.), returning the validation status and any issues found. The validation result is also included in a message for the AI system.

Node Approve (node_approve)

This node evaluates whether the transaction should be approved based on the validation results. It calls an interrupt function, which likely allows for human intervention (approval or rejection) based on the validation status.

It then sets the approved field to True if the decision is “approve” and returns the approval status.

Node Commit (node_commit)

If the transaction is approved, this node commits the changes, finalizing the transaction and ensuring that it is saved or processed. It sends a confirmation message stating that the transaction has been “COMMITTED.”

Running the Transactional AI Workflow with LangGraph

This code executes the full cycle of a transaction processing system, starting from an initial state and progressing through various stages (e.g., profiling, patching, validating) based on the defined nodes. Here’s how it works:

Setting Up the Initial State (state)

The state dictionary is initialized to hold various pieces of information, including:

  • messages: An empty list where AI-generated messages will be stored.
  • raw_rows: The sample ledger data (SAMPLE_LEDGER), which includes a list of transactions.
  • sandbox_rows: An empty list where modified transactions (after applying patches) will be stored.
  • patch: An empty list where the patch (modification operations) will be stored.
  • validation: An empty dictionary where validation results will be stored.
  • approved: A None value initially, which will later hold the decision to approve or reject the transaction.

Conclusion

The system we’ve outlined here leverages LangGraph and LangChain to create a robust, flexible, and human-interactive framework for managing transactional data. 

Elements such as anomaly detection, automated patching, validation processes, and human oversight work together to maintain the reliability and precision of financial transaction records. This design not only automates complex processes but also provides necessary safeguards that protect against errors and inconsistencies.

If you want to take your business to the next level with technology, Techling is the perfect partner for you! We offer a wide range of IT and AI services, including AI answering systems, AI consulting, Agentic Framework, AI software development, Digital transformation, and more. Get in touch with us today to see how our solutions can drive your business forward!

FAQs

What Is Langgraph, And How Is It Related To Chatbot In Transactional Systems?

LangGraph is a framework for building agentic AI systems that manage state transitions, such as transactional systems. When combined with ChatGPT, LangGraph can handle processes like decision-making, anomaly detection, and human interrupts by integrating ChatGPT’s conversational abilities with LangGraph’s transactional capabilities.

How Can Human Interrupts Be Used In Chatbot-Powered Transactional Systems?

Human interrupts in ChatGPT-powered transactional systems can be implemented by pausing the AI’s workflow and prompting a human user for approval or intervention. This is especially useful in scenarios where critical decisions need to be made, such as approving financial transactions or correcting errors in the system.

Why Would I Need Human Intervention In A Chatbot-Driven Transactional System?

Human intervention is necessary when automated decisions are too complex or high-stakes to leave entirely to the AI. For example, financial transactions, fraud detection, and customer service scenarios may require human input to ensure that decisions align with real-world expectations, business policies, and ethical considerations.

How Does Chatbot Handle The Decision-Making Process In A Transactional AI System?

ChatGPT can manage decision-making by analyzing transaction data and generating suggestions. However, when a human interrupt is triggered, ChatGPT pauses its decision-making, prompts the user for their input, and proceeds based on the provided response. This hybrid system ensures that high-level decisions are still made by humans when needed.

Top-Rated Software Development Company

ready to get started?

get consistent results, Collaborate in real time