Compare commits

..

47 Commits

Author SHA1 Message Date
Wei Sun 30b1722cca No public description
PiperOrigin-RevId: 749119500
2025-04-18 12:51:32 -07:00
Wei Sun (Jack) 5eca8214a8 Merge pull request #243 from trandangtrungduc/fix_typos
fix typos in tools/ and tests/
2025-04-18 12:49:05 -07:00
Wei Sun (Jack) e0a360a1a2 Merge branch 'main' into fix_typos 2025-04-18 12:46:33 -07:00
Wei Sun 1cd61242ef No public description
PiperOrigin-RevId: 749110560
2025-04-18 12:21:07 -07:00
Trần Đặng Trung Đức e31cd0b5f8 No public description
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/243 from trandangtrungduc:fix_typos 6e317d69de
PiperOrigin-RevId: 749106557
2025-04-18 12:07:52 -07:00
Wei Sun dfb283e6e0 No public description
PiperOrigin-RevId: 749076119
2025-04-18 10:35:34 -07:00
Hangfei Lin 6e317d69de Merge branch 'main' into fix_typos 2025-04-18 10:25:42 -07:00
Hangfei Lin 732059cf59 Update CHANGELOG.md (#260) 2025-04-18 09:22:30 -07:00
Trần Đặng Trung Đức 6b86bcc549 Merge branch 'main' into fix_typos 2025-04-18 16:26:57 +07:00
Hangfei Lin 45a465e9b0 No public description
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/adk-python/pull/260 from google:hangfei-patch-1 f514134c4fc3ad340dd274a38d01cc6f77056339
PiperOrigin-RevId: 748934896
2025-04-17 22:50:57 -07:00
Trần Đặng Trung Đức e50c463ed4 Merge branch 'main' into fix_typos 2025-04-18 11:56:26 +07:00
Che Liu 995dc8276b No public description
PiperOrigin-RevId: 748918432
2025-04-17 21:31:40 -07:00
trandangtrungduc 2ee1c65e05 fix minor typos 2025-04-18 11:02:10 +07:00
Hangfei Lin b8514f26fe Update python-unit-tests.yml (#257)
fix test dependency
2025-04-17 19:07:14 -07:00
Hangfei Lin 443bc08d2b No public description
PiperOrigin-RevId: 748877073
2025-04-17 18:24:35 -07:00
Google ADK Member 61d4be2d76 No public description
PiperOrigin-RevId: 748777998
2025-04-17 21:47:59 +00:00
trandangtrungduc d057f2d825 fix typos 2025-04-17 17:51:07 +07:00
Hangfei Lin 290058eb05 Update README.md (#193)
* Update README.md
2025-04-14 21:14:38 -07:00
DeanChensj 3e85df2641 Update DatabaseSessionService db_engine construction (#195)
Co-authored-by: Hangfei Lin <hangfei@google.com>
2025-04-14 17:55:15 -07:00
Selcuk Gun 9a44831a08 Add parallel tool call support for litellm (#172)
Co-authored-by: Hangfei Lin <hangfei@google.com>
2025-04-14 17:42:33 -07:00
gsarthakdev 4e8b944e09 Rename 'ctx' parameter to 'tool_context' for consistency (#162)
All other methods that have `tool_context` as an argument, refer to it as "tool_context" in the docstring under Args.

Co-authored-by: Hangfei Lin <hangfei@google.com>
2025-04-14 17:38:09 -07:00
Riccardo Carlesso 26bab52ca8 Update README.md (#185)
fixing bug: task_exectuor -> task_executor
2025-04-14 13:03:36 -07:00
Hangfei Lin 577222509c Update README.md (#126) 2025-04-12 21:00:57 -07:00
Selcuk Gun cfbcc17644 Fix empty list in content on tool calls causing ollama parse error (#102)
This is related to google/adk-python#49
2025-04-12 17:34:57 -07:00
fangyh20 089c1e6428 Fix typos in docstrings of evaluation_generator.py and event.py (#101) (#121)
* Fix typos in docstrings of evaluation_generator.py and event.py (#101)

Corrected 'resposnes' to 'responses', 'uncertainity' to 'uncertainty', 'conversaction' to 'conversation', and 'exeuction' to 'execution' in relevant docstrings for clarity.

* Fix typos in docstrings and comments across multiple files

Corrected 'detla' to 'delta', 'buil-in' to 'built-in', 'walkaround' to 'workaround', and 'conversaction' to 'conversation' for clarity in relevant files. Updated comments for consistency.

---------

Co-authored-by: Hangfei Lin <hangfei@google.com>
2025-04-12 09:55:22 -07:00
Karl Weinmeister d810ff7b28 chore: Add subreddit README badge (#122) 2025-04-12 09:51:09 -07:00
fangyh20 e0d223d117 Add .gitignore file to exclude common Python, IDE, and environment files (#109) 2025-04-12 07:35:53 -07:00
Kshitiz 9cd802fcea Fixed typo in README.md : cooridnator -> coordinator (#112) 2025-04-12 07:16:22 -07:00
Hangfei Lin eecb9e65be Update README.md (#107)
update read me and add feature highlights
2025-04-11 22:49:13 -07:00
Fangyu ee2a75368a Fix typos in docstrings across multiple files (#101)
* Fix typos in docstrings across multiple files: 'conversaction' -> 'conversation' and 'dsiabled' -> 'disabled'. Update comments for clarity.

* Fix typos in comments and docstrings across multiple files

- Corrected "reqeust" to "request" in auth_preprocessor.py
- Fixed "credentails" to "credentials" in auth_tool.py
- Updated "agetn" to "agent" in cli_eval.py
- Changed "creiteria" to "criteria" in cli_tools_click.py

---------

Co-authored-by: fangyu <fangyu.jobs@gmail.com>
Co-authored-by: Hangfei Lin <hangfei@google.com>
2025-04-11 22:19:57 -07:00
Hangfei Lin b68f3aa11f Update README.md (#104) 2025-04-11 20:03:44 -07:00
Hangfei Lin a39977876b Update issue templates (#64)
Update issue template to help users to file the issues at the right place.
2025-04-11 15:48:21 -07:00
Jack Sun 05142a07cc Moves unittests to root folder and adds github action to run unit tests. (#72)
* Move unit tests to root package.

* Adds deps to "test" extra, and mark two broken tests in tests/unittests/auth/test_auth_handler.py

* Adds github workflow

* minor fix in lite_llm.py for python 3.9.

* format pyproject.toml
2025-04-11 08:25:59 -07:00
Hangfei Lin 59117b9b96 Merge pull request #7 from jackwotherspoon/main
docs: update ToolboxTool port in docstring
2025-04-10 18:04:52 -07:00
Hangfei Lin e80d0e4993 Merge branch 'main' into main 2025-04-10 18:04:20 -07:00
Hangfei Lin 278b513493 Merge pull request #22 from Howe829/fix/typos
Fix: typos reponse -> response
2025-04-10 18:03:39 -07:00
HowardChan e637b4df25 Merge branch 'main' into fix/typos 2025-04-11 08:50:59 +08:00
HowardChan 9cbaaf378f Revert main-SLIAU2JL.js file 2025-04-11 08:49:37 +08:00
Hangfei Lin 924549e346 Merge pull request #24 from eltociear/patch-1
fix typo in update evals.py
2025-04-10 10:19:50 -07:00
jackwotherspoon 972620d464 chore: undo ToolboxTool import 2025-04-10 13:35:11 +00:00
Ikko Eltociear Ashimine 7a34c3f5b9 chore: update evals.py
langauge -> language
2025-04-10 15:59:59 +09:00
HowardChan 3f30e0825d Fix:reponse -> response 2025-04-10 14:38:28 +08:00
jackwotherspoon 20a8a11e49 chore: add ToolboxTool to tools.__init__.py 2025-04-09 20:16:26 +00:00
Hangfei Lin 9002ace7e5 Merge pull request #4 from kweinmeister/main
fix: Update README evaluate link
2025-04-09 11:26:30 -07:00
Karl Weinmeister 28837231dd fix: Update README evaluate link 2025-04-09 11:08:06 -07:00
Hangfei Lin f63ec37153 Update CHANGELOG.md 2025-04-09 09:10:01 -07:00
Hangfei Lin 553bede77e Create CHANGELOG.md 2025-04-09 08:53:35 -07:00
185 changed files with 2576 additions and 374 deletions
+35
View File
@@ -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.
+23
View File
@@ -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.
+39
View File
@@ -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
View File
@@ -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
+56
View File
@@ -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
+67 -40
View File
@@ -1,11 +1,13 @@
# Agent Development Kit (ADK)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
[![Python Unit Tests](https://github.com/google/adk-python/actions/workflows/python-unit-tests.yml/badge.svg)](https://github.com/google/adk-python/actions/workflows/python-unit-tests.yml)
[![r/agentdevelopmentkit](https://img.shields.io/badge/Reddit-r%2Fagentdevelopmentkit-FF4500?style=flat&logo=reddit&logoColor=white)](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

+4
View File
@@ -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",
+4 -4
View File
@@ -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.
+1 -1
View File
@@ -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."""
+1 -1
View File
@@ -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(
+1 -1
View File
@@ -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."""
+2 -2
View File
@@ -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]
+1 -1
View File
@@ -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
File diff suppressed because one or more lines are too long
+2
View File
@@ -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(
+279
View File
@@ -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,
)
+7 -3
View File
@@ -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',
],
+2 -2
View File
@@ -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