Repository navigation
docs: Add code assistant tutorial - #1386
Rajkumar7633 wants to merge 1 commit into
Conversation
|
Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). View this failed invocation of the CLA check for more information. For the most up to date status, view the checks section at the bottom of the pull request. |
339221f to
c64aa51
Compare
Rajkumar7633
left a comment
There was a problem hiding this comment.
No existing issue. This PR adds:
-
New code assistant tutorial feature
-
Critical code quality improvements (unsafe Optional.get() fixes)
Problem: -
Missing code assistant tutorial for developers
-
Unsafe Optional.get() calls that could cause NoSuchElementException crashes
-
Inconsistent error handling in LLM flow processing
Solution: -
Added new code-assistant tutorial with 4 tools (generate, review, explain, debug code)
-
Replaced unsafe .get() calls with orElseThrow() for better error handling
-
Added meaningful error messages for debugging
-
Removed duplicate condition checks
Testing Plan:
Unit Tests:
- All 24 modules pass successfully (BUILD SUCCESS)
- ./mvnw test completed in 2:23 min with no failures
Manual E2E Tests:
- Tested code assistant tutorial with GOOGLE_API_KEY
- Verified all 4 tools work correctly via web interface
- Tested existing tutorials still work after changes
|
Hi @Rajkumar7633, thank you for your contribution! We appreciate you taking the time to submit this pull request. To proceed with the review, could you please address the following,
|
46ef6dd to
da774e6
Compare
|
@Rajkumar7633, thank you for addressing the feedback and squashing your commits, Currently this PR is under review by our team, we will keep you posted if any additional information is required. thank you |
damianmomotgoogle
left a comment
There was a problem hiding this comment.
Please also keep PR as single commit and update both commit message and PR title to follow conventional commits.
As this looks to be example/tutorial you could use docs: Add code assistant tutorial
| .modelName() | ||
| .orElseThrow( | ||
| () -> | ||
| new IllegalStateException( |
There was a problem hiding this comment.
This looks like behavior change - if needed please contribute it in a separate PR - this one should be limited to code assistant tutorial itself
| .outputSchema() | ||
| .orElseThrow( | ||
| () -> | ||
| new IllegalStateException( |
There was a problem hiding this comment.
Same ask to keep core logic changes to a separate PR
| } | ||
|
|
||
| int finalConfirmationEventIndex = confirmationResult.get().eventIndex(); | ||
| ConfirmationResult result = |
There was a problem hiding this comment.
Same ask to move core logic changes to a separate PR
96fe2b4 to
9ec717b
Compare
9ec717b to
2f2cf0d
Compare
|
All feedback addressed: core changes moved to #1809, PR is now limited to the code assistant tutorial, squashed to a single conventional commit ( |
| <artifactId>google-adk-tutorials-code-assistant</artifactId> | ||
| <name>Agent Development Kit - Tutorial: Code Assistant</name> | ||
| <description>Code Assistant Agent Tutorial</description> | ||
|
|
There was a problem hiding this comment.
Running mvn exec:java from the README currently fails with The parameters 'mainClass' for goal org.codehaus.mojo:exec-maven-plugin:3.6.3:java are missing or invalid. Please set exec.mainClass like the other tutorials (and drop the spring-boot-maven-plugin block below):
| <properties> | |
| <exec.mainClass>com.google.adk.tutorials.CodeAssistant</exec.mainClass> | |
| </properties> | |
| <build> | ||
| <plugins> | ||
| <plugin> | ||
| <groupId>org.springframework.boot</groupId> | ||
| <artifactId>spring-boot-maven-plugin</artifactId> | ||
| <configuration> | ||
| <mainClass>com.google.adk.tutorials.CodeAssistant</mainClass> | ||
| </configuration> | ||
| </plugin> | ||
| </plugins> | ||
| </build> |
There was a problem hiding this comment.
Two things here:
spring-boot-maven-pluginhas no version and is not managed in the parent, so it resolves to whatever is latest today (4.2.0-M2, a milestone). Withexec.mainClassset above, it isn't needed.- This module shouldn't be published to Maven Central. Releases run
./mvnw -Prelease deployacross the whole reactor, so without a skip it ships asgoogle-adk-tutorials-code-assistant.-Dmaven.deploy.skip/<maven.deploy.skip>doesn't work because the rootpom.xmlhard-codes<skip>false</skip>onmaven-deploy-plugin; override the plugin configuration in this module instead:
| <build> | |
| <plugins> | |
| <plugin> | |
| <groupId>org.springframework.boot</groupId> | |
| <artifactId>spring-boot-maven-plugin</artifactId> | |
| <configuration> | |
| <mainClass>com.google.adk.tutorials.CodeAssistant</mainClass> | |
| </configuration> | |
| </plugin> | |
| </plugins> | |
| </build> | |
| <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> |
With both changes, mvn exec:java starts the server and ./mvnw -Prelease deploy -pl tutorials/code-assistant logs Skipping artifact deployment.
| FunctionTool.create(CodeAssistant.class, "debugCode")) | ||
| .build(); | ||
|
|
||
| public static Map<String, String> generateCode( |
There was a problem hiding this comment.
The four tools don't perform any work: each only echoes its arguments back with a "request received" message while the model does the actual generation, review, and explanation itself. Because the agent would behave the same without them, the tutorial doesn't demonstrate what function tools are for, and the tests only verify that the maps are echoed.
Please give the tools real, deterministic behavior the model can't do on its own.
| public static final BaseAgent ROOT_AGENT = | ||
| LlmAgent.builder() | ||
| .name("code_assistant") | ||
| .model("gemini-2.0-flash") |
There was a problem hiding this comment.
nit: gemini-2.0-flash is an older model; please use a current one (and update the README to match).
2f2cf0d to
6c162d9
Compare
|
Addressed all review feedback:
|
6c162d9 to
73a7073
Compare
|
Polish pass on top of the previous fixes: templates now use Java text blocks via a lookup map (easier to read/extend), all public tool methods are null-safe, diagnostics rules were tightened to avoid false positives, and every line stays within the 100-column style limit. Re-verified end to end: |
73a7073 to
c28c2d2
Compare
damianmomotgoogle
left a comment
There was a problem hiding this comment.
Thanks for the update. The earlier feedback is addressed: the core changes are removed, the POM sets exec.mainClass and skips deployment, the tools perform real work, and the PR is a single conventional commit. I built the module and ran its 12 tests on JDK 17, and I tested the agent against a live Gemini model, where it called all four tools and used their results.
The remaining issues are in the tool logic, where several likely user inputs produce an incorrect result reported as a success. Most notably, generateSnippet returns JavaScript for any language other than Java and Python. See the inline comments for details, and please add a test with each fix.
If fixing all four tools is more work than you'd like, trimming the tutorial to fewer tools is fine; a tutorial doesn't need four.
Minor: please run google-java-format on CodeAssistant.java (it reformats the text blocks and a few wrapped expressions), and new files can use 2026 in the copyright header.
| private static final Pattern TODO_PATTERN = | ||
| Pattern.compile("TODO|FIXME|XXX|HACK", Pattern.CASE_INSENSITIVE); |
There was a problem hiding this comment.
Because this pattern has no word boundaries and is case-insensitive, matching identifiers are counted as markers in both analyzeCode and reviewCode: todoList and hackathon count as one marker each, and Todo todo = new Todo(); counts as three. Markers are conventionally uppercase; the pattern below still matches // TODO: fix this and // FIXME later while skipping identifiers:
| private static final Pattern TODO_PATTERN = | |
| Pattern.compile("TODO|FIXME|XXX|HACK", Pattern.CASE_INSENSITIVE); | |
| private static final Pattern TODO_PATTERN = Pattern.compile("\\b(?:TODO|FIXME|XXX|HACK)\\b"); |
| public static final BaseAgent ROOT_AGENT = | ||
| LlmAgent.builder() | ||
| .name("code_assistant") | ||
| .model("gemini-2.5-flash") |
There was a problem hiding this comment.
nit: the newer samples in this repo use gemini-3.8-flash (examples/workflows, examples/contextcaching). Please update the model name to match here and in the README (line 25); I verified that the agent works with it.
| .model("gemini-2.5-flash") | |
| .model("gemini-3.8-flash") |
| name = "language", | ||
| description = "The programming language of the code (e.g., Java, Python, JavaScript)") | ||
| String language) { | ||
| String[] lines = (code == null ? "" : code).split("\\R", -1); |
There was a problem hiding this comment.
split("\\R", -1) preserves the trailing empty string after a final newline, making lineCount one too high for most inputs: analyzeCode("int x = 1;\n", "Java") returns lineCount=2, and "" returns 1. The test at CodeAssistantTest.java:34 locks this in by expecting 6 for a 5-line class. Using (code == null ? "" : code).lines().toList() with lines.size() on line 194 gives the standard line counts (1, 0, and 5 for those three inputs).
| if (line.length() > LONG_LINE_THRESHOLD) { | ||
| longLines++; | ||
| } | ||
| if ((!trimmed.isEmpty() && line.endsWith(" ")) || line.endsWith("\t")) { |
There was a problem hiding this comment.
nit: because && binds tighter than ||, a whitespace-only line is counted when it ends in a tab, but not when it ends in a space ("\t" gives 1, while " " gives 0). If whitespace-only lines are meant to be skipped:
| if ((!trimmed.isEmpty() && line.endsWith(" ")) || line.endsWith("\t")) { | |
| if (!trimmed.isEmpty() && (line.endsWith(" ") || line.endsWith("\t"))) { |
| for (char c : line.toCharArray()) { | ||
| if (c == '{') { | ||
| braceBalance++; | ||
| } else if (c == '}') { | ||
| braceBalance--; | ||
| } | ||
| } |
There was a problem hiding this comment.
This loop duplicates braceBalance() below; analyzeCode can call that helper instead. Also, both implementations count braces inside comments and string or char literals, so analyzeCode("String s = \"{\";", "Java") reports braceBalance=1, bracesBalanced=false. And because only the final sum is checked, }{ is reported as balanced. Since the README, the Javadoc, and the agent instruction all describe these metrics as exact, please either ignore literals and comments and flag a negative running balance, or remove "exact" from those descriptions.
| findings.add( | ||
| "Contains " + todoCount + " TODO/FIXME-style marker(s) that should be resolved."); | ||
| } | ||
| if (source.contains("while (true)") && !source.contains("break")) { |
There was a problem hiding this comment.
There are two gaps here. First, the substring check misses while(true) without a space. Second, a break anywhere in the snippet suppresses the finding, even when it belongs to an unrelated switch: switch (x) { case 1: break; } followed by while (true) { work(); } produces no finding. Matching with a regex such as while\s*\(\s*true\s*\) handles the spacing, and since a substring search cannot tell which construct a break belongs to, consider dropping that condition and always reporting "verify it has an exit path".
| private static String languageFamily(String language) { | ||
| if (language == null) { | ||
| return "js"; | ||
| } | ||
| String lower = language.toLowerCase(Locale.ROOT); | ||
| if (lower.contains("java") && !lower.contains("javascript")) { | ||
| return "java"; | ||
| } | ||
| if (lower.contains("python") || lower.contains("py")) { | ||
| return "python"; | ||
| } | ||
| return "js"; | ||
| } |
There was a problem hiding this comment.
Every language other than Java and Python—including null—falls through to js, causing the tool to return JavaScript with status=success: generateSnippet("Go", "hello_world") returns console.log("Hello, World!");, and generateSnippet("C++", "class") returns a JavaScript class. In a live run asking for a Go hello world, the model called the tool with language=Go, then apologized that the tool returned JavaScript and wrote the Go code itself, exposing a broken tool to the user. Please match only the languages that have templates—by exact name rather than substrings like contains("py")—and return unsupported for everything else. Listing the supported languages in the unsupported message and in the language parameter's description will also tell the model when not to call the tool.
| if (error.contains("nullpointer") | ||
| || error.contains("npe") | ||
| || error.contains("null pointer")) { |
There was a problem hiding this comment.
These rules match raw substrings against the lowercased message, which misfires in both directions:
java.nio.channels.ConnectionPendingExceptiontriggers the NullPointerException advice becauseconnectionpendingcontainsnpe.DateTimeParseException: Text '2026-13-01' could not be parsedmatchesparseon line 335 and returns "Check for missing semicolons, unclosed strings/brackets, or bad indentation."- javac's standard missing-brace error,
reached end of file while parsing, misses that rule entirely becauseparsingdoes not containparse. - The Python and JavaScript equivalents (
IndexError: list index out of range,RecursionError: maximum recursion depth exceeded,TypeError: Cannot read properties of undefined) fall through to "No rule matched", even though the instruction states that the agent supports Python and JavaScript.
Matching whole words or exception names (for example, using one \b-delimited regex per rule) and adding the Python and JavaScript exception names would fix these cases.
| @Test | ||
| public void rootAgent_isNotNull() { | ||
| assertThat(CodeAssistant.ROOT_AGENT).isNotNull(); | ||
| } | ||
|
|
||
| @Test | ||
| public void rootAgent_hasCorrectName() { | ||
| assertThat(CodeAssistant.ROOT_AGENT.name()).isEqualTo("code_assistant"); | ||
| } |
There was a problem hiding this comment.
These two tests add little value, as every other test already requires the class to load and the agent name is a constant literal. Instead, please add tests covering the cases raised in this review (an unsupported language, JavaScript ===, todoList, a trailing newline, a brace inside a string literal, and the error messages from the debugCode comment) as well as the existing checks that currently lack test coverage: string ==, printStackTrace, while (true), the TODO finding in reviewCode, and the JavaScript templates.
| ## Go to example directory | ||
|
|
||
| ```shell | ||
| cd /google_adk/tutorials/code-assistant |
There was a problem hiding this comment.
nit: an adk-java checkout has no /google_adk directory; from the repository root, the command is cd tutorials/code-assistant, matching live-audio-single-agent. Also, -Dadk.agents.source-dir=$PWD on line 22 has no effect here because AdkWebServer.start(ROOT_AGENT) switches to a static loader that serves only the agents passed to it, so a plain mvn exec:java is sufficient.
c28c2d2 to
7a75881
Compare
|
All feedback addressed in the latest push:
Verified: |
7a75881 to
7582684
Compare
damianmomotgoogle
left a comment
There was a problem hiding this comment.
Thanks, this round addresses everything from the previous review. I rebuilt the module, ran the 28 tests, checked formatting, re-ran the earlier example inputs, and tested the agent against a live gemini-3.8-flash model. Everything looks good.
One issue blocks merging: the end of the README contains stray text that looks like output from an AI coding assistant. See the inline comment for details.
|
|
||
| Wait — I added a stray ``` at the end. Fix.<|close|>think<|sep|><|open|>response<|sep|>I accidentally added a stray closing fence at the end — fixing:<!|close|>think<|sep|><|open|>tools<|sep|><|open|>call tool="edit" index="1"<|sep|><|open|>argument key="file_path" type="string"<|sep|>/Users/apple/Downloads/adk-java/tutorials/code-assistant/README.md No newline at end of file |
There was a problem hiding this comment.
This last line does not belong in the README; it looks like leftover output from an AI coding assistant and includes a local file path. Please remove it and the preceding blank line so that the file ends with the "Learn More" line followed by a final newline (which is currently missing).
7582684 to
582aea7
Compare
|
Fixed — removed the stray assistant output at the end of README.md; the file now ends with the "Learn More" line followed by a final newline. Pushed as 582aea7. |
b759575 to
568a3f2
Compare
damianmomotgoogle
left a comment
There was a problem hiding this comment.
Thanks for the iterations on this. Before merging, we'd like to turn this into a realistic tutorial: an agent people would actually build, with tools that do useful work rather than hardcoded rules and templates.
Right now, the four tools act as lookup tables: generateSnippet returns fixed templates, debugCode maps exception names to canned advice, and analyzeCode/reviewCode apply a handful of regexes. Because the model already does these tasks better than the tables do, the tutorial ends up teaching a pattern we don't want people to copy.
Suggested direction:
- Use child agents for work the model does itself. A
code_assistantcoordinator withsubAgents(...)(e.g.code_writer,code_reviewer,debugger), each with a focused instruction, demonstrates ADK's agent transfer and needs no tools to write, review, or explain code. - Keep function tools only for work the model can't do on its own, backed by real functionality. For example, a
compileJavatool that compiles the snippet with the JDK'sjavax.tools.JavaCompilerand returns the actual diagnostics (line, column, message) lets the debugger and reviewer work from real compiler output and lets the writer verify that its code compiles. - Drop
generateSnippet,debugCode, and the regex checks, and update the tests and README to match.
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.
568a3f2 to
02a85af
Compare
|
Reworked the tutorial per the review direction:
Verified: ./mvnw test -pl tutorials/code-assistant — 10/10 pass; rebased on latest main (02a85af). |
Description
This PR adds a new code assistant tutorial to the
tutorials/modules.New Features
code-assistanttutorial module with 4 function tools that perform real deterministic work the model cannot do on its own:analyzeCode— computes structural metrics (line counts, brace balance ignoring comments/string literals, TODO markers with word boundaries, long lines, trailing whitespace)reviewCode— Java-only static checks (System.out usage, empty catch blocks, string==,while (true)loops, TODO markers); returnsunsupportedfor other languagesgenerateSnippet— canonical templates forhello_world,function,class,mainin Java, Python, JavaScript (exact language match);unsupportedotherwisedebugCode— rule-based diagnostics using word-boundary exception matching for Java, Python, and JavaScript errors (NPE, IndexError, StackOverflow/RecursionError, syntax, timeout)CodeAssistant.javausing thegemini-3.8-flashmodelpom.xmlto include the new moduleexec.mainClass(like other tutorials) and overridesmaven-deploy-pluginwith<skip>true</skip>so it stays out of the Maven Central releaseTesting
Unit Tests
Added
CodeAssistantTest.javawith 28 unit tests covering every tool, including edge cases from review: unsupported languages, identifier-vs-marker TODO matching, trailing newlines, braces inside literals/comments, negative brace balance, JavaScript templates, and Java/Python/JS exception diagnostics. All pass via./mvnw test -pl tutorials/code-assistant.Manual E2E Tests
mvn exec:javaboots the ADK web server with thecode_assistantagent registeredmvn deploylogsSkipping artifact deployment