-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path03_caching.py
More file actions
159 lines (124 loc) · 4.95 KB
/
03_caching.py
File metadata and controls
159 lines (124 loc) · 4.95 KB
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
"""
This example demonstrates the different caching options in WorkflowAI:
1. 'auto' - Cache only when temperature is 0 (default)
2. 'always' - Always use cache if available
3. 'never' - Never use cache, always execute new runs
The example uses a medical SOAP notes extractor to show how caching affects:
- Response consistency (important for medical documentation)
- Cost efficiency
- Execution time
"""
import asyncio
import time
from typing import Literal, TypedDict
from pydantic import BaseModel, Field
import workflowai
from workflowai import Model
# Import CacheUsage type
CacheUsage = Literal["auto", "always", "never"]
class SOAPInput(BaseModel):
"""Input containing a medical consultation transcript."""
transcript: str = Field(
description="The medical consultation transcript to analyze",
)
class SOAPNote(BaseModel):
"""Structured SOAP note components."""
subjective: list[str] = Field(
description="Patient's symptoms, complaints, and history as reported",
examples=["Patient reports severe headache for 3 days", "Denies fever or nausea"],
)
objective: list[str] = Field(
description="Observable, measurable findings from examination",
examples=["BP 120/80", "Temperature 98.6°F", "No visible inflammation"],
)
assessment: list[str] = Field(
description="Diagnosis or clinical impressions",
examples=["Tension headache", "Rule out migraine"],
)
plan: list[str] = Field(
description="Treatment plan and next steps",
examples=["Prescribed ibuprofen 400mg", "Follow up in 2 weeks"],
)
@workflowai.agent(
id="soap-extractor",
model=Model.LLAMA_3_3_70B,
)
async def extract_soap_notes(soap_input: SOAPInput) -> SOAPNote:
"""
Extract SOAP notes from a medical consultation transcript.
Guidelines:
1. Analyze the transcript to identify key medical information
2. Organize information into SOAP format:
- Subjective: Patient's symptoms, complaints, and history
- Objective: Physical examination findings and test results
- Assessment: Diagnosis or clinical impression
- Plan: Treatment plan and next steps
3. Be thorough but concise
4. Use medical terminology appropriately
5. Include all relevant information from the transcript
"""
...
class ResultMetrics(TypedDict):
option: str
duration: float
cost: float
async def demonstrate_caching(transcript: str):
"""Run the same transcript with different caching options and compare results."""
print("\nComparing caching options")
print("-" * 50)
cache_options: list[CacheUsage] = ["auto", "always", "never"]
results: list[ResultMetrics] = []
for cache_option in cache_options:
start_time = time.time()
run = await extract_soap_notes.run(
SOAPInput(transcript=transcript),
use_cache=cache_option,
)
duration = time.time() - start_time
# Store metrics for comparison
results.append({
"option": cache_option,
"duration": duration,
"cost": float(run.cost_usd or 0.0), # Convert None to 0.0
})
# Print comparison table
print("\nResults Comparison:")
print("-" * 50)
print(f"{'Cache Option':<12} {'Duration':<10} {'Cost':<8}")
print("-" * 50)
for r in results:
print(
f"{r['option']:<12} "
f"{r['duration']:.2f}s{'*' if r['duration'] < 0.1 else '':<8} "
f"${r['cost']:<7}",
)
print("-" * 50)
print("* Very fast response indicates cached result")
async def main():
# Example medical consultation transcript
transcript = """
Patient is a 45-year-old female presenting with severe headache for the past 3 days.
She describes the pain as throbbing, primarily on the right side of her head.
Pain level reported as 7/10. Denies fever, nausea, or visual disturbances.
Previous history of migraines, but states this feels different.
Vital signs stable: BP 120/80, HR 72, Temp 98.6°F.
Physical exam shows mild tenderness in right temporal area.
No neurological deficits noted.
Eye examination normal, no papilledema.
Assessment suggests tension headache, but need to rule out migraine.
No red flags for secondary causes identified.
Plan: Prescribed ibuprofen 400mg q6h for pain.
Recommended stress reduction techniques.
Patient education provided regarding headache triggers.
Follow up in 2 weeks, sooner if symptoms worsen.
Return precautions discussed.
"""
print("\nDemonstrating different caching options")
print("=" * 50)
print("This example shows how caching affects the agent's behavior:")
print("- 'auto': Caches only when temperature is 0 (default)")
print("- 'always': Reuses cached results when available")
print("- 'never': Generates new results every time")
await demonstrate_caching(transcript)
if __name__ == "__main__":
asyncio.run(main())