# Plan-and-Solve

<p align="center">
  <strong>Improved Zero-Shot Reasoning via Planning</strong>
</p>

<p align="center">
  <a href="README_CN.md">中文文档</a> | <a href="README.md">English</a>
</p>

<p align="center">
  <a href="#architecture">Architecture</a> •
  <a href="#installation">Installation</a> •
  <a href="#quick-start">Quick Start</a> •
  <a href="#api-reference">API Reference</a>
</p>

---

A Python implementation of **Plan-and-Solve**, a framework that improves zero-shot reasoning by explicitly generating plans before solving problems.

## Architecture

```
Plan-and-Solve Architecture
│
├── PlanAndSolveAgent (Main Agent)
│   ├── Orchestrates planning and solving
│   ├── Handles iterative refinement
│   └── Manages self-checking
│
├── Planner (Plan Generator)
│   ├── Creates step-by-step plans
│   ├── Refines plans on failure
│   └── Manages plan dependencies
│
├── Solver (Plan Executor)
│   ├── Executes plan steps
│   ├── Tracks intermediate results
│   └── Builds final solution
│
└── SelfChecker (Solution Validator)
    ├── Validates solutions
    ├── Identifies issues
    └── Suggests improvements
```

## Core Workflow

```
┌─────────────────────────────────────────────────────────────────┐
│                    Plan-and-Solve Workflow                       │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│   Problem ──▶ Plan ──▶ Execute ──▶ Check ──▶ Solution          │
│                  │           │          │                        │
│                  │           │          └── Failed?              │
│                  │           │                  │                │
│                  │           └──────────────────┘                │
│                  │                   (Refine)                    │
│                  │                                                │
│                  └─────────────────────────────────────────────  │
│                        (Iterate until success)                   │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
```

## Installation

```bash
pip install plan-and-solve
```

## Quick Start

```python
from plansolve import PlanAndSolveAgent

# Define planning function (typically uses an LLM)
def plan_fn(problem: str) -> list:
    # Generate step-by-step plan
    # response = llm.generate(f"Plan how to solve: {problem}")
    return [
        "Understand the problem",
        "Identify key components",
        "Develop solution approach",
        "Execute the solution",
        "Verify the result"
    ]

# Define solving function
def solve_fn(step: str, context: dict) -> str:
    # Execute step with context from previous steps
    # response = llm.generate(f"Execute: {step}\nContext: {context}")
    return f"Result of: {step}"

# Create and run agent
agent = PlanAndSolveAgent(plan_fn=plan_fn, solve_fn=solve_fn)
result = agent.solve("Calculate 15 * 17 using mental math")

print(f"Success: {result.success}")
print(f"Answer: {result.answer}")
print(f"Plan steps: {len(result.plan.steps)}")
```

## Key Components

### Planner

Generates step-by-step plans for solving problems. Can be customized with domain-specific planning logic.

### Solver

Executes plans step by step, maintaining context and building the solution incrementally.

### SelfChecker

Validates solutions and identifies issues, enabling iterative refinement.

## CLI Usage

```bash
# Run a single problem
ps-agent run "What is 15 * 17?"

# Interactive mode
ps-agent interactive

# Export result
ps-agent run "Problem" --export result.json
```

## API Reference

### PlanAndSolveAgent

| Method | Description |
|--------|-------------|
| `solve(problem)` | Solve a problem with planning |
| `quick_solve(problem)` | Quick solve returning just answer |

| Parameter | Description |
|-----------|-------------|
| `plan_fn` | Function to generate plans |
| `solve_fn` | Function to execute steps |
| `check_fn` | Function to validate solutions |
| `max_iterations` | Maximum refinement iterations |

## Academic Reference

Implementation of the **Plan-and-Solve** paper:

> **Plan-and-Solve Prompting: Improving Zero-Shot Reasoning by Large Language Models**
>
> Lei Wang, Wanyu Xu, Yihuai Lan, Zhiqiang Hu, Yunshi Lan, Roy Ka-Wei Lee, Lidong Bing
>
> *ACL 2023*
>
> Paper: https://arxiv.org/abs/2305.04091

```bibtex
@inproceedings{wang2023plan,
  title={Plan-and-Solve Prompting: Improving Zero-Shot Reasoning by Large Language Models},
  author={Wang, Lei and Xu, Wanyu and Lan, Yihuai and Hu, Zhiqiang and Lan, Yunshi and Lee, Roy Ka-Wei and Bing, Lidong},
  booktitle={Proceedings of the Annual Meeting of the Association for Computational Linguistics (ACL)},
  year={2023}
}
```

## License

MIT License

---

<p align="center">
  Made with ❤️ by AI Agent Research Team
</p>