A workflow that demonstrates intelligent caching capabilities. This workflow: - Caches agent responses to avoid redundant API calls - Maintains session state across multiple invocations - Provides instant responses for repeated queries - Reduces costs and improves performan
| 30 | |
| 31 | |
| 32 | class CacheWorkflow(Workflow): |
| 33 | """ |
| 34 | A workflow that demonstrates intelligent caching capabilities. |
| 35 | |
| 36 | This workflow: |
| 37 | - Caches agent responses to avoid redundant API calls |
| 38 | - Maintains session state across multiple invocations |
| 39 | - Provides instant responses for repeated queries |
| 40 | - Reduces costs and improves performance |
| 41 | |
| 42 | Use cases: |
| 43 | - FAQ systems where questions repeat frequently |
| 44 | - Development/testing to avoid repeated API calls |
| 45 | - Systems with predictable query patterns |
| 46 | """ |
| 47 | |
| 48 | # Workflow metadata (descriptive, not functional) |
| 49 | description: str = "A workflow that caches previous outputs for efficiency" |
| 50 | |
| 51 | # Initialize agents as workflow attributes |
| 52 | # This agent will be used to generate responses when cache misses occur |
| 53 | agent = Agent(model=OpenAIChat(id="gpt-4o-mini"), description="General purpose agent for generating responses") |
| 54 | |
| 55 | def run(self, message: str) -> Iterator[RunResponse]: |
| 56 | """ |
| 57 | Execute the workflow with caching logic. |
| 58 | |
| 59 | This method: |
| 60 | 1. Checks if the response is already cached |
| 61 | 2. Returns cached response immediately if found |
| 62 | 3. Generates new response if not cached |
| 63 | 4. Caches the new response for future use |
| 64 | |
| 65 | Args: |
| 66 | message: The input query to process |
| 67 | |
| 68 | Yields: |
| 69 | RunResponse: Streamed response chunks |
| 70 | """ |
| 71 | logger.info(f"Checking cache for '{message}'") |
| 72 | |
| 73 | if self.session_state.get(message): |
| 74 | logger.info(f"Cache hit for '{message}'") |
| 75 | # Return cached response immediately (no API call needed) |
| 76 | yield RunResponse(run_id=self.run_id, content=self.session_state.get(message)) |
| 77 | return |
| 78 | |
| 79 | logger.info(f"Cache miss for '{message}'") |
| 80 | |
| 81 | yield from self.agent.run(message, stream=True) |
| 82 | |
| 83 | self.session_state[message] = self.agent.run_response.content |
| 84 | logger.info("Cached response for future use") |
| 85 | |
| 86 | |
| 87 | def demonstrate_workflows(): |
no test coverage detected
searching dependent graphs…