用于现场客服人员的工具¶
这些工具在实时客服(Live Agent)环境中的使用方式,与在 ADK 的其他任何地方使用方式完全相同:您将相关函数传递给客服人员,然后模型会自动调用这些函数。无论是否处于实时连接状态,编写工具的方式都不会发生变化;因此,工具的定义、使用环境、回调机制以及身份验证流程都保持不变。 自定义工具.
实时连接还提供了两项额外的功能:ADK 会为你在后台执行相应的工具调用(即自动执行那些需要执行的操作)。
run_live() 这个循环机制可以让你避免编写那些处理 Live API 原始接口所需的功能调用逻辑。Live 代理也可以使用这个机制。 流媒体工具这些函数会持续运行,并将中间结果发送回代理(agent);这样,代理就可以在股票价格发生变化或有人在视频画面中出现时立即做出反应,而无需用户再次发出指令。
自动工具执行¶
在您的代理(agent)上定义所需的工具;当需要使用这些工具时,ADK 会自动为您调用它们。 run_live() `loop: it`
该工具会检测模型中的函数调用,同时运行相关的工具(这些工具会与你的 `before/after` 回调函数并行执行),对返回的结果进行格式化,并将函数调用信息及返回结果都作为事件输出。你需要编写的是模型中的函数本身,而不是处理这些底层逻辑的代码。
import os
from google.adk.agents import Agent
from google.adk.tools import google_search
agent = Agent(
name="google_search_agent",
model=os.getenv("DEMO_AGENT_MODEL", "gemini-live-2.5-flash-native-audio"),
tools=[google_search],
instruction="You are a helpful assistant that can search the web.",
)
你通过事件流来观察工具的运行状态;但你从不主动控制这些工具的运行过程。
async for event in runner.run_live(...):
if event.get_function_calls():
print(f"Model calling: {event.get_function_calls()[0].name}")
if event.get_function_responses():
print(f"Tool result: {event.get_function_responses()[0].response}")
确保代理程序能够及时响应用户的请求(即保持其“响应性”)。¶
在聊天窗口中,即使工具运行速度较慢,用户仍然可以忍受(因为用户可以看到进度条或等待指示)。但在实时语音通话中,这种情况就无法忍受了:如果客服人员调用了一个需要 10 秒才能完成的 API,然后突然沉默不语,用户很可能会认为通话已经中断了。因此,你需要一种在运行过程中不会干扰通话流程的工具。ADK 提供了两种实现这一目标的方法;对于那些需要快速响应的情况,ADK 也提供了简单的“阻塞”功能。
| 你的情况 | 使用 | 如何 |
|---|---|---|
| 该工具在不到一秒钟的时间内即可完成返回结果。 | 阻塞(Blocking) (默认值) | 一个普通的…… return tool |
| 漫长的等待……期间却没有任何事情可以描述(或:漫长的等待,却没有任何值得记录的事情发生)。 | 非阻塞工具 | `Set` response_scheduling 或者 behavior 在工具上;通过该工具 |
| 漫长的等待过程确实值得被记录下来(即:这段等待经历很有意义,值得被分享或记录下来)。 | 流媒体工具 | yield 从一个异步生成器(async generator)开始,逐步完成后续的处理(progress from an async generator)。 |
非阻塞工具¶
有些等待过程其实并不值得特别描述:比如一个耗时较长的分析查询、一次批量数据导出操作,或者一个媒体文件生成任务。向用户展示这些任务的进度更新其实并无实际意义(因为用户并没有要求中断当前的对话),也没有任何实际帮助。因此,最好保持简洁明了的沟通方式。 return“Once you have mastered the relevant tools and techniques…”(一旦你掌握了相关的工具和技术……) response_scheduling 将其移至后台(即不再显示在屏幕上):
`background:`
from google.adk.tools import FunctionTool
from google.genai import types
async def export_report(region: str) -> dict:
"""Generate and store the quarterly report. Returns when the export finishes."""
await run_export(region) # a long, plain return-once operation
return {"status": "done", "region": region}
report_tool = FunctionTool(export_report)
report_tool.response_scheduling = types.FunctionResponseScheduling.WHEN_IDLE
在该工具运行期间,代理程序会保持处于“空闲”状态(即不会被其他任务占用);它会回答用户提出的任何其他问题,并在工具完成处理后及时将处理结果提供给用户。一个可运行的示例程序已随软件一起提供。
non_blocking_tool_agent sample.
需要 ADK Python 2.4 或更高版本。
The response_scheduling 该功能已在 adk-python 2.4 中添加,具体支持情况取决于不同的模型。详情请参阅……
支持的模型.
response_scheduling 也负责控制(相关系统或流程)。 当……的时候 最终完成的结果会直接呈现给用户。
| 值 | 行为(Behavior) | 将其用于…… |
|---|---|---|
WHEN_IDLE |
等待自然出现的停顿(即说话者暂时停止说话的时刻)。 | 报告与查询功能,通常是人们的首选。 |
INTERRUPT |
立即交付 | 警报、故障信息,以及“传输失败”的提示。 |
SILENT |
只有在相关的情况下才会被显示/宣布。 | 模型后续可能使用的背景信息 |
设置 behavior 明确地;特意地¶
您还可以将某个工具标记为“非阻塞型”(即该工具不会阻塞其他任务的执行)。 behavior `field`:当该字段被设置时,其优先级会高于其他所有字段。 response_scheduling:
需要 ADK Python 2.10 或更高版本。
The behavior 该字段是在 adk-python 2.10 版本中新增的。
流媒体工具¶
这个流媒体工具会持续运行,并将中间处理结果发送回代理程序;这样,代理程序就可以随时更新用户关于处理进度的信息,或者对输入数据的变化(例如股票价格的变化、有人进入视频画面等)做出反应,而无需用户再次发起请求。要实现这个功能,只需要对代码进行一行修改即可。
async `that` 函数 yield用 “s” 代替原来的内容。 returns. ADK 会自动将任何异步生成器工具视为非阻塞(non-blocking)的。
import asyncio
from typing import AsyncGenerator
async def query_sales_database(region: str) -> AsyncGenerator[str, None]:
"""Run the quarterly sales report. Call this once; it streams its own updates."""
yield "Connecting to the warehouse..."
await asyncio.sleep(4)
yield "Aggregating by product line..."
await asyncio.sleep(4)
yield f"Done. {summarise(region)}"
把它传给…… tools=[...] 就像其他工具一样,该模型也会接收每一个输入数据(或每个输入项)。 yield 作为一个实时更新信息,用户听到的不是“没有数据可显示”,而是“让我先把这些数据调出来……数据还在汇总中……好了:EMEA地区的销售额为 481 万美元,增长了 12.4%”。这种更新方式非常适合用于 RAG(Report, Analysis, and Governance)流程、多阶段数据汇总过程,以及“构建-测试”循环(即先构建数据模型,再对其进行测试的流程);无论在什么情况下,只要数据的更新进度值得被用户知晓,这种更新方式都是非常实用的。
添加 ADK 的保留资源(或:添加 ADK 的预留部分)。 stop_streaming 这个函数是一个空函数(即没有任何实际功能的函数),它的名称仅用于方便用户取消操作。这样,当用户决定不再继续执行某个操作时,就可以直接说:“算了,取消吧。”
视频流媒体工具¶
添加一个 input_stream: LiveRequestQueue 该工具接收来自用户端的实时输入数据(这些数据通过参数和 ADK 接口传输),并将这些数据放入专门的队列中。这样,该工具就可以从队列中获取视频帧,并对这些视频帧做出相应的处理(例如显示、分析等)。
任何流媒体工具的基本要求如下:
- 这一定是一个……
async这个函数被设计为返回一个……(具体类型需要根据上下文来确定)。AsyncGenerator[T, None]……其中T“is” 是你提到的那种类型(type)。yield. - 对于视频内容,请添加相应的处理或显示方式。
input_stream: LiveRequestQueueADK 会自动完成填充工作。
以下模式会从队列中取出最新的数据帧(即最新的信息),同时丢弃过时的数据帧;只有当答案发生变化时,代理才会作出响应(即停止保持沉默状态);否则,代理会继续保持静默状态。
import asyncio
import os
from typing import AsyncGenerator
from google.adk.agents import LiveRequestQueue
from google.adk.agents.llm_agent import Agent
from google.adk.tools.function_tool import FunctionTool
from google.genai import Client
from google.genai import types as genai_types
PROMPT = "How many people are in this image? Reply with a number only."
async def monitor_video_stream(
input_stream: LiveRequestQueue,
) -> AsyncGenerator[str, None]:
"""Report how many people are visible, whenever that number changes."""
client = Client()
last_count = None
while True:
# Drain the queue and keep only the newest frame; older ones are stale.
latest = None
while input_stream._queue.qsize() != 0:
req = await input_stream.get()
if req.blob and req.blob.mime_type == "image/jpeg":
latest = req
if latest is not None:
response = client.models.generate_content(
model="gemini-flash-latest",
contents=genai_types.Content(
role="user",
parts=[
genai_types.Part.from_bytes(
data=latest.blob.data, mime_type=latest.blob.mime_type
),
genai_types.Part.from_text(text=PROMPT),
],
),
)
count = response.candidates[0].content.parts[0].text.strip()
if count != last_count:
last_count = count
yield count
await asyncio.sleep(0.5)
# ADK intercepts this by name; the body stays empty.
def stop_streaming(function_name: str):
"""Stop a running streaming tool.
Args:
function_name: The name of the streaming function to stop.
"""
root_agent = Agent(
# Streaming tools run under run_live(), so the root agent needs a Live
# model. gemini-flash-latest above is only for the one-shot call in the tool.
model=os.getenv("DEMO_AGENT_MODEL", "gemini-live-2.5-flash-native-audio"),
name="video_monitoring_agent",
instruction=(
"You monitor the user's video stream. Call monitor_video_stream once when"
" asked, then report each update it sends. Never call it again to poll."
),
tools=[monitor_video_stream, FunctionTool(stop_streaming)],
)
import com.google.adk.agents.LiveRequestQueue;
import com.google.adk.agents.LlmAgent;
import com.google.adk.tools.Annotations.Schema;
import com.google.adk.tools.FunctionTool;
import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.Part;
import io.reactivex.rxjava3.core.Flowable;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class StreamingTools {
private static final String PROMPT =
"How many people are in this image? Reply with a number only.";
// `inputStream` is a reserved parameter name; ADK passes the video stream in.
@Schema(description = "Report how many people are visible, whenever that number changes.")
public static Flowable<Map<String, Object>> monitorVideoStream(
@Schema(name = "inputStream") LiveRequestQueue inputStream) {
Client client = Client.builder().build();
return inputStream
.get()
.filter(req -> req.blob().isPresent()
&& "image/jpeg".equals(req.blob().get().mimeType()))
.sample(500, TimeUnit.MILLISECONDS) // newest frame every 0.5s
.map(req -> client.models().generateContent(
"gemini-flash-latest",
Content.builder()
.role("user")
.parts(Arrays.asList(
Part.builder().inlineData(req.blob().get()).build(),
Part.fromText(PROMPT)))
.build(),
GenerateContentConfig.builder().build())
.text())
.distinctUntilChanged() // yield only when the count changes
.map(count -> Map.of("result", count));
}
// ADK intercepts this by name; the body stays empty.
@Schema(description = "Stop a running streaming tool.")
public static void stopStreaming(
@Schema(name = "functionName", description = "The streaming function to stop.")
String functionName) {}
public static void main(String[] args) {
LlmAgent rootAgent =
LlmAgent.builder()
.model("gemini-live-2.5-flash-native-audio")
.name("video_monitoring_agent")
.instruction(
"You monitor the user's video stream. Call monitorVideoStream once when"
+ " asked, then report each update it sends. Never call it again to poll.")
.tools(Arrays.asList(
FunctionTool.create(StreamingTools.class, "monitorVideoStream"),
FunctionTool.create(StreamingTools.class, "stopStreaming")))
.build();
}
}
你可以试试:让客服人员监控视频流中的人数,同时观察有人是如何进出画面的。
工具执行上下文(Tool Execution Context)¶
一个工具接收到了…… ToolContext以及一个回调函数(callback)。 CallbackContext这些功能用于获取状态信息、历史数据以及相关“工件”(artifacts)。它们的使用方式与任何 ADK 代理(agent)中的功能完全相同——详见相关文档。
代理上下文(Agent context) ——只有一个重要的区别: “underlying” 的意思是“根本的”或“基础的”。例如,在描述某种现象或问题时,可以使用 “underlying cause”(根本原因)或 “underlying principle”(基本原则)来强调其本质或基础。 InvocationContext “spans the entire” 的意思是“覆盖整个范围”或“包含所有部分”。例如:
- “This software spans the entire software development process.”(该软件涵盖了整个软件开发流程。)
- “The database spans all regions of the country.”(这个数据库覆盖了全国的所有地区。) run_live() 循环(loop)该内容是在您调用相关函数时生成的。
run_live() 这个过程会持续进行,贯穿每一个代理(agent)和每一个对话环节,直到会话结束。在基于请求/响应(request/response)模式的系统中,一次调用(invocation)仅代表一个对话环节;而在实时会话(live session)中,一次调用则涵盖了整个对话过程。
在实时工具中,有两个字段最为常见:
| 字段(Field) | 它能为你提供什么 |
|---|---|
tool_context.run_config |
该会话的(session's) 配置 — 响应方式(response modalities)、转录(transcription)以及相关限制(limits) |
tool_context.state |
会话状态(Session state):可以直接对其进行修改,而 ADK 会自动保存这些更改。 |