アプリ: ワークフロー管理クラス¶
Appクラスは、Agent Development Kit(ADK)エージェントワークフロー全体の上位コンテナです。ルートエージェントによってグループ化されたエージェントのコレクションのライフサイクル、構成、および状態を管理するように設計されています。Appクラスは、エージェントワークフローの全体的な運用インフラストラクチャの懸念事項を、個々のエージェントのタスク指向の推論から分離します。
ADKワークフローでAppオブジェクトを定義することはオプションであり、エージェントコードの整理方法とエージェントの実行方法を変更します。実用的な観点から、Appクラスを使用して、エージェントワークフローの次の機能を構成します。
このガイドでは、ADKエージェントワークフローの構成と管理にAppクラスを使用する方法について説明します。
Appクラスの目的¶
Appクラスは、複雑なエージェントシステムを構築する際に発生するいくつかのアーキテクチャ上の問題に対処します。
- 一元化された構成: APIキーやデータベースクライアントなどの共有リソースを管理するための一元化された単一の場所を提供し、すべてのエージェントに構成を渡す必要がなくなります。
- ライフサイクル管理: Appクラスには起動時およびシャットダウン時のフックが含まれており、複数の呼び出しにわたって存在する必要があるデータベース接続プールやインメモリキャッシュなどの永続的なリソースを確実に管理できます。
- 状態スコープ:
app:*プレフィックスを使用してアプリケーションレベルの状態の明示的な境界を定義し、この状態のスコープと存続期間を開発者に明確にします。 - デプロイ単位: Appの概念は、正式なデプロイ可能単位を確立し、エージェントアプリケーションのバージョン管理、テスト、および提供を簡素化します。
Appオブジェクトを定義する¶
Appクラスは、エージェントワークフローのプライマリコンテナとして使用され、プロジェクトのルートエージェントが含まれています。ルートエージェントは、プライマリコントローラエージェントと追加のサブエージェントのコンテナです。
ルートエージェントでアプリを定義する¶
Agent基本クラスからサブクラスを作成して、ワークフローのルートエージェントを作成します。次に、次のサンプルコードに示すように、Appオブジェクトを定義し、ルートエージェントオブジェクトとオプション機能で構成します。
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,
# オプションで App レベル機能を含める:
# 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,
// オプションで App レベル機能を含める:
// 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)
// オプションで App レベル機能を含める:
// .plugins(plugins)
// .contextCacheConfig(contextCacheConfig)
// .eventsCompactionConfig(eventsCompactionConfig)
.build();
推奨:app変数名を使用する
エージェントプロジェクトコードで、Appオブジェクトを変数名appに設定して、ADKコマンドラインインターフェイスランナーツールと互換性があるようにします。
Appエージェントを実行する¶
次のコードサンプルに示すように、appパラメータを使用してRunnerクラスを使用してエージェントワークフローを実行できます。
import asyncio
from dotenv import load_dotenv
from google.adk.runners import InMemoryRunner
from agent import app # agent.pyからコードをインポート
load_dotenv() # APIキーと設定を読み込む
# インポートされたアプリケーションオブジェクトを使用してランナーを設定する
runner = InMemoryRunner(app=app)
async def main():
try: # run_debug()にはADK Python 1.18以降が必要です。
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'; // agent.tsからコードをインポート
// インポートされたアプリケーションオブジェクトを使用してランナーを設定する
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 {
// アプリケーションオブジェクトを使って Runner を設定する
App app = ...;
Runner runner = Runner.builder()
.app(app) // 先ほど定義した 'app' オブジェクトを使用
.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()));
}
}
Runner.run_debug()のバージョン要件
Runner.run_debug()コマンドには、ADK Python v1.18.0以降が必要です。より多くのセットアップコードが必要なRunner.run()を使用することもできます。詳細については、次を参照してください。
次のステップ¶
より完全なサンプルコードの実装については、Hello Worldアプリのコード例を参照してください。