Repository navigation
docs: Add code assistant tutorial #1386
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
Open
Rajkumar7633
wants to merge
1
commit into
google:main
Choose a base branch
from
Rajkumar7633:feature/code-assistant
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+477
−0
Open
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
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
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,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. |
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,62 @@ | ||||||||||||||||||||||||||||||||||||||||||||||
| <?xml version="1.0" encoding="UTF-8"?> | ||||||||||||||||||||||||||||||||||||||||||||||
| <!-- 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. --> | ||||||||||||||||||||||||||||||||||||||||||||||
| <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>1.15.1-SNAPSHOT</version><!-- {x-version-update:google-adk:current} --> | ||||||||||||||||||||||||||||||||||||||||||||||
| <relativePath>../../pom.xml</relativePath> | ||||||||||||||||||||||||||||||||||||||||||||||
| </parent> | ||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
| <artifactId>google-adk-tutorials-code-assistant</artifactId> | ||||||||||||||||||||||||||||||||||||||||||||||
| <name>Agent Development Kit - Tutorial: Code Assistant</name> | ||||||||||||||||||||||||||||||||||||||||||||||
| <description>Code Assistant Agent Tutorial</description> | ||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
| <properties> | ||||||||||||||||||||||||||||||||||||||||||||||
| <exec.mainClass>com.google.adk.tutorials.CodeAssistant</exec.mainClass> | ||||||||||||||||||||||||||||||||||||||||||||||
| </properties> | ||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
| <dependencies> | ||||||||||||||||||||||||||||||||||||||||||||||
| <dependency> | ||||||||||||||||||||||||||||||||||||||||||||||
| <groupId>com.google.adk</groupId> | ||||||||||||||||||||||||||||||||||||||||||||||
| <artifactId>google-adk-dev</artifactId> | ||||||||||||||||||||||||||||||||||||||||||||||
| <version>${project.version}</version> | ||||||||||||||||||||||||||||||||||||||||||||||
| </dependency> | ||||||||||||||||||||||||||||||||||||||||||||||
| <dependency> | ||||||||||||||||||||||||||||||||||||||||||||||
| <groupId>com.google.truth</groupId> | ||||||||||||||||||||||||||||||||||||||||||||||
| <artifactId>truth</artifactId> | ||||||||||||||||||||||||||||||||||||||||||||||
| <scope>test</scope> | ||||||||||||||||||||||||||||||||||||||||||||||
| </dependency> | ||||||||||||||||||||||||||||||||||||||||||||||
| <dependency> | ||||||||||||||||||||||||||||||||||||||||||||||
| <groupId>junit</groupId> | ||||||||||||||||||||||||||||||||||||||||||||||
| <artifactId>junit</artifactId> | ||||||||||||||||||||||||||||||||||||||||||||||
| <scope>test</scope> | ||||||||||||||||||||||||||||||||||||||||||||||
| </dependency> | ||||||||||||||||||||||||||||||||||||||||||||||
| </dependencies> | ||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
| <build> | ||||||||||||||||||||||||||||||||||||||||||||||
| <plugins> | ||||||||||||||||||||||||||||||||||||||||||||||
| <plugin> | ||||||||||||||||||||||||||||||||||||||||||||||
| <!-- Tutorial only: keep it out of the Maven Central release. --> | ||||||||||||||||||||||||||||||||||||||||||||||
| <artifactId>maven-deploy-plugin</artifactId> | ||||||||||||||||||||||||||||||||||||||||||||||
| <configuration> | ||||||||||||||||||||||||||||||||||||||||||||||
| <skip>true</skip> | ||||||||||||||||||||||||||||||||||||||||||||||
| </configuration> | ||||||||||||||||||||||||||||||||||||||||||||||
| </plugin> | ||||||||||||||||||||||||||||||||||||||||||||||
| </plugins> | ||||||||||||||||||||||||||||||||||||||||||||||
| </build> | ||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+51
to
+61
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. Two things here:
Suggested change
With both changes, |
||||||||||||||||||||||||||||||||||||||||||||||
| </project> | ||||||||||||||||||||||||||||||||||||||||||||||
217 changes: 217 additions & 0 deletions
217
tutorials/code-assistant/src/main/java/com/google/adk/tutorials/CodeAssistant.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,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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<JavaFileObject> diagnostics = new DiagnosticCollector<>(); | ||
| try (StandardJavaFileManager fileManager = | ||
| compiler.getStandardFileManager(diagnostics, null, StandardCharsets.UTF_8)) { | ||
| Iterable<? extends JavaFileObject> units = | ||
| fileManager.getJavaFileObjects(sourceFile.toFile()); | ||
| List<String> options = List.of("-d", classDir.toString()); | ||
| JavaCompiler.CompilationTask task = | ||
| compiler.getTask(null, fileManager, diagnostics, options, null, units); | ||
| boolean success = task.call(); | ||
|
|
||
| Map<String, Object> result = new LinkedHashMap<>(); | ||
| result.put("status", success ? "success" : "compilation_failed"); | ||
| result.put("fileName", typeName + ".java"); | ||
| List<Map<String, Object>> entries = new ArrayList<>(); | ||
| for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) { | ||
| Map<String, Object> 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<String, Object> 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<String> 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); | ||
| } | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Running
mvn exec:javafrom the README currently fails withThe parameters 'mainClass' for goal org.codehaus.mojo:exec-maven-plugin:3.6.3:java are missing or invalid. Please setexec.mainClasslike the other tutorials (and drop thespring-boot-maven-pluginblock below):