功能工具¶
当现成的 ADK 工具无法满足您的需求时,您可以自行创建自定义的 ADK 工具。
```javascript
function tools {
// ...
}
```构建函数工具(Building function tools)允许您创建定制化的功能,例如连接到专有数据库或实现独特的算法。例如,某个函数工具就可以用于实现这样的功能。 myfinancetool这个函数可能用于计算某个特定的财务指标。ADK 还支持长时间运行的函数;因此,如果该计算需要花费一些时间,代理程序可以继续执行其他任务。
ADK 提供了多种创建函数工具的方法,每种方法都适用于不同的复杂性和控制需求:
功能工具¶
将 Python 函数转换为一个工具,是一种将自定义逻辑集成到代理(agents)中的简单方法。当你将某个函数分配给某个代理时…… tools
当列表(list)被传递给该框架时,框架会自动将其包装成一个(specific structure)。 FunctionTool.
它是如何工作的?¶
ADK框架会自动检查你的Python函数的签名(包括函数名称、文档字符串、参数、类型提示以及默认值),从而生成一个描述该函数结构的“模式”(schema)。这个模式会被大型语言模型(LLM)用来理解该函数的用途、使用时机以及它所需的参数。
定义函数签名¶
一个定义明确的函数签名对于大型语言模型(LLM)正确使用您的工具至关重要。
参数¶
参数决定了您的工具在被调用时期望接收的数据。您可以根据工具的实际需求,将这些参数配置为“必填”或“可选”类型。
必填参数¶
一个参数被视为(important/relevant, etc.)…… required 如果该类型有类型提示(type hint),但是…… no
默认值当大型语言模型(LLM)调用该工具时,必须为该参数提供一个值。ADK 并不提供针对每个参数的详细说明;整个文档字符串(docstring)就构成了该工具的顶层文档内容。 description请对每个参数进行详细描述。
示例:必需的参数
def get_weather(city: str, unit: str):
"""
Retrieves the weather for a city in the specified unit.
Args:
city (str): The city name.
unit (str): The temperature unit, either 'Celsius' or 'Fahrenheit'.
"""
# ... function logic ...
return {"status": "success", "report": f"Weather for {city} is sunny."}
在这个例子中,两者都是…… city 和 unit 这些字段是必填的。如果大型语言模型(LLM)尝试调用…… get_weather 如果缺少其中任何一个组件,ADK 会向 LLM 返回错误信息,从而促使 LLM 更正其调用方式。
在 Go 语言中,你可以使用 `struct` 标签来控制 JSON 数据的结构。两个主要的 `struct` 标签是…… json 和 jsonschema.
一个参数被视为(important/relevant, etc.)…… required 如果该结构体的字段满足某个条件(即该字段的值符合某个要求),那么…… 不;并非 拥有;具有 omitempty 或者 omitzero “option in its”这个短语的意思是“某个选项属于(或包含于)某个更大的集合或系统之中”。例如:“This specific option is part of the overall menu system.”(这个具体的选项属于整个菜单系统的一部分。) json tag.
The jsonschema `tag` 用于提供参数的描述。这对于大型语言模型(LLM)来说至关重要,因为它需要理解该参数的具体用途。
示例:必需的参数
// GetWeatherParams defines the arguments for the getWeather tool.
type GetWeatherParams struct {
// This field is REQUIRED (no "omitempty").
// The jsonschema tag provides the description.
Location string `json:"location" jsonschema:"The city and state, e.g., San Francisco, CA"`
// This field is also REQUIRED.
Unit string `json:"unit" jsonschema:"The temperature unit, either 'celsius' or 'fahrenheit'"`
}
在这个例子中,两者都是…… location 和 unit 这些字段是必填的。
在 Java 中,基本数据类型(例如:int、float、char 等) int, double, boolean)本质上是……
required 因为这些值不能为 `null`。对于对象类型(例如……)来说…… String 或者
Integer除非明确标注为“可选”,否则这些内容通常被视为必需的。
The @Schema 注释用于提供参数的描述,并可以明确地定义参数的属性。这对于大型语言模型(LLM)来说至关重要,因为模型需要理解这些参数的具体用途。
示例:必需的参数
// The @Schema annotation on the parameter provides the description.
public static Map<String, Object> getWeather(
@Schema(description = "The city and state, e.g., San Francisco, CA", name = "location")
String location,
@Schema(description = "The temperature unit, either 'Celsius' or 'Fahrenheit'", name = "unit")
String unit) {
// ... function logic ...
return Map.of("status", "success", "report", "Weather for " + location + " is sunny.");
}
在这个例子中,两者都是…… location 和 unit 这些字段是必填的。
在 Kotlin 中,参数被视为……(In Kotlin, parameters are considered……) required 默认情况下,如果这些参数属于“不可为空”(non-nullable)类型且没有默认值,那么大型语言模型(LLM)必须为这些参数提供一个具体的值。
The @Param 注释用于提供参数的描述。这对于大型语言模型(LLM)理解该参数的用途至关重要。
示例:必需的参数
class WeatherService {
/**
* Retrieves the weather for a city in the specified unit.
*/
@Tool
fun getWeather(
@Param("The city and state, e.g., San Francisco, CA") location: String,
@Param("The temperature unit, either 'Celsius' or 'Fahrenheit'") unit: String,
): String {
// ... function logic ...
return "Weather for $location is sunny in $unit."
}
}
在这个例子中,两者都是…… location 和 unit 这些字段是必填的。
可选参数¶
一个参数被视为(important/relevant, etc.)…… 可选的 “只有在你提供……的情况下才行。” default
value这种方法是一种标准的 Python 方式,用于定义可选参数。
通过注释来说明某个参数的性质或用途,可以增加代码的可读性。 typing.Optional[SomeType] 或者 | None
语法(Python 3.10+)确实支持该功能。 不;并非 将该参数设置为可选的:如果没有默认值,该参数仍然属于必填项。
只有那些真正可选的参数才应该使用默认值;对于那些需要从用户请求中获取的信息,或者需要用户自行提供的信息,切勿为其设置默认值。
示例:可选参数
def search_flights(destination: str, departure_date: str, flexible_days: int = 0):
"""
Searches for flights.
Args:
destination (str): The destination city.
departure_date (str): The desired departure date.
flexible_days (int, optional): Number of flexible days for the search. Defaults to 0.
"""
# ... function logic ...
if flexible_days > 0:
return {"status": "success", "report": f"Found flexible flights to {destination}."}
return {"status": "success", "report": f"Found flights to {destination} on {departure_date}."}
在这里, flexible_days 这是可选的。大型语言模型(LLM)可以选择是否提供该信息,但并不是必须提供的。
一个参数被视为(important/relevant, etc.)…… 可选的 如果该结构体的字段具有(某种特性或值)……
omitempty 或者 omitzero “option in its”这个短语的意思是“某个选项属于(或包含于)某个更大的集合或系统之中”。例如:“This specific option is part of the overall menu system.”(这个具体的选项属于整个菜单系统的一部分。) json tag.
示例:可选参数
// GetWeatherParams defines the arguments for the getWeather tool.
type GetWeatherParams struct {
// Location is required.
Location string `json:"location" jsonschema:"The city and state, e.g., San Francisco, CA"`
// Unit is optional.
Unit string `json:"unit,omitempty" jsonschema:"The temperature unit, either 'celsius' or 'fahrenheit'"`
// Days is optional.
Days int `json:"days,omitzero" jsonschema:"The number of forecast days to return (defaults to 1)"`
}
在这里, unit 和 days 这些信息是可选的。大型语言模型(LLM)可以选择是否提供它们,但它们并不是必须提供的。
一个参数可以被视作……(具体含义需根据上下文确定)。 可选的 在 Java 中,可以通过使用允许某种操作的对象类型来实现相关功能。 null 值(例如: Integer 而不是 int);或者通过明确将其定义为可选项(即允许用户不提供该值)来实现。 java.util.Optional.
示例:可选参数
import java.util.Map;
import java.util.Optional;
public static Map<String, Object> searchFlights(
@Schema(description = "The destination city.", name = "destination")
String destination,
@Schema(description = "The desired departure date.", name = "departureDate")
String departureDate,
@Schema(description = "Number of flexible days for the search. Defaults to 0.", name = "flexibleDays")
Optional<Integer> flexibleDays) {
// ... function logic ...
int days = flexibleDays.orElse(0);
if (days > 0) {
return Map.of("status", "success", "report", "Found flexible flights to " + destination + ".");
}
return Map.of("status", "success", "report", "Found flights to " + destination + " on " + departureDate + ".");
}
在这里, flexibleDays 这是可选的。大型语言模型(LLM)可以选择是否提供该信息,但并不是必须提供的。
在 Kotlin 中,参数被视为…… 可选的 如果它是……的话(if it is of a……) `nullable` `type` 或者,如果它具有…… 默认值.
示例:可选参数
class FlightService {
/**
* Searches for flights.
*/
@Tool
fun searchFlights(
@Param("The destination city.") destination: String,
@Param("The desired departure date.") departureDate: String,
@Param("Number of flexible days for the search. Defaults to 0.") flexibleDays: Int? = 0,
): String {
// ... function logic ...
val days = flexibleDays ?: 0
if (days > 0) {
return "Found flexible flights to $destination."
}
return "Found flights to $destination on $departureDate."
}
}
在这里, flexibleDays 这是可选的。大型语言模型(LLM)可以选择是否提供该信息,但并不是必须提供的。
可选参数(Optional parameters): typing.Optional¶
使用 typing.Optional[SomeType] 或者 | None 语法(Python 3.10+)用于表示:该参数是可以被……的(即该参数具有某种特定的用途或可以被某种方式处理)。 None将其与一个默认值结合使用。 None 为了获得一个标准的可选参数,必须使用特定的注解;如果仅使用注解本身,该参数仍会被视为“必需的”(即用户必须提供该参数的值)。
示例: typing.Optional
from typing import Optional
def create_user_profile(username: str, bio: Optional[str] = None):
"""
Creates a new user profile.
Args:
username (str): The user's unique username.
bio (str, optional): A short biography for the user. Defaults to None.
"""
# ... function logic ...
if bio:
return {"status": "success", "message": f"Profile for {username} created with a bio."}
return {"status": "success", "message": f"Profile for {username} created."}
Pydantic 模型参数¶
用 “a” 为某个参数添加注释。 pydantic.BaseModel 子类(subclass),或者通过其他方式(with)
list[Model], Optional[Model]或者是一些模型的组合(union of models)。ADK会将模型的架构(schema)嵌入到工具声明(tool declaration)中,并在函数执行之前,将大型语言模型(LLM)提供的对象转换为你的类(class)的一个实例(instance)。
示例:Pydantic模型参数
import pydantic
class UserProfile(pydantic.BaseModel):
"""A user's profile."""
name: str
age: int
def create_user(profile: UserProfile):
"""
Creates a user account.
Args:
profile (UserProfile): The profile to create the account from.
"""
# 'profile' receives a UserProfile instance, not a dict.
return {"status": "success", "name": profile.name}
可变参数(Variadic parameters)*args 和 **kwargs)¶
虽然你可以包含…… *args (可变的位置参数)以及 **kwargs
在函数签名中使用变量(即关键字参数)来实现其他用途时,这些变量确实可以发挥重要作用。 被 ADK 框架忽略 在为大型语言模型(LLM)生成工具架构时,需要注意的是:该模型本身并不会意识到这些工具的存在,也无法向它们传递任何参数。因此,对于从 LLM 中获取的所有数据,最好都依赖那些被明确定义的参数。
上下文注入(Context Injection)¶
上下文注入(Context Injection)允许您的自定义函数访问代理的环境信息,例如会话状态(session state)或可用的操作(available actions)。要启用该功能,请添加一个参数,其类型应为…… ToolContext 将这些数据传递给您的函数。ADK 会在您的函数运行之前自动注入这些上下文数据,并确保这些参数对大型语言模型(LLM)是不可见的。
from google.adk.tools import ToolContext
def my_tool(arg1: str, tool_context: ToolContext):
# Example: Accessing session state
user_id = tool_context.state.get("user_id")
# Example: Triggering an action
# tool_context.actions.transfer_to_agent = "secondary_agent"
ToolContext 提供对以下内容的访问权限:
state: 一个用于存储会话级数据的、类似字典的对象。actions: 用于控制代理行为的设置(例如)transfer_to_agent.- 方法(Methods):为了处理各种工件(artifacts),例如……
load_artifact或者save_artifact.
自定义参数名称¶
默认情况下,被注入的参数被称为 “ injected parameter”。 tool_context你可以随意为该参数起名。ADK 会通过该参数的特定特征来识别它。 ToolContext 应通过注释来指定类型,而不是直接使用类型名称。例如,如果要使用某个特定的类型名称,就需要通过相应的注释来进行说明。 ctx:
from google.adk.tools import ToolContext
def my_tool(arg1: str, ctx: ToolContext):
# 'ctx' receives the ToolContext because of its type annotation
user_id = ctx.state.get("user_id")
返回类型¶
Function Tool 首选的返回类型是…… 字典 在 Python 中,一个……(in Python, a……) 地图(Map) 或自定义 记录(Record)或 POJO(Plain Old Java Object) 在 Java 中,一个……(in Java, an……) 对象 在 TypeScript 中,或者是一个…… 地图(Map) 或者 数据类(Data Class) 在 Kotlin 中,你可以使用键值对(key-value pairs)来结构化响应数据,从而为大型语言模型(LLM)提供清晰的上下文信息。如果你的函数返回的数据类型不是字典(dictionary)或映射(map),框架会自动将其包装成一个以特定键(single key)为名的字典。 “result”.
请尽量让你的返回值具有较高的描述性(即能够清晰地表达返回的数据的含义)。 例如, 不要返回一个数字形式的错误代码,而是返回一个字典,该字典中包含一个名为 “error_message” 的键,其中存放了可供人类阅读的错误说明。 请记住: **LLM(大型语言模型)**这并不是一段代码,而是需要理解执行结果的部分。作为最佳实践,应在返回的字典中添加一个名为 “status” 的键,以指示整个操作的结果(例如 “success”(成功)、“error”(错误)或 “pending”(待处理),从而为大型语言模型(LLM)提供一个关于操作状态的明确信号。
文档字符串(Docstrings)¶
你函数的文档字符串(docstring)充当了该工具的说明文档。 描述(description) 该文档会被发送给大型语言模型(LLM)。因此,一份编写得当且内容全面的文档字符串对于大型语言模型来说至关重要——它能够帮助模型理解如何有效地使用该工具。你需要清楚地说明函数的功能、参数的含义以及预期的返回值。在 Java 中,你可以使用 Javadoc 注释来实现这一点。
@Schema(description="...") 在你的方法上添加注释,作为方法的描述。在 Kotlin 中,你可以使用 KDoc 注释来实现这一功能。
@Tool(description="...") 和 @Param(description="...") 这些注释用于提供相应的描述信息。
在工具之间传递数据¶
当代理按顺序调用多个工具时,可能需要将数据从一个工具传递到另一个工具。推荐的做法是使用……(此处应填写具体的数据传递方法或技术)。 temp:
会话状态中的前缀(prefix)。
一个工具可以将数据写入到…… temp: 该数据会被存储在一个变量中,后续的工具可以读取这个变量中的内容。
这些数据仅对当前的调用过程有效,在调用结束后就会被丢弃。
共享调用上下文(Shared Invocation Context)
在一个代理(agent)内部,所有工具调用(tool calls)都会共享相同的资源或数据。
InvocationContext这意味着它们也共享相同的临时文件(或资源)。temp:状态(state)是数据在它们之间传递的方式。
示例:¶
示例:
这个工具是一个 Python 函数,它可以获取给定股票代码(Stock ticker/symbol)对应的股票价格。
注意:你需要…… pip install yfinance 在使用此工具之前,请先安装相应的库。
# 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 asyncio
from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
import yfinance as yf
APP_NAME = "stock_app"
USER_ID = "1234"
SESSION_ID = "session1234"
def get_stock_price(symbol: str):
"""
Retrieves the current stock price for a given symbol.
Args:
symbol (str): The stock symbol (e.g., "AAPL", "GOOG").
Returns:
float: The current stock price, or None if an error occurs.
"""
try:
stock = yf.Ticker(symbol)
historical_data = stock.history(period="1d")
if not historical_data.empty:
current_price = historical_data['Close'].iloc[-1]
return current_price
else:
return None
except Exception as e:
print(f"Error retrieving stock price for {symbol}: {e}")
return None
stock_price_agent = Agent(
model='gemini-2.0-flash',
name='stock_agent',
instruction= 'You are an agent who retrieves stock prices. If a ticker symbol is provided, fetch the current price. If only a company name is given, first perform a Google search to find the correct ticker symbol before retrieving the stock price. If the provided ticker symbol is invalid or data cannot be retrieved, inform the user that the stock price could not be found.',
description='This agent specializes in retrieving real-time stock prices. Given a stock ticker symbol (e.g., AAPL, GOOG, MSFT) or the stock name, use the tools and reliable data sources to provide the most up-to-date price.',
tools=[get_stock_price], # You can add Python functions directly to the tools list; they will be automatically wrapped as FunctionTools.
)
# Session and Runner
async def setup_session_and_runner():
session_service = InMemorySessionService()
session = await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
runner = Runner(agent=stock_price_agent, app_name=APP_NAME, session_service=session_service)
return session, runner
# Agent Interaction
async def call_agent_async(query):
content = types.Content(role='user', parts=[types.Part(text=query)])
session, runner = await setup_session_and_runner()
events = runner.run_async(user_id=USER_ID, session_id=SESSION_ID, new_message=content)
async for event in events:
if event.is_final_response() and event.content and event.content.parts:
final_response = event.content.parts[0].text
print("Agent Response: ", final_response)
async def main():
await call_agent_async("stock price of GOOG")
# Note: In Colab, you can directly 'await call_agent_async(...)' at the top level.
if __name__ == "__main__":
asyncio.run(main())
这个工具返回的值会被封装成一个字典(dictionary)。
该工具用于获取模拟后的股票价格数据。
/**
* 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 {Content, Part, createUserContent} from '@google/genai';
import { stringifyContent, FunctionTool, InMemoryRunner, LlmAgent } from '@google/adk';
import {z} from 'zod';
// Define the function to get the stock price
async function getStockPrice({ticker}: {ticker: string}): Promise<Record<string, unknown>> {
console.log(`Getting stock price for ${ticker}`);
// In a real-world scenario, you would fetch the stock price from an API
const price = (Math.random() * 1000).toFixed(2);
return {price: `$${price}`};
}
async function main() {
// Define the schema for the tool's parameters using Zod
const getStockPriceSchema = z.object({
ticker: z.string().describe('The stock ticker symbol to look up.'),
});
// Create a FunctionTool from the function and schema
const stockPriceTool = new FunctionTool({
name: 'getStockPrice',
description: 'Gets the current price of a stock.',
parameters: getStockPriceSchema,
execute: getStockPrice,
});
// Define the agent that will use the tool
const stockAgent = new LlmAgent({
name: 'stock_agent',
model: 'gemini-2.5-flash',
instruction: 'You can get the stock price of a company.',
tools: [stockPriceTool],
});
// Create a runner for the agent
const runner = new InMemoryRunner({agent: stockAgent});
// Create a new session
const session = await runner.sessionService.createSession({
appName: runner.appName,
userId: 'test-user',
});
const userContent: Content = createUserContent('What is the stock price of GOOG?');
// Run the agent and get the response
const response = [];
for await (const event of runner.runAsync({
userId: session.userId,
sessionId: session.id,
newMessage: userContent,
})) {
response.push(event);
}
// Print the final response from the agent
const finalResponse = response[response.length - 1];
if (finalResponse?.content?.parts?.length) {
console.log(stringifyContent(finalResponse));
}
}
main();
这个工具返回的值将是一个对象。
该工具用于获取模拟后的股票价格数据。
import (
"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/model/gemini"
"google.golang.org/adk/v2/runner"
"google.golang.org/adk/v2/session"
"google.golang.org/adk/v2/tool"
"google.golang.org/adk/v2/tool/functiontool"
"google.golang.org/genai"
)
// 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.
package main
import (
"context"
"fmt"
"log"
"strings"
"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/model/gemini"
"google.golang.org/adk/v2/runner"
"google.golang.org/adk/v2/session"
"google.golang.org/adk/v2/tool"
"google.golang.org/adk/v2/tool/agenttool"
"google.golang.org/adk/v2/tool/functiontool"
"google.golang.org/genai"
)
// mockStockPrices provides a simple in-memory database of stock prices
// to simulate a real-world stock data API. This allows the example to
// demonstrate tool functionality without making external network calls.
var mockStockPrices = map[string]float64{
"GOOG": 300.6,
"AAPL": 123.4,
"MSFT": 234.5,
}
// getStockPriceArgs defines the schema for the arguments passed to the getStockPrice tool.
// Using a struct is the recommended approach in the Go ADK as it provides strong
// typing and clear validation for the expected inputs.
type getStockPriceArgs struct {
Symbol string `json:"symbol" jsonschema:"The stock ticker symbol, e.g., GOOG"`
}
// getStockPriceResults defines the output schema for the getStockPrice tool.
type getStockPriceResults struct {
Symbol string `json:"symbol"`
Price float64 `json:"price,omitempty"`
Error string `json:"error,omitempty"`
}
// getStockPrice is a tool that retrieves the stock price for a given ticker symbol
// from the mockStockPrices map. It demonstrates how a function can be used as a
// tool by an agent. If the symbol is found, it returns a struct containing the
// symbol and its price. Otherwise, it returns a struct with an error message.
func getStockPrice(ctx agent.Context, input getStockPriceArgs) (getStockPriceResults, error) {
symbolUpper := strings.ToUpper(input.Symbol)
if price, ok := mockStockPrices[symbolUpper]; ok {
fmt.Printf("Tool: Found price for %s: %f\n", input.Symbol, price)
return getStockPriceResults{Symbol: input.Symbol, Price: price}, nil
}
return getStockPriceResults{}, fmt.Errorf("no data found for symbol")
}
// createStockAgent initializes and configures an LlmAgent.
// This agent is equipped with the getStockPrice tool and is instructed
// on how to respond to user queries about stock prices. It uses the
// Gemini model to understand user intent and decide when to use its tools.
func createStockAgent(ctx context.Context) (agent.Agent, error) {
stockPriceTool, err := functiontool.New(
functiontool.Config{
Name: "get_stock_price",
Description: "Retrieves the current stock price for a given symbol.",
},
getStockPrice)
if err != nil {
return nil, err
}
model, err := gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
if err != nil {
log.Fatalf("Failed to create model: %v", err)
}
return llmagent.New(llmagent.Config{
Name: "stock_agent",
Model: model,
Instruction: "You are an agent who retrieves stock prices. If a ticker symbol is provided, fetch the current price. If only a company name is given, first perform a Google search to find the correct ticker symbol before retrieving the stock price. If the provided ticker symbol is invalid or data cannot be retrieved, inform the user that the stock price could not be found.",
Description: "This agent specializes in retrieving real-time stock prices. Given a stock ticker symbol (e.g., AAPL, GOOG, MSFT) or the stock name, use the tools and reliable data sources to provide the most up-to-date price.",
Tools: []tool.Tool{
stockPriceTool,
},
})
}
// userID and appName are constants used to identify the user and application
// throughout the session. These values are important for logging, tracking,
// and managing state across different agent interactions.
const (
userID = "example_user_id"
appName = "example_app"
)
// callAgent orchestrates the execution of the agent for a given prompt.
// It sets up the necessary services, creates a session, and uses a runner
// to manage the agent's lifecycle. It streams the agent's responses and
// prints them to the console, handling any potential errors during the run.
func callAgent(ctx context.Context, a agent.Agent, prompt string) {
sessionService := session.InMemoryService()
// Create a new session for the agent interactions.
session, err := sessionService.Create(ctx, &session.CreateRequest{
AppName: appName,
UserID: userID,
})
if err != nil {
log.Fatalf("Failed to create the session service: %v", err)
}
config := runner.Config{
AppName: appName,
Agent: a,
SessionService: sessionService,
}
// Create the runner to manage the agent execution.
r, err := runner.New(config)
if err != nil {
log.Fatalf("Failed to create the runner: %v", err)
}
sessionID := session.Session.ID()
userMsg := &genai.Content{
Parts: []*genai.Part{
genai.NewPartFromText(prompt),
},
Role: string(genai.RoleUser),
}
for event, err := range r.Run(ctx, userID, sessionID, userMsg, agent.RunConfig{
StreamingMode: agent.StreamingModeNone,
}) {
if err != nil {
fmt.Printf("\nAGENT_ERROR: %v\n", err)
} else {
for _, p := range event.Content.Parts {
fmt.Print(p.Text)
}
}
}
}
// RunAgentSimulation serves as the entry point for this example.
// It creates the stock agent and then simulates a series of user interactions
// by sending different prompts to the agent. This function showcases how the
// agent responds to various queries, including both successful and unsuccessful
// attempts to retrieve stock prices.
func RunAgentSimulation() {
// Create the stock agent
agent, err := createStockAgent(context.Background())
if err != nil {
panic(err)
}
fmt.Println("Agent created:", agent.Name())
prompts := []string{
"stock price of GOOG",
"What's the price of MSFT?",
"Can you find the stock price for an unknown company XYZ?",
}
// Simulate running the agent with different prompts
for _, prompt := range prompts {
fmt.Printf("\nPrompt: %s\nResponse: ", prompt)
callAgent(context.Background(), agent, prompt)
fmt.Println("\n---")
}
}
// createSummarizerAgent creates an agent whose sole purpose is to summarize text.
func createSummarizerAgent(ctx context.Context) (agent.Agent, error) {
model, err := gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
if err != nil {
return nil, err
}
return llmagent.New(llmagent.Config{
Name: "SummarizerAgent",
Model: model,
Instruction: "You are an expert at summarizing text. Take the user's input and provide a concise summary.",
Description: "An agent that summarizes text.",
})
}
// createMainAgent creates the primary agent that will use the summarizer agent as a tool.
func createMainAgent(ctx context.Context, tools ...tool.Tool) (agent.Agent, error) {
model, err := gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
if err != nil {
return nil, err
}
return llmagent.New(llmagent.Config{
Name: "MainAgent",
Model: model,
Instruction: "You are a helpful assistant. If you are asked to summarize a long text, use the 'summarize' tool. " +
"After getting the summary, present it to the user by saying 'Here is a summary of the text:'.",
Description: "The main agent that can delegate tasks.",
Tools: tools,
})
}
func RunAgentAsToolSimulation() {
ctx := context.Background()
// 1. Create the Tool Agent (Summarizer)
summarizerAgent, err := createSummarizerAgent(ctx)
if err != nil {
log.Fatalf("Failed to create summarizer agent: %v", err)
}
// 2. Wrap the Tool Agent in an AgentTool
summarizeTool := agenttool.New(summarizerAgent, &agenttool.Config{
SkipSummarization: true,
})
// 3. Create the Main Agent and provide it with the AgentTool
mainAgent, err := createMainAgent(ctx, summarizeTool)
if err != nil {
log.Fatalf("Failed to create main agent: %v", err)
}
// 4. Run the main agent
prompt := `
Please summarize this text for me:
Quantum computing represents a fundamentally different approach to computation,
leveraging the bizarre principles of quantum mechanics to process information. Unlike classical computers
that rely on bits representing either 0 or 1, quantum computers use qubits which can exist in a state of superposition - effectively
being 0, 1, or a combination of both simultaneously. Furthermore, qubits can become entangled,
meaning their fates are intertwined regardless of distance, allowing for complex correlations. This parallelism and
interconnectedness grant quantum computers the potential to solve specific types of incredibly complex problems - such
as drug discovery, materials science, complex system optimization, and breaking certain types of cryptography - far
faster than even the most powerful classical supercomputers could ever achieve, although the technology is still largely in its developmental stages.
`
fmt.Printf("\nPrompt: %s\nResponse: ", prompt)
callAgent(context.Background(), mainAgent, prompt)
fmt.Println("\n---")
}
func main() {
fmt.Println("Attempting to run the agent simulation...")
RunAgentSimulation()
fmt.Println("\nAttempting to run the agent-as-a-tool simulation...")
RunAgentAsToolSimulation()
}
这个工具的返回值将是一个……(具体内容需要根据实际情况填写)。 getStockPriceResults `instance.`
该工具用于获取模拟后的股票价格数据。
import com.google.adk.agents.LlmAgent;
import com.google.adk.events.Event;
import com.google.adk.runner.InMemoryRunner;
import com.google.adk.sessions.Session;
import com.google.adk.tools.Annotations.Schema;
import com.google.adk.tools.FunctionTool;
import com.google.genai.types.Content;
import com.google.genai.types.Part;
import io.reactivex.rxjava3.core.Flowable;
import java.util.Map;
import yahoofinance.Stock;
import yahoofinance.YahooFinance;
import java.math.BigDecimal;
public class StockPriceAgent {
private static final String APP_NAME = "stock_agent";
private static final String USER_ID = "user1234";
// No longer using mock stock data - we fetch it live!
@Schema(description = "Retrieves the current stock price for a given symbol.")
public static Map<String, Object> getStockPrice(
@Schema(description = "The stock symbol (e.g., \"AAPL\", \"GOOG\")",
name = "symbol")
String symbol) {
try {
Stock stock = YahooFinance.get(symbol.toUpperCase());
if (stock != null && stock.getQuote().getPrice() != null) {
BigDecimal currentPrice = stock.getQuote().getPrice();
System.out.println("Tool: Found live price for " + symbol + ": " + currentPrice);
return Map.of("symbol", symbol, "price", currentPrice.doubleValue());
} else {
return Map.of("symbol", symbol, "error", "No data found for symbol");
}
} catch (Exception e) {
return Map.of("symbol", symbol, "error", e.getMessage());
}
}
public static void callAgent(String prompt) {
// Create the FunctionTool from the Java method
FunctionTool getStockPriceTool = FunctionTool.create(StockPriceAgent.class, "getStockPrice");
LlmAgent stockPriceAgent =
LlmAgent.builder()
.model("gemini-2.0-flash")
.name("stock_agent")
.instruction(
"You are an agent who retrieves stock prices. If a ticker symbol is provided, fetch the current price. If only a company name is given, first perform a Google search to find the correct ticker symbol before retrieving the stock price. If the provided ticker symbol is invalid or data cannot be retrieved, inform the user that the stock price could not be found.")
.description(
"This agent specializes in retrieving real-time stock prices. Given a stock ticker symbol (e.g., AAPL, GOOG, MSFT) or the stock name, use the tools and reliable data sources to provide the most up-to-date price.")
.tools(getStockPriceTool) // Add the Java FunctionTool
.build();
// Create an InMemoryRunner
InMemoryRunner runner = new InMemoryRunner(stockPriceAgent, APP_NAME);
// InMemoryRunner automatically creates a session service. Create a session using the service
Session session = runner.sessionService().createSession(APP_NAME, USER_ID).blockingGet();
Content userMessage = Content.fromParts(Part.fromText(prompt));
// Run the agent
Flowable<Event> eventStream = runner.runAsync(USER_ID, session.id(), userMessage);
// Stream event response
eventStream.blockingForEach(
event -> {
if (event.finalResponse()) {
System.out.println(event.stringifyContent());
}
});
}
public static void main(String[] args) {
callAgent("stock price of GOOG");
callAgent("What's the price of MSFT?");
callAgent("Can you find the stock price for an unknown company XYZ?");
}
}
这个工具返回的值会被封装到一个 `Map` 对象中。
该工具用于获取模拟后的股票价格数据。
data class StockPrice(val symbol: String, val price: Double)
class StockService {
/**
* Retrieves the stock price for a given symbol.
*/
@Tool
fun getStockPrice(
@Param("The stock symbol, e.g. GOOG") symbol: String,
): StockPrice {
// In a real app, you would call a stock price API here.
return StockPrice(symbol = symbol, price = 123.45)
}
}
fun main() =
runBlocking {
val stockService = StockService()
val agent =
LlmAgent(
name = "stock_agent",
model = Gemini(name = "gemini-flash-latest"),
instruction = Instruction("You are a helpful stock assistant."),
// .generatedTools() is used to get the tools from the annotated class.
tools = stockService.generatedTools(),
)
// ... use the agent ...
}
这个工具返回的值将是一个 Map(映射对象)。
最佳实践¶
虽然你在定义函数时具有相当大的灵活性,但请记住:简单性会提升大型语言模型(LLM)的可用性。请参考以下指导原则:
- 参数越少越好: 尽量减少参数的数量,以降低系统的复杂性。
- 简单数据类型: 优先使用原始数据类型(如整数、浮点数、字符串等)。
str和int尽可能使用自定义类(custom classes)。 - 有意义的名称: 函数的名称及其参数的名称会显著影响大型语言模型(LLM)对该工具的解读和使用方式。请选择能够清晰反映函数用途及其输入参数含义的名称;避免使用诸如“generic_name”之类的通用名称。
do_stuff()或者beAgent(). - “为并行执行而设计”(Build for Parallel Execution): 当同时运行多个工具时,通过实现异步操作来提升函数调用的性能。有关如何为这些工具启用并行执行功能的详细信息,请参阅…… 通过并行执行来提升工具的性能。.
用于处理长时间运行的函数的工具¶
该工具旨在帮助您启动和管理那些需要在您的代理工作流程之外处理的任务;这些任务通常需要较长的处理时间,但不会阻塞代理的执行。该工具属于某个类的子类。 FunctionTool.
在使用……时(When using a……) LongRunningFunctionTool您的函数可以启动这个耗时较长的操作,并且可以选择性地返回一个结果。 初步结果例如,某个长时间运行的操作会生成一个唯一的操作 ID。当调用这个长时间运行的函数工具时,代理运行器会暂停代理的当前执行过程,然后由代理客户端来决定是继续执行任务,还是等待该长时间运行的操作完成。代理客户端可以查询该操作的进度,并返回相应的中间结果或最终结果;之后代理就可以继续执行其他任务了。一个典型的例子是“人工干预”场景:在这种情况下,代理在继续执行任务之前需要获得人类的批准。
警告:执行处理(Execution handling)
“Long Running Function Tools”(长时间运行的函数工具)旨在帮助您启动和……(后续内容未提供)。 管理;操作;处理 作为您的代理工作流程(agent workflow)的一部分,有些任务需要较长时间才能完成(即这些任务属于“耗时较长的任务”)。 不执行(某项操作或任务) 这个任务实际上非常耗时。对于那些需要很长时间才能完成的任务,你应该专门搭建一台服务器来专门处理这些任务。
提示:并行执行(Parallel execution)
根据您正在开发的工具类型,为异步操作进行设计可能比开发一个运行时间较长的工具更为合适。有关更多信息,请参阅…… 通过并行执行来提高工具的性能。.
它是如何工作的?¶
在 Python 中,你可以使用某种方式将一个函数“包裹”起来(即对其进行封装)。 LongRunningFunctionTool在 Java 中,你需要传递一个方法名称。 LongRunningFunctionTool.create()在 TypeScript 中,你需要通过 `new` 关键字来实例化(创建)一个对象或类。 LongRunningFunctionTool class.
- **Initiation:** 当大型语言模型(LLM)调用该工具时,你的函数会启动这个需要长时间运行的操作。
- 初始更新: 您的函数应可选择性地返回一个初始结果(例如,长时间运行的操作的 ID)。ADK 框架会接收该结果,并将其封装后发送回 LLM(大型语言模型)。
FunctionResponse这使大型语言模型(LLM)能够向用户提供信息(例如:任务状态、完成进度百分比、相关消息等)。之后,代理程序的运行就会结束或被暂停。 - “继续还是等待?” 每次代理程序运行完成后,代理客户端可以查询该长时间运行的操作的进度,并决定是否继续执行代理程序(此时会收到一个中间响应,用于更新进度信息),或者等待直到收到最终响应。无论收到的是中间响应还是最终响应,代理客户端都应将其发送回代理程序,以便进行下一次运行。
- 框架处理(Framework Handling): ADK框架负责管理程序的执行过程。它会发送中间结果或最终结果。
FunctionResponse由代理客户端发送给大型语言模型(LLM),以生成一条用户友好的消息。
创建这个工具。¶
定义你的工具函数,并使用相应的包装方式将其封装起来。 LongRunningFunctionTool class:
from typing import Any
from google.adk.tools import LongRunningFunctionTool
# 1. Define the long running function
def ask_for_approval(
purpose: str, amount: float
) -> dict[str, Any]:
"""Ask for approval for the reimbursement."""
# create a ticket for the approval
# Send a notification to the approver with the link of the ticket
return {'status': 'pending', 'approver': 'Sean Zhou', 'purpose' : purpose, 'amount': amount, 'ticket-id': 'approval-ticket-1'}
def reimburse(purpose: str, amount: float) -> dict[str, Any]:
"""Reimburse the amount of money to the employee."""
# send the reimbrusement request to payment vendor
return {'status': 'ok'}
# 2. Wrap the function with LongRunningFunctionTool
long_running_tool = LongRunningFunctionTool(func=ask_for_approval)
// 1. Define the long-running function
function askForApproval(args: {purpose: string; amount: number}) {
/**
* Ask for approval for the reimbursement.
*/
// create a ticket for the approval
// Send a notification to the approver with the link of the ticket
return {
"status": "pending",
"approver": "Sean Zhou",
"purpose": args.purpose,
"amount": args.amount,
"ticket-id": "approval-ticket-1",
};
}
// 2. Instantiate the LongRunningFunctionTool class with the long-running function
const longRunningTool = new LongRunningFunctionTool({
name: "ask_for_approval",
description: "Ask for approval for the reimbursement.",
parameters: z.object({
purpose: z.string().describe("The purpose of the reimbursement."),
amount: z.number().describe("The amount to reimburse."),
}),
execute: askForApproval,
});
import (
"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/model/gemini"
"google.golang.org/adk/v2/tool"
"google.golang.org/adk/v2/tool/functiontool"
"google.golang.org/genai"
)
// CreateTicketArgs defines the arguments for our long-running tool.
type CreateTicketArgs struct {
Urgency string `json:"urgency" jsonschema:"The urgency level of the ticket."`
}
// CreateTicketResults defines the *initial* output of our long-running tool.
type CreateTicketResults struct {
Status string `json:"status"`
TicketId string `json:"ticket_id"`
}
// createTicketAsync simulates the *initiation* of a long-running ticket creation task.
func createTicketAsync(ctx agent.Context, args CreateTicketArgs) (CreateTicketResults, error) {
log.Printf("TOOL_EXEC: 'create_ticket_long_running' called with urgency: %s (Call ID: %s)\n", args.Urgency, ctx.FunctionCallID())
// "Generate" a ticket ID and return it in the initial response.
ticketID := "TICKET-ABC-123"
log.Printf("ACTION: Generated Ticket ID: %s for Call ID: %s\n", ticketID, ctx.FunctionCallID())
// In a real application, you would save the association between the
// FunctionCallID and the ticketID to handle the async response later.
return CreateTicketResults{
Status: "started",
TicketId: ticketID,
}, nil
}
func createTicketAgent(ctx context.Context) (agent.Agent, error) {
ticketTool, err := functiontool.New(
functiontool.Config{
Name: "create_ticket_long_running",
Description: "Creates a new support ticket with a specified urgency level.",
IsLongRunning: true,
},
createTicketAsync,
)
if err != nil {
return nil, fmt.Errorf("failed to create long running tool: %w", err)
}
model, err := gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
if err != nil {
return nil, fmt.Errorf("failed to create model: %v", err)
}
return llmagent.New(llmagent.Config{
Name: "ticket_agent",
Model: model,
Instruction: "You are a helpful assistant for creating support tickets. Provide the status of the ticket at each interaction.",
Tools: []tool.Tool{ticketTool},
})
}
import com.google.adk.agents.LlmAgent;
import com.google.adk.tools.LongRunningFunctionTool;
import java.util.HashMap;
import java.util.Map;
public class ExampleLongRunningFunction {
// Define your Long Running function.
// Ask for approval for the reimbursement.
public static Map<String, Object> askForApproval(String purpose, double amount) {
// Simulate creating a ticket and sending a notification
System.out.println(
"Simulating ticket creation for purpose: " + purpose + ", amount: " + amount);
// Send a notification to the approver with the link of the ticket
Map<String, Object> result = new HashMap<>();
result.put("status", "pending");
result.put("approver", "Sean Zhou");
result.put("purpose", purpose);
result.put("amount", amount);
result.put("ticket-id", "approval-ticket-1");
return result;
}
public static void main(String[] args) throws NoSuchMethodException {
// Pass the method to LongRunningFunctionTool.create
LongRunningFunctionTool approveTool =
LongRunningFunctionTool.create(ExampleLongRunningFunction.class, "askForApproval");
// Include the tool in the agent
LlmAgent approverAgent =
LlmAgent.builder()
// ...
.tools(approveTool)
.build();
}
}
在 Kotlin 中,你可以通过设置相关参数来创建一个能够长时间运行的函数。
isLongRunning 属性(property)被设置为(to)…… true 在……里面;在……期间 @Tool annotation.
data class ReimbursementApproval(
val status: String,
val approver: String,
val purpose: String,
val amount: Double,
val ticketId: String,
)
class ReimbursementService {
/**
* Asks for approval for the reimbursement.
*/
@Tool(isLongRunning = true)
fun askForApproval(
@Param("The purpose of the reimbursement.") purpose: String,
@Param("The amount to be reimbursed.") amount: Double,
): ReimbursementApproval {
// Simulate creating a ticket and sending a notification.
// This tool returns the initial result and then the agent pauses.
return ReimbursementApproval(
status = "pending",
approver = "Sean Zhou",
purpose = purpose,
amount = amount,
ticketId = "approval-ticket-1",
)
}
}
fun main() {
val service = ReimbursementService()
val agent =
LlmAgent(
name = "approver_agent",
model = Gemini(name = "gemini-flash-latest"),
instruction = Instruction("You are a helpful reimbursement assistant."),
tools = service.generatedTools(),
)
}
中间/最终结果的更新¶
代理客户端收到一个包含长时间运行的函数调用的事件,并检查工单的状态。随后,代理客户端可以发送中间响应或最终响应,以更新处理进度。该框架会将这个值(即使其为 `None`)包含在响应内容中。 FunctionResponse 然后被发送回大型语言模型(LLM)。
注意:使用“Resume”功能时,长时间运行的函数会返回相应的响应结果。
如果您的 ADK 代理工作流程已按照以下要求进行配置: 简历
除了该功能外,您还必须提供调用 ID(Invocation ID)。invocation_id)参数
与这个长时间运行的函数响应相关。您提供的调用 ID 必须是与该长时间运行的函数请求相匹配的同一调用;否则,系统会使用该响应来启动一个新的调用。如果您的代理使用了“恢复”(Resume)功能,请考虑将调用 ID 作为参数包含在长时间运行的函数请求中,这样它就可以随响应一起被发送出去。有关使用“恢复”功能的更多详细信息,请参阅…… 恢复
已停止运行的代理程序.
在……里面;在……期间 Kotlin运行时系统会处理来自该函数的调用请求;响应中会包含调用本身的 ID,因此你无需手动传递该 ID。 invocationId 给……;发送到……
runAsync如果某个响应的 ID 与当前会话中的任何函数调用都不匹配,那么程序会抛出异常(throw an exception)。
仅适用于 Java ADK。
在传递数据时…… ToolContext 使用 Function Tools 时,请确保以下条件之一成立:
- 该模式是通过 `ToolContext` 参数传递给函数的。函数签名如下:
- 以下内容……
-parameters`flag` 被设置为 `mvn` 编译器插件。
# Agent Interaction
async def call_agent_async(query):
def get_long_running_function_call(event: Event) -> types.FunctionCall:
# Get the long running function call from the event
if not event.long_running_tool_ids or not event.content or not event.content.parts:
return
for part in event.content.parts:
if (
part
and part.function_call
and event.long_running_tool_ids
and part.function_call.id in event.long_running_tool_ids
):
return part.function_call
def get_function_response(event: Event, function_call_id: str) -> types.FunctionResponse:
# Get the function response for the function call with specified id.
if not event.content or not event.content.parts:
return
for part in event.content.parts:
if (
part
and part.function_response
and part.function_response.id == function_call_id
):
return part.function_response
content = types.Content(role='user', parts=[types.Part(text=query)])
session, runner = await setup_session_and_runner()
print("\nRunning agent...")
events_async = runner.run_async(
session_id=session.id, user_id=USER_ID, new_message=content
)
long_running_function_call, long_running_function_response, ticket_id = None, None, None
async for event in events_async:
# Use helper to check for the specific auth request event
if not long_running_function_call:
long_running_function_call = get_long_running_function_call(event)
else:
_potential_response = get_function_response(event, long_running_function_call.id)
if _potential_response: # Only update if we get a non-None response
long_running_function_response = _potential_response
ticket_id = long_running_function_response.response['ticket-id']
if event.content and event.content.parts:
if text := ''.join(part.text or '' for part in event.content.parts):
print(f'[{event.author}]: {text}')
if long_running_function_response:
# query the status of the corresponding ticket via ticket_id
# send back an intermediate / final response
updated_response = long_running_function_response.model_copy(deep=True)
updated_response.response = {'status': 'approved'}
async for event in runner.run_async(
session_id=session.id, user_id=USER_ID, new_message=types.Content(parts=[types.Part(function_response = updated_response)], role='user')
):
if event.content and event.content.parts:
if text := ''.join(part.text or '' for part in event.content.parts):
print(f'[{event.author}]: {text}')
/**
* 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 { LlmAgent, Runner, FunctionTool, LongRunningFunctionTool, InMemorySessionService, Event, stringifyContent } from '@google/adk';
import {z} from "zod";
import {Content, FunctionCall, FunctionResponse, createUserContent} from "@google/genai";
// 1. Define the long-running function
function askForApproval(args: {purpose: string; amount: number}) {
/**
* Ask for approval for the reimbursement.
*/
// create a ticket for the approval
// Send a notification to the approver with the link of the ticket
return {
"status": "pending",
"approver": "Sean Zhou",
"purpose": args.purpose,
"amount": args.amount,
"ticket-id": "approval-ticket-1",
};
}
// 2. Instantiate the LongRunningFunctionTool class with the long-running function
const longRunningTool = new LongRunningFunctionTool({
name: "ask_for_approval",
description: "Ask for approval for the reimbursement.",
parameters: z.object({
purpose: z.string().describe("The purpose of the reimbursement."),
amount: z.number().describe("The amount to reimburse."),
}),
execute: askForApproval,
});
function reimburse(args: {purpose: string; amount: number}) {
/**
* Reimburse the amount of money to the employee.
*/
// send the reimbursement request to payment vendor
return {status: "ok"};
}
const reimburseTool = new FunctionTool({
name: "reimburse",
description: "Reimburse the amount of money to the employee.",
parameters: z.object({
purpose: z.string().describe("The purpose of the reimbursement."),
amount: z.number().describe("The amount to reimburse."),
}),
execute: reimburse,
});
// 3. Use the tool in an Agent
const reimbursementAgent = new LlmAgent({
model: "gemini-2.5-flash",
name: "reimbursement_agent",
instruction: `
You are an agent whose job is to handle the reimbursement process for
the employees. If the amount is less than $100, you will automatically
approve the reimbursement.
If the amount is greater than $100, you will
ask for approval from the manager. If the manager approves, you will
call reimburse() to reimburse the amount to the employee. If the manager
rejects, you will inform the employee of the rejection.
`,
tools: [reimburseTool, longRunningTool],
});
const APP_NAME = "human_in_the_loop";
const USER_ID = "1234";
const SESSION_ID = "session1234";
// Session and Runner
async function setupSessionAndRunner() {
const sessionService = new InMemorySessionService();
const session = await sessionService.createSession({
appName: APP_NAME,
userId: USER_ID,
sessionId: SESSION_ID,
});
const runner = new Runner({
agent: reimbursementAgent,
appName: APP_NAME,
sessionService: sessionService,
});
return {session, runner};
}
function getLongRunningFunctionCall(event: Event): FunctionCall | undefined {
// Get the long-running function call from the event
if (
!event.longRunningToolIds ||
!event.content ||
!event.content.parts?.length
) {
return;
}
for (const part of event.content.parts) {
if (
part &&
part.functionCall &&
event.longRunningToolIds &&
part.functionCall.id &&
event.longRunningToolIds.includes(part.functionCall.id)
) {
return part.functionCall;
}
}
}
function getFunctionResponse(
event: Event,
functionCallId: string
): FunctionResponse | undefined {
// Get the function response for the function call with specified id.
if (!event.content || !event.content.parts?.length) {
return;
}
for (const part of event.content.parts) {
if (
part &&
part.functionResponse &&
part.functionResponse.id === functionCallId
) {
return part.functionResponse;
}
}
}
// Agent Interaction
async function callAgentAsync(query: string) {
let longRunningFunctionCall: FunctionCall | undefined;
let longRunningFunctionResponse: FunctionResponse | undefined;
let ticketId: string | undefined;
const content: Content = createUserContent(query);
const {session, runner} = await setupSessionAndRunner();
console.log("\nRunning agent...");
const events = runner.runAsync({
sessionId: session.id,
userId: USER_ID,
newMessage: content,
});
for await (const event of events) {
// Use helper to check for the specific auth request event
if (!longRunningFunctionCall) {
longRunningFunctionCall = getLongRunningFunctionCall(event);
} else {
const _potentialResponse = getFunctionResponse(
event,
longRunningFunctionCall.id!
);
if (_potentialResponse) {
// Only update if we get a non-None response
longRunningFunctionResponse = _potentialResponse;
ticketId = (
longRunningFunctionResponse.response as {[key: string]: any}
)[`ticket-id`];
}
}
const text = stringifyContent(event);
if (text) {
console.log(`[${event.author}]: ${text}`);
}
}
if (longRunningFunctionResponse) {
// query the status of the corresponding ticket via ticket_id
// send back an intermediate / final response
const updatedResponse = JSON.parse(
JSON.stringify(longRunningFunctionResponse)
);
updatedResponse.response = {status: "approved"};
for await (const event of runner.runAsync({
sessionId: session.id,
userId: USER_ID,
newMessage: createUserContent(JSON.stringify({functionResponse: updatedResponse})),
})) {
const text = stringifyContent(event);
if (text) {
console.log(`[${event.author}]: ${text}`);
}
}
}
}
async function main() {
// reimbursement that doesn't require approval
await callAgentAsync("Please reimburse 50$ for meals");
// reimbursement that requires approval
await callAgentAsync("Please reimburse 200$ for meals");
}
main();
以下示例演示了一个多步骤的工作流程:首先,用户请求代理创建一个工单;接着,代理会调用该耗时较长的工具(long-running tool);最后,客户端会记录相关操作或结果。 FunctionCall ID。随后,客户端通过发送后续数据来模拟异步操作的完成过程。 FunctionResponse
将这些信息发送回代理,以便提供工单 ID 和最终状态。
// runTurn executes a single turn with the agent and returns the captured function call ID.
func runTurn(ctx context.Context, r *runner.Runner, sessionID, turnLabel string, content *genai.Content) string {
var funcCallID atomic.Value // Safely store the found ID.
fmt.Printf("\n--- %s ---\n", turnLabel)
for event, err := range r.Run(ctx, userID, sessionID, content, agent.RunConfig{
StreamingMode: agent.StreamingModeNone,
}) {
if err != nil {
fmt.Printf("\nAGENT_ERROR: %v\n", err)
continue
}
// Print a summary of the event for clarity.
printEventSummary(event, turnLabel)
// Capture the function call ID from the event.
for _, part := range event.Content.Parts {
if fc := part.FunctionCall; fc != nil {
if fc.Name == "create_ticket_long_running" {
funcCallID.Store(fc.ID)
}
}
}
}
if id, ok := funcCallID.Load().(string); ok {
return id
}
return ""
}
func main() {
ctx := context.Background()
ticketAgent, err := createTicketAgent(ctx)
if err != nil {
log.Fatalf("Failed to create agent: %v", err)
}
// Setup the runner and session.
sessionService := session.InMemoryService()
session, err := sessionService.Create(ctx, &session.CreateRequest{AppName: appName, UserID: userID})
if err != nil {
log.Fatalf("Failed to create session: %v", err)
}
r, err := runner.New(runner.Config{AppName: appName, Agent: ticketAgent, SessionService: sessionService})
if err != nil {
log.Fatalf("Failed to create runner: %v", err)
}
// --- Turn 1: User requests to create a ticket. ---
initialUserMessage := genai.NewContentFromText("Create a high urgency ticket for me.", genai.RoleUser)
funcCallID := runTurn(ctx, r, session.Session.ID(), "Turn 1: User Request", initialUserMessage)
if funcCallID == "" {
log.Fatal("ERROR: Tool 'create_ticket_long_running' not called in Turn 1.")
}
fmt.Printf("ACTION: Captured FunctionCall ID: %s\n", funcCallID)
// --- Turn 2: App provides the final status of the ticket. ---
// In a real application, the ticketID would be retrieved from a database
// using the funcCallID. For this example, we'll use the same ID.
ticketID := "TICKET-ABC-123"
willContinue := false // Signal that this is the final response.
ticketStatusResponse := &genai.FunctionResponse{
Name: "create_ticket_long_running",
ID: funcCallID,
Response: map[string]any{
"status": "approved",
"ticket_id": ticketID,
},
WillContinue: &willContinue,
}
appResponseWithStatus := &genai.Content{
Role: string(genai.RoleUser),
Parts: []*genai.Part{{FunctionResponse: ticketStatusResponse}},
}
runTurn(ctx, r, session.Session.ID(), "Turn 2: App provides ticket status", appResponseWithStatus)
fmt.Println("Long running function completed successfully.")
}
// printEventSummary provides a readable log of agent and LLM interactions.
func printEventSummary(event *session.Event, turnLabel string) {
for _, part := range event.Content.Parts {
// Check for a text part.
if part.Text != "" {
fmt.Printf("[%s][%s_TEXT]: %s\n", turnLabel, event.Author, part.Text)
}
// Check for a function call part.
if fc := part.FunctionCall; fc != nil {
fmt.Printf("[%s][%s_CALL]: %s(%v) ID: %s\n", turnLabel, event.Author, fc.Name, fc.Args, fc.ID)
}
}
}
import com.google.adk.agents.LlmAgent;
import com.google.adk.events.Event;
import com.google.adk.runner.InMemoryRunner;
import com.google.adk.runner.Runner;
import com.google.adk.sessions.Session;
import com.google.adk.tools.Annotations.Schema;
import com.google.adk.tools.LongRunningFunctionTool;
import com.google.adk.tools.ToolContext;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.genai.types.Content;
import com.google.genai.types.FunctionCall;
import com.google.genai.types.FunctionResponse;
import com.google.genai.types.Part;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
public class LongRunningFunctionExample {
private static String USER_ID = "user123";
@Schema(
name = "create_ticket_long_running",
description = """
Creates a new support ticket with a specified urgency level.
Examples of urgency are 'high', 'medium', or 'low'.
The ticket creation is a long-running process, and its ID will be provided when ready.
""")
public static void createTicketAsync(
@Schema(
name = "urgency",
description =
"The urgency level for the new ticket, such as 'high', 'medium', or 'low'.")
String urgency,
@Schema(name = "toolContext") // Ensures ADK injection
ToolContext toolContext) {
System.out.printf(
"TOOL_EXEC: 'create_ticket_long_running' called with urgency: %s (Call ID: %s)%n",
urgency, toolContext.functionCallId().orElse("N/A"));
}
public static void main(String[] args) {
LlmAgent agent =
LlmAgent.builder()
.name("ticket_agent")
.description("Agent for creating tickets via a long-running task.")
.model("gemini-2.0-flash")
.tools(
ImmutableList.of(
LongRunningFunctionTool.create(
LongRunningFunctionExample.class, "createTicketAsync")))
.build();
Runner runner = new InMemoryRunner(agent);
Session session =
runner.sessionService().createSession(agent.name(), USER_ID, null, null).blockingGet();
// --- Turn 1: User requests ticket ---
System.out.println("\n--- Turn 1: User Request ---");
Content initialUserMessage =
Content.fromParts(Part.fromText("Create a high urgency ticket for me."));
AtomicReference<String> funcCallIdRef = new AtomicReference<>();
runner
.runAsync(USER_ID, session.id(), initialUserMessage)
.blockingForEach(
event -> {
printEventSummary(event, "T1");
if (funcCallIdRef.get() == null) { // Capture the first relevant function call ID
event.content().flatMap(Content::parts).orElse(ImmutableList.of()).stream()
.map(Part::functionCall)
.flatMap(Optional::stream)
.filter(fc -> "create_ticket_long_running".equals(fc.name().orElse("")))
.findFirst()
.flatMap(FunctionCall::id)
.ifPresent(funcCallIdRef::set);
}
});
if (funcCallIdRef.get() == null) {
System.out.println("ERROR: Tool 'create_ticket_long_running' not called in Turn 1.");
return;
}
System.out.println("ACTION: Captured FunctionCall ID: " + funcCallIdRef.get());
// --- Turn 2: App provides initial ticket_id (simulating async tool completion) ---
System.out.println("\n--- Turn 2: App provides ticket_id ---");
String ticketId = "TICKET-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
FunctionResponse ticketCreatedFuncResponse =
FunctionResponse.builder()
.name("create_ticket_long_running")
.id(funcCallIdRef.get())
.response(ImmutableMap.of("ticket_id", ticketId))
.build();
Content appResponseWithTicketId =
Content.builder()
.parts(
ImmutableList.of(
Part.builder().functionResponse(ticketCreatedFuncResponse).build()))
.role("user")
.build();
runner
.runAsync(USER_ID, session.id(), appResponseWithTicketId)
.blockingForEach(event -> printEventSummary(event, "T2"));
System.out.println("ACTION: Sent ticket_id " + ticketId + " to agent.");
// --- Turn 3: App provides ticket status update ---
System.out.println("\n--- Turn 3: App provides ticket status ---");
FunctionResponse ticketStatusFuncResponse =
FunctionResponse.builder()
.name("create_ticket_long_running")
.id(funcCallIdRef.get())
.response(ImmutableMap.of("status", "approved", "ticket_id", ticketId))
.build();
Content appResponseWithStatus =
Content.builder()
.parts(
ImmutableList.of(Part.builder().functionResponse(ticketStatusFuncResponse).build()))
.role("user")
.build();
runner
.runAsync(USER_ID, session.id(), appResponseWithStatus)
.blockingForEach(event -> printEventSummary(event, "T3_FINAL"));
System.out.println("Long running function completed successfully.");
}
private static void printEventSummary(Event event, String turnLabel) {
event
.content()
.ifPresent(
content -> {
String text =
content.parts().orElse(ImmutableList.of()).stream()
.map(part -> part.text().orElse(""))
.filter(s -> !s.isEmpty())
.collect(Collectors.joining(" "));
if (!text.isEmpty()) {
System.out.printf("[%s][%s_TEXT]: %s%n", turnLabel, event.author(), text);
}
content.parts().orElse(ImmutableList.of()).stream()
.map(Part::functionCall)
.flatMap(Optional::stream)
.findFirst() // Assuming one function call per relevant event for simplicity
.ifPresent(
fc ->
System.out.printf(
"[%s][%s_CALL]: %s(%s) ID: %s%n",
turnLabel,
event.author(),
fc.name().orElse("N/A"),
fc.args().orElse(ImmutableMap.of()),
fc.id().orElse("N/A")));
});
}
}
private fun printText(event: Event) {
val text = event.content?.parts?.mapNotNull { it.text }?.joinToString("").orEmpty()
if (text.isNotEmpty()) println("[${event.author}]: $text")
}
suspend fun callReimbursementAgent(
runner: InMemoryRunner,
userId: String,
sessionId: String,
query: String,
) {
var pendingCallId: String? = null
var pendingResponse: FunctionResponse? = null
runner
.runAsync(
userId = userId,
sessionId = sessionId,
newMessage = Content(role = "user", parts = listOf(Part(text = query))),
).collect { event ->
val callId = pendingCallId
if (callId == null) {
// A long-running call is the one whose id the event lists in longRunningToolIds.
pendingCallId =
event
.functionCalls()
.firstOrNull { it.id != null && it.id in event.longRunningToolIds }
?.id
} else {
event
.functionResponses()
.firstOrNull { it.id == callId }
?.let { pendingResponse = it }
}
printText(event)
}
// The tool returned "pending" and the invocation paused. Resume it by sending the
// outcome back as a FunctionResponse carrying the same id.
val paused = pendingResponse ?: return
val updated = paused.copy(response = mapOf("status" to "approved"))
runner
.runAsync(
userId = userId,
sessionId = sessionId,
newMessage = Content(role = "user", parts = listOf(Part(functionResponse = updated))),
).collect(::printText)
}
Python 完整示例:报销审批流程
# 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 asyncio
from google.adk.agents import Agent
from google.adk.events import Event
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
from typing import Any
from google.adk.tools import LongRunningFunctionTool
# 1. Define the long running function
def ask_for_approval(
purpose: str, amount: float
) -> dict[str, Any]:
"""Ask for approval for the reimbursement."""
# create a ticket for the approval
# Send a notification to the approver with the link of the ticket
return {'status': 'pending', 'approver': 'Sean Zhou', 'purpose' : purpose, 'amount': amount, 'ticket-id': 'approval-ticket-1'}
def reimburse(purpose: str, amount: float) -> dict[str, Any]:
"""Reimburse the amount of money to the employee."""
# send the reimbrusement request to payment vendor
return {'status': 'ok'}
# 2. Wrap the function with LongRunningFunctionTool
long_running_tool = LongRunningFunctionTool(func=ask_for_approval)
# 3. Use the tool in an Agent
file_processor_agent = Agent(
# Use a model compatible with function calling
model="gemini-2.0-flash",
name='reimbursement_agent',
instruction="""
You are an agent whose job is to handle the reimbursement process for
the employees. If the amount is less than $100, you will automatically
approve the reimbursement.
If the amount is greater than $100, you will
ask for approval from the manager. If the manager approves, you will
call reimburse() to reimburse the amount to the employee. If the manager
rejects, you will inform the employee of the rejection.
""",
tools=[reimburse, long_running_tool]
)
APP_NAME = "human_in_the_loop"
USER_ID = "1234"
SESSION_ID = "session1234"
# Session and Runner
async def setup_session_and_runner():
session_service = InMemorySessionService()
session = await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
runner = Runner(agent=file_processor_agent, app_name=APP_NAME, session_service=session_service)
return session, runner
# Agent Interaction
async def call_agent_async(query):
def get_long_running_function_call(event: Event) -> types.FunctionCall:
# Get the long running function call from the event
if not event.long_running_tool_ids or not event.content or not event.content.parts:
return
for part in event.content.parts:
if (
part
and part.function_call
and event.long_running_tool_ids
and part.function_call.id in event.long_running_tool_ids
):
return part.function_call
def get_function_response(event: Event, function_call_id: str) -> types.FunctionResponse:
# Get the function response for the function call with specified id.
if not event.content or not event.content.parts:
return
for part in event.content.parts:
if (
part
and part.function_response
and part.function_response.id == function_call_id
):
return part.function_response
content = types.Content(role='user', parts=[types.Part(text=query)])
session, runner = await setup_session_and_runner()
print("\nRunning agent...")
events_async = runner.run_async(
session_id=session.id, user_id=USER_ID, new_message=content
)
long_running_function_call, long_running_function_response, ticket_id = None, None, None
async for event in events_async:
# Use helper to check for the specific auth request event
if not long_running_function_call:
long_running_function_call = get_long_running_function_call(event)
else:
_potential_response = get_function_response(event, long_running_function_call.id)
if _potential_response: # Only update if we get a non-None response
long_running_function_response = _potential_response
ticket_id = long_running_function_response.response['ticket-id']
if event.content and event.content.parts:
if text := ''.join(part.text or '' for part in event.content.parts):
print(f'[{event.author}]: {text}')
if long_running_function_response:
# query the status of the corresponding ticket via ticket_id
# send back an intermediate / final response
updated_response = long_running_function_response.model_copy(deep=True)
updated_response.response = {'status': 'approved'}
async for event in runner.run_async(
session_id=session.id, user_id=USER_ID, new_message=types.Content(parts=[types.Part(function_response = updated_response)], role='user')
):
if event.content and event.content.parts:
if text := ''.join(part.text or '' for part in event.content.parts):
print(f'[{event.author}]: {text}')
async def main():
# reimbursement that does not require approval
await call_agent_async("Please reimburse 50$ for meals")
# reimbursement that requires approval
await call_agent_async("Please reimburse 200$ for meals")
# Note: In Colab or another notebook you can await the calls in `main` directly
# at the top level. As a standalone script, run them through asyncio.run().
if __name__ == "__main__":
asyncio.run(main())
这个示例的关键方面¶
LongRunningFunctionTool:该装饰器会包裹传入的方法或函数,并将其标记为“耗时较长”的操作。框架会像调用其他普通函数一样调用该被装饰的函数,但不会消耗该函数返回的值(尤其是那些通过生成器(generator)产生的值)。- 代理指令(Agent instruction):指示大型语言模型(LLM)使用该工具,并解读代理客户端随后发送的进度更新信息及完成状态信息,以便向用户提供反馈。
- 初始返回值无论该函数返回什么值,都会作为第一个参数被发送到 `FunctionResponse` 中;而如果某个函数没有返回任何值或返回了空值,那么该函数就不会被发送到 `FunctionResponse` 中。后续的所有进度更新或完成通知,都是由代理客户端(agent client)发送的 `FunctionResponse` 对象来表示的。
- Kotlin 没有(某些功能或特性)。
LongRunningFunctionToolclass:用以下内容为该函数添加注释:@Tool(isLongRunning = true)或者直接传递(数据)。isLongRunning = true到……BaseToolsubclass. - Kotlin:回合计数(Turn Count):上述工具返回的是一个数值,而不是其他类型的输出。
Unit因此,不可恢复(即无法继续执行)的应用程序会将这个占位符数据发送给模型,并在稍后再次调用该模型;这样一来,第一轮的流程就会以一个临时性的回复结束。而可恢复的应用程序则会在函数调用时暂停执行,而不会再次调用模型。Unit该功能会完全抑制占位符生成的响应内容,从而在任意模式下结束当前函数调用的执行过程。
“Agent-as-a-Tool”(即“将代理(Agent)视为一种工具”)¶
此功能允许您通过将其他代理视为工具来利用它们在系统中的能力。通过“代理即工具”(Agent-as-a-Tool)机制,您可以调用另一个代理来执行特定任务,从而实现高效的操作。 **授权(或转移)责任**从概念上讲,这与创建一个 Python 函数非常相似:该函数会调用另一个代理(agent),并将该代理的响应作为自己的返回值。
与次级代理(sub-agents)的主要区别在于:¶
区分“作为工具的代理”(Agent-as-a-Tool)和“子代理”(sub-agent)是非常重要的。
- “Agent-as-a-Tool”(即“将代理(Agent)视为工具”):这是一种将代理程序设计成可被其他应用程序或系统直接调用的、功能化、可定制的工具的概念。通过这种方式,代理程序可以更灵活地融入各种应用程序中,提高系统的整体效率和灵活性。 当代理 A 以“代理作为工具”(Agent-as-a-Tool)的方式联系代理 B 时,代理 B 的回答是…… 被传回(或返回) 信息首先被发送给代理 A(Agent A),代理 A 会总结用户的回答内容,并生成相应的回复发送给用户。代理 A 仍然保持控制权,继续处理用户后续发送的输入信息。
- 子代理(Sub-agent): 当代理 A 将代理 B 视为子代理并请求其协助处理用户请求时,回答用户问题的责任完全由代理 B 承担。 已转交给代理人 B(Agent B)。A代理实际上已经被排除在处理流程之外;所有后续的用户输入都将由B代理来回答。
使用 AgentTool¶
要将代理(agent)作为工具使用,需要用相应的包装方式将其“包裹”起来。 AgentTool class.
Python:请考虑以下情况…… single_turn 子代理(sub-agent)
在 ADK Python 中,对于标准的内联委托(inline delegation)功能,建议使用以下设置方法:
mode="single_turn" 通过一个子代理(sub-agent)来实现,并将其附加到相应的系统中。
sub_agents=[...] 与其用其他方式将其包裹起来,不如直接使用…… AgentToolADK 将子代理(sub-agent)作为一个工具暴露出来,并在父代理(parent agent)的会话中直接运行该子代理。详见…… 代理(Agent)
协作(Collaboration).
自定义您的代理工具¶
The AgentTool 该类提供了以下属性,用于自定义其行为。
跳过摘要生成步骤。¶
skip_summarization (布尔值)
如果将其设置为…… True这种自定义设置会指示框架跳过基于大型语言模型(LLM)的摘要生成功能,从而直接使用工具代理的原始响应。当工具的输出格式已经非常规范、且无需进一步处理时,使用该功能效果最佳。
- **用途:**
用于指定该功能的特定用途或应用场景。 Python/TypeScript (
skip_summarization); Kotlin/Java (skipSummarization).
示例:
# 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 asyncio
from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.tools.agent_tool import AgentTool
from google.genai import types
APP_NAME="summary_agent"
USER_ID="user1234"
SESSION_ID="1234"
summary_agent = Agent(
model="gemini-2.0-flash",
name="summary_agent",
instruction="""You are an expert summarizer. Please read the following text and provide a concise summary.""",
description="Agent to summarize text",
)
root_agent = Agent(
model='gemini-2.0-flash',
name='root_agent',
instruction="""You are a helpful assistant. When the user provides a text, use the 'summarize' tool to generate a summary. Always forward the user's message exactly as received to the 'summarize' tool, without modifying or summarizing it yourself. Present the response from the tool to the user.""",
tools=[AgentTool(agent=summary_agent, skip_summarization=True)]
)
# Session and Runner
async def setup_session_and_runner():
session_service = InMemorySessionService()
session = await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
runner = Runner(agent=root_agent, app_name=APP_NAME, session_service=session_service)
return session, runner
# Agent Interaction
async def call_agent_async(query):
content = types.Content(role='user', parts=[types.Part(text=query)])
session, runner = await setup_session_and_runner()
events = runner.run_async(user_id=USER_ID, session_id=SESSION_ID, new_message=content)
async for event in events:
if event.is_final_response() and event.content and event.content.parts:
final_response = event.content.parts[0].text
print("Agent Response: ", final_response)
long_text = """Quantum computing represents a fundamentally different approach to computation,
leveraging the bizarre principles of quantum mechanics to process information. Unlike classical computers
that rely on bits representing either 0 or 1, quantum computers use qubits which can exist in a state of superposition - effectively
being 0, 1, or a combination of both simultaneously. Furthermore, qubits can become entangled,
meaning their fates are intertwined regardless of distance, allowing for complex correlations. This parallelism and
interconnectedness grant quantum computers the potential to solve specific types of incredibly complex problems - such
as drug discovery, materials science, complex system optimization, and breaking certain types of cryptography - far
faster than even the most powerful classical supercomputers could ever achieve, although the technology is still largely in its developmental stages."""
async def main():
await call_agent_async(long_text)
# Note: In Colab, you can directly 'await call_agent_async(...)' at the top level.
if __name__ == "__main__":
asyncio.run(main())
/**
* 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 { AgentTool, InMemoryRunner, LlmAgent } from '@google/adk';
import {Part, createUserContent} from '@google/genai';
/**
* This example demonstrates how to use an agent as a tool.
*/
async function main() {
// Define the summarization agent that will be used as a tool
const summaryAgent = new LlmAgent({
name: 'summary_agent',
model: 'gemini-2.5-flash',
description: 'Agent to summarize text',
instruction:
'You are an expert summarizer. Please read the following text and provide a concise summary.',
});
// Define the main agent that uses the summarization agent as a tool.
// skipSummarization is set to true, so the main_agent will directly output
// the result from the summary_agent without further processing.
const mainAgent = new LlmAgent({
name: 'main_agent',
model: 'gemini-2.5-flash',
instruction:
"You are a helpful assistant. When the user provides a text, use the 'summary_agent' tool to generate a summary. Always forward the user's message exactly as received to the 'summary_agent' tool, without modifying or summarizing it yourself. Present the response from the tool to the user.",
tools: [new AgentTool({agent: summaryAgent, skipSummarization: true})],
});
const appName = 'agent-as-a-tool-app';
const runner = new InMemoryRunner({agent: mainAgent, appName});
const longText = `Quantum computing represents a fundamentally different approach to computation,
leveraging the bizarre principles of quantum mechanics to process information. Unlike classical computers
that rely on bits representing either 0 or 1, quantum computers use qubits which can exist in a state of superposition - effectively
being 0, 1, or a combination of both simultaneously. Furthermore, qubits can become entangled,
meaning their fates are intertwined regardless of distance, allowing for complex correlations. This parallelism and
interconnectedness grant quantum computers the potential to solve specific types of incredibly complex problems - such
as drug discovery, materials science, complex system optimization, and breaking certain types of cryptography - far
faster than even the most powerful classical supercomputers could ever achieve, although the technology is still largely in its developmental stages.`;
// Create the session before running the agent
await runner.sessionService.createSession({
appName,
userId: 'user1',
sessionId: 'session1',
});
// Run the agent with the long text to summarize
const events = runner.runAsync({
userId: 'user1',
sessionId: 'session1',
newMessage: createUserContent(longText),
});
// Print the final response from the agent
console.log('Agent Response:');
for await (const event of events) {
if (event.content?.parts?.length) {
const responsePart = event.content.parts.find((p: Part) => p.functionResponse);
if (responsePart && responsePart.functionResponse) {
console.log(responsePart.functionResponse.response);
}
}
}
}
main();
import (
"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/model/gemini"
"google.golang.org/adk/v2/tool"
"google.golang.org/adk/v2/tool/agenttool"
"google.golang.org/genai"
)
// createSummarizerAgent creates an agent whose sole purpose is to summarize text.
func createSummarizerAgent(ctx context.Context) (agent.Agent, error) {
model, err := gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
if err != nil {
return nil, err
}
return llmagent.New(llmagent.Config{
Name: "SummarizerAgent",
Model: model,
Instruction: "You are an expert at summarizing text. Take the user's input and provide a concise summary.",
Description: "An agent that summarizes text.",
})
}
// createMainAgent creates the primary agent that will use the summarizer agent as a tool.
func createMainAgent(ctx context.Context, tools ...tool.Tool) (agent.Agent, error) {
model, err := gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
if err != nil {
return nil, err
}
return llmagent.New(llmagent.Config{
Name: "MainAgent",
Model: model,
Instruction: "You are a helpful assistant. If you are asked to summarize a long text, use the 'summarize' tool. " +
"After getting the summary, present it to the user by saying 'Here is a summary of the text:'.",
Description: "The main agent that can delegate tasks.",
Tools: tools,
})
}
func RunAgentAsToolSimulation() {
ctx := context.Background()
// 1. Create the Tool Agent (Summarizer)
summarizerAgent, err := createSummarizerAgent(ctx)
if err != nil {
log.Fatalf("Failed to create summarizer agent: %v", err)
}
// 2. Wrap the Tool Agent in an AgentTool
summarizeTool := agenttool.New(summarizerAgent, &agenttool.Config{
SkipSummarization: true,
})
// 3. Create the Main Agent and provide it with the AgentTool
mainAgent, err := createMainAgent(ctx, summarizeTool)
if err != nil {
log.Fatalf("Failed to create main agent: %v", err)
}
// 4. Run the main agent
prompt := `
Please summarize this text for me:
Quantum computing represents a fundamentally different approach to computation,
leveraging the bizarre principles of quantum mechanics to process information. Unlike classical computers
that rely on bits representing either 0 or 1, quantum computers use qubits which can exist in a state of superposition - effectively
being 0, 1, or a combination of both simultaneously. Furthermore, qubits can become entangled,
meaning their fates are intertwined regardless of distance, allowing for complex correlations. This parallelism and
interconnectedness grant quantum computers the potential to solve specific types of incredibly complex problems - such
as drug discovery, materials science, complex system optimization, and breaking certain types of cryptography - far
faster than even the most powerful classical supercomputers could ever achieve, although the technology is still largely in its developmental stages.
`
fmt.Printf("\nPrompt: %s\nResponse: ", prompt)
callAgent(context.Background(), mainAgent, prompt)
fmt.Println("\n---")
}
import com.google.adk.agents.LlmAgent;
import com.google.adk.events.Event;
import com.google.adk.runner.InMemoryRunner;
import com.google.adk.sessions.Session;
import com.google.adk.tools.AgentTool;
import com.google.genai.types.Content;
import com.google.genai.types.Part;
import io.reactivex.rxjava3.core.Flowable;
public class AgentToolCustomization {
private static final String APP_NAME = "summary_agent";
private static final String USER_ID = "user1234";
public static void initAgentAndRun(String prompt) {
LlmAgent summaryAgent =
LlmAgent.builder()
.model("gemini-2.0-flash")
.name("summaryAgent")
.instruction(
"You are an expert summarizer. Please read the following text and provide a concise summary.")
.description("Agent to summarize text")
.build();
// Define root_agent
LlmAgent rootAgent =
LlmAgent.builder()
.model("gemini-2.0-flash")
.name("rootAgent")
.instruction(
"You are a helpful assistant. When the user provides a text, always use the 'summaryAgent' tool to generate a summary. Always forward the user's message exactly as received to the 'summaryAgent' tool, without modifying or summarizing it yourself. Present the response from the tool to the user.")
.description("Assistant agent")
.tools(AgentTool.create(summaryAgent, true)) // Set skipSummarization to true
.build();
// Create an InMemoryRunner
InMemoryRunner runner = new InMemoryRunner(rootAgent, APP_NAME);
// InMemoryRunner automatically creates a session service. Create a session using the service
Session session = runner.sessionService().createSession(APP_NAME, USER_ID).blockingGet();
Content userMessage = Content.fromParts(Part.fromText(prompt));
// Run the agent
Flowable<Event> eventStream = runner.runAsync(USER_ID, session.id(), userMessage);
// Stream event response
eventStream.blockingForEach(
event -> {
if (event.finalResponse()) {
System.out.println(event.stringifyContent());
}
});
}
public static void main(String[] args) {
String longText =
"""
Quantum computing represents a fundamentally different approach to computation,
leveraging the bizarre principles of quantum mechanics to process information. Unlike classical computers
that rely on bits representing either 0 or 1, quantum computers use qubits which can exist in a state of superposition - effectively
being 0, 1, or a combination of both simultaneously. Furthermore, qubits can become entangled,
meaning their fates are intertwined regardless of distance, allowing for complex correlations. This parallelism and
interconnectedness grant quantum computers the potential to solve specific types of incredibly complex problems - such
as drug discovery, materials science, complex system optimization, and breaking certain types of cryptography - far
faster than even the most powerful classical supercomputers could ever achieve, although the technology is still largely in its developmental stages.""";
initAgentAndRun(longText);
}
}
import com.google.adk.kt.agents.Instruction
import com.google.adk.kt.agents.LlmAgent
import com.google.adk.kt.models.Gemini
import com.google.adk.kt.runners.InMemoryRunner
import com.google.adk.kt.tools.AgentTool
import com.google.adk.kt.types.Content
import com.google.adk.kt.types.Part
import kotlinx.coroutines.runBlocking
fun main() =
runBlocking {
val appName = "summary_agent"
val userId = "user1234"
// Define a specialized agent to be used as a tool
val summaryAgent =
LlmAgent(
name = "summary_agent",
model = Gemini(name = "gemini-flash-latest"),
description = "Agent to summarize text",
instruction =
Instruction(
"You are an expert summarizer. Please read the following text and provide a concise summary.",
),
)
// Wrap the agent in an AgentTool with skipSummarization = true
val summaryTool =
AgentTool(
agent = summaryAgent,
skipSummarization = true,
)
// Define the root agent that uses the summary tool
val rootAgent =
LlmAgent(
name = "root_agent",
model = Gemini(name = "gemini-flash-latest"),
instruction =
Instruction(
"You are a helpful assistant. When the user provides a text, use the 'summary_agent' tool to generate a summary. Always forward the user's message exactly as received to the 'summary_agent' tool. Present the response from the tool to the user.",
),
tools = listOf(summaryTool),
)
// Create an InMemoryRunner
val runner = InMemoryRunner(agent = rootAgent, appName = appName)
val sessionId = "session_001"
val longText =
"""
Quantum computing represents a fundamentally different approach to computation,
leveraging the bizarre principles of quantum mechanics to process information. Unlike classical computers
that rely on bits representing either 0 or 1, quantum computers use qubits which can exist in a state of superposition - effectively
being 0, 1, or a combination of both simultaneously. Furthermore, qubits can become entangled,
meaning their fates are intertwined regardless of distance, allowing for complex correlations. This parallelism and
interconnectedness grant quantum computers the potential to solve specific types of incredibly complex problems - such
as drug discovery, materials science, complex system optimization, and breaking certain types of cryptography - far
faster than even the most powerful classical supercomputers could ever achieve, although the technology is still largely in its developmental stages.
""".trimIndent()
val userMessage = Content(parts = listOf(Part(text = longText)))
// Run the agent and collect events
runner.runAsync(userId = userId, sessionId = sessionId, newMessage = userMessage).collect {
event ->
if (event.isFinalResponse) {
val finalResponse = event.content?.parts?.firstOrNull()?.text
println("Agent Response: $finalResponse")
}
}
}
它是如何工作的?¶
- 当……的时候
root_agent该系统接收长文本信息,其内部指令要求使用专门用于处理长文本的“总结”工具(即“summarize”工具)来对这些文本进行简化处理。 - 该框架将 “summarize” 视为一个有效的指令/功能。
AgentTool那个用于包裹(或包围)……的东西summary_agent. - 在幕后,
root_agent将会调用(该函数/方法等)。summary_agent以长文本作为输入。 - The
summary_agent将根据其指令处理文本,并生成摘要。 - 来自……的响应是:
summary_agent然后又被传回给……root_agent. - The
root_agent然后可以提取文本的摘要,并向用户生成最终的回复(例如:“以下是该文本的摘要:……”)。
传播接地(grounding)元数据¶
propagate_grounding_metadata (布尔类型,默认值:) False如果设置为…… True该工具会自动将任何由子代理生成的元数据(例如来自 Google 搜索的引用信息)转发到父代理的会话状态中。这种定制功能确保了在使用专门的搜索代理作为工具时,相关引用信息能够被完整保留下来。
from google.adk.agents import Agent
from google.adk.tools import AgentTool
search_specialist_agent = Agent(
# Specify your generative model
model="gemini-flash-latest",
name="search_specialist_agent",
instruction=(
"You are a search expert. Find and "
"compile citations on requested topics."
),
# Add any search tools here
)
search_agent_tool = AgentTool(
agent=search_specialist_agent,
# Keeps citations intact back to the root
propagate_grounding_metadata=True
)
root_agent = Agent(
model="gemini-flash-latest",
name="root_agent",
description=(
"A central coordinator that delegates "
"to specialist agents."
),
tools=[search_agent_tool]
)
控制插件继承机制¶
当你使用某种技术或方法“包装”(即对某个代理对象进行处理)一个代理时…… AgentTool你可以使用该功能来控制程序是否从父程序(parent runner)继承插件。 include_plugins
parameter.
include_plugins=True(默认值): 子代理继承了父代理的所有插件,从而保留了跟踪数据(trace spans)和事件流(event streaming)的功能。include_plugins=False: 子代理在隔离的环境中运行,不会从父代理那里继承任何插件。使用此设置可以确保代理的执行过程是独立的,不会受到父代理插件环境的影响。
from google.adk.tools import agent_tool
# Placeholder definition for MyImageAgent
class MyImageAgent:
def __init__(
self, name="My Agent", description="A simple image agent."
):
self.name = name
# Added description attribute
self.description = description
# Example 1: Isolate MyImageAgent from parent plugins
my_isolated_tool = agent_tool.AgentTool(
agent=MyImageAgent(), # Instantiate MyImageAgent
include_plugins=False
)
# Example 2: Inherit plugins
my_observable_tool = agent_tool.AgentTool(
agent=MyImageAgent(), # Instantiate MyImageAgent
include_plugins=True
)