Setup
Copy
# Create environment
python3 -m venv venv && source venv/bin/activate
# Install packages
pip install praisonaiagents praisonai
# Set API key
export OPENAI_API_KEY="your-key"
Create Sample Data
Copy
# Create quantum circuits
cat > circuits.json << 'EOF'
{
"QFT-8": {"qubits": 8, "depth": 45, "single_qubit_gates": 64, "two_qubit_gates": 28, "algorithm": "QFT"},
"VQE-4": {"qubits": 4, "depth": 120, "single_qubit_gates": 96, "two_qubit_gates": 48, "algorithm": "VQE"},
"QAOA-6": {"qubits": 6, "depth": 80, "single_qubit_gates": 72, "two_qubit_gates": 36, "algorithm": "QAOA"}
}
EOF
# Create optimization rules
cat > optimizations.json << 'EOF'
{
"gate_cancellation": {"applicable": ["consecutive_inverse"], "reduction": 0.15},
"gate_commutation": {"applicable": ["non_overlapping_qubits"], "reduction": 0.10},
"template_matching": {"applicable": ["known_patterns"], "reduction": 0.20},
"depth_reduction": {"applicable": ["parallel_gates"], "reduction": 0.25}
}
EOF
Run: Python Code
Copy
from praisonaiagents import Agent, Agents, Task, tool
from pydantic import BaseModel
from typing import List
import json
# Structured output
class OptimizationResult(BaseModel):
circuit_id: str
original_depth: int
optimized_depth: int
original_gates: int
optimized_gates: int
depth_reduction_pct: float
gate_reduction_pct: float
estimated_fidelity: float
optimizations_applied: List[str]
# Database persistence is configured via memory={} parameter
# Tools
@tool
def get_circuit(circuit_id: str) -> str:
"""Get quantum circuit details."""
with open("circuits.json") as f:
circuits = json.load(f)
return json.dumps(circuits.get(circuit_id, {}))
@tool
def get_optimization_rules() -> str:
"""Get available optimization rules."""
with open("optimizations.json") as f:
return f.read()
@tool
def apply_optimization(circuit_id: str, depth: int, gates: int, optimization_type: str) -> str:
"""Apply optimization to circuit."""
with open("optimizations.json") as f:
rules = json.load(f)
rule = rules.get(optimization_type, {})
reduction = rule.get("reduction", 0)
new_depth = int(depth * (1 - reduction * 0.8)) # Depth reduction
new_gates = int(gates * (1 - reduction)) # Gate reduction
# Fidelity estimation (simplified)
fidelity = 0.99 ** (new_depth / 10) # Decreases with depth
return json.dumps({
"optimization": optimization_type,
"new_depth": new_depth,
"new_gates": new_gates,
"estimated_fidelity": round(fidelity, 4)
})
@tool
def benchmark_circuit(original_depth: int, optimized_depth: int, original_gates: int, optimized_gates: int) -> str:
"""Benchmark optimization results."""
depth_reduction = (original_depth - optimized_depth) / original_depth * 100
gate_reduction = (original_gates - optimized_gates) / original_gates * 100
return json.dumps({
"depth_reduction_pct": round(depth_reduction, 2),
"gate_reduction_pct": round(gate_reduction, 2),
"speedup_estimate": round(original_depth / optimized_depth, 2)
})
# Agents
analyzer = Agent(
name="CircuitAnalyzer",
instructions="Analyze quantum circuits. Use get_circuit tool.",
tools=[get_circuit],
memory={
"db": "sqlite:///quantum_opt.db",
"session_id": "quantum-optimization"
}
)
optimizer = Agent(
name="CircuitOptimizer",
instructions="Apply optimizations. Use get_optimization_rules and apply_optimization tools.",
tools=[get_optimization_rules, apply_optimization]
)
benchmarker = Agent(
name="Benchmarker",
instructions="Benchmark results. Use benchmark_circuit tool.",
tools=[benchmark_circuit]
)
# Tasks
analyze_task = Task(
description="Analyze circuit: {circuit_id}",
agent=analyzer,
expected_output="Circuit metrics"
)
optimize_task = Task(
description="Apply optimizations to reduce depth and gates",
agent=optimizer,
expected_output="Optimized circuit metrics"
)
benchmark_task = Task(
description="Benchmark optimization results",
agent=benchmarker,
expected_output="Optimization report",
output_pydantic=OptimizationResult
)
# Run
agents = Agents(agents=[analyzer, optimizer, benchmarker], tasks=[analyze_task, optimize_task, benchmark_task])
result = agents.start(circuit_id="VQE-4")
print(result)
Run: CLI
Copy
# Optimize single circuit
praisonai "Optimize QFT-8 quantum circuit for depth reduction" --verbose
# With persistence
praisonai "Compare optimization strategies for VQE circuit" --memory --user-id quantum_team
# Batch optimization
praisonai "Optimize all circuits in circuits.json" --telemetry
Run: agents.yaml
Createagents.yaml:
Copy
framework: praisonai
topic: "quantum circuit optimization"
roles:
analyzer:
role: Circuit Analyst
goal: Analyze quantum circuits
backstory: Expert at quantum computing
tasks:
analyze:
description: |
Analyze circuit:
- Qubit count
- Circuit depth
- Gate counts (1Q, 2Q)
- Algorithm type
expected_output: Circuit analysis
optimizer:
role: Circuit Optimizer
goal: Reduce circuit complexity
backstory: Expert at quantum compilation
tasks:
optimize:
description: |
Apply optimizations:
- Gate cancellation
- Gate commutation
- Template matching
- Depth reduction
expected_output: Optimized circuit
benchmarker:
role: Performance Analyst
goal: Measure optimization quality
backstory: Expert at quantum benchmarking
tasks:
benchmark:
description: |
Benchmark results:
- Depth reduction %
- Gate reduction %
- Fidelity estimate
- Speedup factor
expected_output: Optimization report
Copy
praisonai agents.yaml --verbose
Monitor & Verify
Copy
# View optimization history
praisonai --history 10 --user-id quantum_team
# Check metrics
praisonai --metrics
# Export results
praisonai --save quantum_optimization_report
Serve API
Copy
from praisonaiagents import Agent, tool
import json
@tool
def quick_circuit_estimate(qubits: int, depth: int, two_qubit_gates: int) -> str:
"""Quick circuit optimization estimate."""
# Estimate potential reductions
depth_reduction = min(0.4, depth / 200) # Up to 40%
gate_reduction = min(0.3, two_qubit_gates / 100) # Up to 30%
optimized_depth = int(depth * (1 - depth_reduction))
optimized_2q = int(two_qubit_gates * (1 - gate_reduction))
# Fidelity estimate
fidelity = 0.99 ** (optimized_depth / 10) * 0.995 ** optimized_2q
return json.dumps({
"original": {"depth": depth, "2q_gates": two_qubit_gates},
"optimized": {"depth": optimized_depth, "2q_gates": optimized_2q},
"estimated_fidelity": round(fidelity, 4),
"recommendation": "optimize" if fidelity > 0.9 else "simplify_algorithm"
})
agent = Agent(
name="QuantumAPI",
instructions="Estimate quantum circuit optimization potential.",
tools=[quick_circuit_estimate]
)
agent.launch(path="/optimize-circuit", port=8000)
Copy
curl -X POST http://localhost:8000/optimize-circuit \
-H "Content-Type: application/json" \
-d '{"message": "Estimate optimization for 8 qubits, depth 100, 40 two-qubit gates"}'
Cleanup
Copy
rm -f quantum_opt.db circuits.json optimizations.json
deactivate
Features Demonstrated
| Feature | Implementation |
|---|---|
| Multi-agent | Analyzer → Optimizer → Benchmarker |
| Structured Output | Pydantic OptimizationResult |
| Gate Optimization | Cancellation, commutation, templates |
| Fidelity Estimation | Depth-based fidelity model |
| DB Persistence | SQLite via db() |
| CLI | --telemetry for tracking |
| YAML Config | 3-agent quantum pipeline |
| API Endpoint | agent.launch() |

