Skip to content

Commit a7fbc38

Browse files
committed
google looking nice and dandy
1 parent 530e26f commit a7fbc38

6 files changed

Lines changed: 307 additions & 11 deletions

File tree

docs/mint.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@
172172
"v2/integrations/autogen",
173173
"v2/integrations/crewai",
174174
"v2/integrations/google_adk",
175-
"v2/integrations/gemini",
175+
"v2/integrations/google_generative_ai",
176176
"v2/integrations/langchain",
177177
"v2/integrations/litellm",
178178
"v2/integrations/openai",

docs/v2/examples/examples.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ description: 'Examples of AgentOps with various integrations'
1313
Claude integration with tool usage and advanced features
1414
</Card>
1515

16-
<Card title="Gemini" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/deepmind/gemini-logo.png?raw=true" alt="Gemini" />} iconType="image" href="/v2/examples/gemini">
16+
<Card title="Google Generative AI" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/deepmind/gemini-logo.png?raw=true" alt="Gemini" />} iconType="image" href="/v2/examples/google_generative_ai">
1717
Google Gemini models and their examples
1818
</Card>
1919

docs/v2/examples/google_adk.mdx

Lines changed: 296 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,296 @@
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>
Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
---
2-
title: 'Gemini Example'
3-
description: 'Using Google Gemini API with AgentOps for synchronous and streaming text generation'
2+
title: 'Google Generative AI Example'
3+
description: 'Using Google Generative AI API with AgentOps for synchronous and streaming text generation'
44
---
5-
{/* SOURCE_FILE: examples/gemini/gemini_example.ipynb */}
5+
{/* SOURCE_FILE: examples/google_genai/gemini_example.ipynb */}
66

77
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/gemini/gemini_example.ipynb'} target={'_blank'}>Github</a>_
88

9-
# Gemini API Example with AgentOps
9+
# Google Generative AI API Example with AgentOps
1010

1111
This notebook demonstrates how to use AgentOps with Google's Gemini API for observing both synchronous and streaming text generation.
1212

@@ -39,11 +39,11 @@ load_dotenv()
3939
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_agentops_api_key_here")
4040
os.environ["GEMINI_API_KEY"] = os.getenv("GEMINI_API_KEY", "your_gemini_api_key_here")
4141

42-
# Configure the Gemini client with the API key
42+
# Configure the GenAI client with the API key
4343
genai.configure(api_key=os.environ["GEMINI_API_KEY"])
4444
```
4545

46-
Initialize AgentOps:
46+
Initialize AgentOps:
4747
```python
4848
# Initialize AgentOps and Gemini client
4949
agentops.init(tags=["gemini-example", "agentops-example"])

docs/v2/introduction.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ description: "AgentOps is the developer favorite platform for testing, debugging
1818

1919
<CardGroup cols={2}>
2020
<Card title="Anthropic" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/anthropic/anthropic_icon_slate.png?raw=true" alt="Anthropic" />} iconType="image" href="/v2/integrations/anthropic" />
21-
<Card title="Gemini" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/deepmind/gemini-logo.png?raw=true" alt="Gemini" />} iconType="image" href="/v2/integrations/gemini" />
21+
<Card title="Google Generative AI" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/deepmind/gemini-logo.png?raw=true" alt="Gemini" />} iconType="image" href="/v2/integrations/google_generative_ai" />
2222
<Card title="OpenAI" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/openai/openai-logomark.png?raw=true" alt="OpenAI" />} iconType="image" href="/v2/integrations/openai" />
2323
<Card title="LiteLLM" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/litellm/litellm.png?raw=true" alt="LiteLLM" />} iconType="image" href="/v2/integrations/litellm" />
2424
<Card title="Watsonx" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/ibm/ibm-logo.svg?raw=true" alt="IBM" />} iconType="image" href="/v2/integrations/ibm_watsonx_ai" />

examples/gemini/gemini_example.ipynb renamed to examples/google_genai/gemini_example.ipynb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
"id": "580c85ac",
66
"metadata": {},
77
"source": [
8-
"# Gemini API Example with AgentOps\n",
8+
"# Google Generative AI Example with AgentOps\n",
99
"\n",
10-
"This notebook demonstrates how to use AgentOps with Google's Gemini API for observing both synchronous and streaming text generation."
10+
"This notebook demonstrates how to use AgentOps with Google's Generative AI package for observing both synchronous and streaming text generation."
1111
]
1212
},
1313
{

0 commit comments

Comments
 (0)