Skip to content

Module 06 · Lesson 6.3

Shared State and Inter-Agent Communication

40 minUpdated 18 Nov 2026Part of Multi-Agent Systems and Orchestration · AI Agent Development
On this page
  1. What you will learn
  2. Why agents should send structured messages, not free text
  3. The message format used in this module
  4. One case record as shared state, with one owner per field
  5. Append-only notes: a simple audit trail
  6. Validate messages and record handoffs in Python
  7. Conclusion and your next step
  8. Common errors and fixes
  9. Validation checklist
  10. Hands-on exercise
  11. Knowledge check
  12. Frequently asked questions
  13. References

Think of a hospital patient folder. Each nurse and doctor reads the same folder, adds a dated note and signs it. Nobody rewrites an old note. Only the pharmacist fills in the medicine section. And if someone hands you a loose scrap of paper saying "give this patient double", you do not simply do it. You check it against the folder.

Agents that work together need the same habits. This lesson shows how to pass structured messages instead of free text, keep one case record as shared state, decide who may write which field, keep an append-only list of notes, and validate every message in code. Most of it needs no coding. A Python example at the end puts it all together.

What you will learn

  • Write an inter-agent message in a fixed format instead of free text.
  • Design one case record and decide which agent may write each field.
  • Explain why notes should be append-only for auditing.
  • Run Python code that validates messages and records each handoff and note.

Before you start

Why agents should send structured messages, not free text

The easy way to connect two agents is to let one write a paragraph and give it to the other. It works in a demo. Then one day the paragraph drops the order number, or includes a customer's email address, or says something the next agent reads as an instruction.

A structured message has fixed fields, like a form. Code can check each field before anything happens. Compare the two:

Free textStructured message
Looks like"Hi, a customer wants to know about QF-1042, maybe check it?"{"from": "supervisor", "to": "orders_specialist", "task": "Look up QF-1042", "case_id": "C-001"}
Can code check it?Hardly. You would have to guess its meaning.Yes. Each field has a rule.
Can it hide extra data?Yes, anywhere in the sentence.Unexpected fields are rejected.
Easy to log and search?No.Yes. Every message has the same keys.
Structured messages are still plain text on the wire (this one is JSON). What matters is the fixed shape.

JSON is a text format for structured data, written as {"name": "value"} pairs. You have already used it for tool calls and for the reply contract. Here we use it for messages between agents.

The message format used in this module

Every message between agents in the Quillfeather system has exactly four fields:

JSON
{"from": "supervisor", "to": "orders_specialist", "task": "Look up QF-1042", "case_id": "C-001"}
from
The agent that sends the message. One of supervisor, orders_specialist or help_specialist.
to
The agent that receives it. Must also be one of the three known names.
task
A short instruction in plain words, such as "Look up QF-1042". Limited in length.
case_id
The id of the case record this message belongs to, written like C-001.

Notice what is not here: the whole chat history, the customer's email, an address or a payment detail. A message carries only what the receiver needs to do its job. This is the "share the minimum" rule from Context Design: What the Agent Needs at Each Step, applied to agents.

One case record as shared state, with one owner per field

Shared state is information that more than one agent can read. Instead of copying facts between agents, keep one case record and give each agent the case id. Think of it as the patient folder from the start of this lesson. You first met the idea of run state in Conversation State vs. Persistent Memory.

JSONcase.json
{"case_id": "C-001", "customer_message": "Where is QF-1042?", "route": "orders", "notes": ["supervisor: routed to orders"], "handoffs": 1, "result": null}

The rule that keeps shared state safe is one owner per field. If two agents may overwrite the same field, the last one wins and nobody knows why. Decide the owner in advance:

FieldWho may write itRule
case_idThe orchestrator codeSet once when the case is created.
customer_messageThe orchestrator codeSet once. Never edited by an agent.
routesupervisor onlyMust be one of orders, help or person.
resultThe specialist that handled the caseThe final answer or outcome. The supervisor cannot write it.
handoffsThe orchestrator codeA counter that goes up with each handoff. Agents cannot change it.
notesAny agent, by appendingAdd only. Never edit or delete an old note.
A refused write is not an error to hide. Record it as a note.

