function demo_hybrid_response
Demonstrates end-to-end hybrid response processing by converting an LLM response containing text and graphics placeholders into a formatted PDF document.
/tf/active/vicechatdev/e-ink-llm/demo_hybrid_mode.py
97 - 174
moderate
Purpose
This demo function showcases the complete workflow of the hybrid response processing system. It takes a sample LLM response that includes special graphics placeholders (charts, diagrams, illustrations) embedded within markdown text, processes these placeholders to generate actual graphics, and produces a final PDF document combining the formatted text with rendered graphics. This serves as both a demonstration and integration test for the hybrid response handling capabilities.
Source Code
async def demo_hybrid_response():
"""Demonstrate complete hybrid response processing"""
print("\nš Hybrid Response Processing Demo")
print("=" * 50)
# Sample LLM response with graphics placeholders
sample_response = """# Sales Analysis Report
## Executive Summary
Our Q4 2024 performance exceeded expectations with strong growth across all quarters.
[GRAPHIC:chart:Quarterly Sales:{"type":"bar","data":[125000,150000,175000,200000],"labels":["Q1","Q2","Q3","Q4"],"title":"2024 Quarterly Sales ($)","ylabel":"Revenue"}]
## Key Findings
### Growth Trajectory
The data shows consistent upward momentum:
- **Q1 to Q2**: 20% increase
- **Q2 to Q3**: 16.7% increase
- **Q3 to Q4**: 14.3% increase
- **Overall growth**: 60% year-over-year
### Process Optimization
Our improved development workflow contributed to this success:
[GRAPHIC:diagram:Development Process:{"steps":["Market Research","Product Design","Development","Quality Testing","Launch"],"style":"flowchart","direction":"horizontal"}]
## Mathematical Model
The growth pattern follows a quadratic trend, which we can model mathematically:
[GRAPHIC:illustration:Growth Model:{"concept":"quadratic_function","style":"educational","annotations":true}]
## Recommendations
Based on this analysis, we recommend:
1. Continue current growth strategies
2. Invest in process optimization
3. Expand market research capabilities
## Conclusion
The hybrid approach of combining quantitative data with visual representations provides clearer insights for strategic decision-making.
"""
# Initialize hybrid handler (API key would be needed for real use)
handler = HybridResponseHandler(api_key="demo")
# Create temporary output file
with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as tmp:
output_path = tmp.name
print(f"š Processing hybrid response...")
print(f" ⢠Input length: {len(sample_response):,} characters")
print(f" ⢠Graphics detected: {sample_response.count('[GRAPHIC:')}")
try:
# Process the hybrid response
result_path = await handler.process_hybrid_response(
llm_response=sample_response,
metadata={
"source_file": "demo_input.pdf",
"source_type": "demo",
"enable_hybrid_mode": True
},
output_path=output_path,
conversation_id="demo_conv_001",
exchange_number=1
)
if result_path and Path(result_path).exists():
file_size = Path(result_path).stat().st_size
print(f"ā
Hybrid PDF generated successfully")
print(f" ⢠Output: {Path(result_path).name}")
print(f" ⢠Size: {file_size:,} bytes")
print(f" ⢠Path: {result_path}")
else:
print("ā Hybrid PDF generation failed")
except Exception as e:
print(f"ā Error during hybrid processing: {e}")
Return Value
This function does not return any value (implicitly returns None). It performs side effects by creating a temporary PDF file and printing status messages to stdout showing the processing progress, file size, and output path.
Dependencies
asynciotempfilepathlibjsongraphics_generatorhybrid_response_handlerhybrid_pdf_generatortraceback
Required Imports
import asyncio
import tempfile
from pathlib import Path
import json
from graphics_generator import GraphicsGenerator
from graphics_generator import GraphicSpec
from graphics_generator import GraphicType
from hybrid_response_handler import HybridResponseHandler
from hybrid_pdf_generator import HybridPDFGenerator
import traceback
Usage Example
import asyncio
import tempfile
from pathlib import Path
from hybrid_response_handler import HybridResponseHandler
# Run the demo function
async def main():
await demo_hybrid_response()
# Execute the async function
if __name__ == '__main__':
asyncio.run(main())
# Expected output:
# - Console messages showing processing progress
# - A temporary PDF file created with hybrid content
# - File path and size information printed to console
Best Practices
- This is a demonstration function and uses a placeholder API key ('demo'). In production, provide a valid API key through environment variables or secure configuration.
- The function creates temporary files that are not automatically cleaned up. Consider implementing cleanup logic or using context managers for production use.
- Must be called within an async context using asyncio.run() or await from another async function.
- The sample response includes specific graphics placeholder syntax: [GRAPHIC:type:title:json_config]. Ensure your LLM responses follow this format.
- Error handling is basic in this demo. Production implementations should include more robust error handling and logging.
- The temporary file path is printed to console but the file persists after execution. Track and clean up these files in production environments.
- This demo processes a hardcoded sample response. Adapt the pattern for dynamic LLM responses in real applications.
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class HybridResponseHandler 83.8% similar
-
class HybridResponse 72.2% similar
-
function demo_placeholder_parsing 71.3% similar
-
function main_v59 69.5% similar
-
class HybridPromptEnhancer 68.8% similar