defget_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'.
"""# ... 函数逻辑 ...return {"status": "success", "report": f"Weather for {city} is sunny."}
// GetWeatherParams 定义了 getWeather 工具的参数。typeGetWeatherParamsstruct {
// 此字段为必填项(不能“omitempty”)。// jsonschema 标签提供了描述。Locationstring`json:"location" jsonschema:"The city and state, e.g., San Francisco, CA"`// 此字段也是必填项。Unitstring`json:"unit" jsonschema:"The temperature unit, either 'celsius' or 'fahrenheit'"`}
defsearch_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.
"""# ... 函数逻辑 ...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}."}
// GetWeatherParams 定义了 getWeather 工具的参数。typeGetWeatherParamsstruct {
// 位置是必填项。Locationstring`json:"location" jsonschema:"The city and state, e.g., San Francisco, CA"`// 单位是可选项。Unitstring`json:"unit,omitempty" jsonschema:"The temperature unit, either 'celsius' or 'fahrenheit'"`// 天数是可选项。Daysint`json:"days,omitzero" jsonschema:"The number of forecast days to return (defaults to 1)"`}
from typing import Optional
defcreate_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.
"""# ... 函数逻辑 ...if bio:
return {"status": "success", "message": f"Profile for {username} created with a bio."}
return {"status": "success", "message": f"Profile for {username} created."}
# Copyright 2025 Google LLC## Licensed under the Apache License, Version 2.0 (the "License");# 除非遵守许可协议,否则您不得使用此文件。# 您可以在以下位置获取许可副本## http://www.apache.org/licenses/LICENSE-2.0## 除非适用法律要求或书面约定,否则根据许可协议分发的软件# 按“原样”提供# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# 请参阅许可协议以了解管理权限和# limitations under the License.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"defget_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")
ifnot historical_data.empty:
current_price = historical_data['Close'].iloc[-1]
return current_price
else:
returnNoneexceptExceptionas e:
print(f"Error retrieving stock price for {symbol}: {e}")
returnNonestock_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.)
# 会话与 Runnerasyncdefsetup_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 交互asyncdefcall_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)
asyncfor event in events:
if event.is_final_response():
final_response = event.content.parts[0].text
print("Agent Response: ", final_response)
# 注意:在 Colab 中可以直接在顶层使用 'await'。# 如果将此代码作为独立 Python 脚本运行,则需要使用 asyncio.run() 或管理事件循环。await call_agent_async("stock price of GOOG")
该工具的返回值将被封装到一个字典中。
json1 行展开收起expand_more
{"result": "$123"}
此工具用于获取股票价格的模拟值。
go274 行展开收起expand_more
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");// 除非遵守许可协议,否则您不得使用此文件。// 您可以在以下位置获取许可副本//// http://www.apache.org/licenses/LICENSE-2.0//// 除非适用法律要求或书面约定,否则根据许可协议分发的软件// 按“原样”提供// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// 请参阅许可协议以了解管理权限和// limitations under the License.packagemainimport (
"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 提供了一个简单的内存股票价格数据库// 模拟现实中的股票数据 API。这使得示例能够// 无需进行外部网络调用即可展示工具功能。varmockStockPrices = map[string]float64{
"GOOG": 300.6,
"AAPL": 123.4,
"MSFT": 234.5,
}
// getStockPriceArgs 定义了传递给 getStockPrice 工具的参数的模式。// Go ADK 推荐使用结构,因为它能提供强力// 对预期输入进行类型输入和清晰验证。typegetStockPriceArgsstruct {
Symbolstring`json:"symbol" jsonschema:"The stock ticker symbol, e.g., GOOG"`}
// getStockPriceResults 定义了 getStockPrice 工具的输出模式。typegetStockPriceResultsstruct {
Symbolstring`json:"symbol"`Pricefloat64`json:"price,omitempty"`Errorstring`json:"error,omitempty"`}
// getStockPrice 是一种工具,用于获取给定股票代码的股票价格// 来自 mockStockPrices 地图。它演示了函数如何作为// 工具由 Agent 操作。如果找到该符号,它会返回包含// 符号及其价格。否则,返回带有错误信息的结构。funcgetStockPrice(ctxagent.Context, inputgetStockPriceArgs) (getStockPriceResults, error) {
symbolUpper:=strings.ToUpper(input.Symbol)
ifprice, ok:=mockStockPrices[symbolUpper]; ok {
fmt.Printf("Tool: Found price for %s: %f\n", input.Symbol, price)
returngetStockPriceResults{Symbol: input.Symbol, Price: price}, nil }
returngetStockPriceResults{}, fmt.Errorf("no data found for symbol")
}
// createStockAgent 初始化并配置 LlmAgent。// 该 Agent 配备了getStockPrice工具,并接受相关指导// 关于如何回应用户关于股价的询问。它使用// Gemini模型用于理解用户意图并决定何时使用其工具。funccreateStockAgent(ctxcontext.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)
iferr!=nil {
returnnil, err }
model, err:=gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
iferr!=nil {
log.Fatalf("Failed to create model: %v", err)
}
returnllmagent.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,
},
})
}
// 用户ID和应用名是用于识别用户和应用的常量// 在整个会话中。这些数值对于日志记录、跟踪非常重要,// 以及管理不同 Agent 交互间的状态。const (
userID = "example_user_id"appName = "example_app")
// callAgent 负责协调给定提示下的 Agent 执行。// 它会设置必要的服务,创建会话,并使用运行程序// 管理 Agent 的生命周期。它会流式传输 Agent 的响应和// 打印到控制台,处理运行过程中可能出现的错误。funccallAgent(ctxcontext.Context, aagent.Agent, promptstring) {
sessionService:=session.InMemoryService()
// 为 Agent 互动创建一个新会话。session, err:=sessionService.Create(ctx, &session.CreateRequest{
AppName: appName,
UserID: userID,
})
iferr!=nil {
log.Fatalf("Failed to create the session service: %v", err)
}
config:=runner.Config{
AppName: appName,
Agent: a,
SessionService: sessionService,
}
// 创建运行程序来管理 Agent 执行。r, err:=runner.New(config)
iferr!=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),
}
forevent, err:=ranger.Run(ctx, userID, sessionID, userMsg, agent.RunConfig{
StreamingMode: agent.StreamingModeNone,
}) {
iferr!=nil {
fmt.Printf("\nAGENT_ERROR: %v\n", err)
} else {
for_, p:=rangeevent.Content.Parts {
fmt.Print(p.Text)
}
}
}
}
// RunAgentSimulation 是这个例子的切入点。// 它创建库存 Agent,然后模拟一系列用户交互// 通过向 Agent 发送不同的提示。该功能展示了如何// Agent 会回答各种问题,包括成功和失败// 试图恢复股价。funcRunAgentSimulation() {
// 创建股票 Agentagent, err:=createStockAgent(context.Background())
iferr!=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?",
}
// 模拟运行 Agent 时,使用不同的提示for_, prompt:=rangeprompts {
fmt.Printf("\nPrompt: %s\nResponse: ", prompt)
callAgent(context.Background(), agent, prompt)
fmt.Println("\n---")
}
}
// --8<-- [start:agent_tool_example]// createSummarizerAgent 创建了一个专门用于摘要文本的 Agent。funccreateSummarizerAgent(ctxcontext.Context) (agent.Agent, error) {
model, err:=gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
iferr!=nil {
returnnil, err }
returnllmagent.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 创建了将摘要 Agent 作为工具的主 Agent。funccreateMainAgent(ctxcontext.Context, tools...tool.Tool) (agent.Agent, error) {
model, err:=gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
iferr!=nil {
returnnil, err }
returnllmagent.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,
})
}
funcRunAgentAsToolSimulation() {
ctx:=context.Background()
// 1. 创建工具 Agent(摘要器)summarizerAgent, err:=createSummarizerAgent(ctx)
iferr!=nil {
log.Fatalf("Failed to create summarizer agent: %v", err)
}
// 2. 将工具 Agent 封装在 AgentTool 中summarizeTool:=agenttool.New(summarizerAgent, &agenttool.Config{
SkipSummarization: true,
})
// 3. 创建主 Agent 并为其提供 AgentToolmainAgent, err:=createMainAgent(ctx, summarizeTool)
iferr!=nil {
log.Fatalf("Failed to create main agent: %v", err)
}
// 4. 运行主 Agentprompt:=`
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---")
}
// --8<-- [end:agent_tool_example]funcmain() {
fmt.Println("Attempting to run the agent simulation...")
RunAgentSimulation()
fmt.Println("\nAttempting to run the agent-as-a-tool simulation...")
RunAgentAsToolSimulation()
}
# Copyright 2025 Google LLC## Licensed under the Apache License, Version 2.0 (the "License");# 除非遵守许可协议,否则您不得使用此文件。# 您可以在以下位置获取许可副本## http://www.apache.org/licenses/LICENSE-2.0## 除非适用法律要求或书面约定,否则根据许可协议分发的软件# 按“原样”提供# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# 请参阅许可协议以了解管理权限和# 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
# --8<-- [start:define_long_running_function]from typing import Any
from google.adk.tools import LongRunningFunctionTool
# 1. 定义长时间运行的函数defask_for_approval(
purpose: str, amount: float
) -> dict[str, Any]:
"""Ask for approval for the reimbursement."""# 为审批创建一个工单# 向审批人发送带有工单链接的通知return {'status': 'pending', 'approver': 'Sean Zhou', 'purpose' : purpose, 'amount': amount, 'ticket-id': 'approval-ticket-1'}
defreimburse(purpose: str, amount: float) -> dict[str, Any]:
"""Reimburse the amount of money to the employee."""# 将报销请求发送给付款供应商return {'status': 'ok'}
# 2. 使用 LongRunningFunctionTool 包装该函数long_running_tool = LongRunningFunctionTool(func=ask_for_approval)
# --8<-- [end:define_long_running_function]# 3. 在 Agent 中使用工具file_processor_agent = Agent(
# 使用与函数调用兼容的模型 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"# 会话与 Runnerasyncdefsetup_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
# --8<-- [start: call_reimbursement_tool]# Agent 交互asyncdefcall_agent_async(query):
defget_long_running_function_call(event: Event) -> types.FunctionCall:
# 从事件中获取长时间运行的函数调用ifnot event.long_running_tool_ids ornot event.content ornot event.content.parts:
returnfor 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
defget_function_response(event: Event, function_call_id: str) -> types.FunctionResponse:
# 获取指定ID的函数调用的函数响应。ifnot event.content ornot event.content.parts:
returnfor 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, Noneasyncfor event in events_async:
# 使用助手检查特定的授权请求事件ifnot 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:
# 通过 ticket_id 查询相应工单的状态# 发送中间/最终响应 updated_response = long_running_function_response.model_copy(deep=True)
updated_response.response = {'status': 'approved'}
asyncfor 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}')
# --8<-- [end:call_reimbursement_tool]# 注意:在 Colab 中可以直接在顶层使用 'await'。# 如果将此代码作为独立 Python 脚本运行,则需要使用 asyncio.run() 或管理事件循环。# 无需审批的报销# asyncio.run(call_agent_async("请报销50美元的餐费"))await call_agent_async("Please reimburse 50$ for meals") # For Notebooks, uncomment this line and comment the above line# 需要审批的报销# asyncio.run(call_agent_async("请报销200美元的餐费"))await call_agent_async("Please reimburse 200$ for meals") # For Notebooks, uncomment this line and comment the above line
# Copyright 2025 Google LLC## Licensed under the Apache License, Version 2.0 (the "License");# 除非遵守许可协议,否则您不得使用此文件。# 您可以在以下位置获取许可副本## http://www.apache.org/licenses/LICENSE-2.0## 除非适用法律要求或书面约定,否则根据许可协议分发的软件# 按“原样”提供# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# 请参阅许可协议以了解管理权限和# 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
# --8<-- [start:define_long_running_function]from typing import Any
from google.adk.tools import LongRunningFunctionTool
# 1. 定义长时间运行的函数defask_for_approval(
purpose: str, amount: float
) -> dict[str, Any]:
"""Ask for approval for the reimbursement."""# 为审批创建一个工单# 向审批人发送带有工单链接的通知return {'status': 'pending', 'approver': 'Sean Zhou', 'purpose' : purpose, 'amount': amount, 'ticket-id': 'approval-ticket-1'}
defreimburse(purpose: str, amount: float) -> dict[str, Any]:
"""Reimburse the amount of money to the employee."""# 将报销请求发送给付款供应商return {'status': 'ok'}
# 2. 使用 LongRunningFunctionTool 包装该函数long_running_tool = LongRunningFunctionTool(func=ask_for_approval)
# --8<-- [end:define_long_running_function]# 3. 在 Agent 中使用工具file_processor_agent = Agent(
# 使用与函数调用兼容的模型 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"# 会话与 Runnerasyncdefsetup_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
# --8<-- [start: call_reimbursement_tool]# Agent 交互asyncdefcall_agent_async(query):
defget_long_running_function_call(event: Event) -> types.FunctionCall:
# 从事件中获取长时间运行的函数调用ifnot event.long_running_tool_ids ornot event.content ornot event.content.parts:
returnfor 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
defget_function_response(event: Event, function_call_id: str) -> types.FunctionResponse:
# 获取指定ID的函数调用的函数响应。ifnot event.content ornot event.content.parts:
returnfor 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, Noneasyncfor event in events_async:
# 使用助手检查特定的授权请求事件ifnot 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:
# 通过 ticket_id 查询相应工单的状态# 发送中间/最终响应 updated_response = long_running_function_response.model_copy(deep=True)
updated_response.response = {'status': 'approved'}
asyncfor 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}')
# --8<-- [end:call_reimbursement_tool]# 注意:在 Colab 中可以直接在顶层使用 'await'。# 如果将此代码作为独立 Python 脚本运行,则需要使用 asyncio.run() 或管理事件循环。# 无需审批的报销# asyncio.run(call_agent_async("请报销50美元的餐费"))await call_agent_async("Please reimburse 50$ for meals") # For Notebooks, uncomment this line and comment the above line# 需要审批的报销# asyncio.run(call_agent_async("请报销200美元的餐费"))await call_agent_async("Please reimburse 200$ for meals") # For Notebooks, uncomment this line and comment the above line
# Copyright 2025 Google LLC## Licensed under the Apache License, Version 2.0 (the "License");# 除非遵守许可协议,否则您不得使用此文件。# 您可以在以下位置获取许可副本## http://www.apache.org/licenses/LICENSE-2.0## 除非适用法律要求或书面约定,否则根据许可协议分发的软件# 按“原样”提供# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# 请参阅许可协议以了解管理权限和# limitations under the License.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)]
)
# 会话与 Runnerasyncdefsetup_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 交互asyncdefcall_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)
asyncfor event in events:
if event.is_final_response():
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."""# 注意:在 Colab 中可以直接在顶层使用 'await'。# 如果将此代码作为独立 Python 脚本运行,则需要使用 asyncio.run() 或管理事件循环。await call_agent_async(long_text)
go75 行展开收起expand_more
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 创建了一个专门用于摘要文本的 Agent。funccreateSummarizerAgent(ctxcontext.Context) (agent.Agent, error) {
model, err:=gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
iferr!=nil {
returnnil, err }
returnllmagent.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 创建了将摘要 Agent 作为工具的主 Agent。funccreateMainAgent(ctxcontext.Context, tools...tool.Tool) (agent.Agent, error) {
model, err:=gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
iferr!=nil {
returnnil, err }
returnllmagent.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,
})
}
funcRunAgentAsToolSimulation() {
ctx:=context.Background()
// 1. 创建工具 Agent(摘要器)summarizerAgent, err:=createSummarizerAgent(ctx)
iferr!=nil {
log.Fatalf("Failed to create summarizer agent: %v", err)
}
// 2. 将工具 Agent 封装在 AgentTool 中summarizeTool:=agenttool.New(summarizerAgent, &agenttool.Config{
SkipSummarization: true,
})
// 3. 创建主 Agent 并为其提供 AgentToolmainAgent, err:=createMainAgent(ctx, summarizeTool)
iferr!=nil {
log.Fatalf("Failed to create main agent: %v", err)
}
// 4. 运行主 Agentprompt:=`
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---")
}