The handoffs counter is useful later. The next lesson uses it to stop agents from passing a case back and forth forever.

Append-only notes: a simple audit trail

A note is a short line such as supervisor: routed to orders. Append-only means you may add a new note at the end of the list, but you may never change or remove an earlier one. It is like writing in pen in a ship's logbook.

Why does it matter? Because when something goes wrong, you need to answer: who did what, and in which order? If agents can rewrite notes, the evidence is gone. An append-only list gives you a trail you can read from top to bottom.

  • Start each note with the agent's name, then what it did, for example orders_specialist: looked up QF-1042.
  • Record decisions and refusals too, such as supervisor: refused write to result.
  • Keep notes short and free of personal data. Write "looked up an order", not the customer's address.
  • Later, in the module on traces, you will turn this idea into a full record of each run.

Validate messages and record handoffs in Python

The script below has three parts. validate_message() returns a list of problems with a message. hand_off() checks a message and, only if it is clean, counts the handoff and adds a note. write_field() lets only the owner write a field and records a refused write. It uses only the standard library and needs no model.

Pythonmessages.py
import json
import re

AGENTS = ("supervisor", "orders_specialist", "help_specialist")
FIELDS = ("from", "to", "task", "case_id")
OWNERS = {"route": ("supervisor",), "result": ("orders_specialist", "help_specialist")}


def validate_message(msg):
    if set(msg) != set(FIELDS):
        return ["keys must be exactly: " + ", ".join(FIELDS)]
    problems = []
    if msg["from"] not in AGENTS or msg["to"] not in AGENTS:
        problems.append("unknown agent name")
    if not re.fullmatch(r"C-[0-9]{3}", str(msg["case_id"])):
        problems.append("bad case_id")
    task = msg["task"]
    if not isinstance(task, str) or not 1 <= len(task) <= 200:
        problems.append("task must be 1 to 200 characters")
    elif re.search(r"\S+@\S+|\b\d{16}\b", task):
        problems.append("task contains an email or card-like number")
    return problems


def hand_off(case, msg):
    problems = validate_message(msg)
    if not problems and msg["case_id"] != case["case_id"]:
        problems.append("message is for a different case")
    if not problems:
        case["handoffs"] += 1
        case["notes"].append(f"{msg['from']}: handed to {msg['to']}")
    return problems


def write_field(case, agent, field, value):
    if agent not in OWNERS.get(field, ()):
        case["notes"].append(f"{agent}: refused write to {field}")
        return False
    case[field] = value
    return True

Part 1 of 2: the rules. Runs offline with Python 3.10 or later.

Pythonmessages.py
case = {"case_id": "C-001", "customer_message": "Where is QF-1042?", "route": None,
        "notes": [], "handoffs": 0, "result": None}
write_field(case, "supervisor", "route", "orders")
good = {"from": "supervisor", "to": "orders_specialist", "task": "Look up QF-1042", "case_id": "C-001"}
bad = {"from": "supervisor", "to": "billing_bot", "task": "Email me at ana@example.com", "case_id": "C-001"}
print("good:", hand_off(case, good))
print("bad:", hand_off(case, bad))
write_field(case, "supervisor", "result", "refund approved")
write_field(case, "orders_specialist", "result", "QF-1042 is dispatched")
print(json.dumps(case, indent=2))

Part 2 of 2: a demo. Add it to the end of the same file and run python messages.py.

What each part does

  • AGENTS, FIELDS and OWNERS are the rules, written once. OWNERS says who may write route and result.
  • validate_message() first checks that the message has exactly the four keys. A missing or extra key is rejected at once.
  • The later checks collect problems in a list instead of stopping at the first one, so you see everything that is wrong.
  • re.fullmatch(r"C-[0-9]{3}", ...) is a regular expression, a pattern for text. It accepts C-001 and rejects C-1 or case 1.
  • The last check looks for an email-like or card-like number in the task text. It is a simple net, not a complete privacy filter.
  • hand_off() changes the case only when there are no problems. Then it adds 1 to handoffs and appends a note.
  • write_field() looks up the field in OWNERS. A wrong writer gets False and the refusal is appended to the notes.
  • The demo sends one good and one bad message, tries a write by the wrong agent and a write by the right agent, then prints the case record.
