-
Notifications
You must be signed in to change notification settings - Fork 264
feat: Implementation of a session service for the ADK using Firestore #578
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
mohan-ganesh
wants to merge
1
commit into
google:main
from
mohan-ganesh:feat/firestore-session-service
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| /target | ||
| *.prefs | ||
| *.iml | ||
| .idea/ | ||
| .vscode/ | ||
| .DS_Store | ||
| logs/ | ||
| *.log | ||
| *.project | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| ## Firestore Session Service for ADK | ||
|
|
||
| This sub-module contains an implementation of a session service for the ADK (Agent Development Kit) that uses Google Firestore as the backend for storing session data. This allows developers to manage user sessions in a scalable and reliable manner using Firestore's NoSQL database capabilities. | ||
|
|
||
| ## Getting Started | ||
|
|
||
| To integrate this Firestore session service into your ADK project, add the following dependencies to your project's build configuration: pom.xml for Maven or build.gradle for Gradle. | ||
|
|
||
| ## Basic Setup | ||
|
|
||
| ```xml | ||
| <dependencies> | ||
| <!-- ADK Core --> | ||
| <dependency> | ||
| <groupId>com.google.adk</groupId> | ||
| <artifactId>google-adk</artifactId> | ||
| <version>0.3.1-SNAPSHOT</version> | ||
| </dependency> | ||
| <!-- Firestore Session Service --> | ||
| <dependency> | ||
| <groupId>com.google.adk.contrib</groupId> | ||
| <artifactId>firestore-session-service</artifactId> | ||
| <version>0.3.1-SNAPSHOT</version> | ||
| </dependency> | ||
| </dependencies> | ||
| ``` | ||
|
|
||
| ```gradle | ||
| dependencies { | ||
| // ADK Core | ||
| implementation 'com.google.adk:google-adk:0.3.1-SNAPSHOT' | ||
| // Firestore Session Service | ||
| implementation 'com.google.adk.contrib:firestore-session-service:0.3.1-SNAPSHOT' | ||
| } | ||
| ``` | ||
|
|
||
| ## Running the Service | ||
|
|
||
| You can customize your ADK application to use the Firestore session service by providing your own Firestore property settings, otherwise library will use the default settings. | ||
|
|
||
| Sample Property Settings: | ||
|
|
||
| ```properties | ||
| # Firestore collection name for storing session data | ||
| adk.firestore.collection.name=adk-session | ||
| # Google Cloud Storage bucket name for artifact storage | ||
| adk.gcs.bucket.name=your-gcs-bucket-name | ||
| #stop words for keyword extraction | ||
| adk.stop.words=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 | ||
| ``` | ||
|
|
||
| Then, you can use the `FirestoreDatabaseRunner` to start your ADK application with Firestore session management: | ||
|
|
||
| ```java | ||
| import com.google.adk.agents.YourAgent; // Replace with your actual agent class | ||
| import com.google.adk.plugins.BasePlugin; | ||
| import com.google.adk.runner.FirestoreDatabaseRunner; | ||
| import com.google.cloud.firestore.Firestore; | ||
| import com.google.cloud.firestore.FirestoreOptions; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import com.google.adk.sessions.GetSessionConfig; | ||
| import java.util.Optional; | ||
|
|
||
|
|
||
|
|
||
|
|
||
| public class YourApp { | ||
| public static void main(String[] args) { | ||
| Firestore firestore = FirestoreOptions.getDefaultInstance().getService(); | ||
| List<BasePlugin> plugins = new ArrayList<>(); | ||
| // Add any plugins you want to use | ||
|
|
||
|
|
||
| FirestoreDatabaseRunner firestoreRunner = new FirestoreDatabaseRunner( | ||
| new YourAgent(), // Replace with your actual agent instance | ||
| "YourAppName", | ||
| plugins, | ||
| firestore | ||
| ); | ||
|
|
||
| GetSessionConfig config = GetSessionConfig.builder().build(); | ||
| // Example usage of session service | ||
| firestoreRunner.sessionService().getSession("APP_NAME","USER_ID","SESSION_ID", Optional.of(config)); | ||
|
|
||
| } | ||
| } | ||
| ``` | ||
|
|
||
| Make sure to replace `YourAgent` and `"YourAppName"` with your actual agent class and application name. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| <?xml version="1.0" encoding="UTF-8"?> | ||
| <!-- | ||
| Copyright 2025 Google LLC | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| --> | ||
| <project xmlns="http://maven.apache.org/POM/4.0.0" | ||
| xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
| xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | ||
| <modelVersion>4.0.0</modelVersion> | ||
|
|
||
| <parent> | ||
| <groupId>com.google.adk</groupId> | ||
| <artifactId>google-adk-parent</artifactId> | ||
| <version>0.3.1-SNAPSHOT</version><!-- {x-version-update:google-adk:current} --> | ||
| <relativePath>../../pom.xml</relativePath> | ||
| </parent> | ||
|
|
||
| <artifactId>google-adk-firestore-session-service</artifactId> | ||
| <name>Agent Development Kit - Firestore Session Management</name> | ||
| <description>Firestore integration with Agent Development Kit for User Session Management</description> | ||
|
|
||
|
|
||
| <dependencies> | ||
|
|
||
| <dependency> | ||
| <groupId>com.google.adk</groupId> | ||
| <artifactId>google-adk</artifactId> | ||
| <version>${project.version}</version> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>com.google.adk</groupId> | ||
| <artifactId>google-adk-dev</artifactId> | ||
| <version>${project.version}</version> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>com.google.genai</groupId> | ||
| <artifactId>google-genai</artifactId> | ||
| <version>${google.genai.version}</version> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>com.google.cloud</groupId> | ||
| <artifactId>google-cloud-firestore</artifactId> | ||
| <version>3.30.3</version> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>com.google.truth</groupId> | ||
| <artifactId>truth</artifactId> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>org.mockito</groupId> | ||
| <artifactId>mockito-core</artifactId> | ||
| <scope>test</scope> | ||
| </dependency> | ||
|
|
||
| <dependency> | ||
| <groupId>org.junit.jupiter</groupId> | ||
| <artifactId>junit-jupiter-api</artifactId> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>org.junit.jupiter</groupId> | ||
| <artifactId>junit-jupiter-engine</artifactId> | ||
| <scope>test</scope> | ||
| </dependency> | ||
| <dependency> | ||
| <groupId>org.mockito</groupId> | ||
| <artifactId>mockito-junit-jupiter</artifactId> | ||
| <scope>test</scope> | ||
| </dependency> | ||
|
|
||
| </dependencies> | ||
|
|
||
| <build> | ||
| <plugins> | ||
| <plugin> | ||
| <groupId>org.jacoco</groupId> | ||
| <artifactId>jacoco-maven-plugin</artifactId> | ||
| </plugin> | ||
| <plugin> | ||
| <groupId>org.apache.maven.plugins</groupId> | ||
| <artifactId>maven-surefire-plugin</artifactId> | ||
| <configuration> | ||
| <argLine> | ||
| ${jacoco.agent.argLine} | ||
| --add-opens java.base/java.util=ALL-UNNAMED | ||
| --add-opens java.base/java.lang=ALL-UNNAMED | ||
| </argLine> | ||
| </configuration> | ||
| </plugin> | ||
| </plugins> | ||
| </build> | ||
| </project> |
182 changes: 182 additions & 0 deletions
182
...firestore-session-service/src/main/java/com/google/adk/memory/FirestoreMemoryService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,182 @@ | ||
| /* | ||
| * Copyright 2025 Google LLC | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package com.google.adk.memory; | ||
|
|
||
| import com.google.adk.sessions.Session; | ||
| import com.google.adk.utils.Constants; | ||
| import com.google.api.core.ApiFuture; | ||
| import com.google.api.core.ApiFutures; | ||
| import com.google.cloud.firestore.Firestore; | ||
| import com.google.cloud.firestore.Query; | ||
| import com.google.cloud.firestore.QueryDocumentSnapshot; | ||
| import com.google.common.collect.ImmutableList; | ||
| import com.google.common.collect.Lists; | ||
| import com.google.common.util.concurrent.MoreExecutors; | ||
| import com.google.genai.types.Content; | ||
| import com.google.genai.types.Part; | ||
| import io.reactivex.rxjava3.core.Completable; | ||
| import io.reactivex.rxjava3.core.Single; | ||
| import java.util.ArrayList; | ||
| import java.util.HashSet; | ||
| import java.util.List; | ||
| import java.util.Locale; | ||
| import java.util.Map; | ||
| import java.util.Objects; | ||
| import java.util.Set; | ||
| import java.util.regex.Matcher; | ||
| import java.util.regex.Pattern; | ||
| import java.util.stream.Collectors; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| /** | ||
| * FirestoreMemoryService is an implementation of BaseMemoryService that uses Firestore to store and | ||
| * retrieve session memory entries. | ||
| */ | ||
| public class FirestoreMemoryService implements BaseMemoryService { | ||
|
|
||
| private static final Logger logger = LoggerFactory.getLogger(FirestoreMemoryService.class); | ||
| private static final Pattern WORD_PATTERN = Constants.WORD_PATTERN; | ||
|
|
||
| private final Firestore firestore; | ||
|
|
||
| /** Constructor for FirestoreMemoryService */ | ||
| public FirestoreMemoryService(Firestore firestore) { | ||
| this.firestore = firestore; | ||
| } | ||
|
|
||
| /** | ||
| * Adds a session to memory. This is a no-op for FirestoreMemoryService since keywords are indexed | ||
| * when events are appended in FirestoreSessionService. | ||
| */ | ||
| @Override | ||
| public Completable addSessionToMemory(Session session) { | ||
| // No-op. Keywords are indexed when events are appended in | ||
| // FirestoreSessionService. | ||
| return Completable.complete(); | ||
| } | ||
|
|
||
| /** Searches memory entries for the given appName and userId that match the query keywords. */ | ||
| @Override | ||
| public Single<SearchMemoryResponse> searchMemory(String appName, String userId, String query) { | ||
| return Single.fromCallable( | ||
| () -> { | ||
| Objects.requireNonNull(appName, "appName cannot be null"); | ||
| Objects.requireNonNull(userId, "userId cannot be null"); | ||
| Objects.requireNonNull(query, "query cannot be null"); | ||
|
|
||
| Set<String> queryKeywords = extractKeywords(query); | ||
|
|
||
| if (queryKeywords.isEmpty()) { | ||
| return SearchMemoryResponse.builder().build(); | ||
| } | ||
|
|
||
| List<String> queryKeywordsList = new ArrayList<>(queryKeywords); | ||
| List<List<String>> chunks = Lists.partition(queryKeywordsList, 10); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
|
|
||
| List<ApiFuture<List<QueryDocumentSnapshot>>> futures = new ArrayList<>(); | ||
| for (List<String> chunk : chunks) { | ||
| Query eventsQuery = | ||
| firestore | ||
| .collectionGroup(Constants.EVENTS_SUBCOLLECTION_NAME) | ||
| .whereEqualTo("appName", appName) | ||
| .whereEqualTo("userId", userId) | ||
| .whereArrayContainsAny("keywords", chunk); | ||
| futures.add( | ||
| ApiFutures.transform( | ||
| eventsQuery.get(), | ||
| com.google.cloud.firestore.QuerySnapshot::getDocuments, | ||
| MoreExecutors.directExecutor())); | ||
| } | ||
|
|
||
| Set<String> seenEventIds = new HashSet<>(); | ||
| List<MemoryEntry> matchingMemories = new ArrayList<>(); | ||
|
|
||
| for (QueryDocumentSnapshot eventDoc : | ||
| ApiFutures.allAsList(futures).get().stream() | ||
| .flatMap(List::stream) | ||
| .collect(Collectors.toList())) { | ||
| if (seenEventIds.add(eventDoc.getId())) { | ||
| MemoryEntry entry = memoryEntryFromDoc(eventDoc); | ||
| if (entry != null) { | ||
| matchingMemories.add(entry); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return SearchMemoryResponse.builder() | ||
| .setMemories(ImmutableList.copyOf(matchingMemories)) | ||
| .build(); | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Extracts keywords from the given text by splitting on non-word characters, converting to lower | ||
| */ | ||
| private Set<String> extractKeywords(String text) { | ||
| Set<String> keywords = new HashSet<>(); | ||
| if (text != null && !text.isEmpty()) { | ||
| Matcher matcher = WORD_PATTERN.matcher(text.toLowerCase(Locale.ROOT)); | ||
| while (matcher.find()) { | ||
| String word = matcher.group(); | ||
| if (!Constants.STOP_WORDS.contains(word)) { | ||
| keywords.add(word); | ||
| } | ||
| } | ||
| } | ||
| return keywords; | ||
| } | ||
|
|
||
| /** Creates a MemoryEntry from a Firestore document. */ | ||
| @SuppressWarnings("unchecked") | ||
| private MemoryEntry memoryEntryFromDoc(QueryDocumentSnapshot doc) { | ||
| Map<String, Object> data = doc.getData(); | ||
| if (data == null) { | ||
| return null; | ||
| } | ||
|
|
||
| try { | ||
| String author = (String) data.get("author"); | ||
| String timestampStr = (String) data.get("timestamp"); | ||
| Map<String, Object> contentMap = (Map<String, Object>) data.get("content"); | ||
|
|
||
| if (author == null || timestampStr == null || contentMap == null) { | ||
| logger.warn("Skipping malformed event data: {}", data); | ||
| return null; | ||
| } | ||
|
|
||
| List<Map<String, Object>> partsList = (List<Map<String, Object>>) contentMap.get("parts"); | ||
| List<Part> parts = new ArrayList<>(); | ||
| if (partsList != null) { | ||
| for (Map<String, Object> partMap : partsList) { | ||
| if (partMap.containsKey("text")) { | ||
| parts.add(Part.fromText((String) partMap.get("text"))); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return MemoryEntry.builder() | ||
| .author(author) | ||
| .content(Content.fromParts(parts.toArray(new Part[0]))) | ||
| .timestamp(timestampStr) | ||
| .build(); | ||
| } catch (Exception e) { | ||
| logger.error("Failed to parse memory entry from Firestore data: " + data, e); | ||
| return null; | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.