-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathadaptive_routing_workflow_demo.py
More file actions
157 lines (118 loc) · 5.15 KB
/
Copy pathadaptive_routing_workflow_demo.py
File metadata and controls
157 lines (118 loc) · 5.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#!/usr/bin/env python3
"""Demonstration of Adaptive Routing integration with BaseWorkflow.
Shows how workflows automatically use adaptive routing for cost optimization
and quality improvement when enable_adaptive_routing=True.
Run this after you've accumulated telemetry data:
python examples/adaptive_routing_workflow_demo.py
Copyright 2025 Smart-AI-Memory
Licensed under Fair Source License 0.9
"""
import sys
from pathlib import Path
# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from empathy_os.workflows.base import BaseWorkflow, ModelTier
class DemoWorkflow(BaseWorkflow):
"""Demo workflow that uses adaptive routing."""
name = "demo-workflow"
description = "Demonstrates adaptive routing integration"
stages = ["classify", "analyze", "summarize"]
# Static tier map (adaptive routing may override these)
tier_map = {
"classify": ModelTier.CHEAP,
"analyze": ModelTier.CAPABLE,
"summarize": ModelTier.CHEAP,
}
async def run_stage(self, stage_name: str, tier: ModelTier, input_data: dict):
"""Required abstract method - implement stage logic."""
# Simulate stage execution (demo only)
return {"stage": stage_name, "tier": tier.value}, 100, 50
async def run(self, task: str) -> dict:
"""Run the demo workflow.
This is a simple workflow that shows how adaptive routing works.
"""
result = {"task": task, "stages": {}}
print(f"\n📋 Task: {task}")
print(f"🔄 Running {len(self.stages)} stages...")
# Simulate stage execution
for stage_name in self.stages:
# Get tier (may be upgraded by adaptive routing)
tier = self._get_tier_with_routing(
stage_name=stage_name,
input_data={"task": task},
budget_remaining=1.0,
)
print(f"\n Stage: {stage_name}")
print(f" Tier: {tier.value}")
# Get adaptive router to show recommendations
router = self._get_adaptive_router()
if router:
# Show routing stats for this workflow/stage
try:
stats = router.get_routing_stats(
workflow=self.name, stage=stage_name, days=7
)
if stats["total_calls"] > 0:
print(
f" Historical performance: {stats['total_calls']} calls, "
f"${stats['avg_cost']:.4f} avg cost, "
f"{stats['avg_success_rate']:.1%} success"
)
# Check for upgrade recommendation
should_upgrade, reason = router.recommend_tier_upgrade(
workflow=self.name, stage=stage_name
)
if should_upgrade:
print(f" ⚠️ Upgrade recommended: {reason}")
else:
print(f" ✅ {reason}")
else:
print(f" No historical data (using default tier)")
except Exception as e:
print(f" No telemetry data available: {e}")
result["stages"][stage_name] = {"tier": tier.value}
return result
async def main():
"""Run the demo."""
print("=" * 70)
print("ADAPTIVE ROUTING WORKFLOW INTEGRATION DEMO")
print("=" * 70)
# Test 1: Without adaptive routing (static tier map)
print("\n🧪 Test 1: WITHOUT Adaptive Routing (Static Tier Map)")
print("-" * 70)
workflow_static = DemoWorkflow(enable_adaptive_routing=False)
result1 = await workflow_static.run("Analyze code quality")
# Test 2: WITH adaptive routing (telemetry-driven)
print("\n\n🧪 Test 2: WITH Adaptive Routing (Telemetry-Driven)")
print("-" * 70)
workflow_adaptive = DemoWorkflow(enable_adaptive_routing=True)
result2 = await workflow_adaptive.run("Analyze code quality")
# Summary
print("\n\n" + "=" * 70)
print("SUMMARY")
print("=" * 70)
print("\n📊 Tier Comparison:")
print(f"{'Stage':<15} {'Static Tier':<15} {'Adaptive Tier':<15} {'Change'}")
print("-" * 60)
for stage in workflow_static.stages:
static_tier = result1["stages"][stage]["tier"]
adaptive_tier = result2["stages"][stage]["tier"]
if static_tier != adaptive_tier:
change = f"⚠️ Upgraded"
else:
change = "✅ Same"
print(f"{stage:<15} {static_tier:<15} {adaptive_tier:<15} {change}")
print("\n💡 Key Insights:")
print(" • Adaptive routing analyzes telemetry to detect high failure rates")
print(" • Automatically upgrades tiers when failure rate > 20%")
print(" • Works alongside existing routing_strategy if configured")
print(" • Opt-in feature: set enable_adaptive_routing=True")
print("\n✅ Demo complete!")
if __name__ == "__main__":
import asyncio
try:
asyncio.run(main())
except Exception as e:
print(f"\n❌ Error: {e}")
import traceback
traceback.print_exc()