OutputCaptured from a real run
good: []
bad: ['unknown agent name', 'task contains an email or card-like number']
{
  "case_id": "C-001",
  "customer_message": "Where is QF-1042?",
  "route": "orders",
  "notes": [
    "supervisor: handed to orders_specialist",
    "supervisor: refused write to result"
  ],
  "handoffs": 1,
  "result": "QF-1042 is dispatched"
}

Read the result from top to bottom. Only the good message counted as a handoff. The supervisor tried to write a result, was refused, and left a note. The case record tells the whole story without any guessing.

Conclusion and your next step

Agents should talk in fixed, small messages. They should share one case record where each field has one owner. Notes are append-only so you can audit what happened, and your code validates every message before anything changes.

Your next step: write the case record for a task of your own and fill in the owner of each field. Then continue to Avoiding Infinite Loops and Unnecessary Agent Handoffs, where the handoffs counter you just met becomes a safety limit.

For more on keeping data small and safe, see Memory Retention, Privacy and Data Lifecycle and Designing Tool Schemas and Validating Arguments.

Common errors and how to fix them

The next agent asks the customer for the order number again.

Why it happens: The message was free text and the order number got lost.

Fix: Use a structured message and keep facts that matter, such as the order id, in the case record.

The result field changes between runs and nobody knows who wrote it.

Why it happens: Several agents were allowed to write the same field.

Fix: Give every field exactly one owner and refuse writes from anyone else. Log refusals.

An old note disappears and the audit trail has a gap.

Why it happens: Notes were stored as plain text that agents could edit.

Fix: Make notes an append-only list. Code adds to the end and never edits earlier entries.

A customer's email address appears in a log file.

Why it happens: The full customer message was copied into a task or a note.

Fix: Send only what the receiver needs, check task text in code and redact logs.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Log rejected messages without copying the task

Change hand_off() so that a rejected message also adds a note to the case. The note must say who tried to send it and that it was rejected, but must not copy the task text.

You will need

  • The messages.py file from this lesson.
  • The bad message in the demo, whose task text contains an email address.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Add an else branch that runs when problems is not empty.
  • Use msg.get("from", "unknown") because a broken message may lack the key.
  • Only write the agent name and the word rejected. Do not write msg["task"].
Show a model answer

After the if not problems: block, add: else: case["notes"].append(f"{msg.get('from', 'unknown')}: message rejected"). The note records who tried and that it failed, which is enough for an investigation. It leaves out the task text, so the email address never reaches the case record or any log made from it. The counter stays at 1 because only the clean message enters the first branch. Logging what happened without copying the sensitive content is the habit to keep.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Why use a structured message instead of a free-text paragraph between agents?
    Show the answer and explanation

    Answer: B. Fixed fields can be validated and logged. Models read paragraphs perfectly well, so the first option is wrong. Structured messages are not guaranteed to be shorter, so the third option is not the reason.

  2. 2.Which rule keeps shared state safe when several agents use one case record?
    Show the answer and explanation

    Answer: B. One owner per field means you always know who wrote a value. Letting everyone write sounds flexible but hides who changed what, and letting the newest agent win lets a wrong value overwrite a right one.

  3. 3.What does append-only mean for the notes list?
    Show the answer and explanation

    Answer: A. Append-only keeps an honest history that you can audit. Deleting notes when the case ends would remove the evidence you need, and limiting a case to one note would lose the order of events.

Frequently asked questions

What is shared state in a multi-agent system?

It is information that several agents can read, such as one case record. Instead of copying facts from agent to agent, each agent gets the case id and reads or updates the record under clear rules.

How do AI agents communicate with each other?

Usually through messages that your code passes between them. A good design uses a fixed format, such as JSON with named fields, and validates each message before the receiving agent starts work.

Should agents share the whole conversation history?

Usually not. Share the minimum the next agent needs: the task, key facts and a short note. A smaller context is cheaper, less confusing and exposes less personal data.

Why keep an audit trail of agent actions?

When an answer is wrong, you need to see which agent did what, and in which order. An append-only list of short notes lets you replay the story and find the step that went wrong.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.