运行时事件循环(Runtime Event Loop)¶
ADK Runtime 是一个底层引擎,它在用户与应用程序交互的过程中为该应用程序提供支持。该引擎负责处理您定义的代理程序(agents)、工具(tools)以及回调函数(callbacks),并根据用户的输入来协调这些组件的执行过程;同时它还负责管理信息流、状态变化,以及与外部服务(如大型语言模型 LLMs 或存储系统)的交互。
可以将“Runtime”(运行时环境)理解为……(具体含义需要根据上下文来确定)。 “engine” 这是关于您的代理应用程序(agent application)的内容。您负责定义各个组成部分(如代理程序、工具等),而运行时系统(runtime system)则负责处理这些组件之间的连接与协同工作,从而完成用户的请求。
核心理念:事件循环(Event Loop)¶
从根本上说,ADK Runtime 的运行原理是基于……(此处应补充具体的技术原理或框架)。 事件循环(Event Loop)这个循环促进了双方之间的来回交流(即双向沟通)。 Runner 该组件以及您定义的“执行逻辑”(其中包括您的代理程序、它们对大型语言模型(LLM)的调用、回调函数以及相关工具)。

简单来说:
- The
Runner接收用户的查询请求,然后将其传递给主系统(或模块)进行处理。Agent开始处理。 - The
Agent(以及相关的逻辑)会一直运行,直到有需要报告的内容出现(例如响应结果、使用某个工具的请求,或状态变化)——之后才会停止运行。 “yields” 的意思是“产生(某种结果);产量;收益”。例如: - “The new machine yields higher efficiency than the old one.”(这台新机器的效率比旧机器更高。) - “The crops yielded a good harvest this year.”(今年的收成很丰收。) 或者 “emits” 的意思是“发出”或“释放”某种物质、信号或能量。例如,一个灯泡在发光时,实际上是在“发出”光子(一种微小的能量粒子)。在技术或科学语境中,这个术语常用来描述设备或系统如何向外部环境传递信息或数据。 anEvent. - The
Runner接收这个Event处理所有相关的操作(例如通过某种方式保存状态变更)。Services然后,该系统会将事件进一步转发(例如,转发到用户界面)。 - The
Agent“s logic” 简历 仅从它暂停的位置继续执行。 之后;随后 theRunner系统已经处理了该事件,随后可能会观察到由“Runner”(执行者)所做出的更改所带来的影响。 - 这个循环会一直重复,直到代理没有更多事件可以提供给当前用户的查询请求为止。
这个基于事件驱动的循环是控制 ADK 如何执行你的代理代码(agent code)的基本模式。
“心跳”:事件循环——其内部工作机制¶
事件循环(Event Loop)是定义应用程序各组件之间交互的核心运行机制。 Runner 以及您的自定义代码(代理程序、工具、回调函数等,在设计文档中统称为“执行逻辑”或“逻辑组件”)。这种划分方式明确了各方的职责。
注意:
具体的方法名称和参数名称可能会因 SDK 使用的语言而略有不同(例如: agent.run_async(...) 在 Python 中, agent.Run(...) 在 Go 语言中, agent.runAsync(...) (适用于 Java 和 TypeScript)。详情请参阅相应语言的 API 文档。
跑者的角色(即协调者/orchestrator)¶
The Runner 它作为单个用户请求的中心协调者。在该流程中,它的职责包括:
- **Initiation:** 接收最终用户的查询请求。)
new_message)通常会通过该方式将其添加到会话历史记录中。SessionService. - 项目启动(Kick-off): 通过调用主要代理的执行方法来启动事件生成过程(例如:
agent_to_run.run_async(...)). - 接收并处理: 等待代理逻辑的执行完成……
yield或者emitanEvent. 当接收到某个事件时,该组件(Runner)会…… 立即处理 这包括以下内容:- 使用已配置的设置(或资源)。
Services(SessionService,ArtifactService,MemoryService)以提交所指示的更改。event.actions(就像……一样)state_delta,artifact_delta). - 执行其他内部记账工作。
- 使用已配置的设置(或资源)。
- “Yield Upstream”: 这个术语通常用于描述供应链或生产流程中的某种协作或资源共享机制。具体含义可能因上下文而异,但一般来说,它表示“上游方向下游方提供资源或支持”(即上游企业向下游企业提供所需的原材料、产品或服务)。例如,在制造业中,上游供应商可能会向下游制造商提供零部件或半成品,从而帮助后者完成产品的生产。这种协作有助于提高整体供应链的效率和质量。 将处理后的事件进一步传递给其他系统或组件(例如,传递给调用该事件的应用程序或用于显示该事件的用户界面)。
- 迭代: 该信号向代理逻辑表明:针对该事件的处理已经完成,因此代理可以继续执行后续操作(例如生成相关数据或结果)。 next `event.`
概念性的运行循环(Conceptual Runner Loop):
# Simplified view of Runner's main loop logic
async def run_async(new_query, ...) -> AsyncGenerator[Event, None]:
# 1. Append new_query to session event history (via SessionService)
await session_service.append_event(session, Event(author='user', content=new_query))
# 2. Kick off event loop by calling the agent
agent_event_generator = agent_to_run.run_async(context)
async for event in agent_event_generator:
# 3. Process the generated event and commit changes
await session_service.append_event(session, event) # Commits state/artifact deltas etc.
# memory_service.update_memory(...) # If applicable
# artifact_service might have already been called via context during agent run
# 4. Yield event for upstream processing (e.g., UI rendering)
yield event
# Runner implicitly signals agent generator can continue after yielding
// Simplified view of Runner's main loop logic
async * runAsync(newQuery: Content, ...): AsyncGenerator<Event, void, void> {
// 1. Append newQuery to session event history (via SessionService)
await sessionService.appendEvent({
session,
event: createEvent({author: 'user', content: newQuery})
});
// 2. Kick off event loop by calling the agent
const agentEventGenerator = agentToRun.runAsync(context);
for await (const event of agentEventGenerator) {
// 3. Process the generated event and commit changes
// Commits state/artifact deltas etc.
await sessionService.appendEvent({session, event});
// memoryService.updateMemory(...) // If applicable
// artifactService might have already been called via context during agent run
// 4. Yield event for upstream processing (e.g., UI rendering)
yield event;
// Runner implicitly signals agent generator can continue after yielding
}
}
// Simplified conceptual view of the Runner's main loop logic in Go
func (r *Runner) RunConceptual(ctx context.Context, session *session.Session, newQuery *genai.Content) iter.Seq2[*Event, error] {
return func(yield func(*Event, error) bool) {
// 1. Append new_query to session event history (via SessionService)
// ...
userEvent := session.NewEvent(ctx, ctx.InvocationID()) // Simplified for conceptual view
userEvent.Author = "user"
userEvent.LLMResponse = model.LLMResponse{Content: newQuery}
if _, err := r.sessionService.Append(ctx, &session.AppendRequest{Event: userEvent}); err != nil {
yield(nil, err)
return
}
// 2. Kick off event stream by calling the agent
// Assuming agent.Run also returns iter.Seq2[*Event, error]
agentEventsAndErrs := r.agent.Run(ctx, &agent.RunRequest{Session: session, Input: newQuery})
for event, err := range agentEventsAndErrs {
if err != nil {
if !yield(event, err) { // Yield event even if there's an error, then stop
return
}
return // Agent finished with an error
}
// 3. Process the generated event and commit changes
// Only commit non-partial event to a session service (as seen in actual code)
if !event.LLMResponse.Partial {
if _, err := r.sessionService.Append(ctx, &session.AppendRequest{Event: event}); err != nil {
yield(nil, err)
return
}
}
// memory_service.update_memory(...) // If applicable
// artifact_service might have already been called via context during agent run
// 4. Yield event for upstream processing
if !yield(event, nil) {
return // Upstream consumer stopped
}
}
// Agent finished successfully
}
}
// Simplified conceptual view of the Runner's main loop logic in Java.
public Flowable<Event> runConceptual(
Session session,
InvocationContext invocationContext,
Content newQuery
) {
// 1. Append new_query to session event history (via SessionService)
// ...
sessionService.appendEvent(session, userEvent).blockingGet();
// 2. Kick off event stream by calling the agent
Flowable<Event> agentEventStream = agentToRun.runAsync(invocationContext);
// 3. Process each generated event, commit changes, and "yield" or "emit"
return agentEventStream.map(event -> {
// This mutates the session object (adds event, applies stateDelta).
// The return value of appendEvent (a Single<Event>) is conceptually
// just the event itself after processing.
sessionService.appendEvent(session, event).blockingGet(); // Simplified blocking call
// memory_service.update_memory(...) // If applicable - conceptual
// artifact_service might have already been called via context during agent run
// 4. "Yield" event for upstream processing
// In RxJava, returning the event in map effectively yields it to the next operator or subscriber.
return event;
});
}
/**
* Simplified view of Runner's main loop logic in Kotlin
*/
fun runAsync(
userId: String,
sessionId: String,
newMessage: Content,
runner: InMemoryRunner,
sessionService: InMemorySessionService,
): Flow<Event> {
// 1. Append newMessage to session event history (via SessionService)
// 2. Kick off event loop by calling the agent
// 3. Process generated events, commit changes, and yield upstream
return runner
.runAsync(
userId = userId,
sessionId = sessionId,
newMessage = newMessage,
).onEach { event ->
// Process the event and commit changes to services (done internally by Runner)
// sessionService.appendEvent(...)
}
}
执行逻辑的作用(代理、工具、回调函数)¶
你在代理程序(agents)、工具(tools)以及回调函数(callbacks)中编写的代码,负责实际的计算和决策过程。该代码与循环结构(loop)的交互方式包括:
- 执行: 根据当前情况来执行其逻辑。
InvocationContext(包括会话状态在内的所有数据) 正如执行恢复时的情况一样……. - 产量: 当逻辑需要与其他组件进行通信(发送消息、调用某个工具、报告状态变化)时,它会构建相应的通信机制。
Event其中包含相关的内容及操作步骤,然后……yield将此事件恢复到……状态。Runner. - 暂停: 至关重要的是,代理逻辑的执行过程(即代理程序如何根据接收到的指令来执行相应的操作)。 立即暂停。 在……之后
yieldstatement(或return(在 RxJava 中)。它会等待……Runner为了完成第 3 步(数据处理与数据提交)。 - 简历: 只有在……之后才…… the
Runner在处理完该事件后,代理逻辑是否会立即从该事件之后的下一条语句继续执行?yield. - 查看更新后的状态: 在恢复运行后,代理逻辑现在可以可靠地访问会话状态了。
ctx.session.state)反映了那些已被提交的更改(即:这些更改是通过相应的操作或流程被正式记录并应用到系统中的)。Runnerfrom the 之前曾产生过(某种结果或效果) `event.`
概念性执行逻辑(Conceptual Execution Logic):
# Simplified view of logic inside Agent.run_async, callbacks, or tools
# ... previous code runs based on current state ...
# 1. Determine a change or output is needed, construct the event
# Example: Updating state
update_data = {'field_1': 'value_2'}
event_with_state_change = Event(
author=self.name,
actions=EventActions(state_delta=update_data),
content=types.Content(parts=[types.Part(text="State updated.")])
# ... other event fields ...
)
# 2. Yield the event to the Runner for processing & commit
yield event_with_state_change
# <<<<<<<<<<<< EXECUTION PAUSES HERE >>>>>>>>>>>>
# <<<<<<<<<<<< RUNNER PROCESSES & COMMITS THE EVENT >>>>>>>>>>>>
# 3. Resume execution ONLY after Runner is done processing the above event.
# Now, the state committed by the Runner is reliably reflected.
# Subsequent code can safely assume the change from the yielded event happened.
val = ctx.session.state['field_1']
# here `val` is guaranteed to be "value_2" (assuming Runner committed successfully)
print(f"Resumed execution. Value of field_1 is now: {val}")
# ... subsequent code continues ...
# Maybe yield another event later...
// Simplified view of logic inside Agent.runAsync, callbacks, or tools
// ... previous code runs based on current state ...
// 1. Determine a change or output is needed, construct the event
// Example: Updating state
const updateData = {'field_1': 'value_2'};
const eventWithStateChange = createEvent({
author: this.name,
actions: createEventActions({stateDelta: updateData}),
content: {parts: [{text: "State updated."}]}
// ... other event fields ...
});
// 2. Yield the event to the Runner for processing & commit
yield eventWithStateChange;
// <<<<<<<<<<<< EXECUTION PAUSES HERE >>>>>>>>>>>>
// <<<<<<<<<<<< RUNNER PROCESSES & COMMITS THE EVENT >>>>>>>>>>>>
// 3. Resume execution ONLY after Runner is done processing the above event.
// Now, the state committed by the Runner is reliably reflected.
// Subsequent code can safely assume the change from the yielded event happened.
const val = ctx.session.state['field_1'];
// here `val` is guaranteed to be "value_2" (assuming Runner committed successfully)
console.log(`Resumed execution. Value of field_1 is now: ${val}`);
// ... subsequent code continues ...
// Maybe yield another event later...
// Simplified view of logic inside Agent.Run, callbacks, or tools
// ... previous code runs based on current state ...
// 1. Determine a change or output is needed, construct the event
// Example: Updating state
updateData := map[string]interface{}{"field_1": "value_2"}
eventWithStateChange := &Event{
Author: self.Name(),
Actions: &EventActions{StateDelta: updateData},
Content: genai.NewContentFromText("State updated.", "model"),
// ... other event fields ...
}
// 2. Yield the event to the Runner for processing & commit
// In Go, this is done by sending the event to a channel.
eventsChan <- eventWithStateChange
// <<<<<<<<<<<< EXECUTION PAUSES HERE (conceptually) >>>>>>>>>>>>
// The Runner on the other side of the channel will receive and process the event.
// The agent's goroutine might continue, but the logical flow waits for the next input or step.
// <<<<<<<<<<<< RUNNER PROCESSES & COMMITS THE EVENT >>>>>>>>>>>>
// 3. Resume execution ONLY after Runner is done processing the above event.
// In a real Go implementation, this would likely be handled by the agent receiving
// a new RunRequest or context indicating the next step. The updated state
// would be part of the session object in that new request.
// For this conceptual example, we'll just check the state.
val := ctx.State.Get("field_1")
// here `val` is guaranteed to be "value_2" because the Runner would have
// updated the session state before calling the agent again.
fmt.Printf("Resumed execution. Value of field_1 is now: %v\n", val)
// ... subsequent code continues ...
// Maybe send another event to the channel later...
// Simplified view of logic inside Agent.runAsync, callbacks, or tools
// ... previous code runs based on current state ...
// 1. Determine a change or output is needed, construct the event
// Example: Updating state
ConcurrentMap<String, Object> updateData = new ConcurrentHashMap<>();
updateData.put("field_1", "value_2");
EventActions actions = EventActions.builder().stateDelta(updateData).build();
Content eventContent = Content.builder().parts(Part.fromText("State updated.")).build();
Event eventWithStateChange = Event.builder()
.author(self.name())
.actions(actions)
.content(Optional.of(eventContent))
// ... other event fields ...
.build();
// 2. "Yield" the event. In RxJava, this means emitting it into the stream.
// The Runner (or upstream consumer) will subscribe to this Flowable.
// When the Runner receives this event, it will process it (e.g., call sessionService.appendEvent).
// The 'appendEvent' in Java ADK mutates the 'Session' object held within 'ctx' (InvocationContext).
// <<<<<<<<<<<< CONCEPTUAL PAUSE POINT >>>>>>>>>>>>
// In RxJava, the emission of 'eventWithStateChange' happens, and then the stream
// might continue with a 'flatMap' or 'concatMap' operator that represents
// the logic *after* the Runner has processed this event.
// To model the "resume execution ONLY after Runner is done processing":
// The Runner's `appendEvent` is usually an async operation itself (returns Single<Event>).
// The agent's flow needs to be structured such that subsequent logic
// that depends on the committed state runs *after* that `appendEvent` completes.
// This is how the Runner typically orchestrates it:
// Runner:
// agent.runAsync(ctx)
// .concatMapEager(eventFromAgent ->
// sessionService.appendEvent(ctx.session(), eventFromAgent) // This updates ctx.session().state()
// .toFlowable() // Emits the event after it's processed
// )
// .subscribe(processedEvent -> { /* UI renders processedEvent */ });
// So, within the agent's own logic, if it needs to do something *after* an event it yielded
// has been processed and its state changes are reflected in ctx.session().state(),
// that subsequent logic would typically be in another step of its reactive chain.
// For this conceptual example, we'll emit the event, and then simulate the "resume"
// as a subsequent operation in the Flowable chain.
return Flowable.just(eventWithStateChange) // Step 2: Yield the event
.concatMap(yieldedEvent -> {
// <<<<<<<<<<<< RUNNER CONCEPTUALLY PROCESSES & COMMITS THE EVENT >>>>>>>>>>>>
// At this point, in a real runner, ctx.session().appendEvent(yieldedEvent) would have been called
// by the Runner, and ctx.session().state() would be updated.
// Since we are *inside* the agent's conceptual logic trying to model this,
// we assume the Runner's action has implicitly updated our 'ctx.session()'.
// 3. Resume execution.
// Now, the state committed by the Runner (via sessionService.appendEvent)
// is reliably reflected in ctx.session().state().
Object val = ctx.session().state().get("field_1");
// here `val` is guaranteed to be "value_2" because the `sessionService.appendEvent`
// called by the Runner would have updated the session state within the `ctx` object.
System.out.println("Resumed execution. Value of field_1 is now: " + val);
// ... subsequent code continues ...
// If this subsequent code needs to yield another event, it would do so here.
/**
* Simplified view of logic inside Agent.runAsync, callbacks, or tools in Kotlin
*/
suspend fun executionLogic(ctx: InvocationContext) {
// ... previous code runs based on current state ...
// 1. Determine a change or output is needed, construct the event
val updateData = mapOf("field_1" to "value_2")
val eventWithStateChange =
Event(
author = "my_agent",
actions = EventActions(stateDelta = updateData.toMutableMap()),
content = Content.fromText(Role.MODEL, "State updated."),
)
// 2. Yield the event to the Runner for processing & commit
// In Kotlin, this is done by emitting to the Flow
// emit(eventWithStateChange)
// <<<<<<<<<<<< EXECUTION PAUSES HERE >>>>>>>>>>>>
// (Implicitly, when the Flow consumer collects the event and processes it)
// <<<<<<<<<<<< RUNNER PROCESSES & COMMITS THE EVENT >>>>>>>>>>>>
// 3. Resume execution ONLY after Runner is done processing.
// Now, the state committed by the Runner is reliably reflected.
val val1 = ctx.session.state["field_1"]
println("Resumed execution. Value of field_1 is now: $val1")
}
这个合作社在“生产/暂停/恢复”之间的循环模式…… Runner 以及你的执行逻辑(Execution Logic),这些逻辑是通过某种机制(mediated by)来实现的。 Event 对象(objects)是 ADK 运行时(ADK Runtime)的核心组成部分。
运行时(Runtime)的关键组件¶
在 ADK 运行时(ADK Runtime)中,多个组件协同工作以执行代理调用(agent invocation)。了解这些组件的作用有助于理解事件循环(event loop)的运作机制。
-
Runner¶- 角色: 单个用户查询的主要入口点及协调机制。
run_async). - 功能: 负责管理整个事件循环(Event Loop),接收由执行逻辑(Execution Logic)产生的事件,与相关服务协调以处理和执行事件相关的操作(如状态或结果的更新),并将处理后的事件传递给上层系统(例如用户界面 UI)。该组件实质上是根据产生的事件来逐步推进整个流程的。(定义见……)
google.adk.runners).
- 角色: 单个用户查询的主要入口点及协调机制。
-
执行逻辑组件(Execution Logic Components)¶
- 角色: 这些部分包含了您的自定义代码以及核心代理功能。
- 组件:
Agent(BaseAgent,LlmAgent(等等):这些是您的主要逻辑单元,负责处理信息并决定应采取的行动。它们实现了相应的功能。_run_async_impl一种能够生成事件(events)的方法。Tools(BaseTool,FunctionTool,AgentTool等):代理程序使用的外部函数或功能(这些外部函数或功能通常来自第三方库或服务)。LlmAgent这些组件用于与外部世界进行交互或执行特定任务。它们会执行相应的操作并返回结果,这些结果随后会被封装成“事件”(events)的形式进行传递。Callbacks(功能):用户自定义的功能,这些功能被附加到代理程序上(例如……)before_agent_callback,after_model_callback这些机制可以挂接到执行流程中的特定节点上,从而可能改变程序的行为或状态;它们的影响会通过“事件”(events)的形式被记录下来。
- 功能: 执行实际的思考、计算或与外部系统的交互。它们通过某种方式来传达自己的结果或需求。 yielding
Event对象 然后暂停,直到运行器(Runner)处理完这些任务为止。
-
Event¶- 角色: 在双方之间来回传递的消息是……
Runner以及执行逻辑(Execution Logic)。 - 功能: 表示一个“原子性事件”(用户输入、代理程序生成的文本、工具调用的结果、状态变更请求或控制信号)。该事件不仅包含了其本身的具体内容,还包含了该事件可能产生的副作用(即该事件对系统或环境的影响)。
actions喜欢;相似state_delta).
- 角色: 在双方之间来回传递的消息是……
-
Services¶- 角色: 负责管理持久性或共享资源的后端组件。主要由……(此处应填写具体使用这些组件的系统或应用程序)使用。
Runner在事件处理过程中。 - 组件:
SessionService(BaseSessionService,InMemorySessionService(等):负责管理Session对象(包括它们的保存/加载操作)以及相关应用(functions)。state_delta将事件添加到会话状态中(即会话数据中),并将这些事件追加到相应的列表或数组中。event history.ArtifactService(BaseArtifactService,InMemoryArtifactService,GcsArtifactService(用于管理二进制数据文件的存储和检索):虽然……save_artifact在执行逻辑过程中,该功能会通过上下文(context)被调用。artifact_delta如果该事件确认了需要执行的操作(即 Runner/SessionService 需要执行的任务),则相应的操作将会被执行。MemoryService(BaseMemoryService(可选)用于管理用户在不同会话之间的长期语义记忆(即用户长期存储的信息和理解)。
- 功能: 提供持久化层(即用于存储数据的机制)。
Runner与它们进行交互,以确保它们能够接收到所发出的变更信号。event.actions这些数据被可靠地存储了起来。 在……之前 执行逻辑继续进行。
- 角色: 负责管理持久性或共享资源的后端组件。主要由……(此处应填写具体使用这些组件的系统或应用程序)使用。
-
Session¶- 角色: 一个数据容器,用于存储系统的状态(即当前运行情况)以及系统的历史记录(即系统过去的变化过程)。 一次特定的对话 发生在用户与应用程序之间的交互过程中。
- 功能: 存储当前值。
state“dictionary”:所有过去事件(或数据)的列表。events(event history),以及对相关工件的引用。这是该交互过程的主要记录,由……(此处应填写负责管理的机构或部门名称)进行管理。SessionService.
-
Invocation¶- 角色: 这是一个概念性术语,用来表示所有因某种事件而发生的事情。 single 用户查询(user query):从那一刻起……
Runner该系统会一直接收数据,直到代理逻辑完成对该查询的所有事件的处理(即生成所有相关的结果或响应)。 - 功能: 一次调用可能涉及多次代理程序的运行(如果使用了代理程序转移功能的话)。
AgentTool这些操作包括多次大型语言模型(LLM)的调用、工具的执行以及回调函数的执行;所有这些活动都通过一个统一的系统或机制被紧密地连接在一起。invocation_id在……范围内;在……界限之内InvocationContext以 “.” 开头的状态变量:temp:这些变量严格限制在单次调用(即单次函数执行)的范围内使用,调用结束后就会被立即丢弃。
- 角色: 这是一个概念性术语,用来表示所有因某种事件而发生的事情。 single 用户查询(user query):从那一刻起……
这些玩家通过事件循环(Event Loop)持续进行交互,以处理用户的请求。
工作原理:简化的调用方式¶
让我们来追踪一个典型的用户查询流程,该流程包括一个大型语言模型(LLM)代理调用某个工具:

逐步分解(Step-by-Step Breakdown)¶
- 用户输入: 用户发送了一个查询(例如:“法国的首都是哪里?”)。
- “Runner Starts”: 表示运行程序(或任务)的开始时间。
Runner.run_async它开始与……进行交互。SessionService为了加载相关的内容……Session并将用户查询添加为第一个元素。Event该数据会被记录到会话历史记录中(session history)。InvocationContext(ctx)已经准备好了。 - 代理执行(Agent Execution): The
Runner调用(functions/methods)agent.run_async(ctx)在指定的根代理上(例如,某个特定的根代理设备)。LlmAgent). - LLM 调用示例: The
Agent_Llm它判断自己需要某些信息(可能是通过调用某个工具来获取这些信息),然后会准备一个请求以发送出去。LLM假设大型语言模型(LLM)决定执行某个操作(或调用某个函数)。MyTool. - “Yield FunctionCall Event”: The
Agent_Llm接收……FunctionCall来自大型语言模型(LLM)的响应结果会被封装在一个结构中。Event(author='Agent_Llm', content=Content(parts=[Part(function_call=...)])),以及yields或者emits这个事件。 - 代理暂停(Agent Pauses): The
Agent_Llm在执行该操作后,程序会立即暂停。yield. - 运行进程(Runner Processes): The
Runner接收 FunctionCall 事件,并将其传递给……SessionService为了将其记录在历史中。Runner然后将该事件向上游传递(即传递给相关的处理系统或组件)。User(或应用程序)。 - 代理简历(Agent Resumes): The
Runner表示该事件已被处理;同时……Agent_Llm恢复执行。 - 工具执行(Tool Execution): The
Agent_Llm“系统内部的流程现在会继续执行用户所请求的操作。”MyTool它会发起调用(即执行相应的操作)。tool.run_async(...). - 工具返回结果:
MyTool执行该操作并返回结果(例如:{'result': 'Paris'}). - “Yield FunctionResponse Event”: 该代理(agent)……
Agent_Llm) 将工具的输出结果封装到一个结构中Event包含……的FunctionResponse`part`(例如:Event(author='Agent_Llm', content=Content(role='user', parts=[Part(function_response=...)]))). 该事件也可能包含其他内容。actions如果该工具修改了系统的状态(……)state_delta)或已保存的工件(saved artifacts)。artifact_delta). 该代理(agent)yield这个事件。 - 代理暂停(Agent Pauses):
Agent_Llm再次暂停。 - 运行进程(Runner Processes):
Runner接收到 FunctionResponse 事件,并将其传递给……SessionService该条款适用于任何情况(即:无论具体情境如何,该条款均具有适用性)。state_delta/artifact_delta并将该事件记录到历史记录中。Runner该操作会将事件向上游(即系统的其他部分)传递。 - 代理简历(Agent Resumes):
Agent_Llm现在我们已经知道了该工具的输出结果,以及所有状态变化(如果有的话)都已经被成功记录(即:这些变化已经被“提交”到系统中)。 - 最后一次使用大型语言模型(LLM)的示例:
Agent_Llm将工具的结果发送回……LLM用于生成自然语言响应。 - “Yield Final Text Event”:该事件用于生成最终的文本结果。
Agent_Llm从……接收最终的文本。LLM…然后将其包裹在一个结构中。Event(author='Agent_Llm', content=Content(parts=[Part(text=...)])),以及yield就这样吧。 - 代理暂停(Agent Pauses):
Agent_Llm暂停。 - 运行进程(Runner Processes):
Runner接收到最终的文本事件数据,然后将其传递给……SessionService出于历史原因,该数据被向上游传输(即被传递给相关系统或机构)。User这很可能会被标记为……is_final_response(). - 代理恢复工作并完成任务:
Agent_Llm任务已经完成,现在它将……(“resumes”表示“继续执行”或“恢复活动”;后半句“its”指代前文提到的某个对象或实体,但具体内容在原文中未给出。)run_async生成器已完成工作。 - “Runner Completes”: 表示跑步者已经完成了比赛。 The
Runner发现代理的生成器已经耗尽资源,因此该代理会结束本次调用的循环(即停止进一步的处理)。
这个“产生结果/暂停/执行/恢复”的循环机制确保了状态变化的正确应用,并且在执行完某个事件后,逻辑总是基于最新提交的状态来继续运行。
重要的运行时行为(Important Runtime Behaviors)¶
了解 ADK 运行时在处理状态、数据流以及异步操作时的几个关键方面,对于构建可预测且高效的智能体(agents)至关重要。
状态更新与承诺执行时间安排¶
-
规则如下: 当您的代码(无论是在代理程序、工具中,还是在回调函数中)修改会话状态时(例如:
context.state['my_key'] = 'new_value'),这一变更最初会记录在当前系统的本地存储中。InvocationContext这一变更仅适用于……(即:该变更仅对特定的对象或情况有效)。 确保数据会被持久化存储(即数据不会丢失)。 (文件被)保存下来了。SessionService) 之后;随后 theEvent携带相应的(物品或信息)state_delta在其……的状态下;在其……的范围内actions已经被yield该内容由您的代码进行处理,随后再由其他系统或流程进行进一步处理。Runner. -
含义(Implication): 正在运行的代码 之后;随后 从……状态恢复
yield可以可靠地认为:系统中所检测到的状态变化(即那些被系统用来表示“状态已发生变化”的信号)确实反映了实际情况(即系统状态确实发生了变化)。 触发的事件(即被“触发”的那个事件) 这些犯罪行为已经被记录在案(即“已经记录在案”)。
# Inside agent logic (conceptual)
# 1. Modify state
ctx.session.state['status'] = 'processing'
event1 = Event(..., actions=EventActions(state_delta={'status': 'processing'}))
# 2. Yield event with the delta
yield event1
# --- PAUSE --- Runner processes event1, SessionService commits 'status' = 'processing' ---
# 3. Resume execution
# Now it's safe to rely on the committed state
current_status = ctx.session.state['status'] # Guaranteed to be 'processing'
print(f"Status after resuming: {current_status}")
// Inside agent logic (conceptual)
// 1. Modify state
// In TypeScript, you modify state via the context, which tracks the change.
ctx.state.set('status', 'processing');
// The framework will automatically populate actions with the state
// delta from the context. For illustration, it's shown here.
const event1 = createEvent({
actions: createEventActions({stateDelta: {'status': 'processing'}}),
// ... other event fields
});
// 2. Yield event with the delta
yield event1;
// --- PAUSE --- Runner processes event1, SessionService commits 'status' = 'processing' ---
// 3. Resume execution
// Now it's safe to rely on the committed state in the session object.
const currentStatus = ctx.session.state['status']; // Guaranteed to be 'processing'
console.log(`Status after resuming: ${currentStatus}`);
// Inside agent logic (conceptual)
func (a *Agent) RunConceptual(ctx agent.InvocationContext) iter.Seq2[*session.Event, error] {
// The entire logic is wrapped in a function that will be returned as an iterator.
return func(yield func(*session.Event, error) bool) {
// ... previous code runs based on current state from the input `ctx` ...
// e.g., val := ctx.State().Get("field_1") might return "value_1" here.
// 1. Determine a change or output is needed, construct the event
updateData := map[string]interface{}{"field_1": "value_2"}
eventWithStateChange := session.NewEvent(ctx, ctx.InvocationID())
eventWithStateChange.Author = a.Name()
eventWithStateChange.Actions = &session.EventActions{StateDelta: updateData}
// ... other event fields ...
// 2. Yield the event to the Runner for processing & commit.
// The agent's execution continues immediately after this call.
if !yield(eventWithStateChange, nil) {
// If yield returns false, it means the consumer (the Runner)
// has stopped listening, so we should stop producing events.
return
}
// <<<<<<<<<<<< RUNNER PROCESSES & COMMITS THE EVENT >>>>>>>>>>>>
// This happens outside the agent, after the agent's iterator has
// produced the event.
// 3. The agent CANNOT immediately see the state change it just yielded.
// The state is immutable within a single `Run` invocation.
val := ctx.State().Get("field_1")
// `val` here is STILL "value_1" (or whatever it was at the start).
// The updated state ("value_2") will only be available in the `ctx`
// of the *next* `Run` invocation in a subsequent turn.
// ... subsequent code continues, potentially yielding more events ...
finalEvent := session.NewEvent(ctx, ctx.InvocationID())
finalEvent.Author = a.Name()
// ...
yield(finalEvent, nil)
}
}
// Inside agent logic (conceptual)
// ... previous code runs based on current state ...
// 1. Prepare state modification and construct the event
ConcurrentHashMap<String, Object> stateChanges = new ConcurrentHashMap<>();
stateChanges.put("status", "processing");
EventActions actions = EventActions.builder().stateDelta(stateChanges).build();
Content content = Content.builder().parts(Part.fromText("Status update: processing")).build();
Event event1 = Event.builder()
.actions(actions)
// ...
.build();
// 2. Yield event with the delta
return Flowable.just(event1)
.map(
emittedEvent -> {
// --- CONCEPTUAL PAUSE & RUNNER PROCESSING ---
// 3. Resume execution (conceptually)
// Now it's safe to rely on the committed state.
String currentStatus = (String) ctx.session().state().get("status");
System.out.println("Status after resuming (inside agent logic): " + currentStatus); // Guaranteed to be 'processing'
// The event itself (event1) is passed on.
// If subsequent logic within this agent step produced *another* event,
// you'd use concatMap to emit that new event.
return emittedEvent;
});
// ... subsequent agent logic might involve further reactive operators
// or emitting more events based on the now-updated `ctx.session().state()`.
/**
* Conceptual view of state update timing in Kotlin
*/
suspend fun stateUpdateTiming(ctx: InvocationContext) {
// 1. Modify state
ctx.session.state["status"] = "processing"
val event1 =
Event(
author = "my_agent",
actions = EventActions(stateDelta = mutableMapOf("status" to "processing")),
)
// 2. Yield event with the delta (emit to flow)
// emit(event1)
// --- PAUSE --- Runner processes event1, SessionService commits 'status' = 'processing' ---
// 3. Resume execution
// Now it's safe to rely on the committed state
val currentStatus = ctx.session.state["status"] // Guaranteed to be 'processing'
println("Status after resuming: $currentStatus")
}
会话状态的“脏读”(Dirty Reads)¶
- 定义: 虽然承诺(或“承诺的行为”)是在某个特定时刻发生的,但其背后的决心或影响可能会持续很长时间。 之后;随后 产量(yield);代码运行(code running) 在同一调用过程中(即在同一函数或方法的执行过程中),稍后某个时刻但是…… 在……之前 状态变更事件实际上已经被生成并处理完毕了。 经常可以看到本地未提交的更改(即那些尚未被正式保存到数据库中的更改)。这种现象有时被称为“脏读”(dirty read)。
- 示例:
# Code in before_agent_callback
callback_context.state['field_1'] = 'value_1'
# State is locally set to 'value_1', but not yet committed by Runner
# ... agent runs ...
# Code in a tool called later *within the same invocation*
# Readable (dirty read), but 'value_1' isn't guaranteed persistent yet.
val = tool_context.state['field_1'] # 'val' will likely be 'value_1' here
print(f"Dirty read value in tool: {val}")
# Assume the event carrying the state_delta={'field_1': 'value_1'}
# is yielded *after* this tool runs and is processed by the Runner.
// Code in beforeAgentCallback
callbackContext.state.set('field_1', 'value_1');
// State is locally set to 'value_1', but not yet committed by Runner
// --- agent runs ... ---
// --- Code in a tool called later *within the same invocation* ---
// Readable (dirty read), but 'value_1' isn't guaranteed persistent yet.
const val = toolContext.state.get('field_1'); // 'val' will likely be 'value_1' here
console.log(`Dirty read value in tool: ${val}`);
// Assume the event carrying the state_delta={'field_1': 'value_1'}
// is yielded *after* this tool runs and is processed by the Runner.
// Code in before_agent_callback
// The callback would modify the context's session state directly.
// This change is local to the current invocation context.
ctx.State.Set("field_1", "value_1")
// State is locally set to 'value_1', but not yet committed by Runner
// ... agent runs ...
// Code in a tool called later *within the same invocation*
// Readable (dirty read), but 'value_1' isn't guaranteed persistent yet.
val := ctx.State.Get("field_1") // 'val' will likely be 'value_1' here
fmt.Printf("Dirty read value in tool: %v\n", val)
// Assume the event carrying the state_delta={'field_1': 'value_1'}
// is yielded *after* this tool runs and is processed by the Runner.
// Modify state - Code in BeforeAgentCallback
// AND stages this change in callbackContext.eventActions().stateDelta().
callbackContext.state().put("field_1", "value_1");
// --- agent runs ... ---
// --- Code in a tool called later *within the same invocation* ---
// Readable (dirty read), but 'value_1' isn't guaranteed persistent yet.
Object val = toolContext.state().get("field_1"); // 'val' will likely be 'value_1' here
System.out.println("Dirty read value in tool: " + val);
// Assume the event carrying the state_delta={'field_1': 'value_1'}
// is yielded *after* this tool runs and is processed by the Runner.
/**
* Conceptual view of dirty reads in Kotlin
*/
fun dirtyRead(ctx: InvocationContext) {
// Code in a callback
ctx.session.state["field_1"] = "value_1"
// State is locally set to 'value_1', but not yet committed by Runner
// ... agent runs ...
// Code in a tool called later *within the same invocation*
// Readable (dirty read), but 'value_1' isn't guaranteed persistent yet.
val val1 = ctx.session.state["field_1"] // 'val' will likely be 'value_1' here
println("Dirty read value in tool: $val1")
// Assume the event carrying the state_delta={'field_1': 'value_1'}
// is yielded *after* this tool runs and is processed by the Runner.
}
- 影响(或后果):
- 好处: 它允许在单个复杂的处理步骤中,你的逻辑的不同部分(例如,在下一个大型语言模型(LLM)执行之前发生的多个回调或工具调用)通过共享状态来进行协调,而无需等待整个处理流程的完成(即无需等待“yield”或“commit”操作)。
- 注意: 在关键逻辑中过度依赖“脏读”(即未同步读取的数据)可能会带来风险;如果相关操作失败,后果可能会非常严重。 在……之前 该事件负责传递(或承载)……
state_delta该数据由……生成并处理。Runner如果状态变更没有得到确认(即没有完成相应的处理流程),那么这些变更将会被丢失。对于那些涉及系统关键状态转换的操作,必须确保这些转换能够与某个能够成功被处理的事件相关联。
流式输出与非流式输出(Streaming vs. Non-Streaming Output)partial=True)¶
这主要涉及到如何处理来自大型语言模型(LLM)的响应,尤其是在使用流式生成(streaming generation)API时。
- 流媒体传输(Streaming): 大型语言模型(LLM)会逐个字符或以小块的形式生成其响应内容。
- 该框架(通常属于某个更大的系统或项目中)……
BaseLlmFlow)会返回多个结果。Event这些事件中的大多数都会产生一个概念性的响应结果(即一个包含多个对象的响应)。partial=True. - The
Runner在接收到某个事件时……partial=True通常情况下…… 立即将其转发。 数据流向是上游的(用于用户界面显示),但是…… 跳过对其的处理(即不执行对该内容的任何操作)。actions(就像……一样)state_delta). - 最终,该框架会为该响应生成一个最终事件(final event),并将该事件标记为“非部分响应”(non-partial response)。
partial=False或者通过隐式的方式(即不显式地、间接地)实现。turn_complete=True). - The
Runner仅完全处理这个最终事件。(此处“committing any associated”可能指“执行与某项操作相关的所有步骤”或“完成与该操作相关的所有任务”等,具体含义需根据上下文确定。)state_delta或者artifact_delta. - 非流式传输(Non-Streaming): 大型语言模型(LLM)会一次性生成完整的响应内容。该框架会生成一个被标记为“非部分性”(non-partial)的事件。
Runner这些流程会被完全处理(即:所有步骤都会被执行完毕)。 - 为什么这很重要: 确保状态变化是原子性地(即不可分割地)且仅发生一次的,并且这一过程是基于某些特定规则或条件的。 完成 来自大型语言模型(LLM)的响应;同时,用户界面(UI)仍可以随着文本的生成过程逐步显示这些文本。
“异步操作是主要方式”(Async is the primary method)。run_async)¶
- 核心设计(Core Design): ADK 运行时(ADK Runtime)从根本上是基于异步模式和库(例如 Python 的相关库)构建的。
asyncio,Java的RxJava以及原生(native)功能。Promises andAsyncGenerator在 TypeScript 中使用 `s`(即异步操作机制),可以高效地处理并发操作(例如等待大型语言模型(LLM)的响应或工具的执行),同时避免程序出现阻塞。 - **主入口点(Main Entry Point):**
Runner.run_async这是执行代理调用(agent invocations)的主要方法。所有可运行的核心组件(代理(Agents)和特定流程(specific flows)都会使用该方法。asynchronous这些方法是在系统内部(即内部代码中)实现的。 - **同步便利性(Synchronous Convenience)**
run): 同步的Runner.run这个方法的存在主要是为了方便使用(例如,在简单的脚本或测试环境中)。不过,在内部实现上……Runner.run通常只需要进行简单的调用(即不需要执行复杂的操作)。Runner.run_async并为你管理异步事件循环的执行。 - 开发者体验: 我们建议将您的应用程序(例如使用 ADK 的 Web 服务器)设计为异步模式,以实现最佳性能。在 Python 中,这意味着需要使用相应的异步编程技术。
asyncio在 Java 中,可以利用(相关技术或方法)。RxJava“反应式编程模型”(Reactive Programming Model);在 TypeScript 中,这意味着使用原生的(native)功能来进行开发。Promises andAsyncGenerators. - 同步回调/工具: ADK框架支持工具和回调函数中的异步(asynchronous)和同步(synchronous)操作。
- 阻塞式 I/O 操作: 对于那些需要长时间运行的同步 I/O 操作,该框架并不总能防止程序的运行被阻塞。Python 的 ADK 模块会在 asyncio 事件循环中直接调用某些同步工具函数;因此,如果这些函数在执行过程中阻塞了输入或输出操作,就会导致整个事件循环的运行被暂停。在“实时模式”下,你可以设置相应的参数来避免这种情况的发生。
RunConfig.tool_thread_pool_config因此,工具的执行应该在一个后台线程池中完成。Java ADK 通常会使用适当的 RxJava 调度器或封装机制来处理那些会阻塞程序执行的操作。在 TypeScript 中,框架会直接等待函数的执行结果;如果某个同步函数执行了会阻塞 I/O 操作,那么整个事件循环都会被暂停。开发者应尽可能使用异步 I/O API(这些 API 会返回一个 Promise 对象)。 - CPU密集型任务(CPU-Bound Work): 那些纯粹依赖 CPU 处理的同步任务,在这两种环境中都会阻塞其执行线程(即导致该线程无法继续执行其他任务)。
- 阻塞式 I/O 操作: 对于那些需要长时间运行的同步 I/O 操作,该框架并不总能防止程序的运行被阻塞。Python 的 ADK 模块会在 asyncio 事件循环中直接调用某些同步工具函数;因此,如果这些函数在执行过程中阻塞了输入或输出操作,就会导致整个事件循环的运行被暂停。在“实时模式”下,你可以设置相应的参数来避免这种情况的发生。
了解这些行为有助于你编写更加健壮的 ADK(Android Development Kit)应用程序,并解决与状态一致性、数据流更新以及异步执行相关的问题。