mirror of
https://github.com/encounter/adk-python.git
synced 2026-07-09 18:19:28 -07:00
docs: Fix docstring and update module public name list for generating API references
To fix https://github.com/google/adk-docs/issues/131 PiperOrigin-RevId: 783080206
This commit is contained in:
committed by
Copybara-Service
parent
62a611956f
commit
dea1ee14ab
@@ -13,6 +13,7 @@
|
|||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
|
|
||||||
from .base_agent import BaseAgent
|
from .base_agent import BaseAgent
|
||||||
|
from .invocation_context import InvocationContext
|
||||||
from .live_request_queue import LiveRequest
|
from .live_request_queue import LiveRequest
|
||||||
from .live_request_queue import LiveRequestQueue
|
from .live_request_queue import LiveRequestQueue
|
||||||
from .llm_agent import Agent
|
from .llm_agent import Agent
|
||||||
@@ -29,4 +30,8 @@ __all__ = [
|
|||||||
'LoopAgent',
|
'LoopAgent',
|
||||||
'ParallelAgent',
|
'ParallelAgent',
|
||||||
'SequentialAgent',
|
'SequentialAgent',
|
||||||
|
'InvocationContext',
|
||||||
|
'LiveRequest',
|
||||||
|
'LiveRequestQueue',
|
||||||
|
'RunConfig',
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -149,7 +149,7 @@ class InvocationContext(BaseModel):
|
|||||||
"""The running streaming tools of this invocation."""
|
"""The running streaming tools of this invocation."""
|
||||||
|
|
||||||
transcription_cache: Optional[list[TranscriptionEntry]] = None
|
transcription_cache: Optional[list[TranscriptionEntry]] = None
|
||||||
"""Caches necessary, data audio or contents, that are needed by transcription."""
|
"""Caches necessary data, audio or contents, that are needed by transcription."""
|
||||||
|
|
||||||
run_config: Optional[RunConfig] = None
|
run_config: Optional[RunConfig] = None
|
||||||
"""Configurations for live agents under this invocation."""
|
"""Configurations for live agents under this invocation."""
|
||||||
|
|||||||
@@ -168,9 +168,9 @@ class LlmAgent(BaseAgent):
|
|||||||
"""Controls content inclusion in model requests.
|
"""Controls content inclusion in model requests.
|
||||||
|
|
||||||
Options:
|
Options:
|
||||||
default: Model receives relevant conversation history
|
default: Model receives relevant conversation history
|
||||||
none: Model receives no prior history, operates solely on current
|
none: Model receives no prior history, operates solely on current
|
||||||
instruction and input
|
instruction and input
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# Controlled input/output configurations - Start
|
# Controlled input/output configurations - Start
|
||||||
@@ -179,8 +179,9 @@ class LlmAgent(BaseAgent):
|
|||||||
output_schema: Optional[type[BaseModel]] = None
|
output_schema: Optional[type[BaseModel]] = None
|
||||||
"""The output schema when agent replies.
|
"""The output schema when agent replies.
|
||||||
|
|
||||||
NOTE: when this is set, agent can ONLY reply and CANNOT use any tools, such as
|
NOTE:
|
||||||
function tools, RAGs, agent transfer, etc.
|
When this is set, agent can ONLY reply and CANNOT use any tools, such as
|
||||||
|
function tools, RAGs, agent transfer, etc.
|
||||||
"""
|
"""
|
||||||
output_key: Optional[str] = None
|
output_key: Optional[str] = None
|
||||||
"""The key in session state to store the output of the agent.
|
"""The key in session state to store the output of the agent.
|
||||||
@@ -195,9 +196,9 @@ class LlmAgent(BaseAgent):
|
|||||||
planner: Optional[BasePlanner] = None
|
planner: Optional[BasePlanner] = None
|
||||||
"""Instructs the agent to make a plan and execute it step by step.
|
"""Instructs the agent to make a plan and execute it step by step.
|
||||||
|
|
||||||
NOTE: to use model's built-in thinking features, set the `thinking_config`
|
NOTE:
|
||||||
field in `google.adk.planners.built_in_planner`.
|
To use model's built-in thinking features, set the `thinking_config`
|
||||||
|
field in `google.adk.planners.built_in_planner`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
code_executor: Optional[BaseCodeExecutor] = None
|
code_executor: Optional[BaseCodeExecutor] = None
|
||||||
@@ -206,7 +207,8 @@ class LlmAgent(BaseAgent):
|
|||||||
|
|
||||||
Check out available code executions in `google.adk.code_executor` package.
|
Check out available code executions in `google.adk.code_executor` package.
|
||||||
|
|
||||||
NOTE: to use model's built-in code executor, use the `BuiltInCodeExecutor`.
|
NOTE:
|
||||||
|
To use model's built-in code executor, use the `BuiltInCodeExecutor`.
|
||||||
"""
|
"""
|
||||||
# Advance features - End
|
# Advance features - End
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,8 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import abc
|
import abc
|
||||||
from typing import List
|
from typing import List
|
||||||
|
|
||||||
@@ -42,42 +44,35 @@ class BaseCodeExecutor(BaseModel):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
optimize_data_file: bool = False
|
optimize_data_file: bool = False
|
||||||
"""
|
"""If true, extract and process data files from the model request
|
||||||
If true, extract and process data files from the model request
|
|
||||||
and attach them to the code executor.
|
and attach them to the code executor.
|
||||||
Supported data file MimeTypes are [text/csv].
|
|
||||||
|
|
||||||
|
Supported data file MimeTypes are [text/csv].
|
||||||
Default to False.
|
Default to False.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
stateful: bool = False
|
stateful: bool = False
|
||||||
"""
|
"""Whether the code executor is stateful. Default to False."""
|
||||||
Whether the code executor is stateful. Default to False.
|
|
||||||
"""
|
|
||||||
|
|
||||||
error_retry_attempts: int = 2
|
error_retry_attempts: int = 2
|
||||||
"""
|
"""The number of attempts to retry on consecutive code execution errors. Default to 2."""
|
||||||
The number of attempts to retry on consecutive code execution errors. Default to 2.
|
|
||||||
"""
|
|
||||||
|
|
||||||
code_block_delimiters: List[tuple[str, str]] = [
|
code_block_delimiters: List[tuple[str, str]] = [
|
||||||
('```tool_code\n', '\n```'),
|
('```tool_code\n', '\n```'),
|
||||||
('```python\n', '\n```'),
|
('```python\n', '\n```'),
|
||||||
]
|
]
|
||||||
"""
|
"""The list of the enclosing delimiters to identify the code blocks.
|
||||||
The list of the enclosing delimiters to identify the code blocks.
|
|
||||||
For example, the delimiter ('```python\n', '\n```') can be
|
|
||||||
used to identify code blocks with the following format:
|
|
||||||
|
|
||||||
```python
|
For example, the delimiter ('```python\\n', '\\n```') can be
|
||||||
print("hello")
|
used to identify code blocks with the following format::
|
||||||
```
|
|
||||||
|
```python
|
||||||
|
print("hello")
|
||||||
|
```
|
||||||
"""
|
"""
|
||||||
|
|
||||||
execution_result_delimiters: tuple[str, str] = ('```tool_output\n', '\n```')
|
execution_result_delimiters: tuple[str, str] = ('```tool_output\n', '\n```')
|
||||||
"""
|
"""The delimiters to format the code execution result."""
|
||||||
The delimiters to format the code execution result.
|
|
||||||
"""
|
|
||||||
|
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
def execute_code(
|
def execute_code(
|
||||||
|
|||||||
@@ -122,8 +122,9 @@ class Runner:
|
|||||||
) -> Generator[Event, None, None]:
|
) -> Generator[Event, None, None]:
|
||||||
"""Runs the agent.
|
"""Runs the agent.
|
||||||
|
|
||||||
NOTE: This sync interface is only for local testing and convenience purpose.
|
NOTE:
|
||||||
Consider using `run_async` for production usage.
|
This sync interface is only for local testing and convenience purpose.
|
||||||
|
Consider using `run_async` for production usage.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
user_id: The user ID of the session.
|
user_id: The user ID of the session.
|
||||||
@@ -350,7 +351,7 @@ class Runner:
|
|||||||
This feature is **experimental** and its API or behavior may change
|
This feature is **experimental** and its API or behavior may change
|
||||||
in future releases.
|
in future releases.
|
||||||
|
|
||||||
.. note::
|
.. NOTE::
|
||||||
Either `session` or both `user_id` and `session_id` must be provided.
|
Either `session` or both `user_id` and `session_id` must be provided.
|
||||||
"""
|
"""
|
||||||
if session is None and (user_id is None or session_id is None):
|
if session is None and (user_id is None or session_id is None):
|
||||||
@@ -433,9 +434,10 @@ class Runner:
|
|||||||
"""Finds the agent to run to continue the session.
|
"""Finds the agent to run to continue the session.
|
||||||
|
|
||||||
A qualified agent must be either of:
|
A qualified agent must be either of:
|
||||||
|
|
||||||
- The agent that returned a function call and the last user message is a
|
- The agent that returned a function call and the last user message is a
|
||||||
function response to this function call.
|
function response to this function call.
|
||||||
- The root agent;
|
- The root agent.
|
||||||
- An LlmAgent who replied last and is capable to transfer to any other agent
|
- An LlmAgent who replied last and is capable to transfer to any other agent
|
||||||
in the agent hierarchy.
|
in the agent hierarchy.
|
||||||
|
|
||||||
|
|||||||
@@ -35,27 +35,25 @@ from .clients.apihub_client import APIHubClient
|
|||||||
class APIHubToolset(BaseToolset):
|
class APIHubToolset(BaseToolset):
|
||||||
"""APIHubTool generates tools from a given API Hub resource.
|
"""APIHubTool generates tools from a given API Hub resource.
|
||||||
|
|
||||||
Examples:
|
Examples::
|
||||||
|
|
||||||
```
|
apihub_toolset = APIHubToolset(
|
||||||
apihub_toolset = APIHubToolset(
|
apihub_resource_name="projects/test-project/locations/us-central1/apis/test-api",
|
||||||
apihub_resource_name="projects/test-project/locations/us-central1/apis/test-api",
|
service_account_json="...",
|
||||||
service_account_json="...",
|
tool_filter=lambda tool, ctx=None: tool.name in ('my_tool',
|
||||||
tool_filter=lambda tool, ctx=None: tool.name in ('my_tool',
|
'my_other_tool')
|
||||||
'my_other_tool')
|
)
|
||||||
)
|
|
||||||
|
|
||||||
# Get all available tools
|
# Get all available tools
|
||||||
agent = LlmAgent(tools=apihub_toolset)
|
agent = LlmAgent(tools=apihub_toolset)
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
**apihub_resource_name** is the resource name from API Hub. It must include
|
**apihub_resource_name** is the resource name from API Hub. It must include
|
||||||
API name, and can optionally include API version and spec name.
|
API name, and can optionally include API version and spec name.
|
||||||
- If apihub_resource_name includes a spec resource name, the content of that
|
|
||||||
spec will be used for generating the tools.
|
- If apihub_resource_name includes a spec resource name, the content of that
|
||||||
- If apihub_resource_name includes only an api or a version name, the
|
spec will be used for generating the tools.
|
||||||
first spec of the first version of that API will be used.
|
- If apihub_resource_name includes only an api or a version name, the
|
||||||
|
first spec of the first version of that API will be used.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
@@ -78,44 +76,45 @@ class APIHubToolset(BaseToolset):
|
|||||||
):
|
):
|
||||||
"""Initializes the APIHubTool with the given parameters.
|
"""Initializes the APIHubTool with the given parameters.
|
||||||
|
|
||||||
Examples:
|
Examples::
|
||||||
```
|
|
||||||
apihub_toolset = APIHubToolset(
|
|
||||||
apihub_resource_name="projects/test-project/locations/us-central1/apis/test-api",
|
|
||||||
service_account_json="...",
|
|
||||||
)
|
|
||||||
|
|
||||||
# Get all available tools
|
apihub_toolset = APIHubToolset(
|
||||||
agent = LlmAgent(tools=[apihub_toolset])
|
apihub_resource_name="projects/test-project/locations/us-central1/apis/test-api",
|
||||||
|
service_account_json="...",
|
||||||
|
)
|
||||||
|
|
||||||
apihub_toolset = APIHubToolset(
|
# Get all available tools
|
||||||
apihub_resource_name="projects/test-project/locations/us-central1/apis/test-api",
|
agent = LlmAgent(tools=[apihub_toolset])
|
||||||
service_account_json="...",
|
|
||||||
tool_filter = ['my_tool']
|
apihub_toolset = APIHubToolset(
|
||||||
)
|
apihub_resource_name="projects/test-project/locations/us-central1/apis/test-api",
|
||||||
# Get a specific tool
|
service_account_json="...",
|
||||||
agent = LlmAgent(tools=[
|
tool_filter = ['my_tool']
|
||||||
...,
|
)
|
||||||
apihub_toolset,
|
# Get a specific tool
|
||||||
])
|
agent = LlmAgent(tools=[
|
||||||
```
|
...,
|
||||||
|
apihub_toolset,
|
||||||
|
])
|
||||||
|
|
||||||
**apihub_resource_name** is the resource name from API Hub. It must include
|
**apihub_resource_name** is the resource name from API Hub. It must include
|
||||||
API name, and can optionally include API version and spec name.
|
API name, and can optionally include API version and spec name.
|
||||||
|
|
||||||
- If apihub_resource_name includes a spec resource name, the content of that
|
- If apihub_resource_name includes a spec resource name, the content of that
|
||||||
spec will be used for generating the tools.
|
spec will be used for generating the tools.
|
||||||
- If apihub_resource_name includes only an api or a version name, the
|
- If apihub_resource_name includes only an api or a version name, the
|
||||||
first spec of the first version of that API will be used.
|
first spec of the first version of that API will be used.
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
|
||||||
* projects/xxx/locations/us-central1/apis/apiname/...
|
* projects/xxx/locations/us-central1/apis/apiname/...
|
||||||
* https://console.cloud.google.com/apigee/api-hub/apis/apiname?project=xxx
|
* https://console.cloud.google.com/apigee/api-hub/apis/apiname?project=xxx
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
apihub_resource_name: The resource name of the API in API Hub.
|
apihub_resource_name: The resource name of the API in API Hub.
|
||||||
Example: `projects/test-project/locations/us-central1/apis/test-api`.
|
Example: ``projects/test-project/locations/us-central1/apis/test-api``.
|
||||||
access_token: Google Access token. Generate with gcloud cli `gcloud auth
|
access_token: Google Access token. Generate with gcloud cli
|
||||||
auth print-access-token`. Used for fetching API Specs from API Hub.
|
``gcloud auth auth print-access-token``. Used for fetching API Specs from API Hub.
|
||||||
service_account_json: The service account config as a json string.
|
service_account_json: The service account config as a json string.
|
||||||
Required if not using default service credential. It is used for
|
Required if not using default service credential. It is used for
|
||||||
creating the API Hub client and fetching the API Specs from API Hub.
|
creating the API Hub client and fetching the API Specs from API Hub.
|
||||||
|
|||||||
+35
-37
@@ -12,6 +12,8 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from typing import List
|
from typing import List
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
@@ -42,43 +44,39 @@ logger = logging.getLogger("google_adk." + __name__)
|
|||||||
# TODO(cheliu): Apply a common toolset interface
|
# TODO(cheliu): Apply a common toolset interface
|
||||||
class ApplicationIntegrationToolset(BaseToolset):
|
class ApplicationIntegrationToolset(BaseToolset):
|
||||||
"""ApplicationIntegrationToolset generates tools from a given Application
|
"""ApplicationIntegrationToolset generates tools from a given Application
|
||||||
|
|
||||||
Integration or Integration Connector resource.
|
Integration or Integration Connector resource.
|
||||||
Example Usage:
|
|
||||||
```
|
|
||||||
# Get all available tools for an integration with api trigger
|
|
||||||
application_integration_toolset = ApplicationIntegrationToolset(
|
|
||||||
|
|
||||||
project="test-project",
|
Example Usage::
|
||||||
location="us-central1"
|
|
||||||
integration="test-integration",
|
|
||||||
triggers=["api_trigger/test_trigger"],
|
|
||||||
service_account_credentials={...},
|
|
||||||
)
|
|
||||||
|
|
||||||
# Get all available tools for a connection using entity operations and
|
# Get all available tools for an integration with api trigger
|
||||||
# actions
|
application_integration_toolset = ApplicationIntegrationToolset(
|
||||||
# Note: Find the list of supported entity operations and actions for a
|
project="test-project",
|
||||||
connection
|
location="us-central1"
|
||||||
# using integration connector apis:
|
integration="test-integration",
|
||||||
#
|
triggers=["api_trigger/test_trigger"],
|
||||||
https://cloud.google.com/integration-connectors/docs/reference/rest/v1/projects.locations.connections.connectionSchemaMetadata
|
service_account_credentials={...},
|
||||||
application_integration_toolset = ApplicationIntegrationToolset(
|
)
|
||||||
project="test-project",
|
|
||||||
location="us-central1"
|
|
||||||
connection="test-connection",
|
|
||||||
entity_operations=["EntityId1": ["LIST","CREATE"], "EntityId2": []],
|
|
||||||
#empty list for actions means all operations on the entity are supported
|
|
||||||
actions=["action1"],
|
|
||||||
service_account_credentials={...},
|
|
||||||
)
|
|
||||||
|
|
||||||
# Feed the toolset to agent
|
# Get all available tools for a connection using entity operations and
|
||||||
agent = LlmAgent(tools=[
|
# actions
|
||||||
...,
|
# Note: Find the list of supported entity operations and actions for a
|
||||||
application_integration_toolset,
|
# connection using integration connector apis:
|
||||||
])
|
# https://cloud.google.com/integration-connectors/docs/reference/rest/v1/projects.locations.connections.connectionSchemaMetadata
|
||||||
```
|
application_integration_toolset = ApplicationIntegrationToolset(
|
||||||
|
project="test-project",
|
||||||
|
location="us-central1"
|
||||||
|
connection="test-connection",
|
||||||
|
entity_operations=["EntityId1": ["LIST","CREATE"], "EntityId2": []],
|
||||||
|
#empty list for actions means all operations on the entity are supported
|
||||||
|
actions=["action1"],
|
||||||
|
service_account_credentials={...},
|
||||||
|
)
|
||||||
|
|
||||||
|
# Feed the toolset to agent
|
||||||
|
agent = LlmAgent(tools=[
|
||||||
|
...,
|
||||||
|
application_integration_toolset,
|
||||||
|
])
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
@@ -122,11 +120,11 @@ class ApplicationIntegrationToolset(BaseToolset):
|
|||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: If none of the following conditions are met:
|
ValueError: If none of the following conditions are met:
|
||||||
- `integration` is provided.
|
- ``integration`` is provided.
|
||||||
- `connection` is provided and at least one of `entity_operations`
|
- ``connection`` is provided and at least one of ``entity_operations``
|
||||||
or `actions` is provided.
|
or ``actions`` is provided.
|
||||||
Exception: If there is an error during the initialization of the
|
Exception: If there is an error during the initialization of the
|
||||||
integration or connection client.
|
integration or connection client.
|
||||||
"""
|
"""
|
||||||
super().__init__(tool_filter=tool_filter)
|
super().__init__(tool_filter=tool_filter)
|
||||||
self.project = project
|
self.project = project
|
||||||
|
|||||||
@@ -45,13 +45,12 @@ class IntegrationConnectorTool(BaseTool):
|
|||||||
* Generates request params and body
|
* Generates request params and body
|
||||||
* Attaches auth credentials to API call.
|
* Attaches auth credentials to API call.
|
||||||
|
|
||||||
Example:
|
Example::
|
||||||
```
|
|
||||||
# Each API operation in the spec will be turned into its own tool
|
# Each API operation in the spec will be turned into its own tool
|
||||||
# Name of the tool is the operationId of that operation, in snake case
|
# Name of the tool is the operationId of that operation, in snake case
|
||||||
operations = OperationGenerator().parse(openapi_spec_dict)
|
operations = OperationGenerator().parse(openapi_spec_dict)
|
||||||
tool = [RestApiTool.from_parsed_operation(o) for o in operations]
|
tool = [RestApiTool.from_parsed_operation(o) for o in operations]
|
||||||
```
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
EXCLUDE_FIELDS = [
|
EXCLUDE_FIELDS = [
|
||||||
|
|||||||
@@ -49,11 +49,11 @@ class BaseTool(ABC):
|
|||||||
def _get_declaration(self) -> Optional[types.FunctionDeclaration]:
|
def _get_declaration(self) -> Optional[types.FunctionDeclaration]:
|
||||||
"""Gets the OpenAPI specification of this tool in the form of a FunctionDeclaration.
|
"""Gets the OpenAPI specification of this tool in the form of a FunctionDeclaration.
|
||||||
|
|
||||||
NOTE
|
NOTE:
|
||||||
- Required if subclass uses the default implementation of
|
- Required if subclass uses the default implementation of
|
||||||
`process_llm_request` to add function declaration to LLM request.
|
`process_llm_request` to add function declaration to LLM request.
|
||||||
- Otherwise, can be skipped, e.g. for a built-in GoogleSearch tool for
|
- Otherwise, can be skipped, e.g. for a built-in GoogleSearch tool for
|
||||||
Gemini.
|
Gemini.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The FunctionDeclaration of this tool, or None if it doesn't need to be
|
The FunctionDeclaration of this tool, or None if it doesn't need to be
|
||||||
@@ -66,10 +66,10 @@ class BaseTool(ABC):
|
|||||||
) -> Any:
|
) -> Any:
|
||||||
"""Runs the tool with the given arguments and context.
|
"""Runs the tool with the given arguments and context.
|
||||||
|
|
||||||
NOTE
|
NOTE:
|
||||||
- Required if this tool needs to run at the client side.
|
- Required if this tool needs to run at the client side.
|
||||||
- Otherwise, can be skipped, e.g. for a built-in GoogleSearch tool for
|
- Otherwise, can be skipped, e.g. for a built-in GoogleSearch tool for
|
||||||
Gemini.
|
Gemini.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
args: The LLM-filled arguments.
|
args: The LLM-filled arguments.
|
||||||
|
|||||||
@@ -76,10 +76,11 @@ class BaseToolset(ABC):
|
|||||||
async def close(self) -> None:
|
async def close(self) -> None:
|
||||||
"""Performs cleanup and releases resources held by the toolset.
|
"""Performs cleanup and releases resources held by the toolset.
|
||||||
|
|
||||||
NOTE: This method is invoked, for example, at the end of an agent server's
|
NOTE:
|
||||||
lifecycle or when the toolset is no longer needed. Implementations
|
This method is invoked, for example, at the end of an agent server's
|
||||||
should ensure that any open connections, files, or other managed
|
lifecycle or when the toolset is no longer needed. Implementations
|
||||||
resources are properly released to prevent leaks.
|
should ensure that any open connections, files, or other managed
|
||||||
|
resources are properly released to prevent leaks.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def _is_tool_selected(
|
def _is_tool_selected(
|
||||||
|
|||||||
@@ -20,11 +20,11 @@ definition. The rationales to have customized tool are:
|
|||||||
|
|
||||||
1. BigQuery APIs have functions overlaps and LLM can't tell what tool to use
|
1. BigQuery APIs have functions overlaps and LLM can't tell what tool to use
|
||||||
2. BigQuery APIs have a lot of parameters with some rarely used, which are not
|
2. BigQuery APIs have a lot of parameters with some rarely used, which are not
|
||||||
LLM-friendly
|
LLM-friendly
|
||||||
3. We want to provide more high-level tools like forecasting, RAG, segmentation,
|
3. We want to provide more high-level tools like forecasting, RAG, segmentation,
|
||||||
etc.
|
etc.
|
||||||
4. We want to provide extra access guardrails in those tools. For example,
|
4. We want to provide extra access guardrails in those tools. For example,
|
||||||
execute_sql can't arbitrarily mutate existing data.
|
execute_sql can't arbitrarily mutate existing data.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from .bigquery_credentials import BigQueryCredentialsConfig
|
from .bigquery_credentials import BigQueryCredentialsConfig
|
||||||
|
|||||||
@@ -41,14 +41,13 @@ class LangchainTool(FunctionTool):
|
|||||||
name: Optional override for the tool's name
|
name: Optional override for the tool's name
|
||||||
description: Optional override for the tool's description
|
description: Optional override for the tool's description
|
||||||
|
|
||||||
Examples:
|
Examples::
|
||||||
```python
|
|
||||||
from langchain.tools import DuckDuckGoSearchTool
|
from langchain.tools import DuckDuckGoSearchTool
|
||||||
from google.genai.tools import LangchainTool
|
from google.genai.tools import LangchainTool
|
||||||
|
|
||||||
search_tool = DuckDuckGoSearchTool()
|
search_tool = DuckDuckGoSearchTool()
|
||||||
wrapped_tool = LangchainTool(search_tool)
|
wrapped_tool = LangchainTool(search_tool)
|
||||||
```
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_langchain_tool: Union[BaseTool, object]
|
_langchain_tool: Union[BaseTool, object]
|
||||||
|
|||||||
@@ -61,28 +61,27 @@ class MCPToolset(BaseToolset):
|
|||||||
that can be used by an agent. It properly implements the BaseToolset
|
that can be used by an agent. It properly implements the BaseToolset
|
||||||
interface for easy integration with the agent framework.
|
interface for easy integration with the agent framework.
|
||||||
|
|
||||||
Usage:
|
Usage::
|
||||||
```python
|
|
||||||
toolset = MCPToolset(
|
|
||||||
connection_params=StdioServerParameters(
|
|
||||||
command='npx',
|
|
||||||
args=["-y", "@modelcontextprotocol/server-filesystem"],
|
|
||||||
),
|
|
||||||
tool_filter=['read_file', 'list_directory'] # Optional: filter specific tools
|
|
||||||
)
|
|
||||||
|
|
||||||
# Use in an agent
|
toolset = MCPToolset(
|
||||||
agent = LlmAgent(
|
connection_params=StdioServerParameters(
|
||||||
model='gemini-2.0-flash',
|
command='npx',
|
||||||
name='enterprise_assistant',
|
args=["-y", "@modelcontextprotocol/server-filesystem"],
|
||||||
instruction='Help user accessing their file systems',
|
),
|
||||||
tools=[toolset],
|
tool_filter=['read_file', 'list_directory'] # Optional: filter specific tools
|
||||||
)
|
)
|
||||||
|
|
||||||
# Cleanup is handled automatically by the agent framework
|
# Use in an agent
|
||||||
# But you can also manually close if needed:
|
agent = LlmAgent(
|
||||||
# await toolset.close()
|
model='gemini-2.0-flash',
|
||||||
```
|
name='enterprise_assistant',
|
||||||
|
instruction='Help user accessing their file systems',
|
||||||
|
tools=[toolset],
|
||||||
|
)
|
||||||
|
|
||||||
|
# Cleanup is handled automatically by the agent framework
|
||||||
|
# But you can also manually close if needed:
|
||||||
|
# await toolset.close()
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
@@ -103,12 +102,12 @@ class MCPToolset(BaseToolset):
|
|||||||
|
|
||||||
Args:
|
Args:
|
||||||
connection_params: The connection parameters to the MCP server. Can be:
|
connection_params: The connection parameters to the MCP server. Can be:
|
||||||
`StdioConnectionParams` for using local mcp server (e.g. using `npx` or
|
``StdioConnectionParams`` for using local mcp server (e.g. using ``npx`` or
|
||||||
`python3`); or `SseConnectionParams` for a local/remote SSE server; or
|
``python3``); or ``SseConnectionParams`` for a local/remote SSE server; or
|
||||||
`StreamableHTTPConnectionParams` for local/remote Streamable http
|
``StreamableHTTPConnectionParams`` for local/remote Streamable http
|
||||||
server. Note, `StdioServerParameters` is also supported for using local
|
server. Note, ``StdioServerParameters`` is also supported for using local
|
||||||
mcp server (e.g. using `npx` or `python3` ), but it does not support
|
mcp server (e.g. using ``npx`` or ``python3`` ), but it does not support
|
||||||
timeout, and we recommend to use `StdioConnectionParams` instead when
|
timeout, and we recommend to use ``StdioConnectionParams`` instead when
|
||||||
timeout is needed.
|
timeout is needed.
|
||||||
tool_filter: Optional filter to select specific tools. Can be either: - A
|
tool_filter: Optional filter to select specific tools. Can be either: - A
|
||||||
list of tool names to include - A ToolPredicate function for custom
|
list of tool names to include - A ToolPredicate function for custom
|
||||||
|
|||||||
@@ -12,6 +12,8 @@
|
|||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
from typing import Any
|
from typing import Any
|
||||||
@@ -39,8 +41,8 @@ logger = logging.getLogger("google_adk." + __name__)
|
|||||||
class OpenAPIToolset(BaseToolset):
|
class OpenAPIToolset(BaseToolset):
|
||||||
"""Class for parsing OpenAPI spec into a list of RestApiTool.
|
"""Class for parsing OpenAPI spec into a list of RestApiTool.
|
||||||
|
|
||||||
Usage:
|
Usage::
|
||||||
```
|
|
||||||
# Initialize OpenAPI toolset from a spec string.
|
# Initialize OpenAPI toolset from a spec string.
|
||||||
openapi_toolset = OpenAPIToolset(spec_str=openapi_spec_str,
|
openapi_toolset = OpenAPIToolset(spec_str=openapi_spec_str,
|
||||||
spec_str_type="json")
|
spec_str_type="json")
|
||||||
@@ -55,7 +57,6 @@ class OpenAPIToolset(BaseToolset):
|
|||||||
agent = Agent(
|
agent = Agent(
|
||||||
tools=[openapi_toolset.get_tool('tool_name')]
|
tools=[openapi_toolset.get_tool('tool_name')]
|
||||||
)
|
)
|
||||||
```
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
@@ -70,8 +71,8 @@ class OpenAPIToolset(BaseToolset):
|
|||||||
):
|
):
|
||||||
"""Initializes the OpenAPIToolset.
|
"""Initializes the OpenAPIToolset.
|
||||||
|
|
||||||
Usage:
|
Usage::
|
||||||
```
|
|
||||||
# Initialize OpenAPI toolset from a spec string.
|
# Initialize OpenAPI toolset from a spec string.
|
||||||
openapi_toolset = OpenAPIToolset(spec_str=openapi_spec_str,
|
openapi_toolset = OpenAPIToolset(spec_str=openapi_spec_str,
|
||||||
spec_str_type="json")
|
spec_str_type="json")
|
||||||
@@ -86,7 +87,6 @@ class OpenAPIToolset(BaseToolset):
|
|||||||
agent = Agent(
|
agent = Agent(
|
||||||
tools=[openapi_toolset.get_tool('tool_name')]
|
tools=[openapi_toolset.get_tool('tool_name')]
|
||||||
)
|
)
|
||||||
```
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
spec_dict: The OpenAPI spec dictionary. If provided, it will be used
|
spec_dict: The OpenAPI spec dictionary. If provided, it will be used
|
||||||
@@ -96,10 +96,10 @@ class OpenAPIToolset(BaseToolset):
|
|||||||
spec_str_type: The type of the OpenAPI spec string. Can be "json" or
|
spec_str_type: The type of the OpenAPI spec string. Can be "json" or
|
||||||
"yaml".
|
"yaml".
|
||||||
auth_scheme: The auth scheme to use for all tools. Use AuthScheme or use
|
auth_scheme: The auth scheme to use for all tools. Use AuthScheme or use
|
||||||
helpers in `google.adk.tools.openapi_tool.auth.auth_helpers`
|
helpers in ``google.adk.tools.openapi_tool.auth.auth_helpers``
|
||||||
auth_credential: The auth credential to use for all tools. Use
|
auth_credential: The auth credential to use for all tools. Use
|
||||||
AuthCredential or use helpers in
|
AuthCredential or use helpers in
|
||||||
`google.adk.tools.openapi_tool.auth.auth_helpers`
|
``google.adk.tools.openapi_tool.auth.auth_helpers``
|
||||||
tool_filter: The filter used to filter the tools in the toolset. It can be
|
tool_filter: The filter used to filter the tools in the toolset. It can be
|
||||||
either a tool predicate or a list of tool names of the tools to expose.
|
either a tool predicate or a list of tool names of the tools to expose.
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -70,13 +70,12 @@ class RestApiTool(BaseTool):
|
|||||||
* Generates request params and body
|
* Generates request params and body
|
||||||
* Attaches auth credentials to API call.
|
* Attaches auth credentials to API call.
|
||||||
|
|
||||||
Example:
|
Example::
|
||||||
```
|
|
||||||
# Each API operation in the spec will be turned into its own tool
|
# Each API operation in the spec will be turned into its own tool
|
||||||
# Name of the tool is the operationId of that operation, in snake case
|
# Name of the tool is the operationId of that operation, in snake case
|
||||||
operations = OperationGenerator().parse(openapi_spec_dict)
|
operations = OperationGenerator().parse(openapi_spec_dict)
|
||||||
tool = [RestApiTool.from_parsed_operation(o) for o in operations]
|
tool = [RestApiTool.from_parsed_operation(o) for o in operations]
|
||||||
```
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
@@ -92,13 +91,12 @@ class RestApiTool(BaseTool):
|
|||||||
"""Initializes the RestApiTool with the given parameters.
|
"""Initializes the RestApiTool with the given parameters.
|
||||||
|
|
||||||
To generate RestApiTool from OpenAPI Specs, use OperationGenerator.
|
To generate RestApiTool from OpenAPI Specs, use OperationGenerator.
|
||||||
Example:
|
Example::
|
||||||
```
|
|
||||||
# Each API operation in the spec will be turned into its own tool
|
# Each API operation in the spec will be turned into its own tool
|
||||||
# Name of the tool is the operationId of that operation, in snake case
|
# Name of the tool is the operationId of that operation, in snake case
|
||||||
operations = OperationGenerator().parse(openapi_spec_dict)
|
operations = OperationGenerator().parse(openapi_spec_dict)
|
||||||
tool = [RestApiTool.from_parsed_operation(o) for o in operations]
|
tool = [RestApiTool.from_parsed_operation(o) for o in operations]
|
||||||
```
|
|
||||||
|
|
||||||
Hint: Use google.adk.tools.openapi_tool.auth.auth_helpers to construct
|
Hint: Use google.adk.tools.openapi_tool.auth.auth_helpers to construct
|
||||||
auth_scheme and auth_credential.
|
auth_scheme and auth_credential.
|
||||||
|
|||||||
Reference in New Issue
Block a user