应用程序工作流程管理类¶
The 应用程序(App) `class` 是一个用于整个代理开发工具包(Agent Development Kit, ADK)代理工作流程的顶层容器。它的设计目的是管理按某种规则分组的一组代理的生命周期、配置以及状态。 根代理(Root Agent). The 应用程序(App) `class` 将代理工作流程的整体运营基础设施相关的问题,与各个代理基于任务的推理过程区分开来。
定义一个…… 应用程序(App) 在您的 ADK 工作流程中,使用某个特定的对象(object)是可选的;该对象会影响到您组织代理代码(agent code)以及运行代理程序(run agents)的方式。从实际应用的角度来看,您可以根据自己的需求来决定是否使用这个对象。 应用程序(App) 这个类用于配置您的代理工作流程中的以下功能:
本指南介绍了如何使用 `App` 类来配置和管理您的 ADK(Android Development Kit)代理工作流程。
应用程序类的用途(Purpose of the App Class)¶
The 应用程序(App) 该类(class)解决了在构建复杂的代理系统(agent systems)时所出现的几个架构问题。
- 集中式配置: 提供了一个集中式的管理平台,用于管理诸如 API 密钥和数据库客户端之类的共享资源,从而避免了需要将配置信息逐个传递给每个代理(agent)的麻烦。
- 生命周期管理: The 应用程序(App) `class includes` 表示某个类包含了其他类的成员(例如方法、属性等)。 在系统启动时 和 在系统关闭时 这些“钩子”(hooks)能够实现对持久化资源的可靠管理,例如数据库连接池或内存缓存等需要在多次调用过程中持续存在的资源。
- 状态(State)作用域: 它为应用程序级别的状态定义了一个明确的边界。
app:*前缀的作用是让开发者能够清楚地了解该状态的作用范围(scope)及其生命周期(lifetime)。 - 部署单元: The 应用程序(App) “Concept establishes a formal” 的意思是:“这个概念(或理论)为某种形式或结构提供了明确的定义/依据。” `deployable` `unit`这简化了代理应用程序的版本控制、测试以及部署过程。
定义一个 App 对象¶
The 应用程序(App) `class` 被用作代理工作流程(agent workflow)的主要容器,其中包含了项目的核心代理(root agent)。 根代理(Root Agent) 该容器用于存放主控制器代理(primary controller agent)以及所有额外的子代理(additional sub-agents)。
使用根代理(root agent)来定义应用程序。¶
创建一个…… 根代理(Root Agent) 为了优化您的工作流程,可以通过创建该类的一个实例来实现相关功能。 代理(Agent) 首先创建一个类(class),然后定义一个……(然后继续定义其他内容)。 应用程序(App) 使用该对象对其进行配置。 根代理(Root Agent) 对象及其可选功能,如下所示的示例代码所示:
from google.adk.agents.llm_agent import Agent
from google.adk.apps import App
root_agent = Agent(
model='gemini-flash-latest',
name='greeter_agent',
description='An agent that provides a friendly greeting.',
instruction='Reply with Hello, World!',
)
app = App(
name="agents",
root_agent=root_agent,
# Optionally include App-level features:
# plugins, context_cache_config, events_compaction_config,
# resumability_config
)
import {App, LlmAgent} from '@google/adk';
export const rootAgent = new LlmAgent({
model: 'gemini-flash-latest',
name: 'greeter_agent',
description: 'An agent that provides a friendly greeting.',
instruction: 'Reply with Hello, World!',
});
export const app = new App({
name: 'agents',
rootAgent: rootAgent,
// Optionally include App-level features:
// plugins, resumabilityConfig
});
import com.google.adk.agents.LlmAgent;
import com.google.adk.apps.App;
LlmAgent rootAgent = LlmAgent.builder()
.model("gemini-flash-latest")
.name("greeter_agent")
.description("An agent that provides a friendly greeting.")
.instruction("Reply with Hello, World!")
.build();
App app = App.builder()
.name("agents")
.rootAgent(rootAgent)
// Optionally include App-level features:
// .plugins(plugins)
// .contextCacheConfig(contextCacheConfig)
// .eventsCompactionConfig(eventsCompactionConfig)
.build();
import com.google.adk.kt.agents.Instruction
import com.google.adk.kt.agents.LlmAgent
import com.google.adk.kt.apps.App
import com.google.adk.kt.models.Gemini
val rootAgent =
LlmAgent(
model = Gemini(name = "gemini-flash-latest"),
name = "greeter_agent",
description = "An agent that provides a friendly greeting.",
instruction = Instruction("Reply with Hello, World!"),
)
val app =
App(
appName = "agents",
rootAgent = rootAgent,
// Optionally include App-level features:
// plugins, resumabilityConfig, eventsCompactionConfig,
// contextCacheConfig
)
推荐:使用 app 变量名称
在您的代理项目代码中,请设置您的……(请根据实际情况填写具体内容)。 应用程序(App) 反对使用该变量名。
app 因此,它与 ADK 命令行接口运行工具兼容。
运行您的应用程序代理(App Agent)。¶
您可以使用…… Runner 这个类用于运行你的代理工作流程(agent workflow)。
app 参数,如下代码示例所示:
import asyncio
from dotenv import load_dotenv
from google.adk.runners import InMemoryRunner
from agent import app # import code from agent.py
load_dotenv() # load API keys and settings
# Set a Runner using the imported application object
runner = InMemoryRunner(app=app)
async def main():
try: # run_debug() requires ADK Python 1.18 or higher:
response = await runner.run_debug("Hello there!")
except Exception as e:
print(f"An error occurred during agent execution: {e}")
if __name__ == "__main__":
asyncio.run(main())
import {InMemoryRunner, isFinalResponse, stringifyContent} from '@google/adk';
import {app} from './agent.js'; // import code from agent.ts
// Set a Runner using the imported application object
const runner = new InMemoryRunner({app});
async function main() {
try {
for await (const event of runner.runEphemeral({
userId: 'user',
newMessage: {role: 'user', parts: [{text: 'Hello there!'}]},
})) {
if (isFinalResponse(event) && event.content) {
console.log(`Response: ${stringifyContent(event)}`);
}
}
} catch (e) {
console.error(`An error occurred during agent execution: ${e}`);
}
}
main();
import com.google.genai.types.Content;
import com.google.adk.runner.Runner;
public class AppMain {
public static void main(String[] args) throws Exception {
// Set a Runner using the application object
App app = ...;
Runner runner = Runner.builder()
.app(app) // Use the 'app' object defined previously
.build();
runner.runAsync("user", "session-1", Content.fromParts(Part.fromText("Hello there!")))
.filter(event -> event.finalResponse() && event.content().isPresent())
.blockingSubscribe(event -> System.out.println("Response: " + event.stringifyContent()));
}
}
import com.google.adk.kt.runners.InMemoryRunner
import com.google.adk.kt.types.Content
import com.google.adk.kt.types.Role
import kotlinx.coroutines.runBlocking
// Set a Runner using the application object defined in Agent.kt
val runner = InMemoryRunner(app = app)
fun main() =
runBlocking {
try {
runner
.runAsync(
userId = "user",
sessionId = "session-1",
newMessage = Content.fromText(Role.USER, "Hello there!"),
).collect { event ->
if (event.isFinalResponse && event.content != null) {
println("Response: ${event.contentText()}")
}
}
} catch (e: Exception) {
println("An error occurred during agent execution: $e")
}
}
**版本要求(Version requirement for)** Runner.run_debug()
The Runner.run_debug() 该命令需要 ADK Python v1.18.0 或更高版本。
您也可以使用其他版本(如果适用)。 Runner.run()这需要更多的配置代码。有关更多详细信息,请参阅…… Agent Runtime guide.
使用以下命令运行您的应用程序代理:
`Run your App agent with the` AppMain.java 使用您的构建工具(例如 Gradle)编写的代码 application (插件名称):
下一步骤¶
有关更完整的示例代码实现,请参阅…… “Hello World”应用程序 代码示例。