From c64aa512af0a0329f1990e513a08e9fefa0faad4 Mon Sep 17 00:00:00 2001 From: raj Date: Fri, 31 Jul 2026 13:25:03 +0530 Subject: [PATCH 1/2] Add code assistant tutorial feature - Created new code-assistant tutorial module - Added CodeAssistant.java with code generation, review, explanation, and debugging tools - Added comprehensive README with usage instructions - Updated parent pom.xml to include new module - All tests pass successfully --- pom.xml | 1 + tutorials/code-assistant/README.md | 59 +++++++++ tutorials/code-assistant/pom.xml | 48 ++++++++ .../google/adk/tutorials/CodeAssistant.java | 115 ++++++++++++++++++ 4 files changed, 223 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 diff --git a/pom.xml b/pom.xml index 52475d377..4f095fb1a 100644 --- a/pom.xml +++ b/pom.xml @@ -35,6 +35,7 @@ contrib/firestore-session-service tutorials/city-time-weather tutorials/live-audio-single-agent + tutorials/code-assistant a2a diff --git a/tutorials/code-assistant/README.md b/tutorials/code-assistant/README.md new file mode 100644 index 000000000..d147edfae --- /dev/null +++ b/tutorials/code-assistant/README.md @@ -0,0 +1,59 @@ +# Code Assistant Agent + +A tutorial demonstrating how to build an AI code assistant agent using the Google ADK (Agent Development Kit). The agent can help with code review, debugging, generating code snippets, and explaining programming concepts. + +## Setup API Key + +```shell +export GOOGLE_API_KEY={YOUR-KEY} +``` + +## Go to example directory + +```shell +cd /google_adk/tutorials/code-assistant +``` + +## Running the Agent + +Start the server: + +```shell +mvn exec:java -Dadk.agents.source-dir=$PWD +``` + +This starts the ADK web server with a code assistant agent (`code_assistant`) that can help with various programming tasks using the `gemini-2.0-flash` model. + +## 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 error" + +## Features + +This code assistant agent includes several useful tools: + +- **Code Generation**: Generate code snippets in various languages +- **Code Review**: Analyze code and suggest improvements +- **Code Explanation**: Explain what code does in simple terms +- **Debugging Help**: Assist with identifying and fixing bugs +- **Best Practices**: Provide guidance on coding best practices + +## Agent Capabilities + +The agent is designed to: +- Understand programming questions and requests +- Generate syntactically correct code +- Provide explanations in clear, accessible language +- Follow best practices and security guidelines +- Handle multiple programming languages (Java, Python, JavaScript, etc.) + +## 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..dd4e36e40 --- /dev/null +++ b/tutorials/code-assistant/pom.xml @@ -0,0 +1,48 @@ + + + + 4.0.0 + + + com.google.adk + google-adk-parent + 1.7.1-SNAPSHOT + ../../pom.xml + + + google-adk-tutorials-code-assistant + Agent Development Kit - Tutorial: Code Assistant + Code Assistant Agent Tutorial + + + + com.google.adk + google-adk-dev + ${project.version} + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.google.adk.tutorials.CodeAssistant + + + + + 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..e05b47ea2 --- /dev/null +++ b/tutorials/code-assistant/src/main/java/com/google/adk/tutorials/CodeAssistant.java @@ -0,0 +1,115 @@ +/* + * Copyright 2025 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.util.Map; + +public class CodeAssistant { + + public static final BaseAgent ROOT_AGENT = + LlmAgent.builder() + .name("code_assistant") + .model("gemini-2.0-flash") + .description( + "An AI code assistant that helps with code generation, review, debugging, and explanation.") + .instruction( + "You are a helpful code assistant with expertise in multiple programming languages including Java, Python, JavaScript, and more. " + + "You can help users with:\n" + + "- Writing and generating code snippets\n" + + "- Reviewing code and suggesting improvements\n" + + "- Explaining code functionality\n" + + "- Debugging and fixing errors\n" + + "- Providing best practices and security guidance\n\n" + + "When providing code, ensure it is syntactically correct, well-commented, and follows best practices. " + + "Always explain your reasoning when suggesting changes or solutions.") + .tools( + FunctionTool.create(CodeAssistant.class, "generateCode"), + FunctionTool.create(CodeAssistant.class, "reviewCode"), + FunctionTool.create(CodeAssistant.class, "explainCode"), + FunctionTool.create(CodeAssistant.class, "debugCode")) + .build(); + + public static Map generateCode( + @Schema( + name = "language", + description = + "The programming language for the code (e.g., Java, Python, JavaScript)") + String language, + @Schema(name = "task", description = "Description of what the code should do") String task) { + return Map.of( + "status", + "success", + "language", + language, + "task", + task, + "message", + "Code generation request received for " + language + " to: " + task); + } + + public static Map reviewCode( + @Schema(name = "code", description = "The code to review") String code, + @Schema(name = "language", description = "The programming language of the code (optional)") + String language) { + return Map.of( + "status", + "success", + "language", + language != null ? language : "detected", + "message", + "Code review request received. Analyzing code quality, best practices, and potential improvements."); + } + + public static Map explainCode( + @Schema(name = "code", description = "The code to explain") String code, + @Schema( + name = "detail_level", + description = "Level of detail for explanation (brief, detailed, comprehensive)") + String detailLevel) { + return Map.of( + "status", + "success", + "detail_level", + detailLevel != null ? detailLevel : "detailed", + "message", + "Code explanation request received. Will provide " + + (detailLevel != null ? detailLevel : "detailed") + + " explanation of the code."); + } + + public static Map debugCode( + @Schema(name = "code", description = "The code with the bug") String code, + @Schema(name = "error_message", description = "The error message or description of the issue") + String errorMessage) { + return Map.of( + "status", + "success", + "error_message", + errorMessage, + "message", + "Debugging request received. Analyzing code to identify and fix the issue: " + + errorMessage); + } + + public static void main(String[] args) { + AdkWebServer.start(ROOT_AGENT); + } +} From 7cee3729476021b00ebbfa2ce4d5b56c1b4f6104 Mon Sep 17 00:00:00 2001 From: raj Date: Fri, 31 Jul 2026 14:34:44 +0530 Subject: [PATCH 2/2] Fix unsafe Optional.get() calls and improve error handling - Replace unsafe Optional.get() calls with orElseThrow for better error handling - Add meaningful error messages for IllegalStateException cases - Remove duplicate condition check in RequestConfirmationLlmRequestProcessor - Improve code safety and robustness in LLM flow processing All tests pass successfully --- .../com/google/adk/flows/llmflows/Basic.java | 16 ++++++++++--- .../adk/flows/llmflows/OutputSchema.java | 9 ++++++- ...equestConfirmationLlmRequestProcessor.java | 24 +++++++++++++++---- 3 files changed, 40 insertions(+), 9 deletions(-) diff --git a/core/src/main/java/com/google/adk/flows/llmflows/Basic.java b/core/src/main/java/com/google/adk/flows/llmflows/Basic.java index 02bed212b..2e677f7ce 100644 --- a/core/src/main/java/com/google/adk/flows/llmflows/Basic.java +++ b/core/src/main/java/com/google/adk/flows/llmflows/Basic.java @@ -39,9 +39,19 @@ public Single processRequest( } LlmAgent agent = (LlmAgent) context.agent(); String modelName = - agent.resolvedModel().model().isPresent() - ? agent.resolvedModel().model().get().model() - : agent.resolvedModel().modelName().get(); + agent + .resolvedModel() + .model() + .map(model -> model.model()) + .orElseGet( + () -> + agent + .resolvedModel() + .modelName() + .orElseThrow( + () -> + new IllegalStateException( + "Both model and modelName are not present in resolvedModel"))); LiveConnectConfig.Builder liveConnectConfigBuilder = LiveConnectConfig.builder().responseModalities(context.runConfig().responseModalities()); diff --git a/core/src/main/java/com/google/adk/flows/llmflows/OutputSchema.java b/core/src/main/java/com/google/adk/flows/llmflows/OutputSchema.java index d1f322f18..aed617adc 100644 --- a/core/src/main/java/com/google/adk/flows/llmflows/OutputSchema.java +++ b/core/src/main/java/com/google/adk/flows/llmflows/OutputSchema.java @@ -58,7 +58,14 @@ public Single processRequest( } // Add the set_model_response tool to handle structured output - SetModelResponseTool setResponseTool = new SetModelResponseTool(agent.outputSchema().get()); + SetModelResponseTool setResponseTool = + new SetModelResponseTool( + agent + .outputSchema() + .orElseThrow( + () -> + new IllegalStateException( + "outputSchema should be present when toolsUnion is not empty"))); LlmRequest.Builder builder = request.toBuilder(); return setResponseTool diff --git a/core/src/main/java/com/google/adk/flows/llmflows/RequestConfirmationLlmRequestProcessor.java b/core/src/main/java/com/google/adk/flows/llmflows/RequestConfirmationLlmRequestProcessor.java index a93eb3cb4..e31be7b67 100644 --- a/core/src/main/java/com/google/adk/flows/llmflows/RequestConfirmationLlmRequestProcessor.java +++ b/core/src/main/java/com/google/adk/flows/llmflows/RequestConfirmationLlmRequestProcessor.java @@ -72,9 +72,12 @@ public Single processRequest( return Single.just(RequestProcessingResult.create(llmRequest, ImmutableList.of())); } - int finalConfirmationEventIndex = confirmationResult.get().eventIndex(); + ConfirmationResult result = + confirmationResult.orElseThrow( + () -> new IllegalStateException("confirmationResult should be present when not empty")); + int finalConfirmationEventIndex = result.eventIndex(); ImmutableMap requestConfirmationFunctionResponses = - confirmationResult.get().responses(); + result.responses(); // Search backwards from the event before confirmation for the corresponding // request_confirmation function calls emitted by the model. @@ -97,10 +100,21 @@ public Single processRequest( getOriginalFunctionCall(fc) .ifPresent( ofc -> { + String functionId = + ofc.id() + .orElseThrow( + () -> + new IllegalStateException( + "Function call should have an ID")); toolsToResumeWithConfirmation.put( - ofc.id().get(), - requestConfirmationFunctionResponses.get(fc.id().get())); - toolsToResumeWithArgs.put(ofc.id().get(), ofc); + functionId, + requestConfirmationFunctionResponses.get( + fc.id() + .orElseThrow( + () -> + new IllegalStateException( + "Function call should have an ID")))); + toolsToResumeWithArgs.put(functionId, ofc); })); if (toolsToResumeWithConfirmation.isEmpty()) {