Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:666ghj BettaFish ChapterGenerationNode run

From Leeroopedia
Knowledge Sources
Domains Report_Generation, NLP, LLM_Prompting
Last Updated 2026-10-08 00:00 GMT

Overview

Concrete node that generates chapter JSON conforming to an IR schema by calling an LLM with section context, validating the output with IRValidator, and applying repair logic for malformed JSON or block structures.

Description

The ChapterGenerationNode is the most complex node in the ReportEngine pipeline (2032 lines). For each template section, it: 1. Constructs a chapter-level payload (query, reports, word plan, layout, section metadata) 2. Calls the LLM in streaming mode, writing raw JSON to disk via ChapterStorage 3. Parses the LLM output using RobustJSONParser (with json_repair library) 4. Validates the parsed JSON against the IR schema using IRValidator 5. If validation fails, attempts block-level repair (alias normalization, structure fixing) 6. Falls back to alternative LLM clients if the primary fails 7. Returns validated chapter JSON dict with blocks, anchor, order, chapterId

The node handles many edge cases: incomplete JSON, missing blocks, heading-only chapters, paragraph fragments, and inline mark aliasing.

Usage

Import this node when you need to generate report chapters as IR-compliant JSON. It is called by ReportAgent for each section in the template.

Code Reference

Source Location

  • Repository: BettaFish
  • File: `ReportEngine/nodes/chapter_generation_node.py:L92-2032`

Signature

class ChapterGenerationNode(BaseNode):
    def __init__(
        self,
        llm_client,
        validator: IRValidator,
        storage: ChapterStorage,
        fallback_llm_clients: Optional[List[Tuple[str, Any]]] = None,
        error_log_dir: Optional[str | Path] = None,
    ):
        """
        Args:
            llm_client: Primary LLM client
            validator: IR structure validator
            storage: Chapter persistence manager
            fallback_llm_clients: Alternative LLM clients for retry
            error_log_dir: Directory for logging JSON repair failures
        """

    def run(
        self,
        section: TemplateSection,
        context: Dict[str, Any],
        run_dir: Path,
        stream_callback: Optional[Callable[[str, Dict[str, Any]], None]] = None,
        **kwargs,
    ) -> Dict[str, Any]:
        """
        Generate chapter JSON for one template section.

        Args:
            section: Template section with title/order/slug
            context: Generation context (query, reports, word plan, layout)
            run_dir: Output directory for chapter files
            stream_callback: Optional SSE delta callback

        Returns:
            Validated chapter JSON dict (chapterId, title, anchor, order, blocks)
        """

Import

from ReportEngine.nodes import ChapterGenerationNode
from ReportEngine.ir import IRValidator
from ReportEngine.core import ChapterStorage

I/O Contract

Inputs

Name Type Required Description
section TemplateSection Yes Chapter metadata (title, order, slug)
context Dict Yes Generation context (query, reports, word_plan, layout)
run_dir Path Yes Output directory
stream_callback Callable No SSE delta callback

Outputs

Name Type Description
chapter Dict IR-validated chapter JSON with blocks, anchor, order
raw_json file Raw LLM JSON persisted to disk by ChapterStorage

Usage Examples

Generate Chapter

from ReportEngine.nodes import ChapterGenerationNode
from ReportEngine.ir import IRValidator
from ReportEngine.core import ChapterStorage
from ReportEngine.llms import LLMClient

llm = LLMClient(api_key="sk-...", model_name="deepseek-chat", base_url="...")
validator = IRValidator()
storage = ChapterStorage()

node = ChapterGenerationNode(
    llm_client=llm,
    validator=validator,
    storage=storage,
)

chapter = node.run(
    section=sections[0],
    context={
        "query": "武汉大学舆情分析",
        "reports": normalized_reports,
        "word_plan": word_budget,
        "layout": layout_design,
    },
    run_dir=Path("./output/run1"),
)
print(f"Chapter: {chapter['title']} ({len(chapter['blocks'])} blocks)")

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment