-
Notifications
You must be signed in to change notification settings - Fork 3.1k
feat(export): Add workflow export as standalone Python/FastAPI service #2602
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: staging
Are you sure you want to change the base?
Conversation
|
@aadamsx is attempting to deploy a commit to the Sim Team on Vercel. A member of the Team first needs to authorize it. |
Greptile SummaryThis PR adds workflow export as standalone Python/FastAPI services. The implementation includes pre-export validation for unsupported block types and providers, JavaScript-to-Python transpilation, and comprehensive ZIP generation with all necessary runtime files. Key Changes:
Architecture:
Minor Observations:
Confidence Score: 4/5
Important Files Changed
Sequence DiagramsequenceDiagram
participant User
participant UI as WorkflowItem
participant Hook as useExportService
participant API as /api/workflows/[id]/export-service
participant DB as Database
participant Validator as Workflow Validator
participant Transpiler as JS→Python Transpiler
participant ZipGen as ZIP Generator
User->>UI: Right-click workflow
UI->>UI: Show context menu
User->>UI: Click "Export as Service"
UI->>Hook: handleExportService()
Hook->>Hook: Check isExportingRef
Hook->>Hook: setIsExporting(true)
Hook->>API: GET /api/workflows/{id}/export-service
API->>API: Authenticate user/API key
API->>DB: Query workflow by ID
DB-->>API: Return workflow data
API->>API: Fetch workflow state & variables
API->>Validator: validateWorkflowForExport(state)
Validator->>Validator: Check block types
Validator->>Validator: Check provider support
alt Has unsupported blocks/providers
Validator-->>API: Return validation errors
API-->>Hook: 400 with error details
Hook->>Hook: addNotification(error)
Hook->>Hook: setIsExporting(false)
Hook-->>User: Show error notification
else Validation passes
Validator-->>API: Valid workflow
API->>Transpiler: preTranspileWorkflow(state)
Transpiler->>Transpiler: Convert JS blocks to Python
Transpiler-->>API: Transpiled workflow
API->>ZipGen: Generate service ZIP
ZipGen->>ZipGen: Create workflow.json
ZipGen->>ZipGen: Create .env with API keys
ZipGen->>ZipGen: Add Python executor files
ZipGen->>ZipGen: Add Dockerfile & docker-compose
ZipGen->>ZipGen: Add README.md
ZipGen-->>API: ZIP buffer
API-->>Hook: 200 with ZIP file
Hook->>Hook: Create blob & download link
Hook->>Hook: Trigger browser download
Hook->>Hook: setIsExporting(false)
Hook->>Hook: onSuccess?.()
Hook-->>User: Download workflow-service.zip
end
|
eeb6716 to
9140955
Compare
Adds the ability to export Sim Studio workflows as standalone, self-contained Python services that can be deployed independently via Docker, Railway, or any container platform. ## Features ### Multi-Provider LLM Support - **Anthropic**: Claude 3/4 models (Opus, Sonnet, Haiku) - **OpenAI**: GPT-4, GPT-4o, o1, o3 models - **Google**: Gemini Pro, Gemini Flash models - Automatic provider detection from model name - Provider-specific API key environment variables ### Supported Block Types - Start/Trigger blocks - Agent blocks (with multi-provider support) - Function blocks (JavaScript transpiled to Python) - Condition/Router blocks - API blocks (HTTP requests) - Loop blocks (for, forEach, while, doWhile) - Variables blocks - Response blocks ### Export Validation - Pre-export validation for unsupported block types - Pre-export validation for unsupported providers - Clear error messages shown to users before export fails - Prevents silent failures with actionable feedback ### Production Features - FastAPI server with /execute, /health, /ready endpoints - Rate limiting (configurable, default 60 req/min) - Request size limits (configurable, default 10MB) - Automatic retry with exponential backoff - MCP tool support via official Python SDK - File operation sandboxing (WORKSPACE_DIR) - Docker and docker-compose configuration - Environment variable management (.env, .env.example) ### UI Integration - "Export as Service" context menu option - Single workflow export only (no bulk) - User-friendly error alerts for validation failures ## Files Changed - `apps/sim/app/api/workflows/[id]/export-service/route.ts` - API endpoint - `apps/sim/app/api/workflows/[id]/export-service/route.test.ts` - 13 unit tests - `apps/sim/app/workspace/.../hooks/use-export-service.ts` - React hook - `apps/sim/app/workspace/.../context-menu/context-menu.tsx` - UI menu - `apps/sim/app/workspace/.../workflow-item/workflow-item.tsx` - UI wiring ## Testing ```bash cd apps/sim && bun run vitest run "export-service" # 13 tests passing ``` ## Usage 1. Right-click workflow in sidebar 2. Select "Export as Service" 3. Extract ZIP and configure .env with API keys 4. Run: `docker compose up` or `uvicorn main:app` 5. Call: `POST /execute` with workflow inputs
- Replace 'any' types with proper interfaces (WorkflowBlock, WorkflowState, ExportWorkflowState, WorkflowVariable) - Improve transpiler regex pattern to explicitly handle string and numeric bracket notation - Add documentation for regex limitations with nested bracket access - Use nullish coalescing (??) instead of logical OR (||) for safer defaults
Use the existing useNotificationStore to show error messages instead of blocking browser alert(). Notifications appear in the bottom-right corner and can be dismissed by the user.
- Replace all eval() with safe AST-based expression evaluation - Loop condition evaluation now uses _safe_eval_condition() - Condition handler uses _safe_eval_with_context() for variable access - Only allows safe operations: comparisons, boolean ops, len/str/int/bool - Remove shell=True from execute_command to prevent command injection - Shell operators (|, >, <, &&, ;, $) are now rejected with clear error - Commands are parsed with shlex and executed without shell - Fix model detection regex for o1-/o3- patterns - Use word boundary to avoid matching o10, o11, etc.
Replace isExporting state in dependency array with useRef to prevent stale closure issues per hook best practices.
- Move Python templates from embedded strings to templates/ directory (16 files) - Extract validation logic to validate.ts (122 lines) - Extract transpilation logic to transpile.ts (153 lines) - Extract ZIP generation to generate-zip.ts (229 lines) - Reduce route.ts from 2799 to 161 lines (94% reduction) - Fix logger import paths to use @sim/logger - All 13 tests passing 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Native file tools (write, read, list) now require WORKSPACE_DIR to be set - If WORKSPACE_DIR not set, tools return helpful error directing to MCP tools - Agent handler auto-registers local_write_file, local_read_file, local_list_directory when WORKSPACE_DIR is configured - Updated docker-compose.yml to mount ./output volume for container workspace - Updated .env template with WORKSPACE_DIR documentation - Updated README with comprehensive file operations documentation This allows users to choose between: 1. Local file tools (set WORKSPACE_DIR) - sandboxed to workspace directory 2. MCP filesystem tools - handled by external MCP servers 3. Both together - LLM chooses appropriate tool based on descriptions 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Quick start guide with Docker and direct execution - Complete exported files reference table - Multi-provider LLM support (Anthropic, OpenAI, Google) - All supported block types with descriptions - File operations: WORKSPACE_DIR local tools vs MCP tools - API endpoints documentation (/execute, /health, /ready) - Docker deployment instructions - Production configuration environment variables - Security measures (no eval, no shell, sandboxing, etc.) - MCP tool support details - Export validation and error handling 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
…deletion, append, and command execution - Add write_bytes/read_bytes for binary files (images, PDFs) via base64 - Add append_file for log/incremental writes - Add delete_file for cleanup operations - Add file size limits (MAX_FILE_SIZE, default 100MB) - Add command execution opt-in (ENABLE_COMMAND_EXECUTION) - Enhance list_directory with metadata (size, modified, extension) - Add workspace status to /health endpoint - Update .env template and README with comprehensive documentation All 7-8 tools (8 if command execution enabled) auto-register when WORKSPACE_DIR set. Security: Command execution opt-in, file size limits, existing sandboxing maintained. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
Adds support for all Sim Studio LLM providers in exported services: Hosted Providers: - Anthropic (claude-*) - OpenAI (gpt-*, o1-*, o3-*, o4-*) - Google (gemini-*) - DeepSeek (deepseek-*) - xAI (grok-*) - Cerebras (cerebras/*) - Groq (groq/*) - Mistral (mistral-*, magistral-*, codestral-*, etc.) - OpenRouter (openrouter/*) - Azure OpenAI (azure/*) Self-Hosted Providers: - Vertex AI (vertex/*) - Ollama (ollama/*) - vLLM (vllm/*) Implementation: - Generic OpenAI-compatible handler for most providers - Azure OpenAI handler with endpoint/version config - Vertex AI uses Google Gemini SDK - Auto-detection from model name prefixes - Unknown models default to OpenAI (most compatible) Updated files: - agent.py: Multi-provider routing with base URL configs - validate.ts: Accept all 13 providers - generate-zip.ts: .env template with all API keys - route.test.ts: Provider detection tests (22 tests passing) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
b4e8480 to
7817c52
Compare
Summary
Adds the ability to export Sim Studio workflows as standalone, self-contained Python services that can be deployed independently via Docker, Railway, or any container platform.
Features
Multi-Provider LLM Support
Supported Block Types
File Operations
Agents can perform file operations in two ways:
Option 1: Local File Tools (WORKSPACE_DIR)
Set the
WORKSPACE_DIRenvironment variable to enable local file operations:# In .env WORKSPACE_DIR=./workspaceWhen enabled, agents automatically get access to these tools:
local_write_filelocal_write_byteslocal_append_filelocal_read_filelocal_read_byteslocal_delete_filelocal_list_directoryEnable Command Execution (opt-in for security):
# In .env WORKSPACE_DIR=./workspace ENABLE_COMMAND_EXECUTION=trueWhen enabled, agents also get:
local_execute_commandpython script.pyornode process.jsShell operators (
|,>,&&, etc.) are blocked for security.File Size Limits:
All paths are sandboxed to
WORKSPACE_DIR- agents cannot access files outside this directory. Path traversal attacks (../) and symlink escapes are blocked.With Docker: The docker-compose.yml mounts
./outputto the container workspace:docker compose up -d # Files written by agents appear in ./output/Option 2: MCP Filesystem Tools
If your workflow uses MCP filesystem servers, those tools work as configured. MCP servers handle file operations on their own systems - paths and permissions are determined by the MCP server's configuration.
Using Both
You can use both options together. If
WORKSPACE_DIRis set, agents will have access to both local file tools AND any MCP tools configured in the workflow. Tool descriptions help the LLM choose the appropriate tool for each operation.Health Check with Workspace Status
The
/healthendpoint returns workspace configuration status:{ "status": "healthy", "workspace": { "enabled": true, "workspace_dir": "/app/workspace", "command_execution_enabled": false, "max_file_size": 104857600 } }Export Validation
Security
..or symlink escapes)Production Features
Production Configuration
HOST0.0.0.0PORT8080WORKSPACE_DIRENABLE_COMMAND_EXECUTIONfalseMAX_FILE_SIZE104857600(100MB)WORKFLOW_PATHworkflow.jsonRATE_LIMIT_REQUESTS60RATE_LIMIT_WINDOW60MAX_REQUEST_SIZE10485760(10MB)LOG_LEVELINFOUI Integration
Architecture
Files Changed
apps/sim/app/api/workflows/[id]/export-service/route.ts- API endpoint (refactored to 161 lines)apps/sim/app/api/workflows/[id]/export-service/validate.ts- Workflow validationapps/sim/app/api/workflows/[id]/export-service/transpile.ts- JS to Python transpilationapps/sim/app/api/workflows/[id]/export-service/generate-zip.ts- ZIP generationapps/sim/app/api/workflows/[id]/export-service/templates/- 16 Python template filesapps/sim/app/api/workflows/[id]/export-service/route.test.ts- 13 unit testsapps/sim/app/workspace/.../hooks/use-export-service.ts- React hookapps/sim/app/workspace/.../context-menu/context-menu.tsx- UI menuapps/sim/app/workspace/.../workflow-item/workflow-item.tsx- UI wiringREADME.md- Updated with comprehensive export documentationTesting
Usage
WORKSPACE_DIRfor local file operationsENABLE_COMMAND_EXECUTION=truefor command executiondocker compose uporuvicorn main:appPOST /executewith workflow inputs