跳转到内容

使用 Firestore 进行会话状态管理

在 ADK 中得到支持。Java

Google Cloud Firestore ADK 是一种灵活、可扩展的 NoSQL 云数据库,用于存储和同步客户端及服务器端开发所需的数据。 它提供了与 Firestore 的原生集成功能,用于管理持久化的代理会话状态,从而支持连续的多轮对话(即对话过程中不会丢失任何历史记录)。

使用场景

  • 客户支持专员:在处理耗时较长的支持请求时,系统能够保持上下文信息的连续性,从而使客服人员能够在不同的会话中记住之前的故障排查步骤和用户的偏好设置。
  • 个性化助手:构建能够随着时间积累关于用户信息的代理系统,根据历史对话内容来个性化未来的交互体验。
  • 多模态工作流程(Multi-modal Workflows)能够无缝处理涉及图像、视频、音频以及文本对话的复杂用例,同时充分利用内置的 GCS(Google Cloud Storage)文件存储功能。
  • 企业级聊天机器人(Enterprise Chatbots):部署高度可靠、具备对话式交互功能的 AI 应用程序;这些应用程序具备适用于大规模企业环境的生产级数据持久化(即数据存储和管理的稳定性)功能。

先决条件

安装依赖项

注意:

请对两者使用相同版本。 google-adk 和 google-adk-firestore-session-service 为了确保兼容性,下面的示例使用了…… 1.14.0请检查最新的 ADK 版本,并在两个依赖项中都使用该版本。

将以下依赖项添加到您的项目中: pom.xml (Maven)或 build.gradle (Gradle):

Maven

<dependencies>
    <!-- ADK Core -->
    <dependency>
        <groupId>com.google.adk</groupId>
        <artifactId>google-adk</artifactId>
        <version>1.14.0</version>
    </dependency>
    <!-- Firestore Session Service -->
    <dependency>
        <groupId>com.google.adk</groupId>
        <artifactId>google-adk-firestore-session-service</artifactId>
        <version>1.14.0</version>
    </dependency>
</dependencies>

Gradle

dependencies {
    // ADK Core
    implementation 'com.google.adk:google-adk:1.14.0'
    // Firestore Session Service
    implementation 'com.google.adk:google-adk-firestore-session-service:1.14.0'
}

示例:具有 Firestore 会话管理功能的代理(Agent with Firestore Session Management)

使用 FirestoreDatabaseRunner 为了封装你的代理程序(agent)以及基于 Firestore 的会话管理功能,下面提供了一个完整的示例:如何设置一个简单的助手代理程序,该程序能够通过自定义的会话 ID 来记录对话的上下文(即在对话的不同轮次之间保持对话内容的关联性)。

import com.google.adk.agents.BaseAgent;
import com.google.adk.agents.LlmAgent;
import com.google.adk.agents.RunConfig;
import com.google.adk.runner.FirestoreDatabaseRunner;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreOptions;
import io.reactivex.rxjava3.core.Flowable;
import java.util.Map;
import com.google.adk.sessions.FirestoreSessionService;
import com.google.adk.sessions.Session;
import com.google.adk.tools.Annotations.Schema;
import com.google.adk.tools.FunctionTool;
import com.google.genai.types.Content;
import com.google.genai.types.Part;
import com.google.adk.events.Event;
import java.util.Scanner;
import static java.nio.charset.StandardCharsets.UTF_8;

public class YourAgentApplication {

