Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions core/src/main/java/com/google/adk/agents/InvocationContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import com.google.adk.memory.BaseMemoryService;
import com.google.adk.models.LlmCallsLimitExceededException;
import com.google.adk.plugins.PluginManager;
import com.google.adk.reasoning.BaseReasoningBankService;
import com.google.adk.sessions.BaseSessionService;
import com.google.adk.sessions.Session;
import com.google.common.collect.ImmutableSet;
Expand All @@ -42,6 +43,7 @@ public class InvocationContext {
private final BaseSessionService sessionService;
private final BaseArtifactService artifactService;
private final BaseMemoryService memoryService;
private final BaseReasoningBankService reasoningBankService;
private final PluginManager pluginManager;
private final Optional<LiveRequestQueue> liveRequestQueue;
private final Map<String, ActiveStreamingTool> activeStreamingTools = new ConcurrentHashMap<>();
Expand All @@ -60,6 +62,7 @@ private InvocationContext(Builder builder) {
this.sessionService = builder.sessionService;
this.artifactService = builder.artifactService;
this.memoryService = builder.memoryService;
this.reasoningBankService = builder.reasoningBankService;
this.pluginManager = builder.pluginManager;
this.liveRequestQueue = builder.liveRequestQueue;
this.branch = builder.branch;
Expand Down Expand Up @@ -204,6 +207,7 @@ public static InvocationContext copyOf(InvocationContext other) {
.sessionService(other.sessionService)
.artifactService(other.artifactService)
.memoryService(other.memoryService)
.reasoningBankService(other.reasoningBankService)
.pluginManager(other.pluginManager)
.liveRequestQueue(other.liveRequestQueue)
.branch(other.branch)
Expand Down Expand Up @@ -234,6 +238,11 @@ public BaseMemoryService memoryService() {
return memoryService;
}

/** Returns the reasoning bank service for accessing reasoning strategies. */
public BaseReasoningBankService reasoningBankService() {
return reasoningBankService;
}

/** Returns the plugin manager for accessing tools and plugins. */
public PluginManager pluginManager() {
return pluginManager;
Expand Down Expand Up @@ -376,6 +385,7 @@ public static class Builder {
private BaseSessionService sessionService;
private BaseArtifactService artifactService;
private BaseMemoryService memoryService;
private BaseReasoningBankService reasoningBankService;
private PluginManager pluginManager = new PluginManager();
private Optional<LiveRequestQueue> liveRequestQueue = Optional.empty();
private Optional<String> branch = Optional.empty();
Expand Down Expand Up @@ -423,6 +433,18 @@ public Builder memoryService(BaseMemoryService memoryService) {
return this;
}

/**
* Sets the reasoning bank service for accessing reasoning strategies.
*
* @param reasoningBankService the reasoning bank service to use.
* @return this builder instance for chaining.
*/
@CanIgnoreReturnValue
public Builder reasoningBankService(BaseReasoningBankService reasoningBankService) {
this.reasoningBankService = reasoningBankService;
return this;
}

/**
* Sets the plugin manager for accessing tools and plugins.
*
Expand Down Expand Up @@ -608,6 +630,7 @@ public boolean equals(Object o) {
&& Objects.equals(sessionService, that.sessionService)
&& Objects.equals(artifactService, that.artifactService)
&& Objects.equals(memoryService, that.memoryService)
&& Objects.equals(reasoningBankService, that.reasoningBankService)
&& Objects.equals(pluginManager, that.pluginManager)
&& Objects.equals(liveRequestQueue, that.liveRequestQueue)
&& Objects.equals(activeStreamingTools, that.activeStreamingTools)
Expand All @@ -626,6 +649,7 @@ public int hashCode() {
sessionService,
artifactService,
memoryService,
reasoningBankService,
pluginManager,
liveRequestQueue,
activeStreamingTools,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* 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.reasoning;

import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Single;

/**
* Base contract for reasoning bank services.
*
* <p>The service provides functionalities to store and retrieve reasoning strategies that can be
* used to augment LLM prompts with relevant problem-solving approaches.
*
* <p>Based on the ReasoningBank paper (arXiv:2509.25140).
*/
public interface BaseReasoningBankService {

/**
* Stores a reasoning strategy in the bank.
*
* @param appName The name of the application.
* @param strategy The strategy to store.
* @return A Completable that completes when the strategy is stored.
*/
Completable storeStrategy(String appName, ReasoningStrategy strategy);

/**
* Stores a reasoning trace for later distillation into strategies.
*
* @param appName The name of the application.
* @param trace The trace to store.
* @return A Completable that completes when the trace is stored.
*/
Completable storeTrace(String appName, ReasoningTrace trace);

/**
* Searches for reasoning strategies that match the given query.
*
* @param appName The name of the application.
* @param query The query to search for (typically a task description).
* @return A {@link SearchReasoningResponse} containing matching strategies.
*/
Single<SearchReasoningResponse> searchStrategies(String appName, String query);

/**
* Searches for reasoning strategies that match the given query with a limit.
*
* @param appName The name of the application.
* @param query The query to search for.
* @param maxResults Maximum number of strategies to return.
* @return A {@link SearchReasoningResponse} containing matching strategies.
*/
Single<SearchReasoningResponse> searchStrategies(String appName, String query, int maxResults);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
/*
* 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.reasoning;

import com.google.common.collect.ImmutableSet;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Single;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
* An in-memory reasoning bank service for prototyping purposes only.
*
* <p>Uses keyword matching instead of semantic search. For production use, consider implementing a
* service backed by vector embeddings for semantic similarity matching.
*/
public final class InMemoryReasoningBankService implements BaseReasoningBankService {

private static final int DEFAULT_MAX_RESULTS = 5;

// Pattern to extract words for keyword matching.
private static final Pattern WORD_PATTERN = Pattern.compile("[A-Za-z]+");

/** Keys are app names, values are lists of strategies. */
private final Map<String, List<ReasoningStrategy>> strategies;

/** Keys are app names, values are lists of traces. */
private final Map<String, List<ReasoningTrace>> traces;

public InMemoryReasoningBankService() {
this.strategies = new ConcurrentHashMap<>();
this.traces = new ConcurrentHashMap<>();
}

@Override
public Completable storeStrategy(String appName, ReasoningStrategy strategy) {
return Completable.fromAction(
() -> {
List<ReasoningStrategy> appStrategies =
strategies.computeIfAbsent(
appName, k -> Collections.synchronizedList(new ArrayList<>()));
appStrategies.add(strategy);
});
}

@Override
public Completable storeTrace(String appName, ReasoningTrace trace) {
return Completable.fromAction(
() -> {
List<ReasoningTrace> appTraces =
traces.computeIfAbsent(appName, k -> Collections.synchronizedList(new ArrayList<>()));
appTraces.add(trace);
});
}

@Override
public Single<SearchReasoningResponse> searchStrategies(String appName, String query) {
return searchStrategies(appName, query, DEFAULT_MAX_RESULTS);
}

@Override
public Single<SearchReasoningResponse> searchStrategies(
String appName, String query, int maxResults) {
return Single.fromCallable(
() -> {
if (!strategies.containsKey(appName)) {
return SearchReasoningResponse.builder().build();
}

List<ReasoningStrategy> appStrategies = strategies.get(appName);
ImmutableSet<String> queryWords = extractWords(query);

if (queryWords.isEmpty()) {
return SearchReasoningResponse.builder().build();
}

List<ScoredStrategy> scoredStrategies = new ArrayList<>();

for (ReasoningStrategy strategy : appStrategies) {
int score = calculateMatchScore(strategy, queryWords);
if (score > 0) {
scoredStrategies.add(new ScoredStrategy(strategy, score));
}
}

// Sort by score descending
scoredStrategies.sort((a, b) -> Integer.compare(b.score, a.score));

// Take top results
List<ReasoningStrategy> matchingStrategies =
scoredStrategies.stream()
.map(scoredStrategy -> scoredStrategy.strategy)
.limit(maxResults)
.collect(Collectors.toList());

return SearchReasoningResponse.builder().setStrategies(matchingStrategies).build();
});
}

private int calculateMatchScore(ReasoningStrategy strategy, Set<String> queryWords) {
int score = 0;

// Check problem pattern
Set<String> patternWords = extractWords(strategy.problemPattern());
score += countOverlap(queryWords, patternWords) * 3; // Weight pattern matches higher

// Check name
Set<String> nameWords = extractWords(strategy.name());
score += countOverlap(queryWords, nameWords) * 2;

// Check tags
for (String tag : strategy.tags()) {
Set<String> tagWords = extractWords(tag);
score += countOverlap(queryWords, tagWords);
}

// Check steps (lower weight)
for (String step : strategy.steps()) {
Set<String> stepWords = extractWords(step);
if (!Collections.disjoint(queryWords, stepWords)) {
score += 1;
}
}

return score;
}

private int countOverlap(Set<String> set1, Set<String> set2) {
Set<String> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
return intersection.size();
}

private ImmutableSet<String> extractWords(String text) {
if (text == null || text.isEmpty()) {
return ImmutableSet.of();
}

Set<String> words = new HashSet<>();
Matcher matcher = WORD_PATTERN.matcher(text);
while (matcher.find()) {
words.add(matcher.group().toLowerCase(Locale.ROOT));
}
return ImmutableSet.copyOf(words);
}

/** Helper class for scoring strategies during search. */
private static class ScoredStrategy {
final ReasoningStrategy strategy;
final int score;

ScoredStrategy(ReasoningStrategy strategy, int score) {
this.strategy = strategy;
this.score = score;
}
}
}
Loading