Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 2 additions & 2 deletions docs/agents/custom-agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -1234,13 +1234,13 @@ Finally, you instantiate your `StoryFlowAgent` and use the `Runner` as usual.
=== "Go"

```go
# Full runnable code for the StoryFlowAgent example
// Full runnable code for the StoryFlowAgent example
--8<-- "examples/go/snippets/agents/custom-agent/storyflow_agent.go:full_code"
```

=== "Java"

```java
# Full runnable code for the StoryFlowAgent example
// Full runnable code for the StoryFlowAgent example
--8<-- "examples/java/snippets/src/main/java/agents/StoryFlowAgentExample.java:full_code"
```
2 changes: 2 additions & 0 deletions docs/agents/llm-agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,7 @@ reasoning and planning before execution. There are two main planners:
from google.genai import types

my_agent = Agent(
name="my_agent",
model="gemini-flash-latest",
planner=BuiltInPlanner(
thinking_config=types.ThinkingConfig(
Expand All @@ -737,6 +738,7 @@ reasoning and planning before execution. There are two main planners:
from google.adk.planners import PlanReActPlanner

my_agent = Agent(
name="my_agent",
model="gemini-flash-latest",
planner=PlanReActPlanner(),
# ... your tools here
Expand Down
4 changes: 2 additions & 2 deletions docs/agents/models/google-gemma.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ Create an API key in [Google AI Studio](https://aistudio.google.com/app/apikey).
.instruction("""
You are a helpful assistant that can provide current weather.
""")
.tools(FunctionTool.create(this, "getWeather")]
.tools(FunctionTool.create(this, "getWeather"))
.build();

@Schema(name = "getWeather",
Expand Down Expand Up @@ -210,7 +210,7 @@ The following example shows how to use a Gemma 4 vLLM endpoint with ADK agents.
.instruction("""
You are a helpful assistant that can provide the current weather.
""")
.tools(FunctionTool.create(this, "getWeather")]
.tools(FunctionTool.create(this, "getWeather"))
.build();

@Schema(name = "getWeather",
Expand Down
2 changes: 1 addition & 1 deletion docs/apps/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ You can use the ***Runner*** class to run your agent workflow using the
=== "Java"

```java title="AppMain.java"
import com.google.adk.agents.Content;
import com.google.genai.types.Content;
import com.google.adk.runner.Runner;

public class AppMain {
Expand Down
4 changes: 2 additions & 2 deletions docs/artifacts/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -785,7 +785,7 @@ The artifact interaction methods are available directly on instances of `Callbac
public void processLatestReportJava(String userId, String sessionId, String filename) {
// Load the latest version by passing Optional.empty() for the version
artifactService
.loadArtifact(appName, userId, sessionId, filename, Optional.empty())
.loadArtifact(appName, userId, sessionId, filename)
.subscribe(
new MaybeObserver<Part>() {
@Override
Expand Down Expand Up @@ -828,7 +828,7 @@ The artifact interaction methods are available directly on instances of `Callbac

// Example: Load a specific version (e.g., version 0)
/*
artifactService.loadArtifact(appName, userId, sessionId, filename, Optional.of(0))
artifactService.loadArtifact(appName, userId, sessionId, filename, 0)
.subscribe(part -> {
System.out.println("Loaded version 0 of Java artifact '" + filename + "'.");
}, throwable -> {
Expand Down
1 change: 1 addition & 0 deletions docs/context/caching.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ these settings, as shown in the following code sample:
from google.adk.agents.context_cache_config import ContextCacheConfig

root_agent = Agent(
name='my_caching_agent',
# configure an agent using Gemini 2.0 or higher
)

Expand Down
3 changes: 2 additions & 1 deletion docs/context/compaction.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ specific number of workflow events, or invocations, with the current Session.
# (Optional) Event-based, sliding window as supplementary setting
compaction_config = EventsCompactionConfig(
compaction_interval=10, # Number of turns between standard compactions
overlap_size=2, # Number of events to retain as overlapping context
overlap_size=2 # Number of events to retain as overlapping context
)
```

## Configure context compaction
Expand Down
75 changes: 49 additions & 26 deletions docs/context/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,8 @@ Here are the primary context flavors you will encounter:

```go
import (
"fmt"

"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/session"
)
Expand Down Expand Up @@ -239,7 +241,11 @@ Here are the primary context flavors you will encounter:
=== "Go"

```go
import "google.golang.org/adk/v2/agent"
import (
"fmt"

"google.golang.org/adk/v2/agent"
)

--8<-- "examples/go/snippets/context/main.go:readonly_context_instruction"
```
Expand Down Expand Up @@ -314,6 +320,8 @@ Here are the primary context flavors you will encounter:

```go
import (
"fmt"

"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/model"
)
Expand Down Expand Up @@ -532,9 +540,10 @@ You'll frequently need to read information stored within the context.
=== "Java"

```java
// Example: In a Tool function
import com.google.adk.agents.CallbackContext;
import com.google.adk.tools.ToolContext;

// Example: In a Tool function
public void myTool(ToolContext toolContext) {
String userPref = (String) toolContext.state().getOrDefault("user_display_preference", "default_mode");
String apiEndpoint = (String) toolContext.state().get("app:api_endpoint"); // Read app-level state
Expand All @@ -547,8 +556,6 @@ You'll frequently need to read information stored within the context.
}

// Example: In a Callback function
import com.google.adk.agents.CallbackContext;

public void myCallback(CallbackContext callbackContext) {
String lastToolResult = (String) callbackContext.state().get("temp:last_api_result"); // Read temporary state

Expand Down Expand Up @@ -656,6 +663,8 @@ You'll frequently need to read information stored within the context.

```go
import (
"fmt"

"google.golang.org/adk/v2/agent"
"google.golang.org/genai"
)
Expand Down Expand Up @@ -847,12 +856,12 @@ Use artifacts to handle files or large data blobs associated with the session. C
from google.adk.agents.context import Context # Or ToolContext
from google.genai import types

def save_document_reference(context: Context, file_path: str) -> None:
async def save_document_reference(context: Context, file_path: str) -> None:
# Assume file_path is something like "gs://my-bucket/docs/report.pdf" or "/local/path/to/report.pdf"
try:
# Create a Part containing the path/URI text
artifact_part = types.Part.from_text(file_path)
version = context.save_artifact("document_to_summarize.txt", artifact_part)
artifact_part = types.Part.from_text(text=file_path)
version = await context.save_artifact("document_to_summarize.txt", artifact_part)
print(f"Saved document reference '{file_path}' as artifact version {version}")
# Store the filename in state if needed by other tools
context.state["temp:doc_artifact_name"] = "document_to_summarize.txt"
Expand Down Expand Up @@ -940,14 +949,14 @@ Use artifacts to handle files or large data blobs associated with the session. C
# Assume a 'summarize_text' function exists
# from my_summarizer_lib import summarize_text

def summarize_document_tool(tool_context: ToolContext) -> dict:
async def summarize_document_tool(tool_context: ToolContext) -> dict:
artifact_name = tool_context.state.get("temp:doc_artifact_name")
if not artifact_name:
return {"error": "Document artifact name not found in state."}

try:
# 1. Load the artifact part containing the path/URI
artifact_part = tool_context.load_artifact(artifact_name)
artifact_part = await tool_context.load_artifact(artifact_name)
if not artifact_part or not artifact_part.text:
return {"error": f"Could not load artifact or artifact has no text path: {artifact_name}"}

Expand Down Expand Up @@ -1105,9 +1114,9 @@ Use artifacts to handle files or large data blobs associated with the session. C
# Example: In a tool function
from google.adk.tools import ToolContext

def check_available_docs(tool_context: ToolContext) -> dict:
async def check_available_docs(tool_context: ToolContext) -> dict:
try:
artifact_keys = tool_context.list_artifacts()
artifact_keys = await tool_context.list_artifacts()
print(f"Available artifacts: {artifact_keys}")
return {"available_docs": artifact_keys}
except ValueError as e:
Expand Down Expand Up @@ -1351,13 +1360,17 @@ Access relevant information from the past or external sources.
# Example: Tool using memory search
from google.adk.tools import ToolContext

def find_related_info(tool_context: ToolContext, topic: str) -> dict:
async def find_related_info(tool_context: ToolContext, topic: str) -> dict:
try:
search_results = tool_context.search_memory(f"Information about {topic}")
if search_results.results:
print(f"Found {len(search_results.results)} memory results for '{topic}'")
# Process search_results.results (which are SearchMemoryResponseEntry)
top_result_text = search_results.results[0].text
search_results = await tool_context.search_memory(f"Information about {topic}")
if search_results.memories:
print(f"Found {len(search_results.memories)} memory results for '{topic}'")
# Process search_results.memories (which are MemoryEntry objects)
top_entry = search_results.memories[0]
top_result_text = next(
(part.text for part in (top_entry.content.parts or []) if part.text),
"",
)
return {"memory_snippet": top_result_text}
else:
return {"message": "No relevant memories found."}
Expand All @@ -1376,10 +1389,11 @@ Access relevant information from the past or external sources.
async function findRelatedInfo(context: Context, topic: string): Promise<Record<string, string>> {
try {
const searchResults = await context.searchMemory(`Information about ${topic}`);
if (searchResults.results?.length) {
console.log(`Found ${searchResults.results.length} memory results for '${topic}'`);
// Process searchResults.results
const topResultText = searchResults.results[0].text;
if (searchResults.memories.length) {
console.log(`Found ${searchResults.memories.length} memory results for '${topic}'`);
// Process searchResults.memories
const topResultText =
searchResults.memories[0].content.parts?.[0]?.text ?? '';
return { memory_snippet: topResultText };
} else {
return { message: 'No relevant memories found.' };
Expand All @@ -1403,10 +1417,11 @@ Access relevant information from the past or external sources.
public Single<Map<String, String>> findRelatedInfo(ToolContext context, String topic) {
return context.searchMemory("Information about " + topic)
.map(searchResults -> {
if (searchResults != null && searchResults.results() != null && !searchResults.results().isEmpty()) {
System.out.println("Found " + searchResults.results().size() + " memory results for '" + topic + "'");
// Process searchResults.results
String topResultText = searchResults.results().get(0).text();
if (searchResults != null && !searchResults.memories().isEmpty()) {
System.out.println("Found " + searchResults.memories().size() + " memory results for '" + topic + "'");
// Process searchResults.memories
String topResultText =
searchResults.memories().get(0).content().text();
return Map.of("memory_snippet", topResultText);
} else {
return Map.of("message", "No relevant memories found.");
Expand All @@ -1432,6 +1447,7 @@ While most interactions happen via `CallbackContext` or `ToolContext`, sometimes
from google.adk.agents import BaseAgent
from google.adk.agents.invocation_context import InvocationContext
from google.adk.events import Event
from google.genai import types
from typing import AsyncGenerator

class MyControllingAgent(BaseAgent):
Expand All @@ -1445,7 +1461,14 @@ While most interactions happen via `CallbackContext` or `ToolContext`, sometimes
if ctx.session.state.get("critical_error_flag"):
print("Critical error detected, ending invocation.")
ctx.end_invocation = True # Signal framework to stop processing
yield Event(author=self.name, invocation_id=ctx.invocation_id, content="Stopping due to critical error.")
yield Event(
author=self.name,
invocation_id=ctx.invocation_id,
content=types.Content(
role="model",
parts=[types.Part(text="Stopping due to critical error.")],
),
)
return # Stop this agent's execution

# ... Normal agent processing ...
Expand Down
2 changes: 1 addition & 1 deletion docs/deploy/gke.md
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ Use the `capital_agent` example defined on the [LLM agents](../agents/llm-agents
Country string `json:"country" jsonschema:"The country to look up."`
}

func getCapitalCity(_ tool.Context, args getCapitalCityArgs) (string, error) {
func getCapitalCity(_ agent.Context, args getCapitalCityArgs) (string, error) {
capitals := map[string]string{
"france": "Paris",
"japan": "Tokyo",
Expand Down
17 changes: 8 additions & 9 deletions docs/events/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ Once you know the event type, access the relevant data:
if (!responses.isEmpty()) {
for (FunctionResponse response : responses) {
String toolName = response.name().get();
Map<String, String> result= response.response().get(); // Check before getting the response
Map<String, Object> result = response.response().get(); // Check before getting the response
System.out.println(" Tool Result: " + toolName + " -> " + result);
}
}
Expand Down Expand Up @@ -569,15 +569,15 @@ The `event.actions` object signals changes that occurred or should occur. Always
```

=== "Java"
`ConcurrentMap<String, Object> delta = event.actions().stateDelta();`
`Map<String, Object> delta = event.actions().stateDelta();`

```java
import java.util.concurrent.ConcurrentMap;
import java.util.Map;
import com.google.adk.events.EventActions;

EventActions actions = event.actions(); // Assuming event.actions() is not null
if (actions != null && actions.stateDelta() != null && !actions.stateDelta().isEmpty()) {
ConcurrentMap<String, Object> stateChanges = actions.stateDelta();
Map<String, Object> stateChanges = actions.stateDelta();
System.out.println(" State changes: " + stateChanges);
// Update local UI or application state if necessary
}
Expand Down Expand Up @@ -626,19 +626,18 @@ The `event.actions` object signals changes that occurred or should occur. Always
```

=== "Java"
`ConcurrentMap<String, Part> artifactChanges = event.actions().artifactDelta();`
`Map<String, Integer> artifactChanges = event.actions().artifactDelta();`

```java
import java.util.concurrent.ConcurrentMap;
import com.google.genai.types.Part;
import java.util.Map;
import com.google.adk.events.EventActions;

EventActions actions = event.actions(); // Assuming event.actions() is not null
if (actions != null && actions.artifactDelta() != null && !actions.artifactDelta().isEmpty()) {
ConcurrentMap<String, Part> artifactChanges = actions.artifactDelta();
Map<String, Integer> artifactChanges = actions.artifactDelta();
System.out.println(" Artifacts saved: " + artifactChanges);
// UI might refresh an artifact list
// Iterate through artifactChanges.entrySet() to get filename and Part details
// Iterate through artifactChanges.entrySet() to get filename and version
}
```

Expand Down
2 changes: 1 addition & 1 deletion docs/graphs/dynamic.md
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ workflows offer much more flexibility to define the routing logic you need.

check_resp = await ctx.run_node(compile_lint_check, code)

return code
yield Event(output=code)
```

=== "TypeScript"
Expand Down
4 changes: 2 additions & 2 deletions docs/integrations/application-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ workflow as a tool for your agent or create a new one.
To update the `agent.java` file and add the tool to your agent, use the following code:

```java
import com.google.adk.agent.LlmAgent;
import com.google.adk.agents.LlmAgent;
import com.google.adk.tools.BaseTool;
import com.google.common.collect.ImmutableList;

Expand All @@ -374,7 +374,7 @@ workflow as a tool for your agent or create a new one.
// For example, you can start a conversation with the agent.
}
}
```
```

**Note:** To find the list of supported entities and actions for a
connection, use these Connector APIs: `listActions`, `listEntityTypes`.
Expand Down
4 changes: 2 additions & 2 deletions docs/integrations/firestore-session-service.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,10 @@ public class YourAgentApplication {
return LlmAgent.builder()
.name("hello-time-agent")
.description("Tells the current time in a specified city")
.instruction(\"""
.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();
Expand Down
4 changes: 2 additions & 2 deletions docs/integrations/gke-code-executor.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ The `GkeCodeExecutor` can be configured with the following parameters:
```python
from google.adk.agents import LlmAgent
from google.adk.code_executors import GkeCodeExecutor
from google.adk.code_executors import CodeExecutionInput
from google.adk.code_executors.code_execution_utils import CodeExecutionInput
from google.adk.agents.invocation_context import InvocationContext

# Initialize the executor for Sandbox Mode
Expand Down Expand Up @@ -132,7 +132,7 @@ The `GkeCodeExecutor` can be configured with the following parameters:
```python
from google.adk.agents import LlmAgent
from google.adk.code_executors import GkeCodeExecutor
from google.adk.code_executors import CodeExecutionInput
from google.adk.code_executors.code_execution_utils import CodeExecutionInput
from google.adk.agents.invocation_context import InvocationContext

# Initialize the executor for Job Mode
Expand Down
Loading