()
| 314 | # ============================================================================= |
| 315 | |
| 316 | def demo_5_benchmark(): |
| 317 | print("\n" + "=" * 60) |
| 318 | print("Demo 5: Benchmark - Naive vs Control Layer") |
| 319 | print("=" * 60) |
| 320 | |
| 321 | schema = ResponseSchema( |
| 322 | must_be_json=True, |
| 323 | required_keys=["summary", "confidence"], |
| 324 | max_length=400, |
| 325 | forbidden_phrases=["I cannot", "As an AI"], |
| 326 | ) |
| 327 | config = ControlLayerConfig( |
| 328 | total_tokens=800, |
| 329 | max_attempts=3, |
| 330 | base_delay_ms=50, |
| 331 | jitter_ms=10, |
| 332 | ) |
| 333 | |
| 334 | queries = [ |
| 335 | "Explain the token budget mechanism.", |
| 336 | "What is prompt mutation?", |
| 337 | "How does the retry engine work?", |
| 338 | "Describe the fallback router.", |
| 339 | "What does the response validator check?", |
| 340 | "How is injection detected?", |
| 341 | "What is exponential decay in memory?", |
| 342 | "How does re-ranking work in RAG?", |
| 343 | "What is extractive compression?", |
| 344 | "How is quality score computed?", |
| 345 | ] |
| 346 | |
| 347 | # Naive baseline |
| 348 | naive_llm = MockLLM(failure_rate=0.55, failure_mode=FailureMode.SCHEMA_VIOLATION) |
| 349 | naive_pass = 0 |
| 350 | naive_latencies = [] |
| 351 | |
| 352 | print(" Running naive baseline (no control layer)...") |
| 353 | for q in queries: |
| 354 | t0 = time.perf_counter() |
| 355 | response = naive_llm(q) |
| 356 | latency = (time.perf_counter() - t0) * 1000 |
| 357 | naive_latencies.append(latency) |
| 358 | try: |
| 359 | cleaned = response.replace("```json", "").replace("```", "").strip() |
| 360 | data = json.loads(cleaned) |
| 361 | if "summary" in data and "confidence" in data and len(response) <= 400: |
| 362 | naive_pass += 1 |
| 363 | except Exception: |
| 364 | pass |
| 365 | |
| 366 | # Control Layer |
| 367 | cl_llm = MockLLM(failure_rate=0.55, failure_mode=FailureMode.SCHEMA_VIOLATION) |
| 368 | cl_layer = ControlLayer( |
| 369 | llm_fn=cl_llm, |
| 370 | system_prompt="You are a structured assistant. Always return JSON.", |
| 371 | schema=schema, |
| 372 | config=config, |
| 373 | ) |
no test coverage detected