|
| 1 | +""" |
| 2 | +This example demonstrates the different caching options in WorkflowAI: |
| 3 | +1. 'auto' - Cache only when temperature is 0 (default) |
| 4 | +2. 'always' - Always use cache if available |
| 5 | +3. 'never' - Never use cache, always execute new runs |
| 6 | +
|
| 7 | +The example uses a medical SOAP notes extractor to show how caching affects: |
| 8 | +- Response consistency (important for medical documentation) |
| 9 | +- Cost efficiency |
| 10 | +- Execution time |
| 11 | +""" |
| 12 | + |
| 13 | +import asyncio |
| 14 | +import time |
| 15 | +from typing import Literal, TypedDict |
| 16 | + |
| 17 | +from pydantic import BaseModel, Field |
| 18 | + |
| 19 | +import workflowai |
| 20 | +from workflowai import Model, Run |
| 21 | + |
| 22 | +# Import CacheUsage type |
| 23 | +CacheUsage = Literal["auto", "always", "never"] |
| 24 | + |
| 25 | + |
| 26 | +class SOAPInput(BaseModel): |
| 27 | + """Input containing a medical consultation transcript.""" |
| 28 | + transcript: str = Field( |
| 29 | + description="The medical consultation transcript to analyze", |
| 30 | + ) |
| 31 | + |
| 32 | + |
| 33 | +class SOAPNote(BaseModel): |
| 34 | + """Structured SOAP note components.""" |
| 35 | + subjective: list[str] = Field( |
| 36 | + description="Patient's symptoms, complaints, and history as reported", |
| 37 | + examples=["Patient reports severe headache for 3 days", "Denies fever or nausea"], |
| 38 | + ) |
| 39 | + objective: list[str] = Field( |
| 40 | + description="Observable, measurable findings from examination", |
| 41 | + examples=["BP 120/80", "Temperature 98.6°F", "No visible inflammation"], |
| 42 | + ) |
| 43 | + assessment: list[str] = Field( |
| 44 | + description="Diagnosis or clinical impressions", |
| 45 | + examples=["Tension headache", "Rule out migraine"], |
| 46 | + ) |
| 47 | + plan: list[str] = Field( |
| 48 | + description="Treatment plan and next steps", |
| 49 | + examples=["Prescribed ibuprofen 400mg", "Follow up in 2 weeks"], |
| 50 | + ) |
| 51 | + |
| 52 | + |
| 53 | +@workflowai.agent( |
| 54 | + id="soap-extractor", |
| 55 | + model=Model.LLAMA_3_3_70B, |
| 56 | +) |
| 57 | +async def extract_soap_notes(soap_input: SOAPInput) -> Run[SOAPNote]: |
| 58 | + """ |
| 59 | + Extract SOAP notes from a medical consultation transcript. |
| 60 | +
|
| 61 | + Guidelines: |
| 62 | + 1. Analyze the transcript to identify key medical information |
| 63 | + 2. Organize information into SOAP format: |
| 64 | + - Subjective: Patient's symptoms, complaints, and history |
| 65 | + - Objective: Physical examination findings and test results |
| 66 | + - Assessment: Diagnosis or clinical impression |
| 67 | + - Plan: Treatment plan and next steps |
| 68 | +
|
| 69 | + 3. Be thorough but concise |
| 70 | + 4. Use medical terminology appropriately |
| 71 | + 5. Include all relevant information from the transcript |
| 72 | + """ |
| 73 | + ... |
| 74 | + |
| 75 | + |
| 76 | +class ResultMetrics(TypedDict): |
| 77 | + option: str |
| 78 | + duration: float |
| 79 | + cost: float |
| 80 | + |
| 81 | + |
| 82 | +async def demonstrate_caching(transcript: str): |
| 83 | + """Run the same transcript with different caching options and compare results.""" |
| 84 | + |
| 85 | + print("\nComparing caching options") |
| 86 | + print("-" * 50) |
| 87 | + |
| 88 | + cache_options: list[CacheUsage] = ["auto", "always", "never"] |
| 89 | + results: list[ResultMetrics] = [] |
| 90 | + |
| 91 | + for cache_option in cache_options: |
| 92 | + start_time = time.time() |
| 93 | + |
| 94 | + run = await extract_soap_notes( |
| 95 | + SOAPInput(transcript=transcript), |
| 96 | + use_cache=cache_option, |
| 97 | + ) |
| 98 | + |
| 99 | + duration = time.time() - start_time |
| 100 | + |
| 101 | + # Store metrics for comparison |
| 102 | + results.append({ |
| 103 | + "option": cache_option, |
| 104 | + "duration": duration, |
| 105 | + "cost": float(run.cost_usd or 0.0), # Convert None to 0.0 |
| 106 | + }) |
| 107 | + |
| 108 | + # Print comparison table |
| 109 | + print("\nResults Comparison:") |
| 110 | + print("-" * 50) |
| 111 | + print(f"{'Cache Option':<12} {'Duration':<10} {'Cost':<8}") |
| 112 | + print("-" * 50) |
| 113 | + |
| 114 | + for r in results: |
| 115 | + print( |
| 116 | + f"{r['option']:<12} " |
| 117 | + f"{r['duration']:.2f}s{'*' if r['duration'] < 0.1 else '':<8} " |
| 118 | + f"${r['cost']:<7}", |
| 119 | + ) |
| 120 | + |
| 121 | + print("-" * 50) |
| 122 | + print("* Very fast response indicates cached result") |
| 123 | + |
| 124 | + |
| 125 | +async def main(): |
| 126 | + # Example medical consultation transcript |
| 127 | + transcript = """ |
| 128 | + Patient is a 45-year-old female presenting with severe headache for the past 3 days. |
| 129 | + She describes the pain as throbbing, primarily on the right side of her head. |
| 130 | + Pain level reported as 7/10. Denies fever, nausea, or visual disturbances. |
| 131 | + Previous history of migraines, but states this feels different. |
| 132 | +
|
| 133 | + Vital signs stable: BP 120/80, HR 72, Temp 98.6°F. |
| 134 | + Physical exam shows mild tenderness in right temporal area. |
| 135 | + No neurological deficits noted. |
| 136 | + Eye examination normal, no papilledema. |
| 137 | +
|
| 138 | + Assessment suggests tension headache, but need to rule out migraine. |
| 139 | + No red flags for secondary causes identified. |
| 140 | +
|
| 141 | + Plan: Prescribed ibuprofen 400mg q6h for pain. |
| 142 | + Recommended stress reduction techniques. |
| 143 | + Patient education provided regarding headache triggers. |
| 144 | + Follow up in 2 weeks, sooner if symptoms worsen. |
| 145 | + Return precautions discussed. |
| 146 | + """ |
| 147 | + |
| 148 | + print("\nDemonstrating different caching options") |
| 149 | + print("=" * 50) |
| 150 | + print("This example shows how caching affects the agent's behavior:") |
| 151 | + print("- 'auto': Caches only when temperature is 0 (default)") |
| 152 | + print("- 'always': Reuses cached results when available") |
| 153 | + print("- 'never': Generates new results every time") |
| 154 | + |
| 155 | + await demonstrate_caching(transcript) |
| 156 | + |
| 157 | + |
| 158 | +if __name__ == "__main__": |
| 159 | + asyncio.run(main()) |
0 commit comments