Multi-Step LLM Tasks in Practice: From Document Parsing to a Closed Delivery Loop

    Learn how to build reliable multi-step LLM agent workflows, including multimodal long-context parsing with a parse-extract-structure pipeline, a code-test feedback loop for long-running coding agents, framework evaluation pitfalls, coordinator-executor multi-agent division of labor, cost control strategies, and a pre-launch checklist for auditable, rollback-friendly delivery.

    1. How to Handle Multimodal Long-Context Parsing

    In everyday office work and research, source material is scattered across spreadsheets, PDFs, images, and audio/video files. Manually splitting, transcribing, and stitching everything together is slow and prone to information loss. An LLM can read multiple formats in a single task—but only if the pipeline is designed properly. A three-step architecture is recommended: parse, extract, structure.

    The code below is illustrative pseudocode. You need to implement parse_file and build_context yourself based on the parsing libraries you actually use; only the structure and key control points are shown here.

    1. import json
    2. from pathlib import Path
    3. SUPPORTED_SUFFIXES = {".pdf", ".xlsx", ".csv", ".png", ".jpg", ".wav", ".mp3", ".mp4"}
    4. INPUT_TOKEN_BUDGET = 800_000 # Leave headroom for output and tool calls
    5. def check_file(path: Path) -> None:
    6. if not path.exists():
    7. raise FileNotFoundError(f"File not found: {path}")
    8. if path.suffix.lower() not in SUPPORTED_SUFFIXES:
    9. raise ValueError(f"Unsupported file type: {path.suffix}")
    10. def process_multimodal_docs(file_paths, instruction, llm_client, max_retries=2):
    11. paths = [Path(p) for p in file_paths]
    12. for p in paths:
    13. check_file(p)
    14. # 1. Parse: convert each file into text chunks with source tags
    15. chunks = []
    16. for p in paths:
    17. chunks.extend(parse_file(p)) # Returns [{"source": ..., "text": ...}]
    18. # 2. Budget control: truncate low-priority content when over budget, and log it
    19. context = build_context(chunks, INPUT_TOKEN_BUDGET)
    20. prompt = f"""Analyze the following materials, extract key information, and generate a structured report.
    21. Task requirements: {instruction}
    22. Output only results conforming to the JSON Schema; use null for fields that cannot be determined.
    23. Materials:
    24. {context}"""
    25. # 3. Structured output: retry on parse failure; raise after exceeding retry limit
    26. for attempt in range(max_retries + 1):
    27. raw = llm_client.generate(prompt)
    28. try:
    29. return json.loads(raw)
    30. except json.JSONDecodeError:
    31. if attempt == max_retries:
    32. raise

    Key considerations for implementation:

    • File type validation: Only process whitelisted formats. Prevent the model from reading executables or archives.
    • Token budget: Long documents can fill the context window. When over budget, truncate by priority and preserve source information so results remain traceable for manual review.
    • Output validation: Require JSON output and validate it with a parser. Retry on failure—never use unchecked results directly.
    • Permissions and data scope: The agent should only read files designated for the task. Materials containing personal information or trade secrets should be de-identified before being sent to the model and confirmed by the data owner.

    A concrete example: feed the agent an engineering drawing PDF with dimension annotations. The agent extracts the annotated text and table regions, then outputs a CSV dimension table. A human verifies the critical dimensions before archiving. The boundaries of this approach are clear, and failures are easy to locate.

    2. How a Long-Running Coding Agent Closes the Test Feedback Loop

    Traditional code assistants are good at single-shot generation, such as writing one function. Real engineering tasks—cross-file refactoring, system-level debugging—require the agent to work continuously: read code, modify code, run tests, and iterate based on errors.

    Below is a typical feedback loop. The commands are illustrative; replace paths and the test framework with your own.

    1. # Example commands: assumes the project uses pytest 8.x, run from the repo root
    2. # Prerequisites: virtual environment activated, dependencies installed, test data de-identified
    3. cd /path/to/your-repo
    4. python -m pytest tests/test_auth.py -x --tb=short

    The agent’s workflow typically has four steps:

    1. Task understanding and file indexing: Traverse the project directory, map dependencies between modules, and record test entry points.
    2. Change planning and code modification: List the modification plan based on requirements, locate target files, and generate patches. Changes should be confined to planned files.
    3. Run tests and read errors: Execute the test command and capture failed cases and stack traces. The agent uses these to pinpoint the specific file and line, then proposes a fix.
    4. Context compression: As the session grows, the agent summarizes completed steps, discards repetitive intermediate logs, and keeps only unresolved issues and key error messages.

    Common problems worth addressing in advance:

    • Flaky tests: When the same case passes sometimes and fails other times, the agent may misdiagnose it as a code problem. Isolate flaky cases before entering the fix loop.
    • Sensitive data in logs: Error logs may contain tokens or user data. De-identify them before writing into context.
    • Excessive execution privileges: The agent should run in a sandbox with read/write access limited to test and code directories. Never give it production credentials.
    • Infinite loops: Set a maximum iteration count. If tests still fail after several consecutive fixes, stop and hand over to a human.

    3. Why Does the Same Model Perform Differently Across Frameworks?

    When evaluating agent systems, looking only at a model’s base benchmark scores can be misleading. In multi-step tasks, the model handles reasoning, but tool interfaces, prompt templates, and context truncation strategies determine whether that reasoning translates into results. The same model, placed in a framework with poorly designed tool interfaces and messy state management, may show a noticeably lower completion rate.

    If you want to compare two frameworks, control the variables: use the same test set, the same model version, the same number of runs, and document the measurement methodology. When citing any pass-rate figure, also state the benchmark name, test set size, model version, framework, and test date. Numbers missing this information should not drive decisions.

    4. How to Divide Work in Multi-Agent Collaboration

    On large projects, a single-threaded agent easily hits context overload or logical deadlock. Multi-agent collaboration splits the task across different roles. The most common pattern is the coordinator-executor model. The table below compares selection criteria for the two roles.

    Dimension Coordinator / Architect Executor
    Model choice The strongest reasoning model A lightweight, fast model
    Main responsibilities Break down requirements, design architecture, dispatch tasks, review results Atomic tasks such as single-file edits and unit test writing
    Context scope Retains global structure without loading every detail Loads only the assigned files and instructions
    Failure handling Reassigns tasks or adjusts the plan based on failure reports Limited retries; escalates to the coordinator after exceeding the limit
    Cost profile Few calls, high cost per call Many calls, low cost per call
    Main risk Reviews may miss details Multiple executors may edit the same file concurrently

    When multiple executors work in parallel, the top risk is file conflicts. Assign file ownership by module so that each file is handled by only one executor at a time. Before merging, the coordinator should run the full test suite.

    5. What Drives Cost, and How to Control It

    Long documents and multi-round testing consume tokens quickly. Per-task cost typically consists of:

    • Input tokens, including long documents and context repeatedly loaded each round;
    • Output tokens, including reasoning and generated code;
    • Tool call counts;
    • Retries after failures;
    • Repeated computation caused by cache misses.

    Cost control can start from four angles:

    • Cache repeated context: When the same materials are reused across rounds, prioritize cache reuse.
    • Route models by difficulty: Assign simple format conversions to lightweight models and complex reasoning to stronger models.
    • Set budget caps: Define a token or dollar limit per task and trigger alerts when approaching it.
    • Logging and auditing: Record every tool call and token usage for post-hoc analysis. De-identify logs before writing; never record keys or personal information.

    Materials can be centrally managed in object storage, with tasks running in containers for easy scaling based on load. Access permissions should be isolated per project—the agent can only access the resources its current task requires.

    6. Pre-Launch Checklist

    • File type whitelist configured; out-of-scope files are rejected.
    • Input token budget cap in place, with a truncation strategy and logging when exceeded.
    • Model output validated against JSON or a schema, with a retry limit on failure.
    • Sensitive information de-identified before entering the model.
    • Agent runs in a sandbox; credentials follow least-privilege principles.
    • Test commands, dependency versions, and runtime environment documented in the project.
    • For parallel multi-agent edits, each file has exactly one owner.
    • Cost alert thresholds set; tasks can be paused when exceeded.
    • Key conclusions reviewed by a human before delivery.

    The value of LLMs in multi-step tasks depends on whether the pipeline actually works end to end. Turning document parsing, code feedback, and multi-role collaboration into processes that are checkable, rollback-friendly, and auditable is what lets the model reliably close the loop from reading source material to delivering the final report.