Recently, I decided to build a classic AI agent for ordering pizza. The goal was simple: ask for the pizza type, ask for toppings, confirm the order, and save it. But I realized the architecture was broken. I needed a middle layer. A "Draft" area where the agent can mold the data like clay, make mistakes, fix them, and only commit when everything is perfect.Recently, I decided to build a classic AI agent for ordering pizza. The goal was simple: ask for the pizza type, ask for toppings, confirm the order, and save it. But I realized the architecture was broken. I needed a middle layer. A "Draft" area where the agent can mold the data like clay, make mistakes, fix them, and only commit when everything is perfect.

Why I Stopped Letting aI Agents Write Directly to my Database (and Built MemState)

2025/12/05 14:25

Recently, I decided to build a classic AI agent for ordering pizza. The goal was simple: ask for the pizza type, ask for toppings, confirm the order, and save it.

I  used the standard stack: LangChain, LangGraph, and SQLite. \n Here is what my first version looked like:

import sqlite3 from langchain_core.tools import tool from langchain.agents import create_agent from langchain.chat_models import init_chat_model from langgraph.checkpoint.sqlite import SqliteSaver @tool def create_order(pizza_type: str, size: str): """Create a new pizza order.""" # Simulation: Just printing, no real state management here! print(f"Creating order: {size} {pizza_type}") return "Order created." @tool def update_order(new_details: str): """Update existing order.""" return "Order updated." @tool def confirm_order(): """Call this to finalize the order.""" return f"Order sent to kitchen!" llm = init_chat_model(model="gpt-4o", model_provider="openai") agent = create_agent( llm, tools=[create_order, update_order, confirm_order], checkpointer=SqliteSaver(sqlite3.connect("agent.db", check_same_thread=False)), ) config = {"configurable": {"thread_id": "session_1"}} agent.invoke( {"messages": [("user", "I want a large Pepperoni.")]}, config=config )

\ The logic seems fine, right?

  1. User says "I want Pepperoni" → Agent calls create_order.
  2. Database executes INSERT INTO orders ....
  3. User says "No onions please" → Agent calls update_order.
  4. Database executes UPDATE orders ....

Then I realized the architecture was broken.

Imagine if the user says on step 3: "Actually, I changed my mind. I don't want pizza, I want sushi."

Now, my production database has a "dirty" record of a Pepperoni order that was never finished. I have to write logic to delete it, handle cancellations, and clean up the garbage.

I was letting the Agent's "thought process", which is chaotic and prone to mistakes, write directly to my production database. This creates Dirty Writes.

Attempt #1: Vector Memory?

Many developers suggest using tools like Mem0 or Zep. But those are for semantic memory. They help the agent remember that "Alice likes spicy food."

They do not solve the transactional state problem. Vectors cannot guarantee that my order ID is unique or that the price is a valid number.

The Solution: MemState (A "Buffer" for Agents)

I needed a middle layer. A "Draft" area where the agent can mold the data like clay, make mistakes, fix them, and only commit when everything is perfect.

I couldn't find a simple tool for this, so I built MemState.

Think of it as Git, but for Agent data:

  1. Strict Types (Pydantic): The agent cannot save garbage data.
  2. Transactions: Every change is logged. I can rollback if the agent hallucinates.
  3. Constraints: I can prevent duplicates automatically.

Here is the new Agent code:

