Complete Python Implementation of Easy-notebook-advance Frontend Workflow
Notebook-BCC is a complete Python reimplementation of the TypeScript/React workflow system from Easy-notebook-advance. It replicates the entire state machine, stores, executors, and notebook management system with high fidelity.
- β State Machine: Full FSM with hierarchical states (Workflow β Stage β Step β Behavior β Action)
- β Variable Management: Context-aware variable storage across workflow steps
- β TODO List Management: Task tracking with completion status
- β Notebook System: Cell management (code, markdown, thinking cells)
- β Code Execution: Remote Jupyter kernel execution via HTTP API
- β
API Integration: Workflow (
/generating,/planning) and code execution APIs - β Custom Context: Inject user-defined context into API calls
- β Step Control: Limit execution steps, pause/resume (breakpoint debugging)
- β Start Modes: Choose reflection (feedback-driven) or generation (action-driven)
- β Markdown Rendering: Terminal-friendly markdown display with colors
- β CLI Interface: Command-line and interactive REPL modes
- β Persistence: Save/load notebooks and export to markdown
Notebook-BCC/
βββ core/ # State machine core
β βββ state_machine.py # FSM implementation
β βββ states.py # State definitions
β βββ events.py # Event definitions
β βββ context.py # Execution context
βββ stores/ # State management stores
β βββ ai_context_store.py # Variables, TODOs, effects
β βββ pipeline_store.py # Workflow structure
β βββ script_store.py # Action management
β βββ notebook_store.py # Cell management
βββ models/ # Data models
β βββ workflow.py # Workflow structure
β βββ action.py # Action definitions
β βββ cell.py # Notebook cells
βββ executors/ # Execution engines
β βββ code_executor.py # Python code execution
β βββ action_executor.py # Action orchestration
βββ notebook/ # Notebook management
β βββ notebook_manager.py # File operations
β βββ markdown_renderer.py# Markdown display
β βββ cell_renderer.py # Cell rendering
βββ cli/ # Command-line interface
βββ commands.py # CLI commands
βββ repl.py # Interactive REPL
cd Notebook-BCC
# Install dependencies
pip install -r requirements.txt
# Or install manually
pip install requests aiohttp # Required for API communication
pip install numpy pandas matplotlib # Optional, for data science featuresNotebook-BCC communicates with two backend services:
- Backend Jupyter Kernel (default:
http://localhost:18600) - Executes Python code - DSLC Workflow API (default:
http://localhost:28600) - Manages workflow logic
Create a .env file from the template:
cp .env.example .env
# Edit .env with your settingsExample .env:
BACKEND_BASE_URL=http://localhost:18600
DSLC_BASE_URL=http://localhost:28600
NOTEBOOK_ID= # Optional: existing notebook session IDOverride configuration at runtime:
python main.py \
--backend-url http://localhost:9000 \
--dslc-url http://localhost:9001 \
--notebook-id abc123 \
start --problem "Analyze data"Configuration precedence: Command-line args > Environment variables > Defaults
Inject custom data into API calls:
# Via JSON string
python main.py --custom-context '{"user":"alice","priority":"high"}' start
# Via file
python main.py --custom-context context.json startControl execution for debugging:
# Limit to 10 steps
python main.py --max-steps 10 start --problem "Debug workflow"
# Interactive mode (pause at limits)
python main.py --max-steps 5 --interactive startNew in v2.0: All workflows use the unified "Planning First" protocol.
# All executions follow this flow:
# STEP β /planning (check) β /generating (if needed) β execute
python main.py start --problem "Analyze data"Execution Flow:
- Planning First: Every step calls
/planningAPI to check if target is achieved - Conditional Generation: Only calls
/generatingAPI if more actions needed - Intelligent Execution: Avoids redundant work by checking completion status first
π See ADVANCED_USAGE.md for detailed examples and best practices.
# Start a new workflow
python main.py start --problem "Analyze dataset" --context "Sales data Q4 2024"
# Start with custom backend services
python main.py --backend-url http://localhost:9000 start --problem "Data analysis"
# Use existing notebook session
python main.py --notebook-id abc123 start --problem "Continue analysis"
# Show workflow status
python main.py status
# List notebooks
python main.py list
# Show notebook content
python main.py show --notebook notebook_20240101_120000.json
# Export to markdown
python main.py export notebook_20240101_120000.json --output analysis.md# Preview request without sending
python main.py test-request \
--state-file ./docs/examples/ames_housing/payloads/00_STATE_IDLE.json \
--api-type planning
# Export to file
python main.py test-request \
--state-file state.json \
--api-type generating \
--output request_payload.json \
--format prettySee TEST_REQUEST_USAGE.md for detailed guide.
# Apply transition XML to state and generate updated state
python main.py apply-transition \
--state-file ./docs/examples/ames_housing/payloads/00_STATE_IDLE.json \
--transition-file ./docs/examples/ames_housing/payloads/00_Transition_planning_START_WORKFLOW.xml \
--output ./test/updated_state.json \
--format prettyUse cases:
- Simulate workflow state transitions offline
- Test state transformation logic
- Debug workflow progression
- Generate example states for documentation
See APPLY_TRANSITION_USAGE.md for detailed guide.
# Start the REPL
python main.py replInside the REPL:
(workflow) > start My Analysis Task
(workflow) > status
(workflow) > var set dataset_path "/data/analysis.csv"
(workflow) > todo add "Load dataset"
(workflow) > exec print("Hello from Python!")
(workflow) > save my_notebook.json
(workflow) > quit
from Notebook-BCC import (
WorkflowStateMachine,
PipelineStore,
ScriptStore,
NotebookStore,
AIPlanningContextStore,
CodeExecutor
)
# Initialize stores
pipeline_store = PipelineStore()
notebook_store = NotebookStore()
ai_context_store = AIPlanningContextStore()
code_executor = CodeExecutor()
script_store = ScriptStore(
notebook_store=notebook_store,
ai_context_store=ai_context_store,
code_executor=code_executor
)
# Create state machine
state_machine = WorkflowStateMachine(
pipeline_store=pipeline_store,
script_store=script_store,
ai_context_store=ai_context_store
)
# Initialize workflow
workflow = pipeline_store.initialize_workflow({
'problem_name': 'Data Analysis',
'user_goal': 'Analyze sales data',
})
# Start execution
pipeline_store.start_workflow_execution(state_machine)
# Check status
print(state_machine.get_state_info())IDLE
β START_WORKFLOW
STAGE_RUNNING
β START_STEP
STEP_RUNNING
β START_BEHAVIOR
BEHAVIOR_RUNNING
β START_ACTION
ACTION_RUNNING
β COMPLETE_ACTION
ACTION_COMPLETED
β (more actions or COMPLETE_BEHAVIOR)
BEHAVIOR_COMPLETED
β (feedback check)
STEP_COMPLETED
β (next step or COMPLETE_STAGE)
STAGE_COMPLETED
β (next stage or COMPLETE_WORKFLOW)
WORKFLOW_COMPLETED
- START_*: Start workflow/stage/step/behavior/action
- COMPLETE_*: Complete current level
- NEXT_*: Move to next sibling at same level
- UPDATE_*: Request workflow/step updates
- FAIL/CANCEL/RESET: Control events
- Markdown: Text content with markdown formatting
- Code: Python code cells with execution
- Thinking: AI thinking display cells
- Outcome: Result display cells
- Error: Error display cells
# Execute code in isolated namespace
result = code_executor.execute("""
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3]})
print(df)
""")
# Access namespace
variables = code_executor.get_all_variables()Supports:
- Headers (# ## ###)
- Bold (text)
- Italic (text)
- Inline code (
code) - Links (text)
- ANSI colors for terminal
- Color-coded cell types
- Line numbers (optional)
- Output display
- Error highlighting
from notebook import NotebookManager
manager = NotebookManager()
# Save notebook
path = manager.save_notebook(notebook_data, filename="analysis.json")
# Load notebook
notebook = manager.load_notebook("analysis.json")
# Export to markdown
md_path = manager.export_to_markdown(notebook_data)# Add variables
ai_context_store.add_variable("dataset_path", "/data/sales.csv")
ai_context_store.add_variable("start_date", "2024-01-01")
# Get variables
path = ai_context_store.get_variable("dataset_path")
# List all
context = ai_context_store.get_context()
print(context.variables)# Add TODOs
ai_context_store.add_to_do_list("Load dataset")
ai_context_store.add_to_do_list("Clean data")
ai_context_store.add_to_do_list("Train model")
# Check completion
if ai_context_store.is_cur_step_completed():
print("All tasks done!")# Add execution effects
ai_context_store.add_effect("Loaded 1000 rows")
ai_context_store.add_effect("Missing values: 5")
# Get effects
context = ai_context_store.get_context()
print(context.effect['current'])# Start workflow
state_machine.start_workflow(stage_id="stage_1", step_id="step_1")
# Manual transitions
state_machine.transition(WorkflowEvent.START_STEP)
# Get status
info = state_machine.get_state_info()
# Reset
state_machine.reset()# Add action
action = ScriptAction(
id="action_1",
type="code",
content="print('Hello')"
)
script_store.add_action(action)
# Execute action
step = ExecutionStep(action="exec", codecell_id="action_1")
script_store.exec_action(step)# Add cell
cell_data = {
'id': 'cell_1',
'type': 'code',
'content': 'print("Hello")'
}
notebook_store.add_cell(cell_data)
# Get cells
cells = notebook_store.cells
# Export
notebook_data = notebook_store.to_dict()import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)(workflow) > status# Get execution history
history = state_machine.history
for entry in history:
print(f"{entry.from_state} -> {entry.to_state} via {entry.event}")# Run example
python examples/simple_workflow.py
# Test CLI
python main.py repl# Extend ACTION_TYPES in script_store.py
ACTION_TYPES['MY_ACTION'] = 'my_action'
# Add handler in exec_action
elif action_type == ACTION_TYPES['MY_ACTION']:
# Your custom logic here
pass| Feature | Frontend (TS) | Backend (Python) |
|---|---|---|
| State Machine | β Zustand | β Class-based |
| Stores | β Zustand | β Class-based |
| Events | β Enum | β Enum |
| States | β Enum | β Enum |
| Actions | β TypeScript | β Python |
| Cells | β React | β Terminal |
| Persistence | β Browser | β File System |
| Rendering | β HTML/CSS | β ANSI/Terminal |
This is a faithful Python recreation of the TypeScript workflow system. Contributions should maintain compatibility with the frontend design patterns.
[Your License Here]
- Original Frontend: Hu Silan
- Python Implementation: Hu Silan
- Based on Easy-notebook-advance frontend workflow system
- Implements the complete state machine and execution model
- Maintains architectural fidelity with the TypeScript original