# 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.tools import FunctionTool
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
APP_NAME="weather_sentiment_agent"USER_ID="user1234"SESSION_ID="1234"MODEL_ID="gemini-2.0-flash"# 工具 1defget_weather_report(city: str) -> dict:
"""Retrieves the current weather report for a specified city.
Returns:
dict: A dictionary containing the weather information with a 'status' key ('success' or 'error') and a 'report' key with the weather details if successful, or an 'error_message' if an error occurred.
"""if city.lower() =="london":
return {"status": "success", "report": "The current weather in London is cloudy with a temperature of 18 degrees Celsius and a chance of rain."}
elif city.lower() =="paris":
return {"status": "success", "report": "The weather in Paris is sunny with a temperature of 25 degrees Celsius."}
else:
return {"status": "error", "error_message": f"Weather information for '{city}' is not available."}
weather_tool = FunctionTool(func=get_weather_report)
# 工具 2defanalyze_sentiment(text: str) -> dict:
"""Analyzes the sentiment of the given text.
Returns:
dict: A dictionary with 'sentiment' ('positive', 'negative', or 'neutral') and a 'confidence' score.
"""if"good"in text.lower() or"sunny"in text.lower():
return {"sentiment": "positive", "confidence": 0.8}
elif"rain"in text.lower() or"bad"in text.lower():
return {"sentiment": "negative", "confidence": 0.7}
else:
return {"sentiment": "neutral", "confidence": 0.6}
sentiment_tool = FunctionTool(func=analyze_sentiment)
# Agentweather_sentiment_agent = Agent(
model=MODEL_ID,
name='weather_sentiment_agent',
instruction="""You are a helpful assistant that provides weather information and analyzes the sentiment of user feedback.
**If the user asks about the weather in a specific city, use the 'get_weather_report' tool to retrieve the weather details.**
**If the 'get_weather_report' tool returns a 'success' status, provide the weather report to the user.**
**If the 'get_weather_report' tool returns an 'error' status, inform the user that the weather information for the specified city is not available and ask if they have another city in mind.**
**After providing a weather report, if the user gives feedback on the weather (e.g., 'That's good' or 'I don't like rain'), use the 'analyze_sentiment' tool to understand their sentiment.** Then, briefly acknowledge their sentiment.
You can handle these tasks sequentially if needed.""",
tools=[weather_tool, sentiment_tool]
)
asyncdefmain():
"""Main function to run the agent asynchronously."""# 会话和 Runner 设置 session_service = InMemorySessionService()
# 使用 'await' 正确创建会话await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
runner = Runner(agent=weather_sentiment_agent, app_name=APP_NAME, session_service=session_service)
# Agent 交互 query ="weather in london?" print(f"User Query: {query}")
content = types.Content(role='user', parts=[types.Part(text=query)])
# Runner 的 run 方法在内部处理异步循环 events = runner.run(user_id=USER_ID, session_id=SESSION_ID, new_message=content)
for event in events:
if event.is_final_response():
final_response = event.content.parts[0].text
print("Agent Response:", final_response)
# 运行主异步函数的标准方式if __name__ =="__main__":
asyncio.run(main())
go152 行展开收起expand_more
// 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/functiontool""google.golang.org/genai")
typegetWeatherReportArgsstruct {
Citystring`json:"city" jsonschema:"The city for which to get the weather report."`}
typegetWeatherReportResultstruct {
Statusstring`json:"status"`Reportstring`json:"report,omitempty"`}
funcgetWeatherReport(ctxagent.Context, argsgetWeatherReportArgs) (getWeatherReportResult, error) {
ifstrings.ToLower(args.City) =="london" {
returngetWeatherReportResult{Status: "success", Report: "The current weather in London is cloudy with a temperature of 18 degrees Celsius and a chance of rain."}, nil }
ifstrings.ToLower(args.City) =="paris" {
returngetWeatherReportResult{Status: "success", Report: "The weather in Paris is sunny with a temperature of 25 degrees Celsius."}, nil }
returngetWeatherReportResult{}, fmt.Errorf("weather information for '%s' is not available.", args.City)
}
typeanalyzeSentimentArgsstruct {
Textstring`json:"text" jsonschema:"The text to analyze for sentiment."`}
typeanalyzeSentimentResultstruct {
Sentimentstring`json:"sentiment"`Confidencefloat64`json:"confidence"`}
funcanalyzeSentiment(ctxagent.Context, argsanalyzeSentimentArgs) (analyzeSentimentResult, error) {
ifstrings.Contains(strings.ToLower(args.Text), "good") ||strings.Contains(strings.ToLower(args.Text), "sunny") {
returnanalyzeSentimentResult{Sentiment: "positive", Confidence: 0.8}, nil }
ifstrings.Contains(strings.ToLower(args.Text), "rain") ||strings.Contains(strings.ToLower(args.Text), "bad") {
returnanalyzeSentimentResult{Sentiment: "negative", Confidence: 0.7}, nil }
returnanalyzeSentimentResult{Sentiment: "neutral", Confidence: 0.6}, nil}
funcmain() {
ctx:=context.Background()
model, err:=gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
iferr!=nil {
log.Fatal(err)
}
weatherTool, err:=functiontool.New(
functiontool.Config{
Name: "get_weather_report",
Description: "Retrieves the current weather report for a specified city.",
},
getWeatherReport,
)
iferr!=nil {
log.Fatal(err)
}
sentimentTool, err:=functiontool.New(
functiontool.Config{
Name: "analyze_sentiment",
Description: "Analyzes the sentiment of the given text.",
},
analyzeSentiment,
)
iferr!=nil {
log.Fatal(err)
}
weatherSentimentAgent, err:=llmagent.New(llmagent.Config{
Name: "weather_sentiment_agent",
Model: model,
Instruction: "You are a helpful assistant that provides weather information and analyzes the sentiment of user feedback. **If the user asks about the weather in a specific city, use the 'get_weather_report' tool to retrieve the weather details.** **If the 'get_weather_report' tool returns a 'success' status, provide the weather report to the user.** **If the 'get_weather_report' tool returns an 'error' status, inform the user that the weather information for the specified city is not available and ask if they have another city in mind.** **After providing a weather report, if the user gives feedback on the weather (e.g., 'That's good' or 'I don't like rain'), use the 'analyze_sentiment' tool to understand their sentiment.** Then, briefly acknowledge their sentiment. You can handle these tasks sequentially if needed.",
Tools: []tool.Tool{weatherTool, sentimentTool},
})
iferr!=nil {
log.Fatal(err)
}
sessionService:=session.InMemoryService()
runner, err:=runner.New(runner.Config{
AppName: "weather_sentiment_agent",
Agent: weatherSentimentAgent,
SessionService: sessionService,
})
iferr!=nil {
log.Fatal(err)
}
session, err:=sessionService.Create(ctx, &session.CreateRequest{
AppName: "weather_sentiment_agent",
UserID: "user1234",
})
iferr!=nil {
log.Fatal(err)
}
run(ctx, runner, session.Session.ID(), "weather in london?")
run(ctx, runner, session.Session.ID(), "I don't like rain.")
}
funcrun(ctxcontext.Context, r*runner.Runner, sessionIDstring, promptstring) {
fmt.Printf("\n> %s\n", prompt)
events:=r.Run(
ctx,
"user1234",
sessionID,
genai.NewContentFromText(prompt, genai.RoleUser),
agent.RunConfig{
StreamingMode: agent.StreamingModeNone,
},
)
forevent, err:=rangeevents {
iferr!=nil {
log.Fatalf("ERROR during agent execution: %v", err)
}
ifevent.Content.Parts[0].Text!="" {
fmt.Printf("Agent Response: %s\n", event.Content.Parts[0].Text)
}
}
}
# 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.tools import FunctionTool
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.tools import ToolContext
from google.genai import types
APP_NAME="customer_support_agent"USER_ID="user1234"SESSION_ID="1234"defcheck_and_transfer(query: str, tool_context: ToolContext) -> str:
"""Checks if the query requires escalation and transfers to another agent if needed."""if"urgent"in query.lower():
print("Tool: Detected urgency, transferring to the support agent.")
tool_context.actions.transfer_to_agent ="support_agent"return"Transferring to the support agent..."else:
returnf"Processed query: '{query}'. No further action needed."escalation_tool = FunctionTool(func=check_and_transfer)
main_agent = Agent(
model='gemini-2.0-flash',
name='main_agent',
instruction="""You are the first point of contact for customer support of an analytics tool. Answer general queries. If the user indicates urgency, use the 'escalation_tool' tool.""",
tools=[escalation_tool]
)
support_agent = Agent(
model='gemini-2.0-flash',
name='support_agent',
instruction="""You are the dedicated support agent. Mentioned you are a support handler and please help the user with their urgent issue.""")
main_agent.sub_agents = [support_agent]
# 会话与 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=main_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("this is urgent, i cant login")
go129 行展开收起expand_more
// 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/functiontool""google.golang.org/genai")
typecheckAndTransferArgsstruct {
Querystring`json:"query" jsonschema:"The user's query to check for urgency."`}
typecheckAndTransferResultstruct {
Statusstring`json:"status"`}
funccheckAndTransfer(ctxagent.Context, argscheckAndTransferArgs) (checkAndTransferResult, error) {
ifstrings.Contains(strings.ToLower(args.Query), "urgent") {
fmt.Println("Tool: Detected urgency, transferring to the support agent.")
ctx.Actions().TransferToAgent = "support_agent"returncheckAndTransferResult{Status: "Transferring to the support agent..."}, nil }
returncheckAndTransferResult{Status: fmt.Sprintf("Processed query: '%s'. No further action needed.", args.Query)}, nil}
funcmain() {
ctx:=context.Background()
model, err:=gemini.NewModel(ctx, "gemini-flash-latest", &genai.ClientConfig{})
iferr!=nil {
log.Fatal(err)
}
supportAgent, err:=llmagent.New(llmagent.Config{
Name: "support_agent",
Model: model,
Instruction: "You are the dedicated support agent. Mentioned you are a support handler and please help the user with their urgent issue.",
})
iferr!=nil {
log.Fatal(err)
}
checkAndTransferTool, err:=functiontool.New(
functiontool.Config{
Name: "check_and_transfer",
Description: "Checks if the query requires escalation and transfers to another agent if needed.",
},
checkAndTransfer,
)
iferr!=nil {
log.Fatal(err)
}
mainAgent, err:=llmagent.New(llmagent.Config{
Name: "main_agent",
Model: model,
Instruction: "You are the first point of contact for customer support of an analytics tool. Answer general queries. If the user indicates urgency, use the 'check_and_transfer' tool.",
Tools: []tool.Tool{checkAndTransferTool},
SubAgents: []agent.Agent{supportAgent},
})
iferr!=nil {
log.Fatal(err)
}
sessionService:=session.InMemoryService()
runner, err:=runner.New(runner.Config{
AppName: "customer_support_agent",
Agent: mainAgent,
SessionService: sessionService,
})
iferr!=nil {
log.Fatal(err)
}
session, err:=sessionService.Create(ctx, &session.CreateRequest{
AppName: "customer_support_agent",
UserID: "user1234",
})
iferr!=nil {
log.Fatal(err)
}
run(ctx, runner, session.Session.ID(), "this is urgent, i cant login")
}
funcrun(ctxcontext.Context, r*runner.Runner, sessionIDstring, promptstring) {
fmt.Printf("\n> %s\n", prompt)
events:=r.Run(
ctx,
"user1234",
sessionID,
genai.NewContentFromText(prompt, genai.RoleUser),
agent.RunConfig{
StreamingMode: agent.StreamingModeNone,
},
)
forevent, err:=rangeevents {
iferr!=nil {
log.Fatalf("ERROR during agent execution: %v", err)
}
ifevent.Content.Parts[0].Text!="" {
fmt.Printf("Agent Response: %s\n", event.Content.Parts[0].Text)
}
}
}
deflookup_order_status(order_id: str) -> dict:
"""Fetches the current status of a customer's order using its ID.
Use this tool ONLY when a user explicitly asks for the status of
a specific order and provides the order ID. Do not use it for
general inquiries.
Args:
order_id: The unique identifier of the order to look up.
Returns:
A dictionary indicating the outcome.
On success, status is 'success' and includes an 'order' dictionary.
On failure, status is 'error' and includes an 'error_message'.
Example success: {'status': 'success', 'order': {'state': 'shipped', 'tracking_number': '1Z9...'}}
Example error: {'status': 'error', 'error_message': 'Order ID not found.'}
"""# ... 函数实现以获取状态 ...if status_details := fetch_status_from_backend(order_id):
return {
"status": "success",
"order": {
"state": status_details.state,
"tracking_number": status_details.tracking,
},
}
else:
return {"status": "error", "error_message": f"Order ID {order_id} not found."}
go34 行展开收起expand_more
import (
"fmt""google.golang.org/adk/v2/agent")
typelookupOrderStatusArgsstruct {
OrderIDstring`json:"order_id" jsonschema:"The ID of the order to look up."`}
typeorderstruct {
Statestring`json:"state"`TrackingNumberstring`json:"tracking_number"`}
typelookupOrderStatusResultstruct {
Statusstring`json:"status"`Orderorder`json:"order,omitempty"`}
funclookupOrderStatus(ctxagent.Context, argslookupOrderStatusArgs) (*lookupOrderStatusResult, error) {
// ... 函数实现以获取状态 ...statusDetails, ok:=fetchStatusFromBackend(args.OrderID)
if !ok {
returnnil, fmt.Errorf("order ID %s not found", args.OrderID)
}
return&lookupOrderStatusResult{
Status: "success",
Order: order{
State: statusDetails.State,
TrackingNumber: statusDetails.Tracking,
},
}, nil}