    public static void main(String[] args) {
        System.out.println("Starting YourAgentApplication...");

        RunConfig runConfig = RunConfig.builder().build();
        String appName = "hello-time-agent";

        BaseAgent timeAgent = initAgent();

        // Initialize Firestore
        FirestoreOptions firestoreOptions = FirestoreOptions.getDefaultInstance();
        Firestore firestore = firestoreOptions.getService();

        // Use FirestoreDatabaseRunner to persist session state
        FirestoreDatabaseRunner runner = new FirestoreDatabaseRunner(
                timeAgent,
                appName,
                firestore
        );

        // Create a new session or load an existing one
        Session session = new FirestoreSessionService(firestore)
                .createSession(appName, "user1234", null, "12345")
                .blockingGet();

        // Start interactive CLI
        try (Scanner scanner = new Scanner(System.in, UTF_8)) {
            while (true) {
                System.out.print("\\nYou > ");
                String userInput = scanner.nextLine();
                if ("quit".equalsIgnoreCase(userInput)) {
                    break;
                }

                Content userMsg = Content.fromParts(Part.fromText(userInput));
                Flowable<Event> events = runner.runAsync(session.userId(), session.id(), userMsg, runConfig);

                System.out.print("\\nAgent > ");
                events.blockingForEach(event -> {
                    if (event.finalResponse()) {
                        System.out.println(event.stringifyContent());
                    }
                });
            }
        }
    }

    /** Mock tool implementation */
    @Schema(description = "Get the current time for a given city")
    public static Map<String, String> getCurrentTime(
        @Schema(name = "city", description = "Name of the city to get the time for") String city) {
        return Map.of(
            "city", city,
            "time", "The time is 10:30am."
        );
    }

    private static BaseAgent initAgent() {
        return LlmAgent.builder()
            .name("hello-time-agent")
            .description("Tells the current time in a specified city")
            .instruction("""
                You are a helpful assistant that tells the current time in a city.
                Use the 'getCurrentTime' tool for this purpose.
                """)
            .model("gemini-flash-latest")
            .tools(FunctionTool.create(YourAgentApplication.class, "getCurrentTime"))
            .build();
    }
}

配置

注意:

Firestore 会话服务(Firestore Session Service)支持通过属性文件(properties file)进行配置。这样一来,您可以轻松地指定使用特定的 Firestore 数据库,并为存储代理会话数据(agent session data)定义自定义的集合名称(custom collection names)。

您可以通过提供自己的 Firestore 属性设置来自定义您的 ADK 应用程序,以便使用 Firestore 会话服务;否则,该库将使用默认设置。

环境特定的配置(Environment-Specific Configuration)

该库会优先使用与环境相关的属性文件,而非默认设置。具体的处理顺序如下:

  1. 环境变量覆盖(Environment Variable Override)它首先会检查是否存在一个名为……的环境变量。 env如果这个变量被设置了(例如: env=dev在这种情况下,系统会尝试加载一个与模板匹配的属性文件(properties file)。 adk-firestore-{env}.properties (e.g., adk-firestore-dev.properties).
  2. 默认备用方案(Default Fallback):如果…… env 如果变量未设置,或者无法找到与环境相关的文件,那么该库将默认采用其默认的加载方式。 adk-firestore.properties.

示例属性设置:

# Firestore collection name for storing session data
firebase.root.collection.name=adk-session
# Google Cloud Storage bucket name for artifact storage
gcs.adk.bucket.name=your-gcs-bucket-name
# stop words for keyword extraction
keyword.extraction.stopwords=a,about,above,after,again,against,all,am,an,and,any,are,aren't,as,at,be,because,been,before,being,below,between,both,but,by,can't,cannot,could,couldn't,did,didn't,do,does,doesn't,doing,don't,down,during,each,few,for,from,further,had,hadn't,has,hasn't,have,haven't,having,he,he'd,he'll,he's,her,here,here's,hers,herself,him,himself,his,how,i,i'd,i'll,i'm,i've,if,in,into,is

重要的

FirestoreDatabaseRunner 需要…… gcs.adk.bucket.name 需要定义的属性。这是因为运行器在内部会自动初始化该属性。 GcsArtifactService 用于处理多模态(即多种格式)的工件(artifact)存储。如果该属性缺失或为空,应用程序将会抛出异常。 RuntimeException 在系统启动期间,该目录用于存储由代理程序生成或处理的各类文件(如图片、视频、音频文件等)。

资源