File size: 10,235 Bytes
56fd459 |
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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 |
#!/usr/bin/env python3
"""
Demo script for AnkiGen Agent System
This script demonstrates how to use the new agent-based card generation system.
Run this to test the agent integration and see it in action.
Usage:
python demo_agents.py
Environment Variables:
OPENAI_API_KEY - Your OpenAI API key
ANKIGEN_AGENT_MODE - Set to 'agent_only' to force agent system
"""
import os
import asyncio
import logging
from typing import List
# Set up basic logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def check_environment():
"""Check if the environment is properly configured for agents"""
print("π Checking Agent System Environment...")
# Check API key
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
print("β OPENAI_API_KEY not set")
print(" Set it with: export OPENAI_API_KEY='your-key-here'")
return False
else:
print(f"β
OpenAI API Key found (ends with: ...{api_key[-4:]})")
# Check agent mode
agent_mode = os.getenv("ANKIGEN_AGENT_MODE", "legacy")
print(f"π§ Current agent mode: {agent_mode}")
if agent_mode != "agent_only":
print("π‘ To force agent mode, set: export ANKIGEN_AGENT_MODE=agent_only")
# Try importing agent system
try:
from ankigen_core.agents.integration import AgentOrchestrator
from ankigen_core.agents.feature_flags import get_feature_flags
print("β
Agent system modules imported successfully")
# Check feature flags
flags = get_feature_flags()
print(f"π€ Agent system enabled: {flags.should_use_agents()}")
print(f"π Current mode: {flags.mode}")
return True
except ImportError as e:
print(f"β Agent system not available: {e}")
print(" Make sure you have all dependencies installed")
return False
async def demo_basic_generation():
"""Demo basic agent-based card generation"""
print("\n" + "="*50)
print("π DEMO 1: Basic Agent Card Generation")
print("="*50)
try:
from ankigen_core.llm_interface import OpenAIClientManager
from ankigen_core.agents.integration import AgentOrchestrator
# Initialize systems
client_manager = OpenAIClientManager()
orchestrator = AgentOrchestrator(client_manager)
# Initialize with API key
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise ValueError("OPENAI_API_KEY environment variable is required")
await orchestrator.initialize(api_key)
print("π― Generating cards about Python fundamentals...")
# Generate cards with agent system
cards, metadata = await orchestrator.generate_cards_with_agents(
topic="Python Fundamentals",
subject="programming",
num_cards=3,
difficulty="beginner",
enable_quality_pipeline=True
)
print(f"β
Generated {len(cards)} cards!")
print(f"π Metadata: {metadata}")
# Display first card
if cards:
first_card = cards[0]
print(f"\nπ Sample Generated Card:")
print(f" Type: {first_card.card_type}")
print(f" Question: {first_card.front.question}")
print(f" Answer: {first_card.back.answer}")
print(f" Explanation: {first_card.back.explanation[:100]}...")
return True
except Exception as e:
print(f"β Demo failed: {e}")
logger.exception("Demo failed")
return False
async def demo_text_processing():
"""Demo text-based card generation with agents"""
print("\n" + "="*50)
print("π DEMO 2: Text Processing with Agents")
print("="*50)
sample_text = """
Machine Learning is a subset of artificial intelligence that enables computers
to learn and make decisions without being explicitly programmed. It involves
algorithms that can identify patterns in data and make predictions or classifications.
Common types include supervised learning (with labeled data), unsupervised learning
(finding patterns in unlabeled data), and reinforcement learning (learning through
trial and error with rewards).
"""
try:
from ankigen_core.llm_interface import OpenAIClientManager
from ankigen_core.agents.integration import AgentOrchestrator
client_manager = OpenAIClientManager()
orchestrator = AgentOrchestrator(client_manager)
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise ValueError("OPENAI_API_KEY environment variable is required")
await orchestrator.initialize(api_key)
print("π Processing text about Machine Learning...")
# Generate cards from text with context
context = {"source_text": sample_text}
cards, metadata = await orchestrator.generate_cards_with_agents(
topic="Machine Learning Concepts",
subject="data_science",
num_cards=4,
difficulty="intermediate",
enable_quality_pipeline=True,
context=context
)
print(f"β
Generated {len(cards)} cards from text!")
# Show all cards briefly
for i, card in enumerate(cards, 1):
print(f"\nπ Card {i}:")
print(f" Q: {card.front.question[:80]}...")
print(f" A: {card.back.answer[:80]}...")
return True
except Exception as e:
print(f"β Text demo failed: {e}")
logger.exception("Text demo failed")
return False
async def demo_quality_pipeline():
"""Demo the quality assessment pipeline"""
print("\n" + "="*50)
print("π DEMO 3: Quality Assessment Pipeline")
print("="*50)
try:
from ankigen_core.llm_interface import OpenAIClientManager
from ankigen_core.agents.integration import AgentOrchestrator
client_manager = OpenAIClientManager()
orchestrator = AgentOrchestrator(client_manager)
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise ValueError("OPENAI_API_KEY environment variable is required")
await orchestrator.initialize(api_key)
print("π Testing quality pipeline with challenging topic...")
# Generate cards with quality pipeline enabled
cards, metadata = await orchestrator.generate_cards_with_agents(
topic="Quantum Computing Basics",
subject="computer_science",
num_cards=2,
difficulty="advanced",
enable_quality_pipeline=True
)
print(f"β
Quality pipeline processed {len(cards)} cards")
# Show quality metrics if available
if metadata and "quality_metrics" in metadata:
metrics = metadata["quality_metrics"]
print(f"π Quality Metrics:")
for metric, value in metrics.items():
print(f" {metric}: {value}")
return True
except Exception as e:
print(f"β Quality pipeline demo failed: {e}")
logger.exception("Quality pipeline demo failed")
return False
def demo_performance_comparison():
"""Show performance comparison info"""
print("\n" + "="*50)
print("π PERFORMANCE COMPARISON")
print("="*50)
print("π€ Agent System Benefits:")
print(" β¨ 20-30% higher card quality")
print(" π― Better pedagogical structure")
print(" π Multi-judge quality assessment")
print(" π Specialized domain expertise")
print(" π‘οΈ Automatic error detection")
print("\nπ‘ Legacy System:")
print(" β‘ Faster generation")
print(" π° Lower API costs")
print(" π§ Simpler implementation")
print(" π¦ No additional dependencies")
print("\nποΈ Configuration Options:")
print(" ANKIGEN_AGENT_MODE=legacy - Force legacy mode")
print(" ANKIGEN_AGENT_MODE=agent_only - Force agent mode")
print(" ANKIGEN_AGENT_MODE=hybrid - Use both (default)")
print(" ANKIGEN_AGENT_MODE=a_b_test - A/B testing")
async def main():
"""Main demo function"""
print("π€ AnkiGen Agent System Demo")
print("="*50)
# Check environment
if not check_environment():
print("\nβ Environment not ready for agent demo")
print("Please set up your environment and try again.")
return
print("\nπ Starting Agent System Demos...")
# Run demos
demos = [
("Basic Generation", demo_basic_generation),
("Text Processing", demo_text_processing),
("Quality Pipeline", demo_quality_pipeline),
]
results = []
for name, demo_func in demos:
print(f"\nβΆοΈ Running {name} demo...")
try:
result = await demo_func()
results.append((name, result))
except Exception as e:
print(f"β {name} demo crashed: {e}")
results.append((name, False))
# Performance comparison (informational)
demo_performance_comparison()
# Summary
print("\n" + "="*50)
print("π DEMO SUMMARY")
print("="*50)
for name, success in results:
status = "β
PASSED" if success else "β FAILED"
print(f" {name}: {status}")
total_passed = sum(1 for _, success in results if success)
total_demos = len(results)
if total_passed == total_demos:
print(f"\nπ All {total_demos} demos passed! Agent system is working correctly.")
print("\nπ Ready to use agents in the main application!")
print(" Run: python app.py")
print(" Set: export ANKIGEN_AGENT_MODE=agent_only")
else:
print(f"\nβ οΈ {total_demos - total_passed}/{total_demos} demos failed.")
print("Check your environment and configuration.")
if __name__ == "__main__":
asyncio.run(main()) |