Skip to content

Commit c21cd63

Browse files
GWealejoefernandez
andauthored
Fix code samples that do not compile against the shipped SDKs (#2194)
* Fix code samples that do not compile against the shipped SDKs Checked the code samples against the real published libraries and corrected what does not compile or resolve. Verified against google-adk 2.8.0 for Python, @google/adk 2.0.0 for TypeScript, google-adk 1.6.0 for Java, adk-kotlin 0.8.0 for Kotlin, and adk/v2 2.3.0 for Go. Go: tool.Context does not exist in the v2 line and never has. The type is agent.Context, which this repository's own Go examples already use. Nine sites. Four import blocks also omitted the fmt they call. Java: two imports naming packages that do not exist, com.google.adk.agent (the package is agents) and com.google.adk.agents.Content (it is a genai type). Four wrong types, each confirmed against the jar with javap: EventActions.stateDelta returns Map not ConcurrentMap, artifactDelta returns Map<String, Integer> rather than ConcurrentMap<String, Part>, FunctionResponse.response yields Map<String, Object>, and loadArtifact takes the version as an int so the Optional argument matched no overload. Python: four coroutines used without await, which also masked a SearchMemoryResponse.results field that does not exist. The field is memories, holding MemoryEntry objects; the TypeScript and Java tabs of the same example had the same mistake. Also CodeExecutionInput imported from the wrong module, a calendar_tool_set object that does not exist in place of CalendarToolset, two positional Part.from_text calls against a keyword-only signature, five LlmAgent samples missing the required name, and an external access token sample built on an enum member and a field that the package does not define. Also corrects samples that could not parse at all: an unindented plugin class body, bracket and text block typos, a truncated call, an await in a non-async function, an await dedented out of the condition meant to guard it, a mid-file Java import, and a fence that opened at six spaces and closed at eight, which made a page render a literal code fence as body text. * Yield the workflow node's result instead of returning it code_workflow yields, which makes it an async generator, and returning a value from one is a syntax error. A generator node conveys its result by yielding an event whose output the runner copies to the context, which is the form the data handling page already uses. * docs(tools): simplify the toolset headings per review Drop the parenthetical class lists from the two toolset headings in the authentication page. Nothing links to either anchor. --------- Co-authored-by: Joe Fernandez <931947+joefernandez@users.noreply.github.com>
1 parent 290bf4e commit c21cd63

19 files changed

Lines changed: 129 additions & 101 deletions

File tree

docs/agents/custom-agents.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1234,13 +1234,13 @@ Finally, you instantiate your `StoryFlowAgent` and use the `Runner` as usual.
12341234
=== "Go"
12351235

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

12411241
=== "Java"
12421242

12431243
```java
1244-
# Full runnable code for the StoryFlowAgent example
1244+
// Full runnable code for the StoryFlowAgent example
12451245
--8<-- "examples/java/snippets/src/main/java/agents/StoryFlowAgentExample.java:full_code"
12461246
```

docs/agents/llm-agents.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,7 @@ reasoning and planning before execution. There are two main planners:
716716
from google.genai import types
717717

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

739740
my_agent = Agent(
741+
name="my_agent",
740742
model="gemini-flash-latest",
741743
planner=PlanReActPlanner(),
742744
# ... your tools here

docs/agents/models/google-gemma.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ Create an API key in [Google AI Studio](https://aistudio.google.com/app/apikey).
6161
.instruction("""
6262
You are a helpful assistant that can provide current weather.
6363
""")
64-
.tools(FunctionTool.create(this, "getWeather")]
64+
.tools(FunctionTool.create(this, "getWeather"))
6565
.build();
6666

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

216216
@Schema(name = "getWeather",

docs/apps/index.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ You can use the ***Runner*** class to run your agent workflow using the
135135
=== "Java"
136136

137137
```java title="AppMain.java"
138-
import com.google.adk.agents.Content;
138+
import com.google.genai.types.Content;
139139
import com.google.adk.runner.Runner;
140140

141141
public class AppMain {

docs/artifacts/index.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -785,7 +785,7 @@ The artifact interaction methods are available directly on instances of `Callbac
785785
public void processLatestReportJava(String userId, String sessionId, String filename) {
786786
// Load the latest version by passing Optional.empty() for the version
787787
artifactService
788-
.loadArtifact(appName, userId, sessionId, filename, Optional.empty())
788+
.loadArtifact(appName, userId, sessionId, filename)
789789
.subscribe(
790790
new MaybeObserver<Part>() {
791791
@Override
@@ -828,7 +828,7 @@ The artifact interaction methods are available directly on instances of `Callbac
828828

829829
// Example: Load a specific version (e.g., version 0)
830830
/*
831-
artifactService.loadArtifact(appName, userId, sessionId, filename, Optional.of(0))
831+
artifactService.loadArtifact(appName, userId, sessionId, filename, 0)
832832
.subscribe(part -> {
833833
System.out.println("Loaded version 0 of Java artifact '" + filename + "'.");
834834
}, throwable -> {

docs/context/caching.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ these settings, as shown in the following code sample:
2929
from google.adk.agents.context_cache_config import ContextCacheConfig
3030

3131
root_agent = Agent(
32+
name='my_caching_agent',
3233
# configure an agent using Gemini 2.0 or higher
3334
)
3435

docs/context/compaction.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,8 @@ specific number of workflow events, or invocations, with the current Session.
7474
# (Optional) Event-based, sliding window as supplementary setting
7575
compaction_config = EventsCompactionConfig(
7676
compaction_interval=10, # Number of turns between standard compactions
77-
overlap_size=2, # Number of events to retain as overlapping context
77+
overlap_size=2 # Number of events to retain as overlapping context
78+
)
7879
```
7980

8081
## Configure context compaction

docs/context/index.md

Lines changed: 49 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,8 @@ Here are the primary context flavors you will encounter:
172172

173173
```go
174174
import (
175+
"fmt"
176+
175177
"google.golang.org/adk/v2/agent"
176178
"google.golang.org/adk/v2/session"
177179
)
@@ -239,7 +241,11 @@ Here are the primary context flavors you will encounter:
239241
=== "Go"
240242

241243
```go
242-
import "google.golang.org/adk/v2/agent"
244+
import (
245+
"fmt"
246+
247+
"google.golang.org/adk/v2/agent"
248+
)
243249

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

315321
```go
316322
import (
323+
"fmt"
324+
317325
"google.golang.org/adk/v2/agent"
318326
"google.golang.org/adk/v2/model"
319327
)
@@ -532,9 +540,10 @@ You'll frequently need to read information stored within the context.
532540
=== "Java"
533541

534542
```java
535-
// Example: In a Tool function
543+
import com.google.adk.agents.CallbackContext;
536544
import com.google.adk.tools.ToolContext;
537545

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

549558
// Example: In a Callback function
550-
import com.google.adk.agents.CallbackContext;
551-
552559
public void myCallback(CallbackContext callbackContext) {
553560
String lastToolResult = (String) callbackContext.state().get("temp:last_api_result"); // Read temporary state
554561

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

657664
```go
658665
import (
666+
"fmt"
667+
659668
"google.golang.org/adk/v2/agent"
660669
"google.golang.org/genai"
661670
)
@@ -847,12 +856,12 @@ Use artifacts to handle files or large data blobs associated with the session. C
847856
from google.adk.agents.context import Context # Or ToolContext
848857
from google.genai import types
849858

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

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

948957
try:
949958
# 1. Load the artifact part containing the path/URI
950-
artifact_part = tool_context.load_artifact(artifact_name)
959+
artifact_part = await tool_context.load_artifact(artifact_name)
951960
if not artifact_part or not artifact_part.text:
952961
return {"error": f"Could not load artifact or artifact has no text path: {artifact_name}"}
953962

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

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

1354-
def find_related_info(tool_context: ToolContext, topic: str) -> dict:
1363+
async def find_related_info(tool_context: ToolContext, topic: str) -> dict:
13551364
try:
1356-
search_results = tool_context.search_memory(f"Information about {topic}")
1357-
if search_results.results:
1358-
print(f"Found {len(search_results.results)} memory results for '{topic}'")
1359-
# Process search_results.results (which are SearchMemoryResponseEntry)
1360-
top_result_text = search_results.results[0].text
1365+
search_results = await tool_context.search_memory(f"Information about {topic}")
1366+
if search_results.memories:
1367+
print(f"Found {len(search_results.memories)} memory results for '{topic}'")
1368+
# Process search_results.memories (which are MemoryEntry objects)
1369+
top_entry = search_results.memories[0]
1370+
top_result_text = next(
1371+
(part.text for part in (top_entry.content.parts or []) if part.text),
1372+
"",
1373+
)
13611374
return {"memory_snippet": top_result_text}
13621375
else:
13631376
return {"message": "No relevant memories found."}
@@ -1376,10 +1389,11 @@ Access relevant information from the past or external sources.
13761389
async function findRelatedInfo(context: Context, topic: string): Promise<Record<string, string>> {
13771390
try {
13781391
const searchResults = await context.searchMemory(`Information about ${topic}`);
1379-
if (searchResults.results?.length) {
1380-
console.log(`Found ${searchResults.results.length} memory results for '${topic}'`);
1381-
// Process searchResults.results
1382-
const topResultText = searchResults.results[0].text;
1392+
if (searchResults.memories.length) {
1393+
console.log(`Found ${searchResults.memories.length} memory results for '${topic}'`);
1394+
// Process searchResults.memories
1395+
const topResultText =
1396+
searchResults.memories[0].content.parts?.[0]?.text ?? '';
13831397
return { memory_snippet: topResultText };
13841398
} else {
13851399
return { message: 'No relevant memories found.' };
@@ -1403,10 +1417,11 @@ Access relevant information from the past or external sources.
14031417
public Single<Map<String, String>> findRelatedInfo(ToolContext context, String topic) {
14041418
return context.searchMemory("Information about " + topic)
14051419
.map(searchResults -> {
1406-
if (searchResults != null && searchResults.results() != null && !searchResults.results().isEmpty()) {
1407-
System.out.println("Found " + searchResults.results().size() + " memory results for '" + topic + "'");
1408-
// Process searchResults.results
1409-
String topResultText = searchResults.results().get(0).text();
1420+
if (searchResults != null && !searchResults.memories().isEmpty()) {
1421+
System.out.println("Found " + searchResults.memories().size() + " memory results for '" + topic + "'");
1422+
// Process searchResults.memories
1423+
String topResultText =
1424+
searchResults.memories().get(0).content().text();
14101425
return Map.of("memory_snippet", topResultText);
14111426
} else {
14121427
return Map.of("message", "No relevant memories found.");
@@ -1432,6 +1447,7 @@ While most interactions happen via `CallbackContext` or `ToolContext`, sometimes
14321447
from google.adk.agents import BaseAgent
14331448
from google.adk.agents.invocation_context import InvocationContext
14341449
from google.adk.events import Event
1450+
from google.genai import types
14351451
from typing import AsyncGenerator
14361452

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

14511474
# ... Normal agent processing ...

docs/deploy/gke.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,7 @@ Use the `capital_agent` example defined on the [LLM agents](../agents/llm-agents
288288
Country string `json:"country" jsonschema:"The country to look up."`
289289
}
290290

291-
func getCapitalCity(_ tool.Context, args getCapitalCityArgs) (string, error) {
291+
func getCapitalCity(_ agent.Context, args getCapitalCityArgs) (string, error) {
292292
capitals := map[string]string{
293293
"france": "Paris",
294294
"japan": "Tokyo",

docs/events/index.md

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -517,7 +517,7 @@ Once you know the event type, access the relevant data:
517517
if (!responses.isEmpty()) {
518518
for (FunctionResponse response : responses) {
519519
String toolName = response.name().get();
520-
Map<String, String> result= response.response().get(); // Check before getting the response
520+
Map<String, Object> result = response.response().get(); // Check before getting the response
521521
System.out.println(" Tool Result: " + toolName + " -> " + result);
522522
}
523523
}
@@ -569,15 +569,15 @@ The `event.actions` object signals changes that occurred or should occur. Always
569569
```
570570

571571
=== "Java"
572-
`ConcurrentMap<String, Object> delta = event.actions().stateDelta();`
572+
`Map<String, Object> delta = event.actions().stateDelta();`
573573

574574
```java
575-
import java.util.concurrent.ConcurrentMap;
575+
import java.util.Map;
576576
import com.google.adk.events.EventActions;
577577

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

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

631631
```java
632-
import java.util.concurrent.ConcurrentMap;
633-
import com.google.genai.types.Part;
632+
import java.util.Map;
634633
import com.google.adk.events.EventActions;
635634

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

0 commit comments

Comments
 (0)