You've already forked adk-python
mirror of
https://github.com/encounter/adk-python.git
synced 2026-07-09 18:19:28 -07:00
Compare commits
74 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5b999ed6fd | |||
| bb8ebd15f9 | |||
| fef5318a22 | |||
| 018db79d13 | |||
| 77ed1f5f15 | |||
| 4afc9b2f33 | |||
| f8fd6a4f09 | |||
| a953807cce | |||
| fa64545a9d | |||
| 004a0a0f2d | |||
| a117cf0af3 | |||
| 1fd58cb363 | |||
| f03f167779 | |||
| 43f302ce1a | |||
| ecaa7b4c98 | |||
| 279e4fedd0 | |||
| b3b70035c4 | |||
| 22f34e9d2c | |||
| ba6e85eb3f | |||
| c84350345a | |||
| a2b7909fc3 | |||
| b66054dd0d | |||
| 8a9a271141 | |||
| a2832d5ac7 | |||
| 1328e6ef62 | |||
| cd357bf5ae | |||
| a27927dc81 | |||
| 6c217bad82 | |||
| c32cb6eef9 | |||
| 80052700f6 | |||
| c8059428a2 | |||
| e63e2a7106 | |||
| 9ba8eec220 | |||
| 9cfe43334a | |||
| 52284b1bae | |||
| a74d3344bc | |||
| ddf2e2194b | |||
| a30c63c593 | |||
| c5af44cfc0 | |||
| c52f956433 | |||
| 585141e0b7 | |||
| 114db93d70 | |||
| e2518dc371 | |||
| 8c65967cdc | |||
| ebd726f1f5 | |||
| 54680edf3c | |||
| bb3735c9ca | |||
| a09a5e67aa | |||
| 7e0880869b | |||
| 1fc8d20ae8 | |||
| 10e3dfab1a | |||
| 5fba1963c3 | |||
| 7d2cb654f0 | |||
| 88f759a941 | |||
| e295feb4c6 | |||
| d87feb8ddb | |||
| 88114d7c73 | |||
| d0b3b5d857 | |||
| d674178a05 | |||
| dc26aad663 | |||
| 7f12387eb1 | |||
| 8f937b5175 | |||
| c323de5c69 | |||
| b4f1ebea31 | |||
| 944e39ec2a | |||
| 9478a31bf2 | |||
| f2005a2026 | |||
| af635674b5 | |||
| b4ce3b12d1 | |||
| 98a5730115 | |||
| 4b2a8e3186 | |||
| e4d54b66b3 | |||
| 5900273455 | |||
| b5a8bad170 |
@@ -27,14 +27,16 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install google-adk
|
||||
pip install google-adk google-cloud-discoveryengine
|
||||
|
||||
- name: Run Answering Script
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.ADK_TRIAGE_AGENT }}
|
||||
ADK_GCP_SA_KEY: ${{ secrets.ADK_GCP_SA_KEY }}
|
||||
GOOGLE_CLOUD_PROJECT: ${{ secrets.GOOGLE_CLOUD_PROJECT }}
|
||||
GOOGLE_CLOUD_LOCATION: ${{ secrets.GOOGLE_CLOUD_LOCATION }}
|
||||
VERTEXAI_DATASTORE_ID: ${{ secrets.VERTEXAI_DATASTORE_ID }}
|
||||
GEMINI_API_DATASTORE_ID: ${{ secrets.GEMINI_API_DATASTORE_ID }}
|
||||
GOOGLE_GENAI_USE_VERTEXAI: 1
|
||||
OWNER: 'google'
|
||||
REPO: 'adk-python'
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: ["3.9", "3.10", "3.11"]
|
||||
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
name: Upload ADK Docs to Vertex AI Search
|
||||
|
||||
on:
|
||||
# Runs once per day at 16:00 UTC
|
||||
schedule:
|
||||
- cron: '00 16 * * *'
|
||||
# Manual trigger for testing and fixing
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
upload-adk-docs-to-vertex-ai-search:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Clone adk-docs repository
|
||||
run: git clone https://github.com/google/adk-docs.git /tmp/adk-docs
|
||||
|
||||
- name: Clone adk-python repository
|
||||
run: git clone https://github.com/google/adk-python.git /tmp/adk-python
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.11'
|
||||
|
||||
- name: Authenticate to Google Cloud
|
||||
id: auth
|
||||
uses: 'google-github-actions/auth@v2'
|
||||
with:
|
||||
credentials_json: '${{ secrets.ADK_GCP_SA_KEY }}'
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install google-adk markdown google-cloud-storage google-cloud-discoveryengine
|
||||
|
||||
- name: Run Answering Script
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.ADK_TRIAGE_AGENT }}
|
||||
GOOGLE_CLOUD_PROJECT: ${{ secrets.GOOGLE_CLOUD_PROJECT }}
|
||||
GOOGLE_CLOUD_LOCATION: ${{ secrets.GOOGLE_CLOUD_LOCATION }}
|
||||
VERTEXAI_DATASTORE_ID: ${{ secrets.VERTEXAI_DATASTORE_ID }}
|
||||
GOOGLE_GENAI_USE_VERTEXAI: 1
|
||||
GCS_BUCKET_NAME: ${{ secrets.GCS_BUCKET_NAME }}
|
||||
ADK_DOCS_ROOT_PATH: /tmp/adk-docs
|
||||
ADK_PYTHON_ROOT_PATH: /tmp/adk-python
|
||||
PYTHONPATH: contributing/samples
|
||||
run: python -m adk_answering_agent.upload_docs_to_vertex_ai_search
|
||||
@@ -1,5 +1,55 @@
|
||||
# Changelog
|
||||
|
||||
## [1.11.0](https://github.com/google/adk-python/compare/v1.10.0...v1.11.0) (2025-08-14)
|
||||
|
||||
### Features
|
||||
|
||||
* [Tools] Support adding prefix to tool names returned by toolset ([ebd726f](https://github.com/google/adk-python/commit/ebd726f1f5e0a76f383192cace4a80a83204325b))
|
||||
* [Eval] Expose `print_detailed_results` param to `AgentEvaluator.evaluate` ([7e08808](https://github.com/google/adk-python/commit/7e0880869b340e9a5e0d68d6936219e64ab41212))
|
||||
* [Tools] Add Spanner toolset (breaking change to BigQueryTool, consolidating into generic GoogleTool) ([1fc8d20](https://github.com/google/adk-python/commit/1fc8d20ae88451b7ed764aa86c17c3cdfaffa1cf))
|
||||
* [Core] Support both output_schema and tools at the same time in LlmAgent([sample](https://github.com/google/adk-python/tree/main/contributing/samples/output_schema_with_tools)) ([af63567](https://github.com/google/adk-python/commit/af635674b5d3c128cf21737056e091646283aeb7))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* A2A RPC URL got overriden by host and port param of adk api server ([52284b1](https://github.com/google/adk-python/commit/52284b1bae561e0d6c93c9d3240a09f210551b97))
|
||||
* Aclose all async generators to fix OTel tracing context ([a30c63c](https://github.com/google/adk-python/commit/a30c63c5933a770b960b08a6e2f8bf13eece8a22))
|
||||
* Use PreciseTimestamp for create and update time in database session service to improve precision ([585141e](https://github.com/google/adk-python/commit/585141e0b7dda20abb024c7164073862c8eea7ae))
|
||||
* Ignore AsyncGenerator return types in function declarations ([e2518dc](https://github.com/google/adk-python/commit/e2518dc371fe77d7b30328d8d6f5f864176edeac))
|
||||
* Make all subclass of BaseToolset to call parent constructor ([8c65967](https://github.com/google/adk-python/commit/8c65967cdc2dc79fa925ff49a2a8d67c2a248fa9))
|
||||
* Path parameter extraction for complex Google API endpoints ([54680ed](https://github.com/google/adk-python/commit/54680edf3cac7477c281680ec988c0a207c0915d))
|
||||
* Docstring concatenation in 3.13 ([88f759a](https://github.com/google/adk-python/commit/88f759a941c95beef0571f36f8e7a34f27971ba8))
|
||||
* Lazy load retrieval tools and prompt users to install extensions if import failed ([9478a31](https://github.com/google/adk-python/commit/9478a31bf2257f0b668ae7eb91a10863e87c7bed))
|
||||
* Incorrect logic in LlmRequest.append_tools and make BaseTool to call it ([b4ce3b1](https://github.com/google/adk-python/commit/b4ce3b12d109dd0386f4985fc4b27d5b93787532))
|
||||
* Creates an InMemoryMemoryService within the EvaluationGenerator ([e4d54b6](https://github.com/google/adk-python/commit/e4d54b66b38ed334ca92c3bb1a83aca01b19e490))
|
||||
* Uncomment OTel tracing in base_llm_flow.py ([9cfe433](https://github.com/google/adk-python/commit/9cfe43334ae50f814fed663cca7cbe330e663b8c))
|
||||
|
||||
### Improvements
|
||||
|
||||
* Added upper version bounds to dependencies in "pyproject.toml" ([a74d334](https://github.com/google/adk-python/commit/a74d3344bc19e587c5e9f55f3c90fa9d22c478d8))
|
||||
* Update python-version in .github/workflows/python-unit-tests.yml to \["3.9", "3.10", "3.11", "3.12", "3.13"] ([ddf2e21](https://github.com/google/adk-python/commit/ddf2e2194b49667c8e91b4a6afde694474674250))
|
||||
* Update comment to reference "Streamable HTTP Client" ([c52f956](https://github.com/google/adk-python/commit/c52f9564330f0c00d82338cc58df28cb22400b6f))
|
||||
* Remove logging that contains full event data from DatabaseSessionService ([bb3735c](https://github.com/google/adk-python/commit/bb3735c9cab1baa1af2cc22981af3b3984ddfe15))
|
||||
* Add the missing env variables in discussion_answering.yml ([a09a5e6](https://github.com/google/adk-python/commit/a09a5e67aa95cf71b51732ab445232dc4815d83d))
|
||||
* Add Gemini API docs as a new datastore for the ADK Answering Agent ([5fba196](https://github.com/google/adk-python/commit/5fba1963c31eec512558325c480812ccb919a7bb))
|
||||
* Add the missing license header for some sample agents' files ([7d2cb65](https://github.com/google/adk-python/commit/7d2cb654f0d64728741b5de733e572c44c8a5b04))
|
||||
* Add docstring to clarify the behavior of preload memory tool ([88114d7](https://github.com/google/adk-python/commit/88114d7c739ca6a1b9bd19d40ed7160e53054a89))
|
||||
* Add experimental messages for a2a related API ([d0b3b5d](https://github.com/google/adk-python/commit/d0b3b5d857d8105c689bd64204e367102a67eded))
|
||||
* Fixes generate_image sample ([d674178](https://github.com/google/adk-python/commit/d674178a0535be3769edbf6af5a3d8cd3d47fcd2))
|
||||
* Make all FastAPI endpoints async ([7f12387](https://github.com/google/adk-python/commit/7f12387eb19b9335a64b80df00609c3c765480e7))
|
||||
* Group FastAPI endpoints with tags ([c323de5](https://github.com/google/adk-python/commit/c323de5c692223e55372c3797e62d4752835774d))
|
||||
* Allow implementations to skip defining a close method on Toolset ([944e39e](https://github.com/google/adk-python/commit/944e39ec2a7c9ad7f20c08fd66bf544de94a23d7))
|
||||
* Add sample agent to test support of output_schema and tools at the same time for gemini model ([f2005a2](https://github.com/google/adk-python/commit/f2005a20267e1ee8581cb79c37aa55dc8e18c0ea))
|
||||
* Add Github workflow config for uploading ADK docs to knowledge store ([5900273](https://github.com/google/adk-python/commit/59002734559d49a46940db9822b9c5f490220a8c))
|
||||
* Update ADK Answering agent to reference doc site instead of adk-docs repo ([b5a8bad](https://github.com/google/adk-python/commit/b5a8bad170e271b475385dac440c7983ed207df8))
|
||||
|
||||
### Documentation
|
||||
|
||||
* Fixes tool_functions, which is a config-based sample for using tools ([c5af44c](https://github.com/google/adk-python/commit/c5af44cfc0224e2f07ddc7a649a8561e7141fcdc))
|
||||
* Add workflow_triage sample for multi-agent request orchestration ([e295feb](https://github.com/google/adk-python/commit/e295feb4c67cbe8ac4425d9ae230210840378b2e))
|
||||
* Add examples for config agents ([d87feb8](https://github.com/google/adk-python/commit/d87feb8ddb6a5e402c63bd3c35625160eb94e132))
|
||||
* Adds pypi badge to README.md ([dc26aad](https://github.com/google/adk-python/commit/dc26aad663b6ae72223cfec9b91eaf73a636402d))
|
||||
* Update StreamableHTTPConnectionParams docstring to remove SSE references ([8f937b5](https://github.com/google/adk-python/commit/8f937b517548a1ce0569f9698ea55c0a130ef221))
|
||||
|
||||
## [1.10.0](https://github.com/google/adk-python/compare/v1.9.0...v1.10.0) (2025-08-07)
|
||||
|
||||
### Features
|
||||
|
||||
+1
-2
@@ -49,8 +49,7 @@ This project follows
|
||||
|
||||
## Requirement for PRs
|
||||
|
||||
- Each PR should only have one commit. Please squash it if there are multiple PRs.
|
||||
- All PRs, other than small documentation or typo fixes, should have a Issue assoicated. If not, please create one.
|
||||
- All PRs, other than small documentation or typo fixes, should have a Issue associated. If not, please create one.
|
||||
- Small, focused PRs. Keep changes minimal—one concern per PR.
|
||||
- For bug fixes or features, please provide logs or screenshot after the fix is applied to help reviewers better understand the fix.
|
||||
- Please include a `testing plan` section in your PR to talk about how you will test. This will save time for PR review. See `Testing Requirements` section for more details.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# Agent Development Kit (ADK)
|
||||
|
||||
[](LICENSE)
|
||||
[](https://pypi.org/project/google-adk/)
|
||||
[](https://github.com/google/adk-python/actions/workflows/python-unit-tests.yml)
|
||||
[](https://www.reddit.com/r/agentdevelopmentkit/)
|
||||
[](https://deepwiki.com/google/adk-python)
|
||||
@@ -14,7 +15,7 @@
|
||||
</h3>
|
||||
<h3 align="center">
|
||||
Important Links:
|
||||
<a href="https://google.github.io/adk-docs/">Docs</a>,
|
||||
<a href="https://google.github.io/adk-docs/">Docs</a>,
|
||||
<a href="https://github.com/google/adk-samples">Samples</a>,
|
||||
<a href="https://github.com/google/adk-java">Java ADK</a> &
|
||||
<a href="https://github.com/google/adk-web">ADK Web</a>.
|
||||
|
||||
@@ -157,12 +157,43 @@ You can extend this sample by:
|
||||
- Adding audit logging for authentication events
|
||||
- Implementing multi-tenant OAuth token management
|
||||
|
||||
## Deployment to Other Environments
|
||||
|
||||
When deploying the remote BigQuery A2A agent to different environments (e.g., Cloud Run, different hosts/ports), you **must** update the `url` field in the agent card JSON file:
|
||||
|
||||
### Local Development
|
||||
```json
|
||||
{
|
||||
"url": "http://localhost:8001/a2a/bigquery_agent",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Cloud Run Example
|
||||
```json
|
||||
{
|
||||
"url": "https://your-bigquery-service-abc123-uc.a.run.app/a2a/bigquery_agent",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Host/Port Example
|
||||
```json
|
||||
{
|
||||
"url": "https://your-domain.com:9000/a2a/bigquery_agent",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
**Important:** The `url` field in `remote_a2a/bigquery_agent/agent.json` must point to the actual RPC endpoint where your remote BigQuery A2A agent is deployed and accessible.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Connection Issues:**
|
||||
- Ensure the local ADK web server is running on port 8000
|
||||
- Ensure the remote A2A server is running on port 8001
|
||||
- Check that no firewall is blocking localhost connections
|
||||
- **Verify the `url` field in `remote_a2a/bigquery_agent/agent.json` matches the actual deployed location of your remote A2A server**
|
||||
- Verify the agent card URL passed to RemoteA2AAgent constructor matches the running A2A server
|
||||
|
||||
|
||||
@@ -182,3 +213,4 @@ You can extend this sample by:
|
||||
- Check the logs for both the local ADK web server and remote A2A server
|
||||
- Verify OAuth tokens are properly passed between agents
|
||||
- Ensure agent instructions are clear about authentication requirements
|
||||
- **Double-check that the RPC URL in the agent.json file is correct and accessible**
|
||||
|
||||
@@ -24,6 +24,6 @@
|
||||
"tags": ["authentication", "oauth", "security"]
|
||||
}
|
||||
],
|
||||
"url": "http://localhost:8000/a2a/bigquery_agent",
|
||||
"url": "http://localhost:8001/a2a/bigquery_agent",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
|
||||
@@ -107,15 +107,47 @@ You can extend this sample by:
|
||||
- Adding persistent state management
|
||||
- Integrating with external APIs or databases
|
||||
|
||||
## Deployment to Other Environments
|
||||
|
||||
When deploying the remote A2A agent to different environments (e.g., Cloud Run, different hosts/ports), you **must** update the `url` field in the agent card JSON file:
|
||||
|
||||
### Local Development
|
||||
```json
|
||||
{
|
||||
"url": "http://localhost:8001/a2a/check_prime_agent",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Cloud Run Example
|
||||
```json
|
||||
{
|
||||
"url": "https://your-service-abc123-uc.a.run.app/a2a/check_prime_agent",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Host/Port Example
|
||||
```json
|
||||
{
|
||||
"url": "https://your-domain.com:9000/a2a/check_prime_agent",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
**Important:** The `url` field in `remote_a2a/check_prime_agent/agent.json` must point to the actual RPC endpoint where your remote A2A agent is deployed and accessible.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Connection Issues:**
|
||||
- Ensure the local ADK web server is running on port 8000
|
||||
- Ensure the remote A2A server is running on port 8001
|
||||
- Check that no firewall is blocking localhost connections
|
||||
- **Verify the `url` field in `remote_a2a/check_prime_agent/agent.json` matches the actual deployed location of your remote A2A server**
|
||||
- Verify the agent card URL passed to RemoteA2AAgent constructor matches the running A2A server
|
||||
|
||||
|
||||
**Agent Not Responding:**
|
||||
- Check the logs for both the local ADK web server on port 8000 and remote A2A server on port 8001
|
||||
- Verify the agent instructions are clear and unambiguous
|
||||
- **Double-check that the RPC URL in the agent.json file is correct and accessible**
|
||||
|
||||
@@ -116,18 +116,50 @@ You can extend this sample by:
|
||||
- Integrating with external approval systems or databases
|
||||
- Implementing approval timeouts and escalation procedures
|
||||
|
||||
## Deployment to Other Environments
|
||||
|
||||
When deploying the remote approval A2A agent to different environments (e.g., Cloud Run, different hosts/ports), you **must** update the `url` field in the agent card JSON file:
|
||||
|
||||
### Local Development
|
||||
```json
|
||||
{
|
||||
"url": "http://localhost:8001/a2a/human_in_loop",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Cloud Run Example
|
||||
```json
|
||||
{
|
||||
"url": "https://your-approval-service-abc123-uc.a.run.app/a2a/human_in_loop",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Host/Port Example
|
||||
```json
|
||||
{
|
||||
"url": "https://your-domain.com:9000/a2a/human_in_loop",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
**Important:** The `url` field in `remote_a2a/human_in_loop/agent.json` must point to the actual RPC endpoint where your remote approval A2A agent is deployed and accessible.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Connection Issues:**
|
||||
- Ensure the local ADK web server is running on port 8000
|
||||
- Ensure the remote A2A server is running on port 8001
|
||||
- Check that no firewall is blocking localhost connections
|
||||
- **Verify the `url` field in `remote_a2a/human_in_loop/agent.json` matches the actual deployed location of your remote A2A server**
|
||||
- Verify the agent card URL passed to RemoteA2AAgent constructor matches the running A2A server
|
||||
|
||||
**Agent Not Responding:**
|
||||
- Check the logs for both the local ADK web server on port 8000 and remote A2A server on port 8001
|
||||
- Verify the agent instructions are clear and unambiguous
|
||||
- Ensure long-running tool responses are properly formatted with matching IDs
|
||||
- **Double-check that the RPC URL in the agent.json file is correct and accessible**
|
||||
|
||||
**Approval Workflow Issues:**
|
||||
- Verify that updated tool responses use the same `id` and `name` as the original function call
|
||||
|
||||
@@ -24,6 +24,6 @@
|
||||
"tags": ["expenses", "processing", "employee-services"]
|
||||
}
|
||||
],
|
||||
"url": "http://localhost:8000/a2a/human_in_loop",
|
||||
"url": "http://localhost:8001/a2a/human_in_loop",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
|
||||
@@ -12,18 +12,19 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any
|
||||
|
||||
from adk_answering_agent.gemini_assistant.agent import root_agent as gemini_assistant_agent
|
||||
from adk_answering_agent.settings import BOT_RESPONSE_LABEL
|
||||
from adk_answering_agent.settings import IS_INTERACTIVE
|
||||
from adk_answering_agent.settings import OWNER
|
||||
from adk_answering_agent.settings import REPO
|
||||
from adk_answering_agent.settings import VERTEXAI_DATASTORE_ID
|
||||
from adk_answering_agent.utils import error_response
|
||||
from adk_answering_agent.utils import run_graphql_query
|
||||
from adk_answering_agent.tools import add_comment_to_discussion
|
||||
from adk_answering_agent.tools import add_label_to_discussion
|
||||
from adk_answering_agent.tools import convert_gcs_links_to_https
|
||||
from adk_answering_agent.tools import get_discussion_and_comments
|
||||
from google.adk.agents.llm_agent import Agent
|
||||
from google.adk.tools.agent_tool import AgentTool
|
||||
from google.adk.tools.vertex_ai_search_tool import VertexAiSearchTool
|
||||
import requests
|
||||
|
||||
if IS_INTERACTIVE:
|
||||
APPROVAL_INSTRUCTION = (
|
||||
@@ -35,197 +36,6 @@ else:
|
||||
" comment."
|
||||
)
|
||||
|
||||
|
||||
def get_discussion_and_comments(discussion_number: int) -> dict[str, Any]:
|
||||
"""Fetches a discussion and its comments using the GitHub GraphQL API.
|
||||
|
||||
Args:
|
||||
discussion_number: The number of the GitHub discussion.
|
||||
|
||||
Returns:
|
||||
A dictionary with the request status and the discussion details.
|
||||
"""
|
||||
print(f"Attempting to get discussion #{discussion_number} and its comments")
|
||||
query = """
|
||||
query($owner: String!, $repo: String!, $discussionNumber: Int!) {
|
||||
repository(owner: $owner, name: $repo) {
|
||||
discussion(number: $discussionNumber) {
|
||||
id
|
||||
title
|
||||
body
|
||||
createdAt
|
||||
closed
|
||||
author {
|
||||
login
|
||||
}
|
||||
# For each discussion, fetch the latest 20 labels.
|
||||
labels(last: 20) {
|
||||
nodes {
|
||||
id
|
||||
name
|
||||
}
|
||||
}
|
||||
# For each discussion, fetch the latest 100 comments.
|
||||
comments(last: 100) {
|
||||
nodes {
|
||||
id
|
||||
body
|
||||
createdAt
|
||||
author {
|
||||
login
|
||||
}
|
||||
# For each discussion, fetch the latest 50 replies
|
||||
replies(last: 50) {
|
||||
nodes {
|
||||
id
|
||||
body
|
||||
createdAt
|
||||
author {
|
||||
login
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
variables = {
|
||||
"owner": OWNER,
|
||||
"repo": REPO,
|
||||
"discussionNumber": discussion_number,
|
||||
}
|
||||
try:
|
||||
response = run_graphql_query(query, variables)
|
||||
if "errors" in response:
|
||||
return error_response(str(response["errors"]))
|
||||
discussion_data = (
|
||||
response.get("data", {}).get("repository", {}).get("discussion")
|
||||
)
|
||||
if not discussion_data:
|
||||
return error_response(f"Discussion #{discussion_number} not found.")
|
||||
return {"status": "success", "discussion": discussion_data}
|
||||
except requests.exceptions.RequestException as e:
|
||||
return error_response(str(e))
|
||||
|
||||
|
||||
def add_comment_to_discussion(
|
||||
discussion_id: str, comment_body: str
|
||||
) -> dict[str, Any]:
|
||||
"""Adds a comment to a specific discussion.
|
||||
|
||||
Args:
|
||||
discussion_id: The GraphQL node ID of the discussion.
|
||||
comment_body: The content of the comment in Markdown.
|
||||
|
||||
Returns:
|
||||
The status of the request and the new comment's details.
|
||||
"""
|
||||
print(f"Adding comment to discussion {discussion_id}")
|
||||
query = """
|
||||
mutation($discussionId: ID!, $body: String!) {
|
||||
addDiscussionComment(input: {discussionId: $discussionId, body: $body}) {
|
||||
comment {
|
||||
id
|
||||
body
|
||||
createdAt
|
||||
author {
|
||||
login
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
comment_body = (
|
||||
"**Response from ADK Answering Agent (experimental, answer may be"
|
||||
" inaccurate)**\n\n"
|
||||
+ comment_body
|
||||
)
|
||||
|
||||
variables = {"discussionId": discussion_id, "body": comment_body}
|
||||
try:
|
||||
response = run_graphql_query(query, variables)
|
||||
if "errors" in response:
|
||||
return error_response(str(response["errors"]))
|
||||
new_comment = (
|
||||
response.get("data", {}).get("addDiscussionComment", {}).get("comment")
|
||||
)
|
||||
return {"status": "success", "comment": new_comment}
|
||||
except requests.exceptions.RequestException as e:
|
||||
return error_response(str(e))
|
||||
|
||||
|
||||
def get_label_id(label_name: str) -> str | None:
|
||||
"""Helper function to find the GraphQL node ID for a given label name."""
|
||||
print(f"Finding ID for label '{label_name}'...")
|
||||
query = """
|
||||
query($owner: String!, $repo: String!, $labelName: String!) {
|
||||
repository(owner: $owner, name: $repo) {
|
||||
label(name: $labelName) {
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
variables = {"owner": OWNER, "repo": REPO, "labelName": label_name}
|
||||
|
||||
try:
|
||||
response = run_graphql_query(query, variables)
|
||||
if "errors" in response:
|
||||
print(
|
||||
f"[Warning] Error from GitHub API response for label '{label_name}':"
|
||||
f" {response['errors']}"
|
||||
)
|
||||
return None
|
||||
label_info = response["data"].get("repository", {}).get("label")
|
||||
if label_info:
|
||||
return label_info.get("id")
|
||||
print(f"[Warning] Label information for '{label_name}' not found.")
|
||||
return None
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"[Warning] Error from GitHub API: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def add_label_to_discussion(
|
||||
discussion_id: str, label_name: str
|
||||
) -> dict[str, Any]:
|
||||
"""Adds a label to a specific discussion.
|
||||
|
||||
Args:
|
||||
discussion_id: The GraphQL node ID of the discussion.
|
||||
label_name: The name of the label to add (e.g., "bug").
|
||||
|
||||
Returns:
|
||||
The status of the request and the label details.
|
||||
"""
|
||||
print(
|
||||
f"Attempting to add label '{label_name}' to discussion {discussion_id}..."
|
||||
)
|
||||
# First, get the GraphQL ID of the label by its name
|
||||
label_id = get_label_id(label_name)
|
||||
if not label_id:
|
||||
return error_response(f"Label '{label_name}' not found.")
|
||||
|
||||
# Then, perform the mutation to add the label to the discussion
|
||||
mutation = """
|
||||
mutation AddLabel($discussionId: ID!, $labelId: ID!) {
|
||||
addLabelsToLabelable(input: {labelableId: $discussionId, labelIds: [$labelId]}) {
|
||||
clientMutationId
|
||||
}
|
||||
}
|
||||
"""
|
||||
variables = {"discussionId": discussion_id, "labelId": label_id}
|
||||
try:
|
||||
response = run_graphql_query(mutation, variables)
|
||||
if "errors" in response:
|
||||
return error_response(str(response["errors"]))
|
||||
return {"status": "success", "label_id": label_id, "label_name": label_name}
|
||||
except requests.exceptions.RequestException as e:
|
||||
return error_response(str(e))
|
||||
|
||||
|
||||
root_agent = Agent(
|
||||
model="gemini-2.5-pro",
|
||||
name="adk_answering_agent",
|
||||
@@ -244,10 +54,10 @@ root_agent = Agent(
|
||||
* The latest comment is not from you or other agents (marked as "Response from XXX Agent").
|
||||
* The latest comment is asking a question or requesting information.
|
||||
4. Use the `VertexAiSearchTool` to find relevant information before answering.
|
||||
* If you need infromation about Gemini API, ask the `gemini_assistant` agent to provide the information and references.
|
||||
* You can call the `gemini_assistant` agent with multiple queries to find all the relevant information.
|
||||
5. If you can find relevant information, use the `add_comment_to_discussion` tool to add a comment to the discussion.
|
||||
6. If you post a commment and the discussion does not have a label named {BOT_RESPONSE_LABEL},
|
||||
add the label {BOT_RESPONSE_LABEL} to the discussion using the `add_label_to_discussion` tool.
|
||||
|
||||
6. If you post a comment, add the label {BOT_RESPONSE_LABEL} to the discussion using the `add_label_to_discussion` tool.
|
||||
|
||||
IMPORTANT:
|
||||
* {APPROVAL_INSTRUCTION}
|
||||
@@ -255,25 +65,23 @@ root_agent = Agent(
|
||||
information that is not in the document store. Do not invent citations which are not in the document store.
|
||||
* **Be Objective**: your answer should be based on the facts you found in the document store, do not be misled by user's assumptions or user's understanding of ADK.
|
||||
* If you can't find the answer or information in the document store, **do not** respond.
|
||||
* Inlclude a short summary of your response in the comment as a TLDR, e.g. "**TLDR**: <your summary>".
|
||||
* Start with a short summary of your response in the comment as a TLDR, e.g. "**TLDR**: <your summary>".
|
||||
* Have a divider line between the TLDR and your detail response.
|
||||
* Do not respond to any other discussion except the one specified by the user.
|
||||
* Please include your justification for your decision in your output
|
||||
to the user who is telling with you.
|
||||
* If you uses citation from the document store, please provide a footnote
|
||||
referencing the source document format it as: "[1] URL of the document".
|
||||
* Replace the "gs://prefix/" part, e.g. "gs://adk-qa-bucket/", to be "https://github.com/google/"
|
||||
* Add "blob/main/" after the repo name, e.g. "adk-python", "adk-docs", for example:
|
||||
* If the original URL is "gs://adk-qa-bucket/adk-python/src/google/adk/version.py",
|
||||
then the citation URL is "https://github.com/google/adk-python/blob/main/src/google/adk/version.py",
|
||||
* If the original URL is "gs://adk-qa-bucket/adk-docs/docs/index.md",
|
||||
then the citation URL is "https://github.com/google/adk-docs/blob/main/docs/index.md"
|
||||
* If the file is a html file, replace the ".html" to be ".md"
|
||||
referencing the source document format it as: "[1] publicly accessible HTTPS URL of the document".
|
||||
* You **should always** use the `convert_gcs_links_to_https` tool to convert GCS links (e.g. "gs://...") to HTTPS links.
|
||||
* **Do not** use the `convert_gcs_links_to_https` tool for non-GCS links.
|
||||
* Make sure the citation URL is valid. Otherwise do not list this specific citation.
|
||||
""",
|
||||
tools=[
|
||||
VertexAiSearchTool(data_store_id=VERTEXAI_DATASTORE_ID),
|
||||
AgentTool(gemini_assistant_agent),
|
||||
get_discussion_and_comments,
|
||||
add_comment_to_discussion,
|
||||
add_label_to_discussion,
|
||||
convert_gcs_links_to_https,
|
||||
],
|
||||
)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright 2025 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import agent
|
||||
@@ -0,0 +1,94 @@
|
||||
# Copyright 2025 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
from typing import Dict
|
||||
from typing import List
|
||||
|
||||
from adk_answering_agent.settings import ADK_GCP_SA_KEY
|
||||
from adk_answering_agent.settings import GEMINI_API_DATASTORE_ID
|
||||
from adk_answering_agent.utils import error_response
|
||||
from google.adk.agents.llm_agent import Agent
|
||||
from google.api_core.exceptions import GoogleAPICallError
|
||||
from google.cloud import discoveryengine_v1beta as discoveryengine
|
||||
from google.oauth2 import service_account
|
||||
|
||||
|
||||
def search_gemini_api_docs(queries: List[str]) -> Dict[str, Any]:
|
||||
"""Searches Gemini API docs using Vertex AI Search.
|
||||
|
||||
Args:
|
||||
queries: The list of queries to search.
|
||||
|
||||
Returns:
|
||||
A dictionary containing the status of the request and the list of search
|
||||
results, which contains the title, url and snippets.
|
||||
"""
|
||||
try:
|
||||
adk_gcp_sa_key_info = json.loads(ADK_GCP_SA_KEY)
|
||||
client = discoveryengine.SearchServiceClient(
|
||||
credentials=service_account.Credentials.from_service_account_info(
|
||||
adk_gcp_sa_key_info
|
||||
)
|
||||
)
|
||||
except (TypeError, ValueError) as e:
|
||||
return error_response(f"Error creating Vertex AI Search client: {e}")
|
||||
|
||||
serving_config = f"{GEMINI_API_DATASTORE_ID}/servingConfigs/default_config"
|
||||
results = []
|
||||
try:
|
||||
for query in queries:
|
||||
request = discoveryengine.SearchRequest(
|
||||
serving_config=serving_config,
|
||||
query=query,
|
||||
page_size=20,
|
||||
)
|
||||
response = client.search(request=request)
|
||||
for item in response.results:
|
||||
snippets = []
|
||||
for snippet in item.document.derived_struct_data.get("snippets", []):
|
||||
snippets.append(snippet.get("snippet"))
|
||||
|
||||
results.append({
|
||||
"title": item.document.derived_struct_data.get("title"),
|
||||
"url": item.document.derived_struct_data.get("link"),
|
||||
"snippets": snippets,
|
||||
})
|
||||
except GoogleAPICallError as e:
|
||||
return error_response(f"Error from Vertex AI Search: {e}")
|
||||
return {"status": "success", "results": results}
|
||||
|
||||
|
||||
root_agent = Agent(
|
||||
model="gemini-2.5-pro",
|
||||
name="gemini_assistant",
|
||||
description="Answer questions about Gemini API.",
|
||||
instruction="""
|
||||
You are a helpful assistant that responds to questions about Gemini API based on information
|
||||
found in the document store. You can access the document store using the `search_gemini_api_docs` tool.
|
||||
|
||||
When user asks a question, here are the steps:
|
||||
1. Use the `search_gemini_api_docs` tool to find relevant information before answering.
|
||||
* You can call the tool with multiple queries to find all the relevant information.
|
||||
2. Provide a response based on the information you found in the document store. Reference the source document in the response.
|
||||
|
||||
IMPORTANT:
|
||||
* Your response should be based on the information you found in the document store. Do not invent
|
||||
information that is not in the document store. Do not invent citations which are not in the document store.
|
||||
* If you can't find the answer or information in the document store, just respond with "I can't find the answer or information in the document store".
|
||||
* If you uses citation from the document store, please always provide a footnote referencing the source document format it as: "[1] URL of the document".
|
||||
""",
|
||||
tools=[search_gemini_api_docs],
|
||||
)
|
||||
@@ -13,6 +13,7 @@
|
||||
# limitations under the License.
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
|
||||
from adk_answering_agent import agent
|
||||
@@ -21,11 +22,14 @@ from adk_answering_agent.settings import OWNER
|
||||
from adk_answering_agent.settings import REPO
|
||||
from adk_answering_agent.utils import call_agent_async
|
||||
from adk_answering_agent.utils import parse_number_string
|
||||
from google.adk.cli.utils import logs
|
||||
from google.adk.runners import InMemoryRunner
|
||||
|
||||
APP_NAME = "adk_answering_app"
|
||||
USER_ID = "adk_answering_user"
|
||||
|
||||
logs.setup_adk_logger(level=logging.DEBUG)
|
||||
|
||||
|
||||
async def main():
|
||||
runner = InMemoryRunner(
|
||||
|
||||
@@ -31,6 +31,9 @@ if not VERTEXAI_DATASTORE_ID:
|
||||
|
||||
GOOGLE_CLOUD_PROJECT = os.getenv("GOOGLE_CLOUD_PROJECT")
|
||||
GCS_BUCKET_NAME = os.getenv("GCS_BUCKET_NAME")
|
||||
GEMINI_API_DATASTORE_ID = os.getenv("GEMINI_API_DATASTORE_ID")
|
||||
ADK_GCP_SA_KEY = os.getenv("ADK_GCP_SA_KEY")
|
||||
|
||||
ADK_DOCS_ROOT_PATH = os.getenv("ADK_DOCS_ROOT_PATH")
|
||||
ADK_PYTHON_ROOT_PATH = os.getenv("ADK_PYTHON_ROOT_PATH")
|
||||
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
# Copyright 2025 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any
|
||||
from typing import Dict
|
||||
from typing import Optional
|
||||
|
||||
from adk_answering_agent.settings import OWNER
|
||||
from adk_answering_agent.settings import REPO
|
||||
from adk_answering_agent.utils import convert_gcs_to_https
|
||||
from adk_answering_agent.utils import error_response
|
||||
from adk_answering_agent.utils import run_graphql_query
|
||||
import requests
|
||||
|
||||
|
||||
def get_discussion_and_comments(discussion_number: int) -> dict[str, Any]:
|
||||
"""Fetches a discussion and its comments using the GitHub GraphQL API.
|
||||
|
||||
Args:
|
||||
discussion_number: The number of the GitHub discussion.
|
||||
|
||||
Returns:
|
||||
A dictionary with the request status and the discussion details.
|
||||
"""
|
||||
print(f"Attempting to get discussion #{discussion_number} and its comments")
|
||||
query = """
|
||||
query($owner: String!, $repo: String!, $discussionNumber: Int!) {
|
||||
repository(owner: $owner, name: $repo) {
|
||||
discussion(number: $discussionNumber) {
|
||||
id
|
||||
title
|
||||
body
|
||||
createdAt
|
||||
closed
|
||||
author {
|
||||
login
|
||||
}
|
||||
# For each discussion, fetch the latest 20 labels.
|
||||
labels(last: 20) {
|
||||
nodes {
|
||||
id
|
||||
name
|
||||
}
|
||||
}
|
||||
# For each discussion, fetch the latest 100 comments.
|
||||
comments(last: 100) {
|
||||
nodes {
|
||||
id
|
||||
body
|
||||
createdAt
|
||||
author {
|
||||
login
|
||||
}
|
||||
# For each discussion, fetch the latest 50 replies
|
||||
replies(last: 50) {
|
||||
nodes {
|
||||
id
|
||||
body
|
||||
createdAt
|
||||
author {
|
||||
login
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
variables = {
|
||||
"owner": OWNER,
|
||||
"repo": REPO,
|
||||
"discussionNumber": discussion_number,
|
||||
}
|
||||
try:
|
||||
response = run_graphql_query(query, variables)
|
||||
if "errors" in response:
|
||||
return error_response(str(response["errors"]))
|
||||
discussion_data = (
|
||||
response.get("data", {}).get("repository", {}).get("discussion")
|
||||
)
|
||||
if not discussion_data:
|
||||
return error_response(f"Discussion #{discussion_number} not found.")
|
||||
return {"status": "success", "discussion": discussion_data}
|
||||
except requests.exceptions.RequestException as e:
|
||||
return error_response(str(e))
|
||||
|
||||
|
||||
def add_comment_to_discussion(
|
||||
discussion_id: str, comment_body: str
|
||||
) -> dict[str, Any]:
|
||||
"""Adds a comment to a specific discussion.
|
||||
|
||||
Args:
|
||||
discussion_id: The GraphQL node ID of the discussion.
|
||||
comment_body: The content of the comment in Markdown.
|
||||
|
||||
Returns:
|
||||
The status of the request and the new comment's details.
|
||||
"""
|
||||
print(f"Adding comment to discussion {discussion_id}")
|
||||
query = """
|
||||
mutation($discussionId: ID!, $body: String!) {
|
||||
addDiscussionComment(input: {discussionId: $discussionId, body: $body}) {
|
||||
comment {
|
||||
id
|
||||
body
|
||||
createdAt
|
||||
author {
|
||||
login
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
if not comment_body.startswith("**Response from ADK Answering Agent"):
|
||||
comment_body = (
|
||||
"**Response from ADK Answering Agent (experimental, answer may be"
|
||||
" inaccurate)**\n\n"
|
||||
+ comment_body
|
||||
)
|
||||
|
||||
variables = {"discussionId": discussion_id, "body": comment_body}
|
||||
try:
|
||||
response = run_graphql_query(query, variables)
|
||||
if "errors" in response:
|
||||
return error_response(str(response["errors"]))
|
||||
new_comment = (
|
||||
response.get("data", {}).get("addDiscussionComment", {}).get("comment")
|
||||
)
|
||||
return {"status": "success", "comment": new_comment}
|
||||
except requests.exceptions.RequestException as e:
|
||||
return error_response(str(e))
|
||||
|
||||
|
||||
def get_label_id(label_name: str) -> str | None:
|
||||
"""Helper function to find the GraphQL node ID for a given label name."""
|
||||
print(f"Finding ID for label '{label_name}'...")
|
||||
query = """
|
||||
query($owner: String!, $repo: String!, $labelName: String!) {
|
||||
repository(owner: $owner, name: $repo) {
|
||||
label(name: $labelName) {
|
||||
id
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
variables = {"owner": OWNER, "repo": REPO, "labelName": label_name}
|
||||
|
||||
try:
|
||||
response = run_graphql_query(query, variables)
|
||||
if "errors" in response:
|
||||
print(
|
||||
f"[Warning] Error from GitHub API response for label '{label_name}':"
|
||||
f" {response['errors']}"
|
||||
)
|
||||
return None
|
||||
label_info = response["data"].get("repository", {}).get("label")
|
||||
if label_info:
|
||||
return label_info.get("id")
|
||||
print(f"[Warning] Label information for '{label_name}' not found.")
|
||||
return None
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"[Warning] Error from GitHub API: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def add_label_to_discussion(
|
||||
discussion_id: str, label_name: str
|
||||
) -> dict[str, Any]:
|
||||
"""Adds a label to a specific discussion.
|
||||
|
||||
Args:
|
||||
discussion_id: The GraphQL node ID of the discussion.
|
||||
label_name: The name of the label to add (e.g., "bug").
|
||||
|
||||
Returns:
|
||||
The status of the request and the label details.
|
||||
"""
|
||||
print(
|
||||
f"Attempting to add label '{label_name}' to discussion {discussion_id}..."
|
||||
)
|
||||
# First, get the GraphQL ID of the label by its name
|
||||
label_id = get_label_id(label_name)
|
||||
if not label_id:
|
||||
return error_response(f"Label '{label_name}' not found.")
|
||||
|
||||
# Then, perform the mutation to add the label to the discussion
|
||||
mutation = """
|
||||
mutation AddLabel($discussionId: ID!, $labelId: ID!) {
|
||||
addLabelsToLabelable(input: {labelableId: $discussionId, labelIds: [$labelId]}) {
|
||||
clientMutationId
|
||||
}
|
||||
}
|
||||
"""
|
||||
variables = {"discussionId": discussion_id, "labelId": label_id}
|
||||
try:
|
||||
response = run_graphql_query(mutation, variables)
|
||||
if "errors" in response:
|
||||
return error_response(str(response["errors"]))
|
||||
return {"status": "success", "label_id": label_id, "label_name": label_name}
|
||||
except requests.exceptions.RequestException as e:
|
||||
return error_response(str(e))
|
||||
|
||||
|
||||
def convert_gcs_links_to_https(gcs_uris: list[str]) -> Dict[str, Optional[str]]:
|
||||
"""Converts GCS files link into publicly accessible HTTPS links.
|
||||
|
||||
Args:
|
||||
gcs_uris: A list of GCS files links, in the format
|
||||
'gs://bucket_name/prefix/relative_path'.
|
||||
|
||||
Returns:
|
||||
A dictionary mapping the original GCS files links to the converted HTTPS
|
||||
links. If a GCS link is invalid, the corresponding value in the dictionary
|
||||
will be None.
|
||||
"""
|
||||
return {gcs_uri: convert_gcs_to_https(gcs_uri) for gcs_uri in gcs_uris}
|
||||
@@ -12,8 +12,11 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import os
|
||||
import sys
|
||||
from typing import Any
|
||||
from typing import Optional
|
||||
from urllib.parse import urljoin
|
||||
|
||||
from adk_answering_agent.settings import GITHUB_GRAPHQL_URL
|
||||
from adk_answering_agent.settings import GITHUB_TOKEN
|
||||
@@ -58,6 +61,92 @@ def parse_number_string(number_str: str | None, default_value: int = 0) -> int:
|
||||
return default_value
|
||||
|
||||
|
||||
def _check_url_exists(url: str) -> bool:
|
||||
"""Checks if a URL exists and is accessible."""
|
||||
try:
|
||||
# Set a timeout to prevent the program from waiting indefinitely.
|
||||
# allow_redirects=True ensures we correctly handle valid links
|
||||
# after redirection.
|
||||
response = requests.head(url, timeout=5, allow_redirects=True)
|
||||
# Status codes 2xx (Success) or 3xx (Redirection) are considered valid.
|
||||
return response.ok
|
||||
except requests.RequestException:
|
||||
# Catch all possible exceptions from the requests library
|
||||
# (e.g., connection errors, timeouts).
|
||||
return False
|
||||
|
||||
|
||||
def _generate_github_url(repo_name: str, relative_path: str) -> str:
|
||||
"""Generates a standard GitHub URL for a repo file."""
|
||||
return f"https://github.com/google/{repo_name}/blob/main/{relative_path}"
|
||||
|
||||
|
||||
def convert_gcs_to_https(gcs_uri: str) -> Optional[str]:
|
||||
"""Converts a GCS file link into a publicly accessible HTTPS link.
|
||||
|
||||
Args:
|
||||
gcs_uri: The Google Cloud Storage link, in the format
|
||||
'gs://bucket_name/prefix/relative_path'.
|
||||
|
||||
Returns:
|
||||
The converted HTTPS link as a string, or None if the input format is
|
||||
incorrect.
|
||||
"""
|
||||
# Parse the GCS link
|
||||
if not gcs_uri or not gcs_uri.startswith("gs://"):
|
||||
print(f"Error: Invalid GCS link format: {gcs_uri}")
|
||||
return None
|
||||
|
||||
try:
|
||||
# Strip 'gs://' and split by '/', requiring at least 3 parts
|
||||
# (bucket, prefix, path)
|
||||
parts = gcs_uri[5:].split("/", 2)
|
||||
if len(parts) < 3:
|
||||
raise ValueError(
|
||||
"GCS link must contain a bucket, prefix, and relative_path."
|
||||
)
|
||||
|
||||
_, prefix, relative_path = parts
|
||||
except (ValueError, IndexError) as e:
|
||||
print(f"Error: Failed to parse GCS link '{gcs_uri}': {e}")
|
||||
return None
|
||||
|
||||
# Replace .html with .md
|
||||
if relative_path.endswith(".html"):
|
||||
relative_path = relative_path.removesuffix(".html") + ".md"
|
||||
|
||||
# Convert the links for adk-docs
|
||||
if prefix == "adk-docs" and relative_path.startswith("docs/"):
|
||||
path_after_docs = relative_path[len("docs/") :]
|
||||
if not path_after_docs.endswith(".md"):
|
||||
# Use the regular github url
|
||||
return _generate_github_url(prefix, relative_path)
|
||||
|
||||
base_url = "https://google.github.io/adk-docs/"
|
||||
if os.path.basename(path_after_docs) == "index.md":
|
||||
# Use the directory path if it is a index file
|
||||
final_path_segment = os.path.dirname(path_after_docs)
|
||||
else:
|
||||
# Otherwise, use the file name without extention
|
||||
final_path_segment = path_after_docs.removesuffix(".md")
|
||||
|
||||
if final_path_segment and not final_path_segment.endswith("/"):
|
||||
final_path_segment += "/"
|
||||
|
||||
potential_url = urljoin(base_url, final_path_segment)
|
||||
|
||||
# Check if the generated link exists
|
||||
if _check_url_exists(potential_url):
|
||||
return potential_url
|
||||
else:
|
||||
# If it doesn't exist, fallback to the regular github url
|
||||
return _generate_github_url(prefix, relative_path)
|
||||
|
||||
# Convert the links for other cases, e.g. adk-python
|
||||
else:
|
||||
return _generate_github_url(prefix, relative_path)
|
||||
|
||||
|
||||
async def call_agent_async(
|
||||
runner: Runner, user_id: str, session_id: str, prompt: str
|
||||
) -> str:
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
# Bigtable Tools Sample
|
||||
|
||||
## Introduction
|
||||
|
||||
This sample agent demonstrates the Bigtable first-party tools in ADK,
|
||||
distributed via the `google.adk.tools.bigtable` module. These tools include:
|
||||
|
||||
1. `bigtable_list_instances`
|
||||
|
||||
Fetches Bigtable instance ids in a Google Cloud project.
|
||||
|
||||
1. `bigtable_get_instance_info`
|
||||
|
||||
Fetches metadata information about a Bigtable instance.
|
||||
|
||||
1. `bigtable_list_tables`
|
||||
|
||||
Fetches table ids in a Bigtable instance.
|
||||
|
||||
1. `bigtable_get_table_info`
|
||||
|
||||
Fetches metadata information about a Bigtable table.
|
||||
|
||||
1. `bigtable_execute_sql`
|
||||
|
||||
Runs a DQL SQL query in Bigtable database.
|
||||
|
||||
## How to use
|
||||
|
||||
Set up environment variables in your `.env` file for using
|
||||
[Google AI Studio](https://google.github.io/adk-docs/get-started/quickstart/#gemini---google-ai-studio)
|
||||
or
|
||||
[Google Cloud Vertex AI](https://google.github.io/adk-docs/get-started/quickstart/#gemini---google-cloud-vertex-ai)
|
||||
for the LLM service for your agent. For example, for using Google AI Studio you
|
||||
would set:
|
||||
|
||||
* GOOGLE_GENAI_USE_VERTEXAI=FALSE
|
||||
* GOOGLE_API_KEY={your api key}
|
||||
|
||||
### With Application Default Credentials
|
||||
|
||||
This mode is useful for quick development when the agent builder is the only
|
||||
user interacting with the agent. The tools are run with these credentials.
|
||||
|
||||
1. Create application default credentials on the machine where the agent would
|
||||
be running by following https://cloud.google.com/docs/authentication/provide-credentials-adc.
|
||||
|
||||
1. Set `CREDENTIALS_TYPE=None` in `agent.py`
|
||||
|
||||
1. Run the agent
|
||||
|
||||
### With Service Account Keys
|
||||
|
||||
This mode is useful for quick development when the agent builder wants to run
|
||||
the agent with service account credentials. The tools are run with these
|
||||
credentials.
|
||||
|
||||
1. Create service account key by following https://cloud.google.com/iam/docs/service-account-creds#user-managed-keys.
|
||||
|
||||
1. Set `CREDENTIALS_TYPE=AuthCredentialTypes.SERVICE_ACCOUNT` in `agent.py`
|
||||
|
||||
1. Download the key file and replace `"service_account_key.json"` with the path
|
||||
|
||||
1. Run the agent
|
||||
|
||||
### With Interactive OAuth
|
||||
|
||||
1. Follow
|
||||
https://developers.google.com/identity/protocols/oauth2#1.-obtain-oauth-2.0-credentials-from-the-dynamic_data.setvar.console_name.
|
||||
to get your client id and client secret. Be sure to choose "web" as your client
|
||||
type.
|
||||
|
||||
1. Follow https://developers.google.com/workspace/guides/configure-oauth-consent
|
||||
to add scope "https://www.googleapis.com/auth/bigtable.admin" and
|
||||
"https://www.googleapis.com/auth/bigtable.data" as declaration, this is used
|
||||
for review purpose.
|
||||
|
||||
1. Follow
|
||||
https://developers.google.com/identity/protocols/oauth2/web-server#creatingcred
|
||||
to add http://localhost/dev-ui/ to "Authorized redirect URIs".
|
||||
|
||||
Note: localhost here is just a hostname that you use to access the dev ui,
|
||||
replace it with the actual hostname you use to access the dev ui.
|
||||
|
||||
1. For 1st run, allow popup for localhost in Chrome.
|
||||
|
||||
1. Configure your `.env` file to add two more variables before running the
|
||||
agent:
|
||||
|
||||
* OAUTH_CLIENT_ID={your client id}
|
||||
* OAUTH_CLIENT_SECRET={your client secret}
|
||||
|
||||
Note: don't create a separate .env, instead put it to the same .env file that
|
||||
stores your Vertex AI or Dev ML credentials
|
||||
|
||||
1. Set `CREDENTIALS_TYPE=AuthCredentialTypes.OAUTH2` in `agent.py` and run the
|
||||
agent
|
||||
|
||||
## Sample prompts
|
||||
|
||||
* Show me all instances in the my-project.
|
||||
* Show me all tables in the my-instance instance in my-project.
|
||||
* Describe the schema of the my-table table in the my-instance instance in my-project.
|
||||
* Show me the first 10 rows of data from the my-table table in the my-instance instance in my-project.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright 2025 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import agent
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user