https://github.com/longcipher/pocketflow-rs
Pocket Flow: A minimalist AI workflow framework.
https://github.com/longcipher/pocketflow-rs
Last synced: 10 months ago
JSON representation
Pocket Flow: A minimalist AI workflow framework.
- Host: GitHub
- URL: https://github.com/longcipher/pocketflow-rs
- Owner: longcipher
- License: other
- Created: 2025-04-28T07:09:47.000Z (about 1 year ago)
- Default Branch: master
- Last Pushed: 2025-08-08T08:37:01.000Z (11 months ago)
- Last Synced: 2025-08-08T10:24:23.857Z (11 months ago)
- Language: Rust
- Homepage:
- Size: 299 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# PocketFlow-RS
A modern workflow framework ecosystem for Rust, providing type-safe, async workflow execution with powerful integrations including AI agents, cognitive capabilities, and tool automation.
## π¦ Workspace Structure
This is a Cargo workspace containing five specialized crates:
### [`pocketflow-core`](./pocketflow-core/)
The foundation workflow framework providing:
- Type-safe state management with compile-time guarantees
- Async/await support built on Tokio and dptree
- Flexible context system with typed and JSON storage
- Node-based architecture with dependency injection
- Advanced flows with middleware and analytics
- Batch processing and error handling with eyre
### [`pocketflow-mcp`](./pocketflow-mcp/)
Model Context Protocol (MCP) integration for workflows:
- MCP client integration for calling external tools
- MCP server implementation to expose workflow capabilities
- Seamless context integration between MCP and workflows
- Registry management for multiple connections
- HTTP transport with authentication support
### [`pocketflow-cognitive`](./pocketflow-cognitive/)
Cognitive extensions adding AI reasoning capabilities:
- Chain-of-thought and reflection nodes
- Goal-oriented and hierarchical planning
- Multi-layered memory systems (working, episodic, semantic)
- Non-intrusive extension of existing Node types
- MCP integration for AI service calls
### [`pocketflow-agent`](./pocketflow-agent/)
AI Agent framework with genai integration:
- AgentNode implementation for LLM-powered workflows
- Multi-step agent execution with history tracking
- Tool registry integration for agent capabilities
- Streaming and multi-agent coordination support
- Support for multiple AI providers (OpenAI, etc.)
### [`pocketflow-tools`](./pocketflow-tools/)
Comprehensive tool system for workflow automation:
- Tool abstraction with JSON schema validation
- Tool registry for discovery and execution
- Built-in utilities for common operations
- Parameter validation and retry mechanisms
- Integration across the entire ecosystem
- New: Web search (simulate or HTTP GET) and Python execution tools (stdin, JSON stdout parsing)
## π Quick Start
### Basic Workflow with Core
```toml
[dependencies]
pocketflow-core = "0.2.0"
```
```rust
use pocketflow_core::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum WorkflowState {
Start, Processing, Success, Error
}
impl FlowState for WorkflowState {
fn is_terminal(&self) -> bool {
matches!(self, WorkflowState::Success | WorkflowState::Error)
}
}
struct ProcessingNode;
#[async_trait]
impl Node for ProcessingNode {
type State = WorkflowState;
async fn execute(&self, mut context: Context) -> Result<(Context, Self::State)> {
context.set("result", "processed")?;
Ok((context, WorkflowState::Success))
}
fn name(&self) -> String {
"ProcessingNode".to_string()
}
}
#[tokio::main]
async fn main() -> Result<()> {
let flow = SimpleFlow::builder()
.initial_state(WorkflowState::Start)
.node(WorkflowState::Start, ProcessingNode)
.build()?;
let result = flow.execute(Context::new()).await?;
println!("Final state: {:?}", result.final_state);
Ok(())
}
```
### AI Agent Workflow
```toml
[dependencies]
pocketflow-core = "0.2.0"
pocketflow-agent = "0.2.0"
pocketflow-tools = "0.2.0"
```
```rust
use pocketflow_agent::prelude::*;
use pocketflow_core::prelude::*;
use pocketflow_tools::prelude::*;
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<()> {
// Create agent configuration
let agent_config = AgentConfig {
name: "task_processor".to_string(),
model_config: ModelConfig {
provider: ModelProvider::OpenAI,
model_name: "gpt-4o-mini".to_string(),
..Default::default()
},
system_prompt: "You are a helpful task processing agent".to_string(),
..Default::default()
};
// Create tool registry
let mut tool_registry = ToolRegistry::new();
let text_tool = pocketflow_tools::custom::helpers::uppercase_tool();
tool_registry.register_tool(Box::new(text_tool)).await?;
// Create agent node with tools
let agent_node = AgentNode::new(agent_config)
.with_tools(Arc::new(tool_registry));
// Use in workflow
let mut context = Context::new();
context.set("input", "Process this text with AI")?;
let (result_context, _state) = agent_node.execute(context).await?;
if let Ok(Some(result)) = result_context.get_json::("agent_result") {
println!("Agent response: {:?}", result.final_answer);
}
Ok(())
}
```
### Cognitive Workflow with Planning
```toml
[dependencies]
pocketflow-core = "0.2.0"
pocketflow-cognitive = "0.2.0"
pocketflow-mcp = "0.2.0"
```
```rust
use pocketflow_cognitive::prelude::*;
use pocketflow_core::prelude::*;
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<()> {
// Mock MCP client for cognitive services
let mcp_client = Arc::new(MockMcpClient::new());
// Create planning node
let planner = GoalOrientedPlanningNode::builder()
.name("task_planner")
.with_mcp_client(mcp_client)
.with_goal(Goal {
id: "optimize_workflow".to_string(),
description: "Optimize data processing workflow".to_string(),
success_criteria: vec!["Reduce latency by 30%".to_string()],
constraints: vec!["Budget under $5k".to_string()],
priority: 8,
})
.on_success(WorkflowState::Success)
.on_error(WorkflowState::Error)
.build()?;
let flow = SimpleFlow::builder()
.initial_state(WorkflowState::Start)
.node(WorkflowState::Start, planner)
.build()?;
let result = flow.execute(Context::new()).await?;
println!("Planning completed: {:?}", result.final_state);
Ok(())
}
```
### Cognitive Agent and Plan Execution (think β plan β execute)
The cognitive crate includes ready-made nodes to chain reasoning, planning, and execution:
- CognitiveAgentNode: performs thinking then planning and stores results in context.
- IterativeCognitiveAgentNode: think β plan β reflect loop with optional simulated progress.
- PlanExecutionNode: executes plan steps via an MCP tool with robust success criteria.
Highlights:
- Success criteria enforcement per step: substring, regex, and JSON Pointer equals/exists/contains.
- Per-step overrides: enforce_success_criteria, max_retries, initial_backoff_ms, stop_on_error.
- Retries with exponential backoff and optional early stop-on-error.
Examples to try:
```bash
cargo run --example iterative_agent_demo --package pocketflow-cognitive
cargo run --example think_plan_execute --package pocketflow-cognitive
```
### Web Search + Python Tools Example
`pocketflow-tools` ships with two practical tools:
- WebSearchTool: perform simulated or HTTP GET-based search/fetch (JSON output)
- PythonExecutionTool: run Python code/files with timeout, stdin (string/JSON), and auto-parse stdout JSON into stdout_json
Run the end-to-end example:
```bash
cargo run --example search_and_python_flow --package pocketflow-tools
```
## ποΈ Architecture
```text
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββββββ
β pocketflow-core β β pocketflow-mcp β β pocketflow-cognitiveβ
βββββββββββββββββββ€ ββββββββββββββββββββ€ βββββββββββββββββββββββ€
β β’ Node trait β β β’ MCP Client β β β’ ThinkingNode β
β β’ Context β β β’ MCP Server β β β’ PlanningNode β
β β’ FlowState β β β’ Registry β β β’ Memory Systems β
β β’ SimpleFlow β β β’ Context Ext β β β’ Cognitive Traits β
β β’ AdvancedFlow β β β’ MCP Nodes β β β’ Goal-Oriented β
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββββββ
β β β
βββββββββ¬βββββββββββββββββΌββββββββββββββββββββββββββ
β β
βββββββββββββββββββββββββββ β βββββββββββββββββββββββ
β pocketflow-agent β β β pocketflow-tools β
βββββββββββββββββββββββββββ€ β βββββββββββββββββββββββ€
β β’ AgentNode β β β β’ Tool trait β
β β’ GenAI Integration β β β β’ ToolRegistry β
β β’ Multi-Agent Support β β β β’ Parameter Schema β
β β’ Execution History β β β β’ Validation β
β β’ Streaming β β β β’ Built-in Tools β
βββββββββββββββββββββββββββ β βββββββββββββββββββββββ
β β β
ββββββββββββββββββΌβββββββββββββββ
β
βββββββββββββββββββββββββββ
β Your Application β
β β
β β’ Custom Nodes β
β β’ Workflow Logic β
β β’ AI Agents β
β β’ Cognitive Planning β
β β’ Tool Integration β
β β’ MCP Services β
βββββββββββββββββββββββββββ
```
## π§ Development
The workspace is configured with shared dependencies and development tools:
```bash
# Format all code
just format
# Run all lints
just lint
# Test all crates
just test
# Run examples from specific crates
cargo run --example basic --package pocketflow-core
cargo run --example simple_agent_demo --package pocketflow-agent
cargo run --example thinking_workflow --package pocketflow-cognitive
cargo run --example simple_mcp_demo --package pocketflow-mcp
cargo run --example iterative_agent_demo --package pocketflow-cognitive
cargo run --example think_plan_execute --package pocketflow-cognitive
cargo run --example search_and_python_flow --package pocketflow-tools
```
## π Features by Crate
### Core Framework Features
- β
Type-safe state machines
- β
Async workflow execution
- β
Context management (typed + JSON)
- β
Node composition patterns
- β
Middleware system
- β
Analytics and monitoring
- β
Batch processing
- β
Error handling with eyre
### MCP Integration Features
- β
MCP client for tool calling
- β
MCP server implementation
- β
Workflow context extensions
- β
Registry management
- β
HTTP transport with authentication
- β³ WebSocket transport (planned)
- β³ Prompt templates (planned)
### Cognitive Extensions Features
- β
Chain-of-thought reasoning
- β
Goal-oriented planning
- β
Hierarchical planning
- β
Multi-layered memory systems
- β
Reflection and explanation nodes
- β
MCP integration for AI services
- β
Adaptive planning (node included; configurable)
- β
Plan execution with success criteria enforcement (substring/regex/JSON Pointer)
- β
Per-step overrides for enforcement and retry/backoff/stop-on-error
- β³ Learning capabilities (planned)
### AI Agent Features
- β
GenAI integration (OpenAI, etc.)
- β
AgentNode for workflow integration
- β
Multi-step execution with history
- β
Tool registry integration
- β
Streaming support
- β
Multiple agent coordination
- β³ Custom model providers (planned)
- β³ Advanced agent orchestration (planned)
### Tool System Features
- β
Tool abstraction with JSON schema
- β
Parameter validation
- β
Tool registry and discovery
- β
Built-in utility tools
- β
Retry and timeout mechanisms
- β
Custom tool development
- β
Web search tool (simulate/HTTP GET, header/limit support)
- β
Python execution tool (stdin string/JSON, stdout JSON auto-parse)
- β³ Tool composition (planned)
- β³ Advanced caching (planned)
## π― Use Cases
### Data Processing Pipelines
Use `pocketflow-core` for structured data transformations with state tracking and error handling.
### AI-Powered Workflows
Combine `pocketflow-agent` with `pocketflow-tools` to build intelligent workflows that can reason, plan, and execute complex tasks using LLMs.
### Cognitive Task Planning
Use `pocketflow-cognitive` for workflows that need planning, reasoning, and memory capabilities for complex problem-solving.
### API Orchestration
Chain multiple service calls with error handling, retry logic, and state management using the core framework.
### Tool Automation
Use `pocketflow-tools` to create standardized, validated tool interfaces for workflow automation.
### AI Agent Ecosystems
Build multi-agent systems using `pocketflow-agent` with coordination, communication, and task delegation.
### MCP Service Integration
Use `pocketflow-mcp` as a protocol for service-to-service communication and external tool integration within workflows.
## π Documentation
- [Core Framework Documentation](./pocketflow-core/README.md)
- [MCP Integration Documentation](./pocketflow-mcp/README.md)
- [Cognitive Extensions Documentation](./pocketflow-cognitive/README.md)
- [AI Agent Framework Documentation](./pocketflow-agent/README.md)
- [Tool System Documentation](./pocketflow-tools/README.md)
- [API Documentation](https://docs.rs/pocketflow-core)
- [Examples Directory](./pocketflow-core/examples/)
## π€ Contributing
Contributions are welcome! Please:
1. Check existing issues and PRs
2. Follow the coding conventions
3. Add tests for new features
4. Update documentation as needed
## π License
This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.