|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Weather Assistant Agent. |
| 16 | +
|
| 17 | +This agent provides weather information for cities worldwide. |
| 18 | +It demonstrates OAuth2 client credentials flow transparently |
| 19 | +through AuthenticatedFunctionTool usage. |
| 20 | +""" |
| 21 | + |
| 22 | +from fastapi.openapi.models import OAuth2 |
| 23 | +from fastapi.openapi.models import OAuthFlowClientCredentials |
| 24 | +from fastapi.openapi.models import OAuthFlows |
| 25 | +from google.adk.agents.llm_agent import Agent |
| 26 | +from google.adk.auth.auth_credential import AuthCredential |
| 27 | +from google.adk.auth.auth_credential import AuthCredentialTypes |
| 28 | +from google.adk.auth.auth_credential import OAuth2Auth |
| 29 | +from google.adk.auth.auth_tool import AuthConfig |
| 30 | +from google.adk.tools.authenticated_function_tool import AuthenticatedFunctionTool |
| 31 | +import requests |
| 32 | + |
| 33 | + |
| 34 | +# OAuth2 configuration for weather API access |
| 35 | +def create_auth_config() -> AuthConfig: |
| 36 | + """Create OAuth2 auth configuration for weather API.""" |
| 37 | + |
| 38 | + # Define OAuth2 scheme with client credentials flow |
| 39 | + flows = OAuthFlows( |
| 40 | + clientCredentials=OAuthFlowClientCredentials( |
| 41 | + tokenUrl="http://localhost:8080/token", |
| 42 | + scopes={ |
| 43 | + "read": "Read access to weather data", |
| 44 | + "write": "Write access for data updates", |
| 45 | + "admin": "Administrative access", |
| 46 | + }, |
| 47 | + ) |
| 48 | + ) |
| 49 | + auth_scheme = OAuth2(flows=flows) |
| 50 | + |
| 51 | + # Create credential with client ID and secret |
| 52 | + raw_credential = AuthCredential( |
| 53 | + auth_type=AuthCredentialTypes.OAUTH2, |
| 54 | + oauth2=OAuth2Auth( |
| 55 | + client_id="test_client", |
| 56 | + client_secret="test_secret", |
| 57 | + ), |
| 58 | + ) |
| 59 | + |
| 60 | + return AuthConfig( |
| 61 | + auth_scheme=auth_scheme, |
| 62 | + raw_auth_credential=raw_credential, |
| 63 | + credential_key="weather_api_client", |
| 64 | + ) |
| 65 | + |
| 66 | + |
| 67 | +def get_weather_data(city: str = "San Francisco", credential=None) -> str: |
| 68 | + """Get current weather data for a specified city. |
| 69 | +
|
| 70 | + Args: |
| 71 | + city: City name to get weather for |
| 72 | + credential: API credential (automatically injected by AuthenticatedFunctionTool) |
| 73 | +
|
| 74 | + Returns: |
| 75 | + Current weather information for the city. |
| 76 | + """ |
| 77 | + |
| 78 | + try: |
| 79 | + # Use the credential to make authenticated requests to weather API |
| 80 | + headers = {} |
| 81 | + if credential and credential.oauth2 and credential.oauth2.access_token: |
| 82 | + headers["Authorization"] = f"Bearer {credential.oauth2.access_token}" |
| 83 | + |
| 84 | + # Call weather API endpoint |
| 85 | + params = {"city": city, "units": "metric"} |
| 86 | + response = requests.get( |
| 87 | + "http://localhost:8080/api/weather", |
| 88 | + headers=headers, |
| 89 | + params=params, |
| 90 | + timeout=10, |
| 91 | + ) |
| 92 | + |
| 93 | + if response.status_code == 200: |
| 94 | + data = response.json() |
| 95 | + result = f"🌤️ Weather for {city}:\n" |
| 96 | + result += f"Temperature: {data.get('temperature', 'N/A')}°C\n" |
| 97 | + result += f"Condition: {data.get('condition', 'N/A')}\n" |
| 98 | + result += f"Humidity: {data.get('humidity', 'N/A')}%\n" |
| 99 | + result += f"Wind Speed: {data.get('wind_speed', 'N/A')} km/h\n" |
| 100 | + result += f"Last Updated: {data.get('timestamp', 'N/A')}\n" |
| 101 | + return result |
| 102 | + else: |
| 103 | + return ( |
| 104 | + f"❌ Failed to get weather data: {response.status_code} -" |
| 105 | + f" {response.text}" |
| 106 | + ) |
| 107 | + |
| 108 | + except Exception as e: |
| 109 | + return f"❌ Error getting weather data: {str(e)}" |
| 110 | + |
| 111 | + |
| 112 | +# Create the weather assistant agent |
| 113 | +root_agent = Agent( |
| 114 | + name="WeatherAssistant", |
| 115 | + description=( |
| 116 | + "Weather assistant that provides current weather information for cities" |
| 117 | + " worldwide." |
| 118 | + ), |
| 119 | + model="gemini-2.5-pro", |
| 120 | + instruction=( |
| 121 | + "You are a helpful Weather Assistant that provides current weather" |
| 122 | + " information for any city worldwide.\n\nWhen users ask for weather:\n•" |
| 123 | + " Ask for the city name if not provided\n• Provide temperature in" |
| 124 | + " Celsius\n• Include helpful details like humidity, wind speed, and" |
| 125 | + " conditions\n• Be friendly and conversational about the weather\n\nIf" |
| 126 | + " there are any issues getting weather data, apologize and suggest" |
| 127 | + " trying again or checking for a different city name." |
| 128 | + ), |
| 129 | + tools=[ |
| 130 | + AuthenticatedFunctionTool( |
| 131 | + func=get_weather_data, auth_config=create_auth_config() |
| 132 | + ), |
| 133 | + ], |
| 134 | +) |
0 commit comments