From 02a85afd48baa80d242c42842809945ab0c9744f Mon Sep 17 00:00:00 2001 From: raj Date: Sat, 14 Nov 2026 03:02:27 +0530 Subject: [PATCH] docs: Add code assistant tutorial Add a multi-agent code assistant tutorial: a code_assistant coordinator delegates to code_writer, code_reviewer, and debugger sub-agents via agent transfer, and shares a compileJava function tool backed by the JDK compiler that returns real diagnostics. Includes a README and unit tests. --- pom.xml | 1 + tutorials/code-assistant/README.md | 57 +++++ tutorials/code-assistant/pom.xml | 62 +++++ .../google/adk/tutorials/CodeAssistant.java | 217 ++++++++++++++++++ .../adk/tutorials/CodeAssistantTest.java | 140 +++++++++++ 5 files changed, 477 insertions(+) create mode 100644 tutorials/code-assistant/README.md create mode 100644 tutorials/code-assistant/pom.xml create mode 100644 tutorials/code-assistant/src/main/java/com/google/adk/tutorials/CodeAssistant.java create mode 100644 tutorials/code-assistant/src/test/java/com/google/adk/tutorials/CodeAssistantTest.java diff --git a/pom.xml b/pom.xml index e34bb57f7..8b1c70563 100644 --- a/pom.xml +++ b/pom.xml @@ -35,6 +35,7 @@ examples tutorials/city-time-weather tutorials/live-audio-single-agent + tutorials/code-assistant a2a tokt diff --git a/tutorials/code-assistant/README.md b/tutorials/code-assistant/README.md new file mode 100644 index 000000000..55ed8ba4e --- /dev/null +++ b/tutorials/code-assistant/README.md @@ -0,0 +1,57 @@ +# Code Assistant Agent + +A tutorial demonstrating how to build a multi-agent AI code assistant using the Google ADK (Agent Development Kit). A coordinator agent delegates to specialized sub-agents that write, review, and debug code. + +## Setup API Key + +```shell +export GOOGLE_API_KEY={YOUR-KEY} +``` + +## Go to example directory + +```shell +cd tutorials/code-assistant +``` + +## Running the Agent + +Start the server: + +```shell +mvn exec:java +``` + +This starts the ADK web server with the `code_assistant` agent, which uses the `gemini-3.8-flash` model. + +## Architecture + +`code_assistant` is a coordinator that routes each request to one of three sub-agents via ADK agent transfer: + +- **`code_writer`** — writes and explains code in Java, Python, and JavaScript. Verifies Java snippets by compiling them before answering. +- **`code_reviewer`** — reviews code for correctness, style, and best practices, grounding findings in real compiler diagnostics for Java. +- **`debugger`** — diagnoses compile errors, exceptions, and logic bugs, reproducing Java problems with the compiler when a snippet is provided. + +Writing, reviewing, and explaining are tasks the model does itself, so the sub-agents have no special tools for them — the tutorial demonstrates `subAgents(...)` delegation instead. + +## The `compileJava` Function Tool + +Sub-agents share one function tool for work the model cannot do on its own: `compileJava` compiles a Java snippet with the JDK's `javax.tools.JavaCompiler` and returns the actual diagnostics (kind, line, column, message). This lets the writer verify code compiles, the reviewer cite real compiler errors, and the debugger reproduce failures. + +`compileJava` requires running on a JDK (not a JRE). For non-Java input it returns `status: "unsupported"`, and for empty input it returns `status: "error"`. + +## Usage + +Once running, you can interact with the agent through: + +- **Web interface:** `http://localhost:8080` +- **Agent name:** `code_assistant` +- **Try asking:** + - "Write a Java function to reverse a string" + - "Review this code and suggest improvements" + - "Explain what this code does" + - "Help me debug this compile error" + +## Learn More + +See https://google.github.io/adk-docs/get-started/quickstart/#java for more information. diff --git a/tutorials/code-assistant/pom.xml b/tutorials/code-assistant/pom.xml new file mode 100644 index 000000000..9e8e9fb56 --- /dev/null +++ b/tutorials/code-assistant/pom.xml @@ -0,0 +1,62 @@ + + + + 4.0.0 + + + com.google.adk + google-adk-parent + 1.15.1-SNAPSHOT + ../../pom.xml + + + google-adk-tutorials-code-assistant + Agent Development Kit - Tutorial: Code Assistant + Code Assistant Agent Tutorial + + + com.google.adk.tutorials.CodeAssistant + + + + + com.google.adk + google-adk-dev + ${project.version} + + + com.google.truth + truth + test + + + junit + junit + test + + + + + + + + maven-deploy-plugin + + true + + + + + diff --git a/tutorials/code-assistant/src/main/java/com/google/adk/tutorials/CodeAssistant.java b/tutorials/code-assistant/src/main/java/com/google/adk/tutorials/CodeAssistant.java new file mode 100644 index 000000000..7cc713c62 --- /dev/null +++ b/tutorials/code-assistant/src/main/java/com/google/adk/tutorials/CodeAssistant.java @@ -0,0 +1,217 @@ +/* + * Copyright 2026 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.tutorials; + +import com.google.adk.agents.BaseAgent; +import com.google.adk.agents.LlmAgent; +import com.google.adk.tools.Annotations.Schema; +import com.google.adk.tools.FunctionTool; +import com.google.adk.web.AdkWebServer; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.tools.Diagnostic; +import javax.tools.DiagnosticCollector; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.ToolProvider; + +public class CodeAssistant { + + private static final Pattern PUBLIC_TYPE_PATTERN = + Pattern.compile( + "\\bpublic\\s+(?:abstract\\s+|final\\s+|sealed\\s+)*" + + "(?:class|interface|enum|record|@interface)\\s+(\\w+)"); + + private static final LlmAgent CODE_WRITER = + LlmAgent.builder() + .name("code_writer") + .model("gemini-3.8-flash") + .description("Writes and explains code snippets in Java, Python, and JavaScript.") + .instruction( + "You are a code writer. Produce correct, idiomatic code for the user's request, " + + "with brief explanations of the key decisions. When the user provides Java " + + "code, call compileJava to verify it actually compiles, and fix any " + + "diagnostics the compiler reports before answering. Keep answers focused on " + + "the code itself.") + .tools(FunctionTool.create(CodeAssistant.class, "compileJava")) + .build(); + + private static final LlmAgent CODE_REVIEWER = + LlmAgent.builder() + .name("code_reviewer") + .model("gemini-3.8-flash") + .description("Reviews code for correctness, style, and best practices.") + .instruction( + "You are a code reviewer. When reviewing Java code, call compileJava first and " + + "base your findings on the real compiler diagnostics (line, column, " + + "message) together with your own analysis of style and best practices. " + + "Report concrete issues with line references, ordered by severity, and " + + "suggest fixes. If the code is not Java, review it directly without the " + + "compile tool.") + .tools(FunctionTool.create(CodeAssistant.class, "compileJava")) + .build(); + + private static final LlmAgent DEBUGGER = + LlmAgent.builder() + .name("debugger") + .model("gemini-3.8-flash") + .description("Diagnoses compile errors, runtime exceptions, and logic bugs.") + .instruction( + "You are a debugger. When the user reports a Java compile or runtime problem, " + + "call compileJava on the code to reproduce the compiler diagnostics, then " + + "explain the root cause and the minimal fix. For runtime errors, reason " + + "from the stack trace and the code; call compileJava when a snippet is " + + "provided to check it still parses. Be concrete: name the line, the cause, " + + "and the fix.") + .tools(FunctionTool.create(CodeAssistant.class, "compileJava")) + .build(); + + public static final BaseAgent ROOT_AGENT = + LlmAgent.builder() + .name("code_assistant") + .model("gemini-3.8-flash") + .description( + "A multi-agent code assistant that writes, reviews, and debugs code by delegating" + + " to specialized sub-agents.") + .instruction( + "You are a code assistant coordinator. Delegate every request to the right" + + " sub-agent instead of answering directly:\n" + + "- code_writer: writing, generating, or explaining code\n" + + "- code_reviewer: reviewing code, finding issues, suggesting improvements\n" + + "- debugger: diagnosing compile errors, exceptions, and bugs\n\n" + + "Route the user's request to exactly one sub-agent, then relay its answer. " + + "If a request spans multiple concerns (for example, write code and then " + + "review it), delegate to each sub-agent in turn and combine their results.") + .subAgents(CODE_WRITER, CODE_REVIEWER, DEBUGGER) + .build(); + + /** + * Compiles a Java source snippet with the JDK compiler and returns the real diagnostics. + * + * @param code a complete Java source file (a public type must match the file name derived from + * it) + * @param language the language of the snippet; only Java is supported + * @return compilation status plus per-diagnostic line, column, and message + */ + public static Map compileJava( + @Schema(name = "code", description = "The Java source code to compile") String code, + @Schema(name = "language", description = "The language of the code; only Java is supported") + String language) { + if (!"java".equalsIgnoreCase(language == null ? "" : language.trim())) { + Map unsupported = new LinkedHashMap<>(); + unsupported.put("status", "unsupported"); + unsupported.put("language", language); + unsupported.put("message", "compileJava only supports Java source code."); + return unsupported; + } + if (code == null || code.isBlank()) { + Map empty = new LinkedHashMap<>(); + empty.put("status", "error"); + empty.put("message", "No code provided to compile."); + return empty; + } + + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + if (compiler == null) { + Map noCompiler = new LinkedHashMap<>(); + noCompiler.put("status", "error"); + noCompiler.put( + "message", "No system Java compiler available; compileJava requires a JDK, not a JRE."); + return noCompiler; + } + + try { + Path workDir = Files.createTempDirectory("adk-compile-java"); + try { + Path sourceDir = Files.createDirectories(workDir.resolve("src")); + Path classDir = Files.createDirectories(workDir.resolve("classes")); + String typeName = publicTypeName(code).orElse("Snippet"); + Path sourceFile = sourceDir.resolve(typeName + ".java"); + Files.writeString(sourceFile, code, StandardCharsets.UTF_8); + + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + try (StandardJavaFileManager fileManager = + compiler.getStandardFileManager(diagnostics, null, StandardCharsets.UTF_8)) { + Iterable units = + fileManager.getJavaFileObjects(sourceFile.toFile()); + List options = List.of("-d", classDir.toString()); + JavaCompiler.CompilationTask task = + compiler.getTask(null, fileManager, diagnostics, options, null, units); + boolean success = task.call(); + + Map result = new LinkedHashMap<>(); + result.put("status", success ? "success" : "compilation_failed"); + result.put("fileName", typeName + ".java"); + List> entries = new ArrayList<>(); + for (Diagnostic d : diagnostics.getDiagnostics()) { + Map entry = new LinkedHashMap<>(); + entry.put("kind", d.getKind().toString()); + entry.put("line", d.getLineNumber()); + entry.put("column", d.getColumnNumber()); + entry.put("message", d.getMessage(null)); + entries.add(entry); + } + result.put("diagnosticCount", entries.size()); + result.put("diagnostics", entries); + return result; + } + } finally { + deleteRecursively(workDir); + } + } catch (IOException e) { + Map result = new LinkedHashMap<>(); + result.put("status", "error"); + result.put("message", "Failed to set up compilation: " + e.getMessage()); + return result; + } + } + + /** Returns the name of the first public top-level type, used to name the source file. */ + private static java.util.Optional publicTypeName(String code) { + Matcher matcher = PUBLIC_TYPE_PATTERN.matcher(code); + return matcher.find() ? java.util.Optional.of(matcher.group(1)) : java.util.Optional.empty(); + } + + private static void deleteRecursively(Path dir) { + try (var stream = Files.walk(dir)) { + stream + .sorted(java.util.Comparator.reverseOrder()) + .forEach( + path -> { + try { + Files.deleteIfExists(path); + } catch (IOException ignored) { + // Best-effort cleanup of a temp directory. + } + }); + } catch (IOException ignored) { + // Best-effort cleanup of a temp directory. + } + } + + public static void main(String[] args) { + AdkWebServer.start(ROOT_AGENT); + } +} diff --git a/tutorials/code-assistant/src/test/java/com/google/adk/tutorials/CodeAssistantTest.java b/tutorials/code-assistant/src/test/java/com/google/adk/tutorials/CodeAssistantTest.java new file mode 100644 index 000000000..bd9fdc0bc --- /dev/null +++ b/tutorials/code-assistant/src/test/java/com/google/adk/tutorials/CodeAssistantTest.java @@ -0,0 +1,140 @@ +/* + * Copyright 2026 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.tutorials; + +import static com.google.common.truth.Truth.assertThat; + +import java.util.List; +import java.util.Map; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public final class CodeAssistantTest { + + private static final String HELLO_WORLD = + """ + public class HelloWorld { + public static void main(String[] args) { + System.out.println("Hello, World!"); + } + } + """; + + private static final String BROKEN_SNIPPET = + """ + public class Broken { + public static void main(String[] args) { + int x = ; + } + } + """; + + // ---- agent structure ---- + + @Test + public void rootAgent_isCoordinatorWithSubAgents() { + assertThat(CodeAssistant.ROOT_AGENT.name()).isEqualTo("code_assistant"); + assertThat( + CodeAssistant.ROOT_AGENT.subAgents().stream() + .map(agent -> agent.name()) + .collect(java.util.stream.Collectors.toList())) + .containsExactly("code_writer", "code_reviewer", "debugger"); + } + + // ---- compileJava ---- + + @Test + public void compileJava_validSnippetCompiles() { + Map result = CodeAssistant.compileJava(HELLO_WORLD, "Java"); + assertThat(result).containsEntry("status", "success"); + assertThat(result).containsEntry("fileName", "HelloWorld.java"); + assertThat(result).containsEntry("diagnosticCount", 0); + } + + @Test + public void compileJava_snippetWithoutPublicTypeUsesSnippetFileName() { + String code = "class Greeter {\n String greet() { return \"hi\"; }\n}\n"; + Map result = CodeAssistant.compileJava(code, "Java"); + assertThat(result).containsEntry("status", "success"); + assertThat(result).containsEntry("fileName", "Snippet.java"); + } + + @Test + public void compileJava_brokenSnippetReturnsRealDiagnostics() { + Map result = CodeAssistant.compileJava(BROKEN_SNIPPET, "Java"); + assertThat(result).containsEntry("status", "compilation_failed"); + assertThat(result).containsEntry("fileName", "Broken.java"); + + @SuppressWarnings("unchecked") + List> diagnostics = (List>) result.get("diagnostics"); + assertThat(diagnostics).isNotEmpty(); + Map first = diagnostics.get(0); + assertThat(first).containsKey("line"); + assertThat(first).containsKey("column"); + assertThat(first.get("message")).isNotNull(); + assertThat(first.get("line")).isEqualTo(3L); + } + + @Test + public void compileJava_missingSemicolonAndBraceProduceMultipleDiagnostics() { + String code = + """ + public class Bad { + public static void main(String[] args) { + int x = 1 + System.out.println(x); + """; + Map result = CodeAssistant.compileJava(code, "Java"); + assertThat(result).containsEntry("status", "compilation_failed"); + @SuppressWarnings("unchecked") + List> diagnostics = (List>) result.get("diagnostics"); + assertThat(diagnostics.size()).isGreaterThan(1); + } + + @Test + public void compileJava_unsupportedLanguageReturnsUnsupported() { + Map result = CodeAssistant.compileJava("print('hi')", "Python"); + assertThat(result).containsEntry("status", "unsupported"); + assertThat(result).containsEntry("language", "Python"); + } + + @Test + public void compileJava_nullLanguageReturnsUnsupported() { + Map result = CodeAssistant.compileJava(HELLO_WORLD, null); + assertThat(result).containsEntry("status", "unsupported"); + } + + @Test + public void compileJava_nullCodeReturnsError() { + Map result = CodeAssistant.compileJava(null, "Java"); + assertThat(result).containsEntry("status", "error"); + } + + @Test + public void compileJava_blankCodeReturnsError() { + Map result = CodeAssistant.compileJava(" \n ", "Java"); + assertThat(result).containsEntry("status", "error"); + } + + @Test + public void compileJava_lowercaseJavaLanguageIsAccepted() { + Map result = CodeAssistant.compileJava(HELLO_WORLD, "java"); + assertThat(result).containsEntry("status", "success"); + } +}