# How MathModelWorkFlow Orchestrates the Mathematical Modeling Process in jihe520/mathmodelagent

> Discover how MathModelWorkFlow in jihe520/mathmodelagent orchestrates mathematical modeling. This guide explores its state machine and LLM agents for creating competition-ready reports efficiently. Learn more today.

- Repository: [Sanjin/mathmodelagent](https://github.com/jihe520/mathmodelagent)
- Tags: how-to-guide
- Published: 2026-03-04

---

**The MathModelWorkFlow class acts as a deterministic state machine that coordinates four specialized LLM agents—Coordinator, Modeler, Coder, and Writer—to transform raw problem descriptions into complete, competition-ready modeling reports through an asynchronous, multi-stage pipeline.**

The `MathModelWorkFlow` class in the [jihe520/mathmodelagent](https://github.com/jihe520/mathmodelagent) repository serves as the central orchestrator for end-to-end mathematical modeling automation. Located in [`/backend/app/core/workflow.py`](https://github.com/jihe520/mathmodelagent/blob/main//backend/app/core/workflow.py), its `execute` coroutine (lines 32-84) implements a rigid pipeline that decomposes academic problems, generates executable Python code, and drafts LaTeX-formatted research papers without human intervention.

## Workflow Initialization and LLM Factory Setup

The orchestration begins by instantiating isolated language model clients through the `LLMFactory` pattern. This ensures each task maintains separate LLM contexts for different cognitive roles.

```python
llm_factory = LLMFactory(self.task_id)
coordinator_llm, modeler_llm, coder_llm, writer_llm = llm_factory.get_all_llms()

```

The factory returns four distinct clients: **Coordinator** (intent analysis), **Modeler** (solution architecture), **Coder** (code generation), and **Writer** (report composition). Each client operates under the same `task_id` but maintains separate conversation histories and system prompts.

## Stage 1: Coordinator Agent Intent Recognition

The workflow delegates initial problem analysis to the `CoordinatorAgent`, which extracts the overall intent and decomposes complex problems into discrete sub-questions.

```python
coordinator_agent = CoordinatorAgent(self.task_id, coordinator_llm)
coordinator_response = await coordinator_agent.run(problem.ques_all)

```

According to the A2A schema defined in [`/backend/app/schemas/A2A.py`](https://github.com/jihe520/mathmodelagent/blob/main//backend/app/schemas/A2A.py) (lines 5-7), the coordinator returns a `CoordinatorToModeler` object containing `questions` and `ques_count` fields. This structured output enables parallel processing of multi-part mathematical problems by subsequent agents.

## Stage 2: Modeler Agent Solution Architecture

Following intent recognition, the `ModelerAgent` consumes the coordinator's decomposition and generates a high-level solution sketch. This stage translates natural language requirements into a JSON-structured execution plan.

```python
modeler_agent = ModelerAgent(self.task_id, modeler_llm)
modeler_response = await modeler_agent.run(coordinator_response)

```

The modeler's output adheres to the `ModelerToCoder` schema (implemented in [`/backend/app/core/agents/modeler_agent.py`](https://github.com/jihe520/mathmodelagent/blob/main//backend/app/core/agents/modeler_agent.py), lines 22-48), specifying mathematical approaches, required datasets, and algorithmic strategies. This JSON outline serves as the technical blueprint that drives all subsequent code generation.

## Stage 3: Environment Preparation and Code Execution

Before invoking the coder, the workflow initializes a sandboxed execution environment and research tools.

### Jupyter Interpreter Provisioning

The `create_interpreter` factory (located in [`/backend/app/tools/interpreter_factory.py`](https://github.com/jihe520/mathmodelagent/blob/main//backend/app/tools/interpreter_factory.py)) spawns an isolated Jupyter notebook kernel. A `NotebookSerializer` attaches to this interpreter to persist execution history and generated artifacts.

### Literature Search Integration

An `OpenAlexScholar` instance initializes for academic paper retrieval, configured via `settings.OPENALEX_EMAIL` for API access to relevant mathematical modeling precedents.

## Stage 4: Coder Agent Implementation

The CoderAgent operates within a loop defined by the **Flows** object ([`/backend/app/core/flows.py`](https://github.com/jihe520/mathmodelagent/blob/main//backend/app/core/flows.py), lines 26-59), processing each sub-task from the modeler's outline sequentially.

```python

# Pseudocode representing the sub-task iteration

for subtask in flows.get_coder_flows():
    prompt = flows.build_coder_prompt(modeler_response, subtask)
    result = await coder_agent.run(prompt, subtask_title)
    interpreter.execute(result.code)
    user_output.persist_figures(interpreter.artifacts)

```

The coder implements a **write-run-retry** pattern: it generates Python code, executes it in the sandboxed interpreter, analyzes error traces, and automatically regenerates corrected implementations until successful execution or maximum retry limits. Generated figures automatically persist to the task's working directory through `UserOutput` handlers.

## Stage 5: Writer Agent Report Composition

Concurrent with coding completion, the workflow triggers the `WriterAgent` to draft textual sections. The `Flows` class generates writer prompts that blend the coder's output, interpreter execution logs, and LaTeX/Markdown templates (`config_template`).

```python
writer_prompt = flows.get_writer_prompt(subtask_key, code_result, interpreter_output)
writer_message = await writer_agent.run(writer_prompt)
user_output.store_section(subtask_key, writer_message)

```

Each `WriterMessage` populates a `UserOutput` container, building the report incrementally as sub-tasks complete.

## Stage 6: Write-Up Phase and Final Assembly

After processing all solution sub-tasks, the workflow executes a second pass through `flows.get_write_flows()` to generate high-level document sections.

These **non-executable** sections include:
- Title page and abstract generation
- Model assumption documentation
- Evaluation and sensitivity analysis narratives
- Conclusion synthesis

The writer agent processes these prompts without interpreter interaction, filling the remaining structural components of the academic paper.

## Real-Time Feedback and State Management

Throughout execution, the workflow maintains WebSocket communication via `redis_manager.publish_message` (defined in [`/backend/app/services/redis_manager.py`](https://github.com/jihe520/mathmodelagent/blob/main//backend/app/services/redis_manager.py)). Status updates—including stage transitions like "识别用户意图和拆解问题完成,任务转交给建模手"—push to the frontend every major pipeline transition (workflow.py, lines 55-62).

The orchestration maintains state through the `SystemMessage` schema, enabling clients to track progress from problem decomposition through final document generation.

## Summary

- **MathModelWorkFlow** implements a deterministic five-stage pipeline: Intent → Architecture → Code → Draft → Assemble.
- The `execute` coroutine in [`/backend/app/core/workflow.py`](https://github.com/jihe520/mathmodelagent/blob/main//backend/app/core/workflow.py) coordinates four specialized LLM agents through the `LLMFactory` pattern, ensuring task isolation.
- **CoordinatorAgent** decomposes problems via the `CoordinatorToModeler` schema; **ModelerAgent** outputs JSON solution blueprints.
- **CoderAgent** executes a write-run-retry loop within sandboxed Jupyter interpreters, persisting figures through `UserOutput`.
- **WriterAgent** composes sections using blended prompts from the `Flows` class, handling both executable solution text and high-level academic narrative.
- Real-time progress streams through Redis-backed WebSocket messages, providing frontend visibility into the mathematical modeling automation.

## Frequently Asked Questions

### How does MathModelWorkFlow handle multi-part mathematical problems?

The workflow leverages the **CoordinatorAgent** to split complex problem statements into discrete sub-questions stored in the `CoordinatorToModeler` schema. The `Flows` object (lines 26-59 in [`flows.py`](https://github.com/jihe520/mathmodelagent/blob/main/flows.py)) then iterates over these sub-tasks, allowing the **CoderAgent** and **WriterAgent** to process each component sequentially while maintaining contextual coherence through the shared `task_id` and `UserOutput` persistence layer.

### What execution environment does the CoderAgent use for generated code?

The CoderAgent operates within a sandboxed **Jupyter notebook interpreter** created via `create_interpreter` in [`/backend/app/tools/interpreter_factory.py`](https://github.com/jihe520/mathmodelagent/blob/main//backend/app/tools/interpreter_factory.py). This environment includes a `NotebookSerializer` for execution history persistence and implements automatic error handling where the LLM analyzes traceback outputs and regenerates corrected code until successful execution or retry exhaustion.

### How does the workflow separate solution generation from final report writing?

MathModelWorkFlow implements a **two-pass architecture**: the first pass (`flows.get_coder_flows()`) handles executable sub-tasks requiring Python computation and figure generation, while the second pass (`flows.get_write_flows()`) generates non-executable narrative sections including abstracts, assumptions, and evaluations. Both passes utilize the same `WriterAgent` but with different prompt templates and execution contexts.

### Where is the final modeling report stored after workflow completion?

Upon completion of all sub-tasks, the workflow invokes `user_output.save_result()` (defined in [`/backend/app/models/user_output.py`](https://github.com/jihe520/mathmodelagent/blob/main//backend/app/models/user_output.py)), which writes the compiled markdown document and ancillary files (figures, data exports) to the task-specific working directory. This persistence mechanism captures both the computational artifacts from the interpreter and the textual sections generated by the WriterAgent.