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
47 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 30b1722cca | |||
| 5eca8214a8 | |||
| e0a360a1a2 | |||
| 1cd61242ef | |||
| e31cd0b5f8 | |||
| dfb283e6e0 | |||
| 6e317d69de | |||
| 732059cf59 | |||
| 6b86bcc549 | |||
| 45a465e9b0 | |||
| e50c463ed4 | |||
| 995dc8276b | |||
| 2ee1c65e05 | |||
| b8514f26fe | |||
| 443bc08d2b | |||
| 61d4be2d76 | |||
| d057f2d825 | |||
| 290058eb05 | |||
| 3e85df2641 | |||
| 9a44831a08 | |||
| 4e8b944e09 | |||
| 26bab52ca8 | |||
| 577222509c | |||
| cfbcc17644 | |||
| 089c1e6428 | |||
| d810ff7b28 | |||
| e0d223d117 | |||
| 9cd802fcea | |||
| eecb9e65be | |||
| ee2a75368a | |||
| b68f3aa11f | |||
| a39977876b | |||
| 05142a07cc | |||
| 59117b9b96 | |||
| e80d0e4993 | |||
| 278b513493 | |||
| e637b4df25 | |||
| 9cbaaf378f | |||
| 924549e346 | |||
| 972620d464 | |||
| 7a34c3f5b9 | |||
| 3f30e0825d | |||
| 20a8a11e49 | |||
| 9002ace7e5 | |||
| 28837231dd | |||
| f63ec37153 | |||
| 553bede77e |
@@ -0,0 +1,35 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
** Please make sure you read the contribution guide and file the issues in the rigth place. **
|
||||
[Contribution guide.](https://google.github.io/adk-docs/contributing-guide/)
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Install '...'
|
||||
2. Run '....'
|
||||
3. Open '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Desktop (please complete the following information):**
|
||||
- OS: [e.g. iOS]
|
||||
- Python version(python -V):
|
||||
- ADK version(pip show google-adk):
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
** Please make sure you read the contribution guide and file the issues in the rigth place. **
|
||||
[Contribution guide.](https://google.github.io/adk-docs/contributing-guide/)
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -0,0 +1,39 @@
|
||||
name: Python Unit Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: ["3.9", "3.10", "3.11"]
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Install uv
|
||||
run: curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
uv venv .venv
|
||||
source .venv/bin/activate
|
||||
uv sync --extra test --extra eval
|
||||
|
||||
- name: Run unit tests with pytest
|
||||
run: |
|
||||
source .venv/bin/activate
|
||||
pytest tests/unittests \
|
||||
--ignore=tests/unittests/tools/google_api_tool/test_googleapi_to_openapi_converter.py \
|
||||
--ignore=tests/unittests/artifacts/test_artifact_service.py
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
|
||||
# Virtual Environment
|
||||
venv/
|
||||
ENV/
|
||||
env/
|
||||
.env
|
||||
.venv
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
.DS_Store
|
||||
|
||||
# Testing
|
||||
.coverage
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.pytest_cache/
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
logs/
|
||||
log/
|
||||
|
||||
# Local development settings
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
# Google Cloud specific
|
||||
.gcloudignore
|
||||
.gcloudignore.local
|
||||
|
||||
# Documentation
|
||||
docs/_build/
|
||||
site/
|
||||
|
||||
# Misc
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
*.bak
|
||||
*.tmp
|
||||
*.temp
|
||||
@@ -0,0 +1,56 @@
|
||||
# Changelog
|
||||
|
||||
## 0.2.0
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* Fix typo in method name in `Event`: has_trailing_code_exeuction_result --> has_trailing_code_execution_result.
|
||||
|
||||
### Features
|
||||
|
||||
* `adk` CLI:
|
||||
* Introduce `adk create` cli tool to help creating agents.
|
||||
* Adds `--verbosity` option to `adk deploy cloud_run` to show detailed cloud
|
||||
run deploy logging.
|
||||
* Improve the initialization error message for `DatabaseSessionService`.
|
||||
* Lazy loading for Google 1P tools to minimize the initial latency.
|
||||
* Support emitting state-change-only events from planners.
|
||||
* Lots of Dev UI updates, including:
|
||||
* Show planner thoughts and actions in the Dev UI.
|
||||
* Support MCP tools in Dev UI.
|
||||
(NOTE: `agent.py` interface is temp solution and is subject to change)
|
||||
* Auto-select the only app if only one app is available.
|
||||
* Show grounding links generated by Google Search Tool.
|
||||
* `.env` file is reloaded on every agent run.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* `LiteLlm`: arg parsing error and python 3.9 compatibility.
|
||||
* `DatabaseSessionService`: adds the missing fields; fixes event with empty
|
||||
content not being persisted.
|
||||
* Google API Discovery response parsing issue.
|
||||
* `load_memory_tool` rendering issue in Dev UI.
|
||||
* Markdown text overflows in Dev UI.
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* Adds unit tests in Github action.
|
||||
* Improves test coverage.
|
||||
* Various typo fixes.
|
||||
|
||||
## 0.1.0
|
||||
|
||||
### Features
|
||||
|
||||
* Initial release of the Agent Development Kit (ADK).
|
||||
* Multi-agent, agent-as-workflow, and custom agent support
|
||||
* Tool authentication support
|
||||
* Rich tool support, e.g. bult-in tools, google-cloud tools, third-party tools, and MCP tools
|
||||
* Rich callback support
|
||||
* Built-in code execution capability
|
||||
* Asynchronous runtime and execution
|
||||
* Session, and memory support
|
||||
* Built-in evaluation support
|
||||
* Development UI that makes local devlopment easy
|
||||
* Deploy to Google Cloud Run, Agent Engine
|
||||
* (Experimental) Live(Bidi) auido/video agent support and Compositional Function Calling(CFC) support
|
||||
@@ -1,11 +1,13 @@
|
||||
# Agent Development Kit (ADK)
|
||||
|
||||
[](LICENSE)
|
||||
[](https://github.com/google/adk-python/actions/workflows/python-unit-tests.yml)
|
||||
[](https://www.reddit.com/r/agentdevelopmentkit/)
|
||||
|
||||
<html>
|
||||
<h1 align="center">
|
||||
<img src="assets/agent-development-kit.png" width="256"/>
|
||||
</h1>
|
||||
<h2 align="center">
|
||||
<img src="https://raw.githubusercontent.com/google/adk-python/main/assets/agent-development-kit.png" width="256"/>
|
||||
</h2>
|
||||
<h3 align="center">
|
||||
An open-source, code-first Python toolkit for building, evaluating, and deploying sophisticated AI agents with flexibility and control.
|
||||
</h3>
|
||||
@@ -16,22 +18,30 @@
|
||||
</h3>
|
||||
</html>
|
||||
|
||||
The Agent Development Kit (ADK) is designed for developers seeking fine-grained control and flexibility when building advanced AI agents that are tightly integrated with services in Google Cloud. It allows you to define agent behavior, orchestration, and tool use directly in code, enabling robust debugging, versioning, and deployment anywhere – from your laptop to the cloud.
|
||||
Agent Development Kit (ADK) is designed for developers seeking fine-grained
|
||||
control and flexibility when building advanced AI agents that are tightly
|
||||
integrated with services in Google Cloud. It allows you to define agent
|
||||
behavior, orchestration, and tool use directly in code, enabling robust
|
||||
debugging, versioning, and deployment anywhere – from your laptop to the cloud.
|
||||
|
||||
|
||||
---
|
||||
|
||||
## ✨ Key Features
|
||||
|
||||
* **Code-First Development:** Define agents, tools, and orchestration logic for maximum control, testability, and versioning.
|
||||
* **Multi-Agent Architecture:** Build modular and scalable applications by composing multiple specialized agents in flexible hierarchies.
|
||||
* **Rich Tool Ecosystem:** Equip agents with diverse capabilities using pre-built tools, custom Python functions, API specifications, or integrating existing tools.
|
||||
* **Flexible Orchestration:** Define workflows using built-in agents for predictable pipelines, or leverage LLM-driven dynamic routing for adaptive behavior.
|
||||
* **Integrated Developer Experience:** Develop, test, and debug locally with a CLI and visual web UI.
|
||||
* **Built-in Evaluation:** Measure agent performance by evaluating response quality and step-by-step execution trajectory.
|
||||
* **Deployment Ready:** Containerize and deploy your agents anywhere – scale with Vertex AI Agent Engine, Cloud Run, or Docker.
|
||||
* **Native Streaming Support:** Build real-time, interactive experiences with native support for bidirectional streaming (text and audio).
|
||||
* **State, Memory & Artifacts:** Manage short-term conversational context, configure long-term memory, and handle file uploads/downloads.
|
||||
* **Extensibility:** Customize agent behavior deeply with callbacks and easily integrate third-party tools and services.
|
||||
- **Rich Tool Ecosystem**: Utilize pre-built tools, custom functions,
|
||||
OpenAPI specs, or integrate existing tools to give agents diverse
|
||||
capabilities, all for tight integration with the Google ecosystem.
|
||||
|
||||
- **Code-First Development**: Define agent logic, tools, and orchestration
|
||||
directly in Python for ultimate flexibility, testability, and versioning.
|
||||
|
||||
- **Modular Multi-Agent Systems**: Design scalable applications by composing
|
||||
multiple specialized agents into flexible hierarchies.
|
||||
|
||||
- **Deploy Anywhere**: Easily containerize and deploy agents on Cloud Run or
|
||||
scale seamlessly with Vertex AI Agent Engine.
|
||||
|
||||
|
||||
## 🚀 Installation
|
||||
|
||||
@@ -41,54 +51,67 @@ You can install the ADK using `pip`:
|
||||
pip install google-adk
|
||||
```
|
||||
|
||||
## 🏁 Getting Started
|
||||
## 📚 Documentation
|
||||
|
||||
Create your first agent (`my_agent/agent.py`):
|
||||
Explore the full documentation for detailed guides on building, evaluating, and
|
||||
deploying agents:
|
||||
|
||||
* **[Documentation](https://google.github.io/adk-docs)**
|
||||
|
||||
## 🏁 Feature Highlight
|
||||
|
||||
### Define a single agent:
|
||||
|
||||
```python
|
||||
# my_agent/agent.py
|
||||
from google.adk.agents import Agent
|
||||
from google.adk.tools import google_search
|
||||
|
||||
root_agent = Agent(
|
||||
name="search_assistant",
|
||||
model="gemini-2.0-flash-exp", # Or your preferred Gemini model
|
||||
model="gemini-2.0-flash", # Or your preferred Gemini model
|
||||
instruction="You are a helpful assistant. Answer user questions using Google Search when needed.",
|
||||
description="An assistant that can search the web.",
|
||||
tools=[google_search]
|
||||
)
|
||||
```
|
||||
|
||||
Create `my_agent/__init__.py`:
|
||||
### Define a multi-agent system:
|
||||
|
||||
Define a multi-agent system with coordinator agent, greeter agent, and task execution agent. Then ADK engine and the model will guide the agents works together to accomplish the task.
|
||||
|
||||
```python
|
||||
# my_agent/__init__.py
|
||||
from . import agent
|
||||
from google.adk.agents import LlmAgent, BaseAgent
|
||||
|
||||
# Define individual agents
|
||||
greeter = LlmAgent(name="greeter", model="gemini-2.0-flash", ...)
|
||||
task_executor = LlmAgent(name="task_executor", model="gemini-2.0-flash", ...)
|
||||
|
||||
# Create parent agent and assign children via sub_agents
|
||||
coordinator = LlmAgent(
|
||||
name="Coordinator",
|
||||
model="gemini-2.0-flash",
|
||||
description="I coordinate greetings and tasks.",
|
||||
sub_agents=[ # Assign sub_agents here
|
||||
greeter,
|
||||
task_executor
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
Run it via the CLI (from the directory *containing* `my_agent`):
|
||||
### Development UI
|
||||
|
||||
A built-in development UI to help you test, evaluate, debug, and showcase your agent(s).
|
||||
|
||||
<img src="https://raw.githubusercontent.com/google/adk-python/main/assets/adk-web-dev-ui-function-call.png"/>
|
||||
|
||||
### Evaluate Agents
|
||||
|
||||
```bash
|
||||
adk run my_agent
|
||||
adk eval \
|
||||
samples_for_testing/hello_world \
|
||||
samples_for_testing/hello_world/hello_world_eval_set_001.evalset.json
|
||||
```
|
||||
|
||||
Or launch the Web UI from the folder that contains `my_agent` folder:
|
||||
|
||||
```bash
|
||||
adk web
|
||||
```
|
||||
|
||||
For a full step-by-step guide, check out the [quickstart](https://google.github.io/adk-docs/get-started/quickstart/) or [sample agents](https://github.com/google/adk-samples).
|
||||
|
||||
## 📚 Resources
|
||||
|
||||
Explore the full documentation for detailed guides on building, evaluating, and deploying agents:
|
||||
|
||||
* **[Get Started](https://google.github.io/adk-docs/get-started/)**
|
||||
* **[Browse Sample Agents](https://github.com/google/adk-samples)**
|
||||
* **[Evaluate Agents](https://google.github.io/adk-docs/guides/evaluate-agents/)**
|
||||
* **[Deploy Agents](https://google.github.io/adk-docs/deploy/)**
|
||||
* **[API Reference](https://google.github.io/adk-docs/api-reference/)**
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
@@ -98,6 +121,10 @@ We welcome contributions from the community! Whether it's bug reports, feature r
|
||||
|
||||
This project is licensed under the Apache 2.0 License - see the [LICENSE](LICENSE) file for details.
|
||||
|
||||
## Preview
|
||||
|
||||
This feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of the [Service Specific Terms](https://cloud.google.com/terms/service-terms#1). Pre-GA features are available "as is" and might have limited support. For more information, see the [launch stage descriptions](https://cloud.google.com/products?hl=en#product-launch-stages).
|
||||
|
||||
---
|
||||
|
||||
*Happy Agent Building!*
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 463 KiB |
@@ -79,7 +79,11 @@ eval = [
|
||||
|
||||
test = [
|
||||
# go/keep-sorted start
|
||||
"anthropic>=0.43.0", # For anthropic model tests
|
||||
"langchain-community>=0.3.17",
|
||||
"langgraph>=0.2.60", # For LangGraphAgent
|
||||
"litellm>=1.63.11", # For LiteLLM tests
|
||||
"llama-index-readers-file>=0.4.0", # for retrieval tests
|
||||
"pytest-asyncio>=0.25.0",
|
||||
"pytest-mock>=3.14.0",
|
||||
"pytest-xdist>=3.6.1",
|
||||
|
||||
@@ -120,7 +120,7 @@ class BaseAgent(BaseModel):
|
||||
self,
|
||||
parent_context: InvocationContext,
|
||||
) -> AsyncGenerator[Event, None]:
|
||||
"""Entry method to run an agent via text-based conversaction.
|
||||
"""Entry method to run an agent via text-based conversation.
|
||||
|
||||
Args:
|
||||
parent_context: InvocationContext, the invocation context of the parent
|
||||
@@ -152,7 +152,7 @@ class BaseAgent(BaseModel):
|
||||
self,
|
||||
parent_context: InvocationContext,
|
||||
) -> AsyncGenerator[Event, None]:
|
||||
"""Entry method to run an agent via video/audio-based conversaction.
|
||||
"""Entry method to run an agent via video/audio-based conversation.
|
||||
|
||||
Args:
|
||||
parent_context: InvocationContext, the invocation context of the parent
|
||||
@@ -171,7 +171,7 @@ class BaseAgent(BaseModel):
|
||||
async def _run_async_impl(
|
||||
self, ctx: InvocationContext
|
||||
) -> AsyncGenerator[Event, None]:
|
||||
"""Core logic to run this agent via text-based conversaction.
|
||||
"""Core logic to run this agent via text-based conversation.
|
||||
|
||||
Args:
|
||||
ctx: InvocationContext, the invocation context for this agent.
|
||||
@@ -187,7 +187,7 @@ class BaseAgent(BaseModel):
|
||||
async def _run_live_impl(
|
||||
self, ctx: InvocationContext
|
||||
) -> AsyncGenerator[Event, None]:
|
||||
"""Core logic to run this agent via video/audio-based conversaction.
|
||||
"""Core logic to run this agent via video/audio-based conversation.
|
||||
|
||||
Args:
|
||||
ctx: InvocationContext, the invocation context for this agent.
|
||||
|
||||
@@ -124,7 +124,7 @@ class InvocationContext(BaseModel):
|
||||
agent_2, and agent_2 is the parent of agent_3.
|
||||
|
||||
Branch is used when multiple sub-agents shouldn't see their peer agents'
|
||||
conversaction history.
|
||||
conversation history.
|
||||
"""
|
||||
agent: BaseAgent
|
||||
"""The current agent of this invocation context. Readonly."""
|
||||
|
||||
@@ -32,7 +32,7 @@ class RemoteAgent(BaseAgent):
|
||||
sub_agents: list[BaseAgent] = Field(
|
||||
default_factory=list, init=False, frozen=True
|
||||
)
|
||||
"""Sub-agent is dsiabled in RemoteAgent."""
|
||||
"""Sub-agent is disabled in RemoteAgent."""
|
||||
|
||||
@override
|
||||
async def _run_async_impl(
|
||||
|
||||
@@ -42,7 +42,7 @@ class RunConfig(BaseModel):
|
||||
"""Speech configuration for the live agent."""
|
||||
|
||||
response_modalities: Optional[list[str]] = None
|
||||
"""The output modalities. If not set, its default to AUDIO."""
|
||||
"""The output modalities. If not set, it's default to AUDIO."""
|
||||
|
||||
save_input_blobs_as_artifacts: bool = False
|
||||
"""Whether or not to save the input blobs as artifacts."""
|
||||
|
||||
@@ -76,7 +76,7 @@ class _AuthLlmRequestProcessor(BaseLlmRequestProcessor):
|
||||
|
||||
for i in range(len(events) - 2, -1, -1):
|
||||
event = events[i]
|
||||
# looking for the system long running reqeust euc function call
|
||||
# looking for the system long running request euc function call
|
||||
function_calls = event.get_function_calls()
|
||||
if not function_calls:
|
||||
continue
|
||||
@@ -92,7 +92,7 @@ class _AuthLlmRequestProcessor(BaseLlmRequestProcessor):
|
||||
if not tools_to_resume:
|
||||
continue
|
||||
|
||||
# found the the system long running reqeust euc function call
|
||||
# found the the system long running request euc function call
|
||||
# looking for original function call that requests euc
|
||||
for j in range(i - 1, -1, -1):
|
||||
event = events[j]
|
||||
|
||||
@@ -19,7 +19,7 @@ from .auth_schemes import AuthScheme
|
||||
|
||||
|
||||
class AuthConfig(BaseModel):
|
||||
"""The auth config sent by tool asking client to collect auth credentails and
|
||||
"""The auth config sent by tool asking client to collect auth credentials and
|
||||
|
||||
adk and client will help to fill in the response
|
||||
"""
|
||||
|
||||
File diff suppressed because one or more lines are too long
+65
-81
File diff suppressed because one or more lines are too long
@@ -82,6 +82,8 @@ async def run_interactively(
|
||||
)
|
||||
while True:
|
||||
query = input('user: ')
|
||||
if not query or not query.strip():
|
||||
continue
|
||||
if query == 'exit':
|
||||
break
|
||||
async for event in runner.run_async(
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
# 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 os
|
||||
import subprocess
|
||||
from typing import Optional
|
||||
from typing import Tuple
|
||||
|
||||
import click
|
||||
|
||||
_INIT_PY_TEMPLATE = """\
|
||||
from . import agent
|
||||
"""
|
||||
|
||||
_AGENT_PY_TEMPLATE = """\
|
||||
from google.adk.agents import Agent
|
||||
|
||||
root_agent = Agent(
|
||||
model='{model_name}',
|
||||
name='root_agent',
|
||||
description='A helpful assistant for user questions.',
|
||||
instruction='Answer user questions to the best of your knowledge',
|
||||
)
|
||||
"""
|
||||
|
||||
|
||||
_GOOGLE_API_MSG = """
|
||||
Don't have API Key? Create one in AI Studio: https://aistudio.google.com/apikey
|
||||
"""
|
||||
|
||||
_GOOGLE_CLOUD_SETUP_MSG = """
|
||||
You need an existing Google Cloud account and project, check out this link for details:
|
||||
https://google.github.io/adk-docs/get-started/quickstart/#gemini---google-cloud-vertex-ai
|
||||
"""
|
||||
|
||||
_OTHER_MODEL_MSG = """
|
||||
Please see below guide to configure other models:
|
||||
https://google.github.io/adk-docs/agents/models
|
||||
"""
|
||||
|
||||
_SUCCESS_MSG = """
|
||||
Agent created in {agent_folder}:
|
||||
- .env
|
||||
- __init__.py
|
||||
- agent.py
|
||||
"""
|
||||
|
||||
|
||||
def _get_gcp_project_from_gcloud() -> str:
|
||||
"""Uses gcloud to get default project."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["gcloud", "config", "get-value", "project"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
return result.stdout.strip()
|
||||
except (subprocess.CalledProcessError, FileNotFoundError):
|
||||
return ""
|
||||
|
||||
|
||||
def _get_gcp_region_from_gcloud() -> str:
|
||||
"""Uses gcloud to get default region."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["gcloud", "config", "get-value", "compute/region"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
return result.stdout.strip()
|
||||
except (subprocess.CalledProcessError, FileNotFoundError):
|
||||
return ""
|
||||
|
||||
|
||||
def _prompt_str(
|
||||
prompt_prefix: str,
|
||||
*,
|
||||
prior_msg: Optional[str] = None,
|
||||
default_value: Optional[str] = None,
|
||||
) -> str:
|
||||
if prior_msg:
|
||||
click.secho(prior_msg, fg="green")
|
||||
while True:
|
||||
value: str = click.prompt(
|
||||
prompt_prefix, default=default_value or None, type=str
|
||||
)
|
||||
if value and value.strip():
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _prompt_for_google_cloud(
|
||||
google_cloud_project: Optional[str],
|
||||
) -> str:
|
||||
"""Prompts user for Google Cloud project ID."""
|
||||
google_cloud_project = (
|
||||
google_cloud_project
|
||||
or os.environ.get("GOOGLE_CLOUD_PROJECT", None)
|
||||
or _get_gcp_project_from_gcloud()
|
||||
)
|
||||
|
||||
google_cloud_project = _prompt_str(
|
||||
"Enter Google Cloud project ID", default_value=google_cloud_project
|
||||
)
|
||||
|
||||
return google_cloud_project
|
||||
|
||||
|
||||
def _prompt_for_google_cloud_region(
|
||||
google_cloud_region: Optional[str],
|
||||
) -> str:
|
||||
"""Prompts user for Google Cloud region."""
|
||||
google_cloud_region = (
|
||||
google_cloud_region
|
||||
or os.environ.get("GOOGLE_CLOUD_LOCATION", None)
|
||||
or _get_gcp_region_from_gcloud()
|
||||
)
|
||||
|
||||
google_cloud_region = _prompt_str(
|
||||
"Enter Google Cloud region",
|
||||
default_value=google_cloud_region or "us-central1",
|
||||
)
|
||||
return google_cloud_region
|
||||
|
||||
|
||||
def _prompt_for_google_api_key(
|
||||
google_api_key: Optional[str],
|
||||
) -> str:
|
||||
"""Prompts user for Google API key."""
|
||||
google_api_key = google_api_key or os.environ.get("GOOGLE_API_KEY", None)
|
||||
|
||||
google_api_key = _prompt_str(
|
||||
"Enter Google API key",
|
||||
prior_msg=_GOOGLE_API_MSG,
|
||||
default_value=google_api_key,
|
||||
)
|
||||
return google_api_key
|
||||
|
||||
|
||||
def _generate_files(
|
||||
agent_folder: str,
|
||||
*,
|
||||
google_api_key: Optional[str] = None,
|
||||
google_cloud_project: Optional[str] = None,
|
||||
google_cloud_region: Optional[str] = None,
|
||||
model: Optional[str] = None,
|
||||
):
|
||||
"""Generates a folder name for the agent."""
|
||||
os.makedirs(agent_folder, exist_ok=True)
|
||||
|
||||
dotenv_file_path = os.path.join(agent_folder, ".env")
|
||||
init_file_path = os.path.join(agent_folder, "__init__.py")
|
||||
agent_file_path = os.path.join(agent_folder, "agent.py")
|
||||
|
||||
with open(dotenv_file_path, "w", encoding="utf-8") as f:
|
||||
lines = []
|
||||
if google_api_key:
|
||||
lines.append("GOOGLE_GENAI_USE_VERTEXAI=0")
|
||||
elif google_cloud_project and google_cloud_region:
|
||||
lines.append("GOOGLE_GENAI_USE_VERTEXAI=1")
|
||||
if google_api_key:
|
||||
lines.append(f"GOOGLE_API_KEY={google_api_key}")
|
||||
if google_cloud_project:
|
||||
lines.append(f"GOOGLE_CLOUD_PROJECT={google_cloud_project}")
|
||||
if google_cloud_region:
|
||||
lines.append(f"GOOGLE_CLOUD_LOCATION={google_cloud_region}")
|
||||
f.write("\n".join(lines))
|
||||
|
||||
with open(init_file_path, "w", encoding="utf-8") as f:
|
||||
f.write(_INIT_PY_TEMPLATE)
|
||||
|
||||
with open(agent_file_path, "w", encoding="utf-8") as f:
|
||||
f.write(_AGENT_PY_TEMPLATE.format(model_name=model))
|
||||
|
||||
click.secho(
|
||||
_SUCCESS_MSG.format(agent_folder=agent_folder),
|
||||
fg="green",
|
||||
)
|
||||
|
||||
|
||||
def _prompt_for_model() -> str:
|
||||
model_choice = click.prompt(
|
||||
"""\
|
||||
Choose a model for the root agent:
|
||||
1. gemini-2.0-flash-001
|
||||
2. Other models (fill later)
|
||||
Choose model""",
|
||||
type=click.Choice(["1", "2"]),
|
||||
)
|
||||
if model_choice == "1":
|
||||
return "gemini-2.0-flash-001"
|
||||
else:
|
||||
click.secho(_OTHER_MODEL_MSG, fg="green")
|
||||
return "<FILL_IN_MODEL>"
|
||||
|
||||
|
||||
def _prompt_to_choose_backend(
|
||||
google_api_key: Optional[str],
|
||||
google_cloud_project: Optional[str],
|
||||
google_cloud_region: Optional[str],
|
||||
) -> Tuple[Optional[str], Optional[str], Optional[str]]:
|
||||
"""Prompts user to choose backend.
|
||||
|
||||
Returns:
|
||||
A tuple of (google_api_key, google_cloud_project, google_cloud_region).
|
||||
"""
|
||||
backend_choice = click.prompt(
|
||||
"1. Google AI\n2. Vertex AI\nChoose a backend",
|
||||
type=click.Choice(["1", "2"]),
|
||||
)
|
||||
if backend_choice == "1":
|
||||
google_api_key = _prompt_for_google_api_key(google_api_key)
|
||||
elif backend_choice == "2":
|
||||
click.secho(_GOOGLE_CLOUD_SETUP_MSG, fg="green")
|
||||
google_cloud_project = _prompt_for_google_cloud(google_cloud_project)
|
||||
google_cloud_region = _prompt_for_google_cloud_region(google_cloud_region)
|
||||
return google_api_key, google_cloud_project, google_cloud_region
|
||||
|
||||
|
||||
def run_cmd(
|
||||
agent_name: str,
|
||||
*,
|
||||
model: Optional[str],
|
||||
google_api_key: Optional[str],
|
||||
google_cloud_project: Optional[str],
|
||||
google_cloud_region: Optional[str],
|
||||
):
|
||||
"""Runs `adk create` command to create agent template.
|
||||
|
||||
Args:
|
||||
agent_name: str, The name of the agent.
|
||||
google_api_key: Optional[str], The Google API key for using Google AI as
|
||||
backend.
|
||||
google_cloud_project: Optional[str], The Google Cloud project for using
|
||||
VertexAI as backend.
|
||||
google_cloud_region: Optional[str], The Google Cloud region for using
|
||||
VertexAI as backend.
|
||||
"""
|
||||
agent_folder = os.path.join(os.getcwd(), agent_name)
|
||||
# check folder doesn't exist or it's empty. Otherwise, throw
|
||||
if os.path.exists(agent_folder) and os.listdir(agent_folder):
|
||||
# Prompt user whether to override existing files using click
|
||||
if not click.confirm(
|
||||
f"Non-empty folder already exist: '{agent_folder}'\n"
|
||||
"Override existing content?",
|
||||
default=False,
|
||||
):
|
||||
raise click.Abort()
|
||||
|
||||
if not model:
|
||||
model = _prompt_for_model()
|
||||
|
||||
if not google_api_key and not (google_cloud_project and google_cloud_region):
|
||||
if model.startswith("gemini"):
|
||||
google_api_key, google_cloud_project, google_cloud_region = (
|
||||
_prompt_to_choose_backend(
|
||||
google_api_key, google_cloud_project, google_cloud_region
|
||||
)
|
||||
)
|
||||
|
||||
_generate_files(
|
||||
agent_folder,
|
||||
google_api_key=google_api_key,
|
||||
google_cloud_project=google_cloud_project,
|
||||
google_cloud_region=google_cloud_region,
|
||||
model=model,
|
||||
)
|
||||
@@ -82,8 +82,9 @@ def to_cloud_run(
|
||||
app_name: str,
|
||||
temp_folder: str,
|
||||
port: int,
|
||||
with_cloud_trace: bool,
|
||||
trace_to_cloud: bool,
|
||||
with_ui: bool,
|
||||
verbosity: str,
|
||||
):
|
||||
"""Deploys an agent to Google Cloud Run.
|
||||
|
||||
@@ -108,8 +109,9 @@ def to_cloud_run(
|
||||
app_name: The name of the app, by default, it's basename of `agent_folder`.
|
||||
temp_folder: The temp folder for the generated Cloud Run source files.
|
||||
port: The port of the ADK api server.
|
||||
with_cloud_trace: Whether to enable Cloud Trace.
|
||||
trace_to_cloud: Whether to enable Cloud Trace.
|
||||
with_ui: Whether to deploy with UI.
|
||||
verbosity: The verbosity level of the CLI.
|
||||
"""
|
||||
app_name = app_name or os.path.basename(agent_folder)
|
||||
|
||||
@@ -142,7 +144,7 @@ def to_cloud_run(
|
||||
port=port,
|
||||
command='web' if with_ui else 'api_server',
|
||||
install_agent_deps=install_agent_deps,
|
||||
trace_to_cloud_option='--trace_to_cloud' if with_cloud_trace else '',
|
||||
trace_to_cloud_option='--trace_to_cloud' if trace_to_cloud else '',
|
||||
)
|
||||
dockerfile_path = os.path.join(temp_folder, 'Dockerfile')
|
||||
os.makedirs(temp_folder, exist_ok=True)
|
||||
@@ -169,6 +171,8 @@ def to_cloud_run(
|
||||
*region_options,
|
||||
'--port',
|
||||
str(port),
|
||||
'--verbosity',
|
||||
verbosity,
|
||||
'--labels',
|
||||
'created-by=adk',
|
||||
],
|
||||
|
||||
@@ -112,14 +112,14 @@ def get_evaluation_criteria_or_default(
|
||||
|
||||
|
||||
def get_root_agent(agent_module_file_path: str) -> Agent:
|
||||
"""Returns root agent given the agetn module."""
|
||||
"""Returns root agent given the agent module."""
|
||||
agent_module = _get_agent_module(agent_module_file_path)
|
||||
root_agent = agent_module.agent.root_agent
|
||||
return root_agent
|
||||
|
||||
|
||||
def try_get_reset_func(agent_module_file_path: str) -> Any:
|
||||
"""Returns reset function for the agent, if present, given the agetn module."""
|
||||
"""Returns reset function for the agent, if present, given the agent module."""
|
||||
agent_module = _get_agent_module(agent_module_file_path)
|
||||
reset_func = getattr(agent_module.agent, "reset_data", None)
|
||||
return reset_func
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user