FoundationAgents/MetaGPT · error · KeyError

missing required key to init Message.instruct_content from d

Error message

missing required key to init Message.instruct_content from dict

What it means

Message.check_instruct_content rehydrates instruct_content from a serialized dict. It accepts dicts with a "class" key plus either "mapping" (custom ActionNode models) or "module" (importable BaseModel subclasses). A dict carrying "class" but neither of those keys raises this KeyError, because there is no way to reconstruct the model class.

Source

Thrown at metagpt/schema.py:262

    @field_validator("id", mode="before")
    @classmethod
    def check_id(cls, id: str) -> str:
        return id if id else uuid.uuid4().hex

    @field_validator("instruct_content", mode="before")
    @classmethod
    def check_instruct_content(cls, ic: Any) -> BaseModel:
        if ic and isinstance(ic, dict) and "class" in ic:
            if "mapping" in ic:
                # compatible with custom-defined ActionOutput
                mapping = actionoutput_str_to_mapping(ic["mapping"])
                actionnode_class = import_class("ActionNode", "metagpt.actions.action_node")  # avoid circular import
                ic_obj = actionnode_class.create_model_class(class_name=ic["class"], mapping=mapping)
            elif "module" in ic:
                # subclasses of BaseModel
                ic_obj = import_class(ic["class"], ic["module"])
            else:
                raise KeyError("missing required key to init Message.instruct_content from dict")
            ic = ic_obj(**ic["value"])
        return ic

    @field_validator("cause_by", mode="before")
    @classmethod
    def check_cause_by(cls, cause_by: Any) -> str:
        return any_to_str(cause_by if cause_by else import_class("UserRequirement", "metagpt.actions.add_requirement"))

    @field_validator("sent_from", mode="before")
    @classmethod
    def check_sent_from(cls, sent_from: Any) -> str:
        return any_to_str(sent_from if sent_from else "")

    @field_validator("send_to", mode="before")
    @classmethod
    def check_send_to(cls, send_to: Any) -> set:
        return any_to_str_set(send_to if send_to else {MESSAGE_ROUTE_TO_ALL})

View on GitHub (pinned to 11cdf466d0)

Solutions

  1. Regenerate the serialized message with the current MetaGPT version so mapping/module is included
  2. Repair the stored dict to include "module" (importable path of the pydantic class) alongside "class" and "value"
  3. If the instruct content is not needed, drop the malformed instruct_content key instead of passing a partial dict

Example fix

// before
msg = Message.model_validate({"content": "x", "instruct_content": {"class": "InvoicePath", "value": {...}}})  # KeyError

// after
msg = Message.model_validate({"content": "x", "instruct_content": {"class": "InvoicePath", "module": "metagpt.actions.invoice_ocr", "value": {...}}})
Defensive patterns

Strategy: validation

Validate before calling

ic = raw.get("instruct_content")
if isinstance(ic, dict):
    assert "class" in ic, "instruct_content dict needs 'class'"
    assert "mapping" in ic or "module" in ic, "instruct_content dict needs 'mapping' or 'module' to rebuild the class"

Type guard

def is_rehydratable_instruct_content(ic) -> bool:
    if not isinstance(ic, dict):
        return True  # non-dict passes through unchanged
    return "class" in ic and ("mapping" in ic or "module" in ic)

Try / catch

try:
    msg = Message.model_validate(data)
except KeyError as e:
    if "missing required key" in str(e):
        data["instruct_content"].setdefault("module", "metagpt.schema")  # or drop the field
        msg = Message.model_validate(data)
    else:
        raise

Prevention

When it happens

Trigger: Message(**dict_from_json) / Message.model_validate where the serialized instruct_content dict lost its "mapping" or "module" entry — e.g. hand-edited storage JSON, partial serialization, or a custom dict built with only class/value keys.

Common situations: Loading persisted team/workspace state where instruct_content was saved by an older MetaGPT version; manually crafting Message dicts for replay/testing; schema changes removing the module field.

Related errors


AI-assisted analysis of FoundationAgents/MetaGPT@11cdf466d0 (2026-08-14). Data as JSON: /api/errors/b129e98678a469a8. Report an issue: GitHub.