|
| 1 | +--- |
| 2 | +title: 'Google Adk' |
| 3 | +description: 'Google ADK Example: Human Approval Workflow with AgentOps' |
| 4 | +--- |
| 5 | +{/* SOURCE_FILE: examples/google_adk/human_approval.ipynb */} |
| 6 | + |
| 7 | +_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/google_adk/human_approval.ipynb'} target={'_blank'}>Github</a>_ |
| 8 | + |
| 9 | +# Google ADK Example: Human Approval Workflow with AgentOps |
| 10 | + |
| 11 | +This notebook demonstrates a complete human approval workflow using the Google ADK (Agent Development Kit), integrated with AgentOps for observability. |
| 12 | + |
| 13 | +**Key Features:** |
| 14 | +- **Sequential Agent Processing:** The workflow uses multiple agents chained together to handle different stages of the approval process. |
| 15 | +- **External Tool Integration:** An agent interacts with an external tool that simulates (or in this version, directly prompts for) human approval. |
| 16 | +- **Session State Management:** Information is passed between agents and persisted using session state. |
| 17 | +- **AgentOps Observability:** All agent actions, tool calls, and LLM interactions are traced and can be viewed in your AgentOps dashboard. |
| 18 | +- **Interactive Human Input:** The approval step now requires direct input from the user. |
| 19 | + |
| 20 | +## 1. Setup and Dependencies |
| 21 | + |
| 22 | +First, let's install the necessary libraries if they are not already present and import them. |
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | +## Installation |
| 27 | +<CodeGroup> |
| 28 | + ```bash pip |
| 29 | + pip install agentops asyncio google-adk nest_asyncio python-dotenv |
| 30 | + ``` |
| 31 | + ```bash poetry |
| 32 | + poetry add agentops asyncio google-adk nest_asyncio python-dotenv |
| 33 | + ``` |
| 34 | + ```bash uv |
| 35 | + uv add agentops asyncio google-adk nest_asyncio python-dotenv |
| 36 | + ``` |
| 37 | +</CodeGroup> |
| 38 | + |
| 39 | + |
| 40 | +```python |
| 41 | +import json |
| 42 | +import os |
| 43 | +import asyncio |
| 44 | +from google.adk.agents import LlmAgent, SequentialAgent |
| 45 | +from google.adk.tools import FunctionTool |
| 46 | +from google.adk.runners import Runner |
| 47 | +from google.adk.sessions import InMemorySessionService |
| 48 | +from google.genai import types |
| 49 | +from pydantic import BaseModel, Field |
| 50 | +import nest_asyncio |
| 51 | +import agentops |
| 52 | +from dotenv import load_dotenv |
| 53 | +``` |
| 54 | + |
| 55 | +## 2. Configuration and Initialization |
| 56 | + |
| 57 | +Load environment variables (especially `AGENTOPS_API_KEY` and your Google API key for Gemini) and initialize AgentOps. |
| 58 | + |
| 59 | + |
| 60 | +```python |
| 61 | +# Load environment variables from .env file |
| 62 | +load_dotenv() |
| 63 | +nest_asyncio.apply() |
| 64 | +AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") or "your_agentops_api_key_here" |
| 65 | +# Initialize AgentOps - Just 2 lines! |
| 66 | +agentops.init(AGENTOPS_API_KEY, trace_name="adk-human-approval-notebook", auto_start_session=False) |
| 67 | +``` |
| 68 | + |
| 69 | +Define some constants for our application. |
| 70 | + |
| 71 | + |
| 72 | +```python |
| 73 | +APP_NAME = "human_approval_app_notebook" |
| 74 | +USER_ID = "test_user_notebook_123" |
| 75 | +SESSION_ID = "approval_session_notebook_456" |
| 76 | +MODEL_NAME = "gemini-1.5-flash" |
| 77 | +agentops.start_trace(trace_name=APP_NAME, tags=["google_adk","notebook"]) |
| 78 | +``` |
| 79 | + |
| 80 | +## 3. Define Schemas |
| 81 | + |
| 82 | +Pydantic models are used to define the structure of data for approval requests and decisions. This helps with validation and clarity. |
| 83 | + |
| 84 | + |
| 85 | +```python |
| 86 | +class ApprovalRequest(BaseModel): |
| 87 | + amount: float = Field(description="The amount requiring approval") |
| 88 | + reason: str = Field(description="The reason for the request") |
| 89 | +class ApprovalDecision(BaseModel): |
| 90 | + decision: str = Field(description="The approval decision: 'approved' or 'rejected'") |
| 91 | + comments: str = Field(description="Additional comments from the approver") |
| 92 | +``` |
| 93 | + |
| 94 | +## 4. External Approval Tool (with Human Interaction) |
| 95 | + |
| 96 | +This tool now directly prompts the user for an approval decision. In a real-world scenario, this might involve sending a notification to an approver and waiting for their response through a UI or API. |
| 97 | + |
| 98 | + |
| 99 | +```python |
| 100 | +async def external_approval_tool(amount: float, reason: str) -> str: |
| 101 | + """ |
| 102 | + Prompts for human approval and returns the decision as a JSON string. |
| 103 | + """ |
| 104 | + print(f"🔔 HUMAN APPROVAL REQUIRED:") |
| 105 | + print(f" Amount: ${amount:,.2f}") |
| 106 | + print(f" Reason: {reason}") |
| 107 | + decision = "" |
| 108 | + while decision.lower() not in ["approved", "rejected"]: |
| 109 | + decision = input(" Enter decision (approved/rejected): ").strip().lower() |
| 110 | + if decision.lower() not in ["approved", "rejected"]: |
| 111 | + print(" Invalid input. Please enter 'approved' or 'rejected'.") |
| 112 | + comments = input(" Enter comments (optional): ").strip() |
| 113 | + print(f" Decision: {decision.upper()}") |
| 114 | + print(f" Comments: {comments if comments else 'N/A'}") |
| 115 | + return json.dumps({ |
| 116 | + "decision": decision, |
| 117 | + "comments": comments, |
| 118 | + "amount": amount, |
| 119 | + "reason": reason |
| 120 | + }) |
| 121 | + |
| 122 | +# Create the approval tool instance |
| 123 | +approval_tool = FunctionTool(func=external_approval_tool) |
| 124 | +``` |
| 125 | + |
| 126 | +## 5. Define Agents |
| 127 | + |
| 128 | +We define three agents for our workflow: |
| 129 | +1. **`PrepareApprovalAgent`**: Extracts details from the user's request. |
| 130 | +2. **`RequestHumanApprovalAgent`**: Uses the `external_approval_tool` to get a decision. |
| 131 | +3. **`ProcessDecisionAgent`**: Processes the decision and formulates a final response. |
| 132 | + |
| 133 | + |
| 134 | +```python |
| 135 | +# Agent 1: Prepare the approval request |
| 136 | +prepare_request = LlmAgent( |
| 137 | + model=MODEL_NAME, |
| 138 | + name="PrepareApprovalAgent", |
| 139 | + description="Extracts and prepares approval request details from user input", |
| 140 | + instruction="""You are an approval request preparation agent. |
| 141 | + Your task: |
| 142 | + 1. Extract the amount and reason from the user's request |
| 143 | + 2. Store these values in the session state with keys 'approval_amount' and 'approval_reason' |
| 144 | + 3. Validate that both amount and reason are provided |
| 145 | + 4. Respond with a summary of what will be submitted for approval |
| 146 | + If the user input is missing amount or reason, ask for clarification. |
| 147 | + """, |
| 148 | + output_key="request_prepared" |
| 149 | +) |
| 150 | + |
| 151 | +# Agent 2: Request human approval using the tool |
| 152 | +request_approval = LlmAgent( |
| 153 | + model=MODEL_NAME, |
| 154 | + name="RequestHumanApprovalAgent", |
| 155 | + description="Calls the external approval system with prepared request details", |
| 156 | + instruction="""You are a human approval request agent. |
| 157 | + Your task: |
| 158 | + 1. Get the 'approval_amount' and 'approval_reason' from the session state |
| 159 | + 2. Use the external_approval_tool with these values |
| 160 | + 3. Store the approval decision in session state with key 'human_decision' |
| 161 | + 4. Respond with the approval status |
| 162 | + Always use the exact values from the session state for the tool call. |
| 163 | + """, |
| 164 | + tools=[approval_tool], |
| 165 | + output_key="approval_requested" |
| 166 | +) |
| 167 | + |
| 168 | +# Agent 3: Process the approval decision |
| 169 | +process_decision = LlmAgent( |
| 170 | + model=MODEL_NAME, |
| 171 | + name="ProcessDecisionAgent", |
| 172 | + description="Processes the human approval decision and provides final response", |
| 173 | + instruction="""You are a decision processing agent. |
| 174 | + Your task: |
| 175 | + 1. Check the 'human_decision' from session state |
| 176 | + 2. Parse the approval decision JSON |
| 177 | + 3. If approved: congratulate and provide next steps |
| 178 | + 4. If rejected: explain the rejection and suggest alternatives |
| 179 | + 5. Provide a clear, helpful final response to the user |
| 180 | +
|
| 181 | + Be professional and helpful in your response. |
| 182 | + """, |
| 183 | + output_key="final_decision" |
| 184 | +) |
| 185 | +``` |
| 186 | + |
| 187 | +## 6. Create Sequential Workflow |
| 188 | + |
| 189 | +Combine the agents into a sequential workflow. The `SequentialAgent` ensures that the sub-agents are executed in the specified order. |
| 190 | + |
| 191 | + |
| 192 | +```python |
| 193 | +approval_workflow = SequentialAgent( |
| 194 | + name="HumanApprovalWorkflowNotebook", |
| 195 | + description="Complete workflow for processing approval requests with human oversight", |
| 196 | + sub_agents=[prepare_request, request_approval, process_decision] |
| 197 | +) |
| 198 | +``` |
| 199 | + |
| 200 | +## 7. Session Management and Runner |
| 201 | + |
| 202 | +Set up an in-memory session service and the workflow runner. |
| 203 | + |
| 204 | + |
| 205 | +```python |
| 206 | +session_service = InMemorySessionService() |
| 207 | +# Create runner |
| 208 | +workflow_runner = Runner( |
| 209 | + agent=approval_workflow, |
| 210 | + app_name=APP_NAME, |
| 211 | + session_service=session_service |
| 212 | +) |
| 213 | +``` |
| 214 | + |
| 215 | +## 8. Helper Function to Run Workflow |
| 216 | + |
| 217 | +This function encapsulates the logic to run the workflow for a given user request and session ID. |
| 218 | + |
| 219 | + |
| 220 | +```python |
| 221 | +async def run_approval_workflow_notebook(user_request: str, session_id: str): |
| 222 | + """Run the complete approval workflow with a user request in the notebook environment""" |
| 223 | + print(f"{'='*60}") |
| 224 | + print(f" Starting Approval Workflow for Session: {session_id}") |
| 225 | + print(f"{'='*60}") |
| 226 | + print(f"User Request: {user_request}") |
| 227 | + # Create user message |
| 228 | + user_content = types.Content( |
| 229 | + role='user', |
| 230 | + parts=[types.Part(text=user_request)] |
| 231 | + ) |
| 232 | + step_count = 0 |
| 233 | + final_response = "No response received" |
| 234 | + # Run the workflow |
| 235 | + async for event in workflow_runner.run_async( |
| 236 | + user_id=USER_ID, |
| 237 | + session_id=session_id, |
| 238 | + new_message=user_content, |
| 239 | + ): |
| 240 | + if event.author and event.content: |
| 241 | + step_count += 1 |
| 242 | + print(f"📋 Step {step_count} - {event.author}:") |
| 243 | + if event.content.parts: |
| 244 | + response_text = event.content.parts[0].text |
| 245 | + print(f" {response_text}") |
| 246 | + if event.is_final_response(): |
| 247 | + final_response = response_text |
| 248 | + session = await session_service.get_session( |
| 249 | + app_name=APP_NAME, |
| 250 | + user_id=USER_ID, |
| 251 | + session_id=session_id, |
| 252 | + ) |
| 253 | + print(f"{'='*60}") |
| 254 | + print(f"📊 Workflow Complete - Session State ({session_id}):") |
| 255 | + print(f"{'='*60}") |
| 256 | + for key, value in session.state.items(): |
| 257 | + print(f" {key}: {value}") |
| 258 | + print(f"🎯 Final Response: {final_response}") |
| 259 | + return final_response |
| 260 | +``` |
| 261 | + |
| 262 | +## 9. Main Execution Logic |
| 263 | + |
| 264 | +This cell contains the main logic to run the workflow with a few test cases. Each test case will run in its own session. |
| 265 | + |
| 266 | + |
| 267 | +```python |
| 268 | +async def main_notebook(): |
| 269 | + test_requests = [ |
| 270 | + "I need approval for $750 for team lunch and celebrations", |
| 271 | + "Please approve $3,000 for a conference ticket and travel expenses", |
| 272 | + "I need $12,000 approved for critical software licenses renewal" |
| 273 | + ] |
| 274 | + for i, request in enumerate(test_requests, 1): |
| 275 | + current_session_id = f"approval_session_notebook_{456 + i -1}" |
| 276 | + # Create the session before running the workflow |
| 277 | + await session_service.create_session( |
| 278 | + app_name=APP_NAME, |
| 279 | + user_id=USER_ID, |
| 280 | + session_id=current_session_id |
| 281 | + ) |
| 282 | + print(f"Created session: {current_session_id}") |
| 283 | + await run_approval_workflow_notebook(request, current_session_id) |
| 284 | +try: |
| 285 | + asyncio.run(main_notebook()) |
| 286 | + agentops.end_trace(end_state="Success") |
| 287 | +except Exception as e: |
| 288 | + print(f"Error: {e}") |
| 289 | + agentops.end_trace(end_state="Error") |
| 290 | +``` |
| 291 | + |
| 292 | + |
| 293 | +<script type="module" src="/scripts/github_stars.js"></script> |
| 294 | +<script type="module" src="/scripts/scroll-img-fadein-animation.js"></script> |
| 295 | +<script type="module" src="/scripts/button_heartbeat_animation.js"></script> |
| 296 | +<script type="module" src="/scripts/adjust_api_dynamically.js"></script> |
0 commit comments