Open-Dedalus Examples and Tutorials

August 23, 2025 ยท View on GitHub

This directory contains comprehensive examples demonstrating all features of the Open-Dedalus SDK.

Quick Start

Before running examples, install dependencies and set up your API keys:

# Install Open-Dedalus from source
git clone https://github.com/your-username/open-dedalus.git
cd open-dedalus/python
pip install -e .

# Or install with development dependencies  
pip install -e .[dev]

# Set up environment variables
export OPENAI_API_KEY="your-openai-key"
export ANTHROPIC_API_KEY="your-anthropic-key"  
# ... other provider keys as needed

Examples Overview

Basic Examples

Advanced Features

Infrastructure

Running Examples

Run Individual Examples

# Basic hello world
python examples/01_hello_world.py

# Tools example  
python examples/02_basic_tools.py

# Streaming example
python examples/03_streaming.py

Run All Examples

# Run example validation script
python examples/run_examples.py

# Run specific category
python examples/run_examples.py --category basic
python examples/run_examples.py --category advanced

Example Categories

1. Getting Started (Basic)

These examples demonstrate core functionality:

  • Hello World: Basic chat completion
  • Basic Tools: Function calling
  • Streaming: Real-time responses
  • Error Handling: Robust error management

2. Provider Integration (Intermediate)

Examples showing multi-provider support:

  • Provider Comparison: Same task across different providers
  • Provider-Specific Features: Leveraging unique capabilities
  • Fallback Strategies: Handling provider failures

3. Advanced Features (Advanced)

Complex scenarios and advanced usage:

  • Multi-Model Workflows: Intelligent handoffs
  • MCP Integration: External tool integration
  • Policy Systems: Dynamic behavior control
  • Tool Chaining: Complex multi-step operations

4. Real-World Applications (Production)

Complete applications demonstrating production usage:

  • Research Assistant: Information gathering and analysis
  • Code Review Bot: Automated code analysis
  • Content Generator: Multi-step content creation
  • Data Analysis Pipeline: Complex data processing

Learning Path

Beginner Path

  1. 01_hello_world.py - Understand basic usage
  2. 02_basic_tools.py - Learn tool integration
  3. 03_streaming.py - Add real-time features
  4. tutorials/getting_started.md - Comprehensive setup guide

Intermediate Path

  1. 04_mcp_integration.py - External tool integration
  2. advanced_examples/provider_comparison.py - Multi-provider usage
  3. advanced_examples/error_handling.py - Production error management
  4. tutorials/production_deployment.md - Production best practices

Advanced Path

  1. 06_model_handoffs.py - Intelligent routing
  2. 07_tool_chaining.py - Complex workflows
  3. 08_policy.py - Dynamic behavior
  4. advanced_examples/research_assistant.py - Complete application

Common Patterns

Pattern 1: Basic Workflow

import asyncio
from dedalus_labs import AsyncDedalus, DedalusRunner

async def basic_workflow():
    async with AsyncDedalus() as client:
        runner = DedalusRunner(client)
        
        result = await runner.run(
            input="Your prompt here",
            model="openai/gpt-4o-mini"
        )
        
        return result.final_output

Pattern 2: Tool Integration

def my_tool(param: str) -> str:
    """Tool description for AI model."""
    return f"Processed: {param}"

async def tool_workflow():
    async with AsyncDedalus() as client:
        runner = DedalusRunner(client)
        
        result = await runner.run(
            input="Use my_tool with parameter 'hello'",
            model="openai/gpt-4.1",
            tools=[my_tool]
        )
        
        return result

Pattern 3: Multi-Model Handoffs

from dedalus_labs.handoffs import HandoffStrategy

async def handoff_workflow():
    async with AsyncDedalus() as client:
        runner = DedalusRunner(client)
        
        result = await runner.run(
            input="Complex task requiring multiple models",
            model=["openai/gpt-4.1", "anthropic/claude-3-5-sonnet-20241022"],
            handoff_strategy=HandoffStrategy.INTELLIGENT
        )
        
        return result

Pattern 4: Streaming Responses

from dedalus_labs.utils.streaming import stream_async

async def streaming_workflow():
    async with AsyncDedalus() as client:
        runner = DedalusRunner(client)
        
        stream = await runner.run(
            input="Generate a long response",
            model="openai/gpt-4o-mini",
            stream=True
        )
        
        await stream_async(stream)

Configuration Examples

Environment Setup

Create a .env file:

# Core providers
OPENAI_API_KEY=your-openai-key
ANTHROPIC_API_KEY=your-anthropic-key
GOOGLE_API_KEY=your-google-key

# Additional providers (optional)
FIREWORKS_API_KEY=your-fireworks-key
GROQ_API_KEY=your-groq-key
PERPLEXITY_API_KEY=your-perplexity-key

