Automating the Code Review Process Using the WriteCodeReview Action in MetaGPT

The WriteCodeReview action in MetaGPT automates code review by using an LLM to evaluate source files against design documents, generating structured feedback and automatically rewriting code when the verdict is LBTM (looks bad to me) instead of LGTM (looks good to me).

MetaGPT is a multi-agent framework that simulates a software company by assigning specialized roles—such as product manager, architect, and engineer—to AI agents. Automating the code review process using the WriteCodeReview action allows these engineering agents to self-correct during development, ensuring generated code aligns with system design and task requirements without manual intervention.

How WriteCodeReview Works in MetaGPT

Core Components and File Locations

The WriteCodeReview action is implemented as a subclass of metagpt.actions.action.Action in metagpt/actions/write_code_review.py. It relies on several prompt templates—including PROMPT_TEMPLATE, EXAMPLE_AND_INSTRUCTION, FORMAT_EXAMPLE, and REWRITE_CODE_TEMPLATE—to structure LLM interactions.

Supporting utilities include:

The Review and Rewrite Loop

The action executes an iterative think-act cycle:

  1. Context Assembly – Gathers system design, task descriptions, and existing source files via WriteCode.get_codes().
  2. Prompt Construction – Injects context into PROMPT_TEMPLATE.
  3. LLM Evaluation – Calls self._aask to generate a structured review.
  4. Result Parsing – Uses CodeParser.parse_block("Code Review Result", …) to extract the verdict (LGTM or LBTM).
  5. Conditional Rewrite – If LBTM, constructs REWRITE_CODE_TEMPLATE to generate corrected code.
  6. Iteration Control – Repeats up to code_validate_k_times (default 1, configurable via config.code_validate_k_times).
  7. Persistence – Writes the final code back to the repository and logs changes via EditorReporter.

Implementing Automated Code Review with WriteCodeReview

Direct Usage in Scripts

Instantiate WriteCodeReview directly when building custom workflows:

from metagpt.actions.write_code_review import WriteCodeReview
from metagpt.schema import CodingContext, Document
from metagpt.utils.project_repo import ProjectRepo

# Initialize workspace

repo = ProjectRepo(root_path="tmp_demo")
repo.init()

# Prepare context with code to review

code = """
def add(a, b):
    return a + 
"""
coding_ctx = CodingContext(
    filename="math.py",
    design_doc=Document(content="Implement a simple addition function."),
    code_doc=Document(content=code),
)

# Execute review

review_action = WriteCodeReview(i_context=coding_ctx, repo=repo, context=repo.context)
await review_action.run()

# Access rewritten code

print(coding_ctx.code_doc.content)

Using the ValidateAndRewriteCode Tool

For agent integration, use the registered tool wrapper:

from metagpt.actions.write_code_review import ValidateAndRewriteCode

# Configure validation iterations

await ValidateAndRewriteCode().run(
    code_path="my_project/math.py",
    system_design_input="Design doc: a simple arithmetic library.",
    project_schedule_input="Task: expose add(a, b) that returns a+b.",
    code_validate_k_times=2,
)

ValidateAndRewriteCode is decorated with @register_tool, enabling automatic invocation by other MetaGPT roles through the tool-calling interface.

Running Unit Tests

Verify the action behavior using the built-in test suite:

pytest -q tests/metagpt/actions/test_write_code_review.py

The test creates a CodingContext with intentionally broken code, invokes WriteCodeReview, and asserts that the resulting code_doc.content contains valid, non-empty source code.

Key Files in the Code Review Pipeline

File Purpose
metagpt/actions/write_code_review.py Core action implementation, prompt templates, and ValidateAndRewriteCode tool registration.
metagpt/actions/write_code.py Provides WriteCode.get_codes() for gathering contextual source files.
metagpt/utils/common.py Contains CodeParser for extracting structured blocks from LLM responses.
metagpt/utils/project_repo.py ProjectRepo abstraction for workspace I/O and document management.
metagpt/utils/report.py EditorReporter for logging review and rewrite events.
metagpt/schema.py Data models including CodingContext and Document.
tests/metagpt/actions/test_write_code_review.py Unit tests demonstrating expected usage patterns.

Summary

  • The WriteCodeReview action in MetaGPT automates code review by leveraging LLM prompts to evaluate source files against design specifications.
  • It implements an iterative review-rewrite loop that parses LLM verdicts (LGTM/LBTM) and automatically generates corrected code when issues are detected.
  • The action integrates seamlessly with MetaGPT's multi-agent architecture through ValidateAndRewriteCode, which is registered as a tool for automatic invocation by engineering roles.
  • Configuration options like code_validate_k_times allow tuning of review iterations for complex refactoring tasks.

Frequently Asked Questions

What is the WriteCodeReview action in MetaGPT?

The WriteCodeReview action is a core component of the MetaGPT framework that automates code quality assurance. It uses large language models to analyze source code against system design documents, generating structured feedback and automatically rewriting code when the review verdict is LBTM (looks bad to me) rather than LGTM (looks good to me).

How does WriteCodeReview handle code rewrites?

When the initial review detects issues, the action constructs a REWRITE_CODE_TEMPLATE prompt that includes the original code, the review comments, and specific instructions for correction. It then queries the LLM again to generate a fixed version, parses the response using CodeParser, and updates the code_doc.content field. This process repeats up to code_validate_k_times iterations.

Can I customize the number of review iterations?

Yes, the review loop is configurable via the code_validate_k_times parameter, which defaults to 1 but can be increased for complex codebases. When using the ValidateAndRewriteCode tool, pass code_validate_k_times=2 (or higher) to the run method. You can also set this globally in your MetaGPT configuration file under the code_validate_k_times key.

How do I integrate WriteCodeReview into a custom MetaGPT role?

You can integrate the action either by direct instantiation or through the tool registry. For direct use, instantiate WriteCodeReview with a CodingContext and ProjectRepo, then call await action.run(). For automatic tool invocation, use ValidateAndRewriteCode, which is decorated with @register_tool and can be called by any role through MetaGPT's standard tool-calling interface without manual context management.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →