Overview

This cookbook showcases advanced Python coding examples that demonstrate HyperFlow's sophisticated polymorphic coercion framework and rich media capabilities. Each example is designed to work with HyperFlow's visual programming environment and showcases the power of the new input/output type system.

All examples leverage:

Getting Started Examples

These foundational examples introduce core concepts and demonstrate basic patterns that are essential for building more sophisticated applications.

Database Access with SafeSQLExecutor

Query databases safely with automatic SQL injection protection and table access control:

# Basic database query with SafeSQLExecutor
# Access customer data from a secure database connection

# Initialize SafeSQLExecutor with connection string and security settings
conn = "mysql+pymysql://user:password@localhost:3306/company_db"
sql = SafeSQLExecutor(conn, allowed_tables=["customers", "orders"], read_only=True, timeout=30)

# Execute a safe SQL query
customers = sql.execute_query("""
    SELECT customer_name, email, city, total_orders 
    FROM customers 
    WHERE city = :city AND total_orders > :min_orders
    ORDER BY total_orders DESC
""", {"city": "Seoul", "min_orders": 5})

# Process the results
if customers:
    # Create a summary report
    summary = f"""# High-Value Seoul Customers

## Query Results
Found {len(customers)} customers in Seoul with more than 5 orders.

## Customer List
"""
    for customer in customers:
        summary += f"- **{customer['customer_name']}** ({customer['email']}) - {customer['total_orders']} orders\\n"
    
    # Output structured results
    output = {
        "summary_report": summary,
        "customer_data": customers,
        "query_info": {
            "row_count": len(customers)
        }
    }
else:
    # Handle no results
    output = {
        "message": "No customers found matching criteria"
    }

Key Features Demonstrated:

Segment Metadata Enhancement

Add JSON metadata to existing segments, enriching them with additional context:

# Enhance segments with metadata from JSON input
# input1: List of segments (SegmentSelectionValue)
# input2: JSON metadata to add to all segments

import json

# Parse the JSON metadata from input2
try:
    if isinstance(input2, str):
        metadata_to_add = json.loads(input2)
    else:
        metadata_to_add = input2
except (json.JSONDecodeError, TypeError):
    # Handle invalid JSON gracefully
    metadata_to_add = {"error": "Invalid JSON provided"}

# Process each segment and add the new metadata
enhanced_segments = []

for segment in input1:
    # Start with the existing segment
    enhanced_segment = {
        "text": segment.get("text", ""),
        "metadata": segment.get("metadata", []).copy()  # Copy existing metadata
    }
    
    # Add new metadata from JSON input
    for key, value in metadata_to_add.items():
        enhanced_segment["metadata"].append({
            "key": key,
            "value": str(value)  # Convert to string for consistency
        })
    
    # Preserve any existing provenance or thunk data
    if "provenance" in segment:
        enhanced_segment["provenance"] = segment["provenance"]
    if "thunk" in segment:
        enhanced_segment["thunk"] = segment["thunk"]
    
    enhanced_segments.append(enhanced_segment)

# Create processing summary
processing_summary = f"""# Segment Metadata Enhancement

## Processing Summary
- **Segments Processed**: {len(enhanced_segments)}
- **Metadata Fields Added**: {len(metadata_to_add)}
- **New Metadata**: {', '.join(metadata_to_add.keys())}

## Enhancement Details
Each segment has been enriched with the provided metadata while preserving existing information.
"""

# Output enhanced segments with summary
output = enhanced_segments

# Alternative: Include summary as first item
# output = [
#     {
#         "dataType": "text",
#         "mimetype": "text/markdown",
#         "data": processing_summary
#     },
#     {
#         "dataType": "text",
#         "mimetype": "application/json", 
#         "data": json.dumps({"enhanced_segments": enhanced_segments}, indent=2)
#     }
# ]