# Development settings
DEBUG=false
LOG_LEVEL=INFO

Custom Configuration

from dedalus_labs import AsyncDedalus
from dedalus_labs.handoffs import HandoffStrategy

# Custom client configuration
client = AsyncDedalus(
    api_key="custom-key",
    base_url="https://custom-endpoint.com"
)

# Custom runner configuration
runner = DedalusRunner(client)
runner.handoff_router.strategy = HandoffStrategy.EXPERTISE

Error Handling Examples

Graceful Error Handling

async def robust_workflow():
    try:
        async with AsyncDedalus() as client:
            runner = DedalusRunner(client)
            
            result = await runner.run(
                input="Your prompt",
                model="openai/gpt-4o-mini",
                max_steps=5
            )
            
            return result.final_output
            
    except Exception as e:
        print(f"Workflow failed: {e}")
        return "Sorry, I couldn't complete that task."

Provider Fallback

async def fallback_workflow(prompt: str):
    providers = ["openai/gpt-4o-mini", "anthropic/claude-3-haiku-20240307"]
    
    for provider in providers:
        try:
            async with AsyncDedalus() as client:
                runner = DedalusRunner(client)
                
                result = await runner.run(
                    input=prompt,
                    model=provider
                )
                
                return result.final_output
                
        except Exception as e:
            print(f"Provider {provider} failed: {e}")
            continue
    
    return "All providers failed"

Performance Tips

Optimization Strategies

  1. Reuse Clients: Keep client instances alive for multiple requests
  2. Connection Pooling: Use async context managers properly
  3. Streaming: Use streaming for long responses
  4. Tool Optimization: Keep tools simple and fast
  5. Model Selection: Choose appropriate models for each task

Example: Optimized Client Usage

class OptimizedDedalusClient:
    def __init__(self):
        self.client = None
        self.runner = None
    
    async def __aenter__(self):
        self.client = AsyncDedalus()
        await self.client.__aenter__()
        self.runner = DedalusRunner(self.client)
        return self
    
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if self.client:
            await self.client.__aexit__(exc_type, exc_val, exc_tb)
    
    async def process(self, prompt: str, **kwargs):
        return await self.runner.run(input=prompt, **kwargs)

# Usage
async def optimized_usage():
    async with OptimizedDedalusClient() as client:
        # Multiple requests with the same client
        result1 = await client.process("First task", model="openai/gpt-4o-mini")
        result2 = await client.process("Second task", model="openai/gpt-4o-mini") 
        result3 = await client.process("Third task", model="openai/gpt-4o-mini")
        
        return [result1, result2, result3]

Testing Your Examples

Validation Script

Run the validation script to test all examples:

python examples/run_examples.py --validate

Manual Testing

Test individual examples:

# Test with minimal output
python examples/01_hello_world.py

# Test with debug output
DEBUG=true python examples/02_basic_tools.py

# Test specific provider
OPENAI_API_KEY=your-key python examples/01_hello_world.py

Contributing Examples

When adding new examples:

  1. Follow Naming Convention: NN_descriptive_name.py
  2. Include Docstring: Clear description of what the example demonstrates
  3. Add Error Handling: Show robust error management
  4. Use Type Hints: Include proper type annotations
  5. Add to README: Update this documentation

Example Template

"""
Example Title - Brief description of what this demonstrates

This example shows:
- Feature 1
- Feature 2  
- Feature 3

Usage:
    python examples/NN_example_name.py
"""

import asyncio
from dedalus_labs import AsyncDedalus, DedalusRunner


async def main():
    """Main example function"""
    try:
        async with AsyncDedalus() as client:
            runner = DedalusRunner(client)
            
            # Your example code here
            result = await runner.run(
                input="Example prompt",
                model="openai/gpt-4o-mini"
            )
            
            print(f"Result: {result.final_output}")
            
    except Exception as e:
        print(f"Example failed: {e}")


if __name__ == "__main__":
    print("Example: Description of what this example does")
    asyncio.run(main())

Troubleshooting

Common Issues

  1. Import Errors: Ensure Open-Dedalus is installed: pip install dedalus-labs
  2. API Key Errors: Check environment variables are set correctly
  3. Model Errors: Verify model names and provider availability
  4. Network Errors: Check internet connection and API endpoints

Debug Mode

Enable debug mode for detailed logging:

DEBUG=true VERBOSE=true python examples/01_hello_world.py

Getting Help

  • Documentation: See ../agent/API_DOCUMENTATION.md
  • Tests: See ../tests/README.md for testing guide
  • Issues: Report issues in the project repository

Happy coding with Open-Dedalus! ๐Ÿš€