from langchain_core.tools import tool from langchain.agents import create_agent from langchain.chat_models import init_chat_model from pydantic import BaseModel from memstate import MemoryStore, Fact, Constraint, SQLiteStorage from memstate.integrations.langgraph import MemStateCheckpointer class PizzaOrder(BaseModel): status: str = "new" pizza_type: str size: str toppings: list[str] = [] storage = SQLiteStorage("pizza_shop.db") memory = MemoryStore(storage) # 🔥 KILLER FEATURE: Singleton Constraint # A single user can have ONLY ONE active order in a single session. # If the agent attempts to create a second one, MemState will automatically update the first. memory.register_schema("order", PizzaOrder, Constraint(singleton_key="session_id")) checkpointer = MemStateCheckpointer(memory=memory) @tool def update_order(pizza_type: str, size: str, toppings: list[str]): """Call this tool to create or update the pizza order.""" # We use thread_id as a unique key (singleton_key) # In a real application, thread_id is passed through the context (config) session_id = "session_1" # The agent simply "throws" the fact. It doesn't need to check whether the order exists. # MemState will decide for itself: INSERT or UPDATE. fid = memory.commit( Fact( type="order", payload={ "session_id": session_id, "pizza_type": pizza_type, "size": size, "toppings": toppings } ) ) return f"Order state saved. Fact ID: {fid}" @tool def confirm_order(): """Call this to finalize the order.""" orders = memory.query(typename="order", json_filters={"session_id": "session_1"}) return f"Order {orders[0]['payload']} sent to kitchen!" llm = init_chat_model(model="gpt-4o", model_provider="openai") agent = create_agent( llm, tools=[update_order, confirm_order], checkpointer=checkpointer, ) config = {"configurable": {"thread_id": "session_1"}} agent.invoke( {"messages": [("user", "I want a large Pepperoni.")]}, config=config )

Why is this better?

  1. The "Draft" Concept: While the user is changing their mind ("add mushrooms", "remove cheese"), we are only updating the local MemState. My main production database stays clean.
  2. Validation: If the Agent hallucinates and tries to set the pizza price to "one million", the Pydantic schema in MemState will reject it before it corrupts the state.
  3. One Clean Write: When the user finally says "Confirm", I can simply query the final, validated JSON from MemState and do one clean INSERT into my main database.

Summary

MemState turns the chaos of a conversation into a structured transaction. It supports rollback() (Time Travel), LangGraph checkpoints, and runs on SQLite or Redis.

It’s Open Source. I would love your feedback:

https://github.com/scream4ik/MemState

Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact service@support.mexc.com for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.

You May Also Like

US Prosecutors Seek 12-Year Prison for Do Kwon Over Terra Collapse

US Prosecutors Seek 12-Year Prison for Do Kwon Over Terra Collapse

        Highlights:  US prosecutors requested a 12-year prison sentence for Do Kwon after the Terra collapse. Terraform’s $40 billion downfall caused huge losses and sparked a long downturn in crypto markets.  Do Kwon will face sentencing on December 11 and must give up $19 million in earnings.   US prosecutors have asked a judge to give Do Kwon, Terraform Labs co-founder, a 12-year prison sentence for his role in the remarkable $40 billion collapse of the Terra and Luna tokens. The request also seeks to finalize taking away Kwon’s criminal earnings.  The court filing came in New York’s Southern District on Thursday. This is about four months after Kwon admitted guilt on two charges: wire fraud and conspiracy to defraud. Prosecutors said Kwon caused more losses than Samuel Bankman-Fried, Alexander Mashinsky, and Karl Sebastian Greenwood combined.  U.S. prosecutors have asked a New York federal judge to sentence Terraform Labs co-founder Do Kwon to 12 years in prison, calling his role in the 2022 TerraUSD collapse a “colossal” fraud that triggered broader crypto-market failures, including the downfall of FTX. Sentencing is… — Wu Blockchain (@WuBlockchain) December 5, 2025  Terraform Collapse Shakes Crypto Market Authorities explained that Terraform’s collapse affected the entire crypto market. They said it helped trigger what is now called the ‘Crypto Winter.’ The filing stressed that Kwon’s conduct harmed many investors and the broader crypto world. On Thursday, prosecutors said Kwon must give up just over $19 million. They added that they will not ask for any additional restitution. They said: “The cost and time associated with calculating each investor-victim’s loss, determining whether the victim has already been compensated through the pending bankruptcy, and then paying out a percentage of the victim’s losses, will delay payment and diminish the amount of money ultimately paid to victims.” Authorities will sentence Do Kwon on December 11. They charged him in March 2023 with multiple crimes, including securities fraud, market manipulation, money laundering, and wire fraud. All connections are tied to his role at Terraform. After Terra fell in 2022, authorities lost track of Kwon until they arrested him in Montenegro on unrelated charges and sent him to the U.S. Do Kwon’s Legal Case and Sentencing In April last year, a jury ruled that both Terraform and Kwon committed civil fraud. They found the company and its co-founder misled investors about how the business operated and its finances. Jay Clayton, U.S. Attorney for the Southern District of New York, submitted the sentencing request in November.  TERRA STATEMENT: “We are very disappointed with the verdict, which we do not believe is supported by the evidence. We continue to maintain that the SEC does not have the legal authority to bring this case at all, and we are carefully weighing our options and next steps.” — Zack Guzmán  (@zGuz) April 5, 2024  The news of Kwon’s sentencing caused Terraform’s token, LUNA, to jump over 40% in one day, from $0.07 to $0.10. Still, this rise remains small compared to its all-time high of more than $19, which the ecosystem reached before collapsing in May 2022. In a November court filing, Do Kwon’s lawyers asked for a maximum five-year sentence. They argued for a shorter term partly because he could face up to 40 years in prison in South Korea, where prosecutors are also pursuing a case against him. The legal team added that even if Kwon serves time in the U.S., he would not be released freely. He would be moved from prison to an immigration detention center and then sent to Seoul to face pretrial detention for his South Korea charges.    eToro Platform    Best Crypto Exchange   Over 90 top cryptos to trade Regulated by top-tier entities User-friendly trading app 30+ million users    9.9   Visit eToro eToro is a multi-asset investment platform. The value of your investments may go up or down. Your capital is at risk. Don’t invest unless you’re prepared to lose all the money you invest. This is a high-risk investment, and you should not expect to be protected if something goes wrong. 
Share
Coinstats2025/12/06 02:14
Cashing In On University Patents Means Giving Up On Our Innovation Future

Cashing In On University Patents Means Giving Up On Our Innovation Future

The post Cashing In On University Patents Means Giving Up On Our Innovation Future appeared on BitcoinEthereumNews.com. “It’s a raid on American innovation that would deliver pennies to the Treasury while kneecapping the very engine of our economic and medical progress,” writes Pipes. Getty Images Washington is addicted to taxing success. Now, Commerce Secretary Howard Lutnick is floating a plan to skim half the patent earnings from inventions developed at universities with federal funding. It’s being sold as a way to shore up programs like Social Security. In reality, it’s a raid on American innovation that would deliver pennies to the Treasury while kneecapping the very engine of our economic and medical progress. Yes, taxpayer dollars support early-stage research. But the real payoff comes later—in the jobs created, cures discovered, and industries launched when universities and private industry turn those discoveries into real products. By comparison, the sums at stake in patent licensing are trivial. Universities collectively earn only about $3.6 billion annually in patent income—less than the federal government spends on Social Security in a single day. Even confiscating half would barely register against a $6 trillion federal budget. And yet the damage from such a policy would be anything but trivial. The true return on taxpayer investment isn’t in licensing checks sent to Washington, but in the downstream economic activity that federally supported research unleashes. Thanks to the bipartisan Bayh-Dole Act of 1980, universities and private industry have powerful incentives to translate early-stage discoveries into real-world products. Before Bayh-Dole, the government hoarded patents from federally funded research, and fewer than 5% were ever licensed. Once universities could own and license their own inventions, innovation exploded. The result has been one of the best returns on investment in government history. Since 1996, university research has added nearly $2 trillion to U.S. industrial output, supported 6.5 million jobs, and launched more than 19,000 startups. Those companies pay…
Share
BitcoinEthereumNews2025/09/18 03:26