### Example Usage Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/cli/index.html An example command to start the ADK web server with session service URI and port. ```bash adk web –session_service_uri=[uri] –port=[port] path/to/agents_dir ``` -------------------------------- ### Example() Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/examples/Example.html Default constructor for the `Example` class. ```APIDOC ## Constructor: Example() ### Description Default constructor for the `Example` class. ### Method Constructor ### Signature `Example()` ``` -------------------------------- ### Initialize and Run a Live Audio Conversation in Java Source: https://github.com/google/adk-docs/blob/main/docs/get-started/streaming/quickstart-streaming-java.md This comprehensive example demonstrates the full setup for a live audio conversation, including ADK runner initialization, session creation, audio format configuration, and concurrent tasks for microphone input and speaker output processing. ```java import com.google.adk.agents.LiveRequestQueue; import com.google.adk.agents.RunConfig; import com.google.adk.events.Event; import com.google.adk.runner.Runner; import com.google.adk.sessions.InMemorySessionService; import com.google.common.collect.ImmutableList; import com.google.genai.types.Blob; import com.google.genai.types.Modality; import com.google.genai.types.PrebuiltVoiceConfig; import com.google.genai.types.Content; import com.google.genai.types.Part; import com.google.genai.types.SpeechConfig; import com.google.genai.types.VoiceConfig; import io.reactivex.rxjava3.core.Flowable; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URL; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.Mixer; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.TargetDataLine; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import agents.ScienceTeacherAgent; /** Main class to demonstrate running the {@link LiveAudioAgent} for a voice conversation. */ public final class LiveAudioRun { private final String userId; private final String sessionId; private final Runner runner; private static final javax.sound.sampled.AudioFormat MIC_AUDIO_FORMAT = new javax.sound.sampled.AudioFormat(16000.0f, 16, 1, true, false); private static final javax.sound.sampled.AudioFormat SPEAKER_AUDIO_FORMAT = new javax.sound.sampled.AudioFormat(24000.0f, 16, 1, true, false); private static final int BUFFER_SIZE = 4096; public LiveAudioRun() { this.userId = "test_user"; String appName = "LiveAudioApp"; this.sessionId = UUID.randomUUID().toString(); InMemorySessionService sessionService = new InMemorySessionService(); this.runner = new Runner(ScienceTeacherAgent.ROOT_AGENT, appName, null, sessionService); ConcurrentMap initialState = new ConcurrentHashMap<>(); var unused = sessionService.createSession(appName, userId, initialState, sessionId).blockingGet(); } private void runConversation() throws Exception { System.out.println("Initializing microphone input and speaker output..."); RunConfig runConfig = RunConfig.builder() .setStreamingMode(RunConfig.StreamingMode.BIDI) .setResponseModalities(ImmutableList.of(new Modality("AUDIO"))) .setSpeechConfig( SpeechConfig.builder() .voiceConfig( VoiceConfig.builder() .prebuiltVoiceConfig( PrebuiltVoiceConfig.builder().voiceName("Aoede").build()) .build()) .languageCode("en-US") .build()) .build(); LiveRequestQueue liveRequestQueue = new LiveRequestQueue(); Flowable eventStream = this.runner.runLive( runner.sessionService().createSession(userId, sessionId).blockingGet(), liveRequestQueue, runConfig); AtomicBoolean isRunning = new AtomicBoolean(true); AtomicBoolean conversationEnded = new AtomicBoolean(false); ExecutorService executorService = Executors.newFixedThreadPool(2); // Task for capturing microphone input Future microphoneTask = executorService.submit(() -> captureAndSendMicrophoneAudio(liveRequestQueue, isRunning)); // Task for processing agent responses and playing audio Future outputTask = executorService.submit( () -> { try { processAudioOutput(eventStream, isRunning, conversationEnded); } catch (Exception e) { System.err.println("Error processing audio output: " + e.getMessage()); e.printStackTrace(); isRunning.set(false); } }); // Wait for user to press Enter to stop the conversation System.out.println("Conversation started. Press Enter to stop..."); System.in.read(); System.out.println("Ending conversation..."); isRunning.set(false); try { // Give some time for ongoing processing to complete microphoneTask.get(2, TimeUnit.SECONDS); outputTask.get(2, TimeUnit.SECONDS); } catch (Exception e) { System.out.println("Stopping tasks..."); } liveRequestQueue.close(); executorService.shutdownNow(); System.out.println("Conversation ended."); } ``` -------------------------------- ### Run the adk web server Source: https://github.com/google/adk-docs/blob/main/docs/a2a/quickstart-consuming.md Command to start the ADK web server in a separate terminal. ```bash # In a separate terminal, run the adk web server adk web contributing/samples/ ``` -------------------------------- ### Install ADK with A2A dependencies Source: https://github.com/google/adk-docs/blob/main/docs/a2a/quickstart-consuming.md Installs the necessary Python dependencies for the Agent Development Kit, including A2A support. ```bash pip install google-adk[a2a] ``` -------------------------------- ### Clone Restate ADK Example Repository Source: https://github.com/google/adk-docs/blob/main/docs/integrations/restate.md Clone the example repository and navigate into the 'hello-world' directory to set up the project. ```bash git clone https://github.com/restatedev/restate-google-adk-example.git cd restate-google-adk-example/examples/hello-world ``` -------------------------------- ### Start Remote Prime Agent server with debug logging Source: https://github.com/google/adk-docs/blob/main/docs/a2a/quickstart-consuming.md Starts the A2A server with debug-level logging enabled for more detailed inspection during testing. ```bash adk api_server --a2a --port 8001 contributing/samples/a2a/a2a_basic/remote_a2a --log_level debug ``` -------------------------------- ### RemoteA2aAgent Configuration Source: https://github.com/google/adk-docs/blob/main/docs/a2a/quickstart-consuming.md Example showing how to configure a RemoteA2aAgent with custom converters and request interceptors. ```python <...code truncated...> from google.adk.agents.remote_a2a_agent import AGENT_CARD_WELL_KNOWN_PATH from google.adk.agents.remote_a2a_agent import RemoteA2aAgent prime_agent = RemoteA2aAgent( name="prime_agent", description="Agent that handles checking if numbers are prime.", agent_card=( f"http://localhost:8001/a2a/check_prime_agent{AGENT_CARD_WELL_KNOWN_PATH}" ), use_legacy=False, config=A2aRemoteAgentConfig( a2a_message_converter=my_a2a_message_converter, request_interceptors=[my_request_interceptor], ), ) <...code truncated> ``` -------------------------------- ### Combined Operations Interaction Source: https://github.com/google/adk-docs/blob/main/docs/a2a/quickstart-consuming.md An example interaction using both local and remote agents. ```text User: Roll a 10-sided die and check if it's prime Bot: I rolled an 8 for you. Bot: 8 is not a prime number. ``` -------------------------------- ### start(com.google.adk.agents.BaseAgent... agents) Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/web/AdkWebServer.html Initializes and starts the AdkWebServer with the specified agents. ```APIDOC ## Method: start ### Description Initializes and starts the AdkWebServer with the specified agents. ### Signature static void start(com.google.adk.agents.BaseAgent... agents) ### Parameters #### Method Parameters - **agents** (com.google.adk.agents.BaseAgent...) - Required - One or more BaseAgent instances to be registered with the server. ``` -------------------------------- ### Expected server startup output Source: https://github.com/google/adk-docs/blob/main/docs/a2a/quickstart-consuming.md The console output indicating that the A2A server has successfully started and is listening on the specified port. ```shell INFO: Started server process [56558] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://127.0.0.1:8001 (Press CTRL+C to quit) ``` -------------------------------- ### public void init(PlanningContext context) Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/planner/SequentialPlanner.html Initializes the planner with context and available agents. This method is called once before the planning loop starts. It can be overridden to perform setup like building dependency graphs. ```APIDOC ## public void init(PlanningContext context) ### Description Initialize the planner with context and available agents. Called once before the planning loop starts. Default implementation is a no-op. Override to perform setup like building dependency graphs. ### Method Method ### Signature `public void init(PlanningContext context)` ### Parameters #### Method Parameters - **context** ([PlanningContext](../agents/PlanningContext.html "class in com.google.adk.agents")) - The planning context. ``` -------------------------------- ### build() Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/examples/Example.Builder.html Constructs and returns a new `Example` instance with the configured input and output. ```APIDOC ## Method: build() ### Description Constructs and returns a new `Example` instance with the configured input and output. ### Signature ```java abstract com.google.adk.examples.Example build() ``` ### Returns - (`com.google.adk.examples.Example`) - A new `Example` instance. ``` -------------------------------- ### buildExampleSi(BaseExampleProvider exampleProvider, String query) Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/examples/ExampleUtils.html Builds a formatted few-shot example string for the given query. The string can be used for system instructions (i.e., the method name means "Build Example System Instructions"). ```APIDOC ## buildExampleSi(BaseExampleProvider exampleProvider, String query) ### Description Builds a formatted few-shot example string for the given query. The string can be used for system instructions (i.e., the method name means "Build Example System Instructions"). ### Method public static String buildExampleSi(com.google.adk.examples.BaseExampleProvider exampleProvider, java.lang.String query) ### Parameters - **exampleProvider** (com.google.adk.examples.BaseExampleProvider) - Source of examples. - **query** (java.lang.String) - User query. ### Returns formatted string with few-shot examples. ``` -------------------------------- ### setExampleProvider(BaseExampleProvider) Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/tools/ExampleTool.Builder.html Sets a provider for examples for the ExampleTool being built. This method allows for explicit setting of an example provider. ```APIDOC ## setExampleProvider(com.google.adk.examples.BaseExampleProvider provider) ### Description Sets the example provider for the `ExampleTool` being built. ### Parameters - **provider** (com.google.adk.examples.BaseExampleProvider) - The example provider to set. ### Returns `com.google.adk.tools.ExampleTool.Builder` - The current Builder instance for method chaining. ``` -------------------------------- ### ExampleUtils.buildExampleSi Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/examples/class-use/BaseExampleProvider.html Builds a formatted few-shot example string for the given query. ```APIDOC ## Method: static String ExampleUtils.buildExampleSi(BaseExampleProvider exampleProvider, String query) ### Description Builds a formatted few-shot example string for the given query. ### Parameters - **exampleProvider** (com.google.adk.examples.BaseExampleProvider) - **query** (java.lang.String) ### Returns java.lang.String ``` -------------------------------- ### Start Remote Prime Agent server Source: https://github.com/google/adk-docs/blob/main/docs/a2a/quickstart-consuming.md Starts the A2A server to expose the `check_prime_agent` on port 8001, making it accessible to other agents. ```bash adk api_server --a2a --port 8001 contributing/samples/a2a/a2a_basic/remote_a2a ``` -------------------------------- ### Request Time Off Tool Example (Java) Source: https://github.com/google/adk-docs/blob/main/docs/tools-custom/confirmation.md Example implementation for a tool that processes time off requests for an employee using Java, demonstrating advanced confirmation. ```java public Map requestTimeOff( @Schema(name="days") int days, ToolContext toolContext) { // Request day off for the employee. // ... Optional toolConfirmation = toolContext.toolConfirmation(); if (toolConfirmation.isEmpty()) { toolContext.requestConfirmation( "Please approve or reject the tool call requestTimeOff() by " + "responding with a FunctionResponse with an expected " + "ToolConfirmation payload.", Map.of("approved_days", 0) ); // Return intermediate status indicating that the tool is waiting for // a confirmation response: return Map.of("status", "Manager approval is required."); } Map payload = (Map) toolConfirmation.get().payload(); int approvedDays = (int) payload.get("approved_days"); approvedDays = Math.min(approvedDays, days); if (approvedDays == 0) { return Map.of("status", "The time off request is rejected.", "approved_days", 0); } return Map.of( "status", "ok", "approved_days", approvedDays ); } ``` -------------------------------- ### public ExampleTool build() Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/tools/ExampleTool.Builder.html Builds and returns a new `ExampleTool` instance with the configured properties. ```APIDOC ## public ExampleTool build() ### Description Builds and returns a new `ExampleTool` instance with the configured properties. ### Method build ### Parameters None ### Returns A new `ExampleTool` instance. ``` -------------------------------- ### com.google.adk.examples.ExampleUtils.buildExampleSi(com.google.adk.examples.BaseExampleProvider,java.lang.String) Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/index-all.html Static method to build a formatted few-shot example string for a given query using a specified example provider. ```APIDOC ## com.google.adk.examples.ExampleUtils.buildExampleSi ### Description Builds a formatted few-shot example string for the given query. ### Type Static Method ### Signature static java.lang.String buildExampleSi(com.google.adk.examples.BaseExampleProvider provider, java.lang.String query) ### Parameters - **provider** (com.google.adk.examples.BaseExampleProvider) - The provider for base examples. - **query** (java.lang.String) - The query string. ### Returns java.lang.String - A formatted few-shot example string. ``` -------------------------------- ### Request Time Off Tool Example (Go) Source: https://github.com/google/adk-docs/blob/main/docs/tools-custom/confirmation.md Example implementation for a tool that processes time off requests for an employee using Go, demonstrating advanced confirmation. ```go func requestTimeOff(ctx tool.Context, args RequestTimeOffArgs) (map[string]any, error) { confirmation := ctx.ToolConfirmation() if confirmation == nil { ctx.RequestConfirmation( "Please approve or reject the tool call requestTimeOff() by "+ "responding with a FunctionResponse with an expected "+ "ToolConfirmation payload.", map[string]any{"approved_days": 0}, ) return map[string]any{"status": "Manager approval is required."}, nil } payload := confirmation.Payload.(map[string]any) // Values in map[string]any from JSON are float64 by default in Go approvedDays := int(payload["approved_days"].(float64)) approvedDays = min(approvedDays, args.Days) if approvedDays == 0 { return map[string]any{"status": "The time off request is rejected.", "approved_days": 0}, nil } return map[string]any{ "status": "ok", "approved_days": approvedDays, }, nil } ``` -------------------------------- ### Request Time Off Tool Example (Python) Source: https://github.com/google/adk-docs/blob/main/docs/tools-custom/confirmation.md Example implementation for a tool that processes time off requests for an employee using Python, demonstrating advanced confirmation. ```python def request_time_off(days: int, tool_context: ToolContext): """Request day off for the employee.""" # ... tool_confirmation = tool_context.tool_confirmation if not tool_confirmation: tool_context.request_confirmation( hint=( 'Please approve or reject the tool call request_time_off() by' ' responding with a FunctionResponse with an expected' ' ToolConfirmation payload.' ), payload={ 'approved_days': 0, }, ) # Return intermediate status indicating that the tool is waiting for # a confirmation response: return {'status': 'Manager approval is required.'} approved_days = tool_confirmation.payload['approved_days'] approved_days = min(approved_days, days) if approved_days == 0: return {'status': 'The time off request is rejected.', 'approved_days': 0} return { 'status': 'ok', 'approved_days': approved_days, } ``` -------------------------------- ### Complete ADK agent with Monocle tracing example Source: https://github.com/google/adk-docs/blob/main/docs/integrations/monocle.md Full example demonstrating Monocle telemetry initialization, agent creation with a tool, session setup, and async execution with automatic tracing of all interactions. ```python from monocle_apptrace import setup_monocle_telemetry from google.adk.agents import Agent from google.adk.runners import InMemoryRunner from google.genai import types # Initialize Monocle telemetry - must be called before using ADK setup_monocle_telemetry(workflow_name="weather_app") # Define a tool function def get_weather(city: str) -> dict: """Retrieves the current weather report for a specified city. Args: city (str): The name of the city for which to retrieve the weather report. Returns: dict: status and result or error msg. """ if city.lower() == "new york": return { "status": "success", "report": ( "The weather in New York is sunny with a temperature of 25 degrees" " Celsius (77 degrees Fahrenheit)." ), } else: return { "status": "error", "error_message": f"Weather information for '{city}' is not available.", } # Create an agent with tools agent = Agent( name="weather_agent", model="gemini-flash-latest", description="Agent to answer questions using weather tools.", instruction="You must use the available tools to find an answer.", tools=[get_weather] ) app_name = "weather_app" user_id = "test_user" session_id = "test_session" runner = InMemoryRunner(agent=agent, app_name=app_name) session_service = runner.session_service await session_service.create_session( app_name=app_name, user_id=user_id, session_id=session_id ) # Run the agent (all interactions will be automatically traced) async for event in runner.run_async( user_id=user_id, session_id=session_id, new_message=types.Content(role="user", parts=[ types.Part(text="What is the weather in New York?")] ) ): if event.is_final_response(): print(event.content.parts[0].text.strip()) ``` -------------------------------- ### build() Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/examples/Example.Builder.html Builds and returns a new `Example` object with the configured parameters. ```APIDOC ## build() ### Description Builds and returns a new `Example` object with the configured parameters. ### Signature public abstract com.google.adk.examples.Example build() ### Returns (com.google.adk.examples.Example) - A new `Example` object. ``` -------------------------------- ### Sample folder structure Source: https://github.com/google/adk-docs/blob/main/docs/a2a/quickstart-consuming.md Shows the directory layout of the `a2a_basic` sample, including the remote agent's files. ```text a2a_basic/ ├── remote_a2a/ │ └── check_prime_agent/ │ ├── __init__.py │ ├── agent.json │ └── agent.py ├── README.md ├── __init__.py └── agent.py # local root agent ``` -------------------------------- ### Get Session Response (JSON) Source: https://github.com/google/adk-docs/blob/main/docs/runtime/api-server.md Example JSON response showing the retrieved session details, including state and events. ```json {"id":"s_abc","appName":"my_sample_agent","userId":"u_123","state":{"visit_count":5},"events":[...],"lastUpdateTime":1743711430.022186} ``` -------------------------------- ### getExamples(String query) Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/examples/BaseExampleProvider.html Retrieves a list of examples based on the provided query string. ```APIDOC ## Method: `getExamples(String query)` ### Description Retrieves a list of examples based on the provided query string. ### Method Signature ```java List getExamples(String query) ``` ### Parameters - **query** (String) - The query string to use for retrieving examples. ### Return Value - `List` - A list of `Example` objects matching the query. ``` -------------------------------- ### a2a_basic/remote_a2a/check_prime_agent/agent-card.json Source: https://github.com/google/adk-docs/blob/main/docs/a2a/quickstart-consuming.md Example agent card for the `check_prime_agent` describing its capabilities and skills. ```json { "capabilities": {}, "defaultInputModes": ["text/plain"], "defaultOutputModes": ["application/json"], "description": "An agent specialized in checking whether numbers are prime. It can efficiently determine the primality of individual numbers or lists of numbers.", "name": "check_prime_agent", "skills": [ { "id": "prime_checking", "name": "Prime Number Checking", "description": "Check if numbers in a list are prime using efficient mathematical algorithms", "tags": ["mathematical", "computation", "prime", "numbers"] } ], "url": "http://localhost:8001/a2a/check_prime_agent", "version": "1.0.0" } ``` -------------------------------- ### ExampleTool.Builder.addExample(Example ex) Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/examples/class-use/Example.html No description ```APIDOC ## Method: `addExample(Example ex)` ### Class `com.google.adk.tools.ExampleTool.Builder` ### Return Type `com.google.adk.tools.ExampleTool.Builder` ### Parameters - **ex** (`com.google.adk.examples.Example`) ``` -------------------------------- ### Install ADK for Go Source: https://github.com/google/adk-docs/blob/main/docs/tutorials/multi-tool-agent.md Add the Google Agent Development Kit (ADK) as a dependency to your Go project using `go get`. ```bash go get google.golang.org/adk ``` -------------------------------- ### build() Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/tools/ExampleTool.Builder.html Constructs and returns a new ExampleTool instance with all the properties configured through the builder. ```APIDOC ## build() ### Description Constructs and returns a new `ExampleTool` instance with the configured properties. ### Parameters (None) ### Returns `com.google.adk.tools.ExampleTool` - A new `ExampleTool` instance. ``` -------------------------------- ### Simple Dice Rolling Interaction Source: https://github.com/google/adk-docs/blob/main/docs/a2a/quickstart-consuming.md An example interaction with a local Roll Agent. ```text User: Roll a 6-sided die Bot: I rolled a 4 for you. ``` -------------------------------- ### Example Usage: Integration with API Trigger Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/python/google-adk.html Demonstrates how to initialize `ApplicationIntegrationToolset` to get tools for an integration with an API trigger. ```python # Get all available tools for an integration with api trigger application_integration_toolset = ApplicationIntegrationToolset( project="test-project", location="us-central1" integration="test-integration", triggers=["api_trigger/test_trigger"], service_account_credentials={...}, ) ``` -------------------------------- ### com.google.adk.examples.Example.Builder.build() Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/index-all.html Builds an `Example` object from its builder. ```APIDOC ## Method: com.google.adk.examples.Example.Builder.build() ### Description Builds an `Example` object from its builder. ### Class `com.google.adk.examples.Example.Builder` ### Method Name `build()` ``` -------------------------------- ### Load Skills from Filesystem and Initialize SkillToolset Source: https://github.com/google/adk-docs/blob/main/docs/skills/index.md Use these examples to load skills from a local directory and then initialize a SkillToolset. This approach allows for local development and testing of skills. ```Python import pathlib from google.adk.skills import load_skill_from_dir from google.adk.tools import skill_toolset greeting_skill = load_skill_from_dir( pathlib.Path(__file__).parent / "skills" / "greeting-skill" ) weather_skill = load_skill_from_dir( pathlib.Path(__file__).parent / "skills" / "weather-skill" ) my_skill_toolset = skill_toolset.SkillToolset( skills=[weather_skill, greeting_skill], ) ``` ```Go import ( "os" "google.golang.org/adk/tool/skilltoolset/skill" "google.golang.org/adk/tool/skilltoolset" ) // ... source := skill.NewFileSystemSource(os.DirFS("./skills")) // This example doesn't use any optional wrappers, but you can use them if // needed, e.g.: // source, _, err = skill.WithFrontmatterPreloadSource(ctx, source) // source, _, err = skill.WithCompletePreloadSource(ctx, source) // For more information about these and other wrappers, see // https://pkg.go.dev/google.golang.org/adk/v2/tool/skilltoolset/skill#Source. skillToolset, err := skilltoolset.New(ctx, skilltoolset.Config{ Source: source, }) if err != nil { // handle error } ``` -------------------------------- ### Initialize and Run AG-UI Project Source: https://github.com/google/adk-docs/blob/main/docs/integrations/ag-ui.md Commands to scaffold a new project, configure environment variables, and start development servers. ```bash npx copilotkit@latest create -f adk ``` ```bash export GOOGLE_API_KEY="your-api-key" ``` ```bash npm install && npm run dev ``` -------------------------------- ### List Available Artifacts (Java) Source: https://github.com/google/adk-docs/blob/main/docs/context/index.md This snippet provides an example of using `toolContext.listArtifacts()` to get a list of available artifact keys in a Java tool function. ```java // Example: In a tool function import com.google.adk.tools.ToolContext; import io.reactivex.rxjava3.core.Single; import java.util.List; import java.util.Map; public Map checkAvailableDocs(ToolContext toolContext) { try { Single> artifactKeys = toolContext.listArtifacts(); System.out.println("Available artifacts: " + artifactKeys.blockingGet().toString()); return Map.of("availableDocs", artifactKeys.blockingGet()); } catch (IllegalArgumentException e) { return Map.of("error", "Artifact service error: " + e); } } ``` -------------------------------- ### Initialize McpToolset and Run LlmAgent in Java Source: https://github.com/google/adk-docs/blob/main/docs/tools-custom/mcp-tools.md This Java example initializes an McpToolset to connect to an MCP filesystem server, creates an LlmAgent with these tools, and sends a prompt to list files in a directory. ```java package agents; import com.google.adk.agents.LlmAgent; import com.google.adk.runner.InMemoryRunner; import com.google.adk.sessions.SessionKey; import com.google.adk.tools.mcp.McpToolset; import com.google.adk.tools.mcp.StdioServerParameters; import com.google.genai.types.Content; import com.google.genai.types.Part; import java.util.List; public class McpAgentCreator { /** * Initializes an McpToolset, retrieves tools from an MCP server using stdio, * creates an LlmAgent with these tools, sends a prompt to the agent, * and ensures the toolset is closed. * @param args Command line arguments (not used). */ public static void main(String[] args) { //Note: you may have permissions issues if the folder is outside home String yourFolderPath = "~/path/to/folder"; StdioServerParameters serverParams = StdioServerParameters.builder() .command("npx") .args(List.of( "-y", "@modelcontextprotocol/server-filesystem", yourFolderPath )) .build(); try (McpToolset toolset = new McpToolset(serverParams.toServerParameters())) { LlmAgent agent = LlmAgent.builder() .model("gemini-flash-latest") .name("enterprise_assistant") .description("An agent to help users access their file systems") .instruction( "Help user accessing their file systems. You can list files in a directory." ) .tools(toolset) .build(); System.out.println("Agent created: " + agent.name()); InMemoryRunner runner = new InMemoryRunner(agent); String userId = "user123"; String sessionId = "1234"; String promptText = "Which files are in this directory - " + yourFolderPath + "?"; // Explicitly create the session first SessionKey sessionKey = runner.sessionService().createSession(runner.appName(), userId, null, sessionId).blockingGet().sessionKey(); System.out.println("Session created: " + sessionId + " for user: " + userId); Content promptContent = Content.fromParts(Part.fromText(promptText)); System.out.println("\nSending prompt: \"" + promptText + "\" to agent...\n"); runner.runAsync(sessionKey, promptContent) .blockingForEach(event -> { System.out.println("Event received: " + event.toJson()); }); } catch (Exception e) { System.err.println("An error occurred: " + e.getMessage()); e.printStackTrace(); } } } ``` -------------------------------- ### GET userContent Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/typescript/classes/Context.html Retrieves the user content that started the current invocation. This is a read-only getter that returns the Content object or undefined if no user content is present. ```APIDOC ## GET userContent ### Description Retrieve the user content that started this invocation. ### Method GET (Property Accessor) ### Returns - **userContent** (Content | undefined) - The user content that started this invocation ### Inheritance Inherited from ReadonlyContext.userContent ### Source Defined in agents/readonly_context.ts:22 ``` -------------------------------- ### Example.Builder.build() Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/examples/class-use/Example.html No description ```APIDOC ## Method: `build()` ### Class `com.google.adk.examples.Example.Builder` ### Return Type `com.google.adk.examples.Example` ### Parameters (None) ``` -------------------------------- ### Prime Number Checking Interaction Source: https://github.com/google/adk-docs/blob/main/docs/a2a/quickstart-consuming.md An example interaction with a remote Prime Agent via A2A. ```text User: Is 7 a prime number? Bot: Yes, 7 is a prime number. ``` -------------------------------- ### ExampleTool.Builder.exampleProvider Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/examples/class-use/BaseExampleProvider.html No description ```APIDOC ## Method: ExampleTool.Builder exampleProvider(BaseExampleProvider provider) ### Parameters - **provider** (com.google.adk.examples.BaseExampleProvider) ### Returns com.google.adk.tools.ExampleTool.Builder ``` -------------------------------- ### Initialize LlmAgent with Gemini Flash Model (TypeScript) Source: https://github.com/google/adk-docs/blob/main/docs/agents/models/google-gemini.md Initializes an LlmAgent with `gemini-flash-latest` for a fast and helpful Gemini assistant. This example shows a basic setup in TypeScript. ```typescript import {LlmAgent} from '@google/adk'; // --- Example #2: using a powerful Gemini Pro model with API Key in model --- export const rootAgent = new LlmAgent({ name: 'hello_time_agent', model: 'gemini-flash-latest', description: 'Gemini flash agent', instruction: `You are a fast and helpful Gemini assistant.`, }); ``` -------------------------------- ### initialize() Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/tools/computeruse/BaseComputer.html Initialize the computer. ```APIDOC ## initialize()\n\n### Description\nInitialize the computer.\n\n### Method Signature\nio.reactivex.rxjava3.core.Completable initialize()\n\n### Return Value\n- **io.reactivex.rxjava3.core.Completable** ``` -------------------------------- ### BaseExampleProvider.getExamples(String query) Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/examples/class-use/Example.html No description ```APIDOC ## Method: `getExamples(String query)` ### Class `com.google.adk.examples.BaseExampleProvider` ### Return Type `java.util.List` ### Parameters - **query** (`java.lang.String`) ``` -------------------------------- ### GCP export setup Source: https://github.com/google/adk-docs/blob/main/docs/observability/traces.md Example in Python to export traces to Google Cloud Trace programmatically using the OpenTelemetry Google Cloud exporter. ```python from google.adk.telemetry.google_cloud import get_gcp_exporters from google.adk.telemetry.setup import maybe_set_otel_providers import os gcp_exporters = get_gcp_exporters( enable_cloud_tracing = True, ) os.environ["OTEL_SERVICE_NAME"] = "your-adk-agent" os.environ["OTEL_RESOURCE_ATTRIBUTES"] = "key1=value1,key2=value2" maybe_set_otel_providers([gcp_exporters]) ``` -------------------------------- ### Send confirmation via curl Source: https://github.com/google/adk-docs/blob/main/docs/tools-custom/confirmation.md Example of sending a FunctionResponse event to the /run_sse endpoint using curl to confirm a tool call. ```bash curl -X POST http://localhost:8000/run_sse \ -H "Content-Type: application/json" \ -d '{ "app_name": "human_tool_confirmation", "user_id": "user", "session_id": "7828f575-2402-489f-8079-74ea95b6a300", "new_message": { "parts": [ { "function_response": { "id": "adk-13b84a8c-c95c-4d66-b006-d72b30447e35", "name": "adk_request_confirmation", "response": { "confirmed": true, "payload": { "approved_days": 5 } } } } ], "role": "user" } }' ``` -------------------------------- ### main(String[]) Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/example/mcpfilesystem/McpFilesystemRun.html This method serves as the entry point for the sample runner, allowing the application to be executed from the command line. ```APIDOC ## Method: `main(String[])` ### Description Entry point for the sample runner. ### Signature `public static void main(String[] args)` ### Parameters - **args** (String[]) - Optional - Optional command-line arguments. Pass `--run-extended` for additional prompts. ``` -------------------------------- ### Navigate to A2A Basic Sample Directory Source: https://github.com/google/adk-docs/blob/main/docs/a2a/quickstart-consuming-java.md Change to the a2a_basic sample directory in the adk-java source code to access the quickstart implementation. ```bash cd contrib/samples/a2a_basic ``` -------------------------------- ### Example Usage: Connection with Entity Operations and Actions Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/python/google-adk.html Illustrates how to initialize `ApplicationIntegrationToolset` to get tools for a connection using specified entity operations and actions. ```python # Get all available tools for a connection using entity operations and # actions # Note: Find the list of supported entity operations and actions for a # connection using integration connector apis: # https://cloud.google.com/integration-connectors/docs/reference/rest/v1/projects.locations.connections.connectionSchemaMetadata application_integration_toolset = ApplicationIntegrationToolset( project="test-project", location="us-central1" connection="test-connection", entity_operations=["EntityId1": ["LIST","CREATE"], "EntityId2": []], #empty list for actions means all operations on the entity are supported actions=["action1"], service_account_credentials={...}, ) ``` -------------------------------- ### main(String[] args) Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/example/helloworld/HelloWorldRun.html The `main` method serves as the entry point for the `HelloWorldRun` application, accepting an array of string arguments. ```APIDOC ## Method: main(String[] args) ### Description The `main` method is the entry point for the `HelloWorldRun` application. It accepts command-line arguments as an array of strings. ### Signature `public static void main(String[] args)` ### Parameters - **args** (String[]) - Command-line arguments passed to the application. ### Returns `void` - This method does not return any value. ``` -------------------------------- ### Conceptual Setup: Agent as a Tool Source: https://github.com/google/adk-docs/blob/main/docs/agents/custom-agents.md Example demonstrating how to wrap a custom `BaseAgent` in an `AgentTool` and include it in an `LlmAgent`'s tools list in TypeScript. ```typescript // Conceptual Setup: Agent as a Tool import { LlmAgent, BaseAgent, AgentTool, InvocationContext } from '@google/adk'; import type { Part, createEvent, Event } from '@google/genai'; // Define a target agent (could be LlmAgent or custom BaseAgent) class ImageGeneratorAgent extends BaseAgent { // Example custom agent constructor() { super({name: 'ImageGen', description: 'Generates an image based on a prompt.'}); } // ... internal logic ... async *runAsyncImpl(ctx: InvocationContext): AsyncGenerator { // Simplified run logic const prompt = ctx.session.state['image_prompt'] || 'default prompt'; // ... generate image bytes ... const imageBytes = new Uint8Array(); // placeholder const imagePart: Part = {inlineData: {data: Buffer.from(imageBytes).toString('base64'), mimeType: 'image/png'}}; yield createEvent({content: {parts: [imagePart]}}); } async *runLiveImpl(ctx: InvocationContext): AsyncGenerator { // Not implemented for this agent. } } const imageAgent = new ImageGeneratorAgent(); const imageTool = new AgentTool({agent: imageAgent}); // Wrap the agent // Parent agent uses the AgentTool const artistAgent = new LlmAgent({ name: 'Artist', model: 'gemini-flash-latest', instruction: 'Create a prompt and use the ImageGen tool to generate the image.', tools: [imageTool] // Include the AgentTool }); // Artist LLM generates a prompt, then calls: // {functionCall: {name: 'ImageGen', args: {image_prompt: 'a cat wearing a hat'}}} // Framework calls imageTool.runAsync(...), which runs ImageGeneratorAgent. // The resulting image Part is returned to the Artist agent as the tool result. ``` -------------------------------- ### Create Web Entry Point for Kotlin Agent Source: https://github.com/google/adk-docs/blob/main/docs/get-started/kotlin.md Define `WebMain.kt` to set up and start the `AdkWebServer`, configuring it with services and your agent for web-based interaction. ```kotlin package com.example.agent import com.google.adk.kt.artifacts.InMemoryArtifactService import com.google.adk.kt.sessions.InMemorySessionService import com.google.adk.kt.webserver.AdkWebServer import com.google.adk.kt.webserver.loaders.SingleAgentLoader import com.google.adk.kt.webserver.telemetry.ApiServerSpanExporter fun main() { val agent = HelloTimeAgent.rootAgent val sessionService = InMemorySessionService() val artifactService = InMemoryArtifactService() val server = AdkWebServer( port = 8080, sessionService = sessionService, artifactService = artifactService, agentLoader = SingleAgentLoader(agent), apiServerSpanExporter = ApiServerSpanExporter(), ) println("Starting ADK web server on http://localhost:8080...") server.start(wait = true) } ``` -------------------------------- ### Conceptual Setup: Agent as a Tool Source: https://github.com/google/adk-docs/blob/main/docs/agents/custom-agents.md Example demonstrating how to wrap a custom `BaseAgent` in an `AgentTool` and include it in an `LlmAgent`'s tools list in Python. ```python # Conceptual Setup: Agent as a Tool from google.adk.agents import LlmAgent, BaseAgent from google.adk.tools import agent_tool from pydantic import BaseModel # Define a target agent (could be LlmAgent or custom BaseAgent) class ImageGeneratorAgent(BaseAgent): # Example custom agent name: str = "ImageGen" description: str = "Generates an image based on a prompt." # ... internal logic ... async def _run_async_impl(self, ctx): # Simplified run logic prompt = ctx.session.state.get("image_prompt", "default prompt") # ... generate image bytes ... image_bytes = b"..." yield Event(author=self.name, content=types.Content(parts=[types.Part.from_bytes(image_bytes, "image/png")])) image_agent = ImageGeneratorAgent() image_tool = agent_tool.AgentTool(agent=image_agent) # Wrap the agent # Parent agent uses the AgentTool artist_agent = LlmAgent( name="Artist", model="gemini-flash-latest", instruction="Create a prompt and use the ImageGen tool to generate the image.", tools=[image_tool] # Include the AgentTool ) # Artist LLM generates a prompt, then calls: # FunctionCall(name='ImageGen', args={'image_prompt': 'a cat wearing a hat'}) # Framework calls image_tool.run_async(...), which runs ImageGeneratorAgent. # The resulting image Part is returned to the Artist agent as the tool result. ``` -------------------------------- ### Configure LLM Agent with Streaming Tools (Java) Source: https://github.com/google/adk-docs/blob/main/docs/streaming/streaming-tools.md This example demonstrates how to initialize an `LlmAgent` with specific instructions and register custom streaming functions, like `monitorVideoStream` and `stopStreaming`, as callable tools. ```Java public static void main(String[] args) { LlmAgent rootAgent = LlmAgent.builder() .model("gemini-flash-latest") .name("video_streaming_agent") .instruction( "You are a monitoring agent. You can do video monitoring and stock price monitoring\n" + "using the provided tools/functions.\n" + "When users want to monitor a video stream,\n" + "You can use monitorVideoStream function to do that. When monitorVideoStream\n" + "returns the alert, you should tell the users.\n" + "When users want to monitor a stock price, you can use monitorStockPrice.\n" + "Don't ask too many questions. Don't be too talkative." ) .tools(Arrays.asList( FunctionTool.create(StreamingTools.class, "monitorVideoStream"), FunctionTool.create(StreamingTools.class, "monitorStockPrice"), FunctionTool.create(StreamingTools.class, "stopStreaming") )) .build(); } } ``` -------------------------------- ### public ExampleTool.Builder exampleProvider(BaseExampleProvider provider) Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/tools/ExampleTool.Builder.html Sets the example provider for the `ExampleTool`. ```APIDOC ## public ExampleTool.Builder exampleProvider(BaseExampleProvider provider) ### Description Sets the example provider for the `ExampleTool`. ### Method exampleProvider ### Parameters #### Method Parameters - **provider** (BaseExampleProvider) - Required - The example provider to set. ### Returns The current `ExampleTool.Builder` instance for method chaining. ``` -------------------------------- ### Initialize LlmAgent with Gemini Flash Model (Python) Source: https://github.com/google/adk-docs/blob/main/docs/agents/models/google-gemini.md Initializes an LlmAgent using the `gemini-flash-latest` model identifier. This example demonstrates a basic setup for a fast and helpful Gemini assistant in Python. ```python from google.adk.agents import LlmAgent # --- Example using a stable Gemini Flash model --- agent_gemini_flash = LlmAgent( # Use the latest stable Flash model identifier model="gemini-flash-latest", name="gemini_flash_agent", instruction="You are a fast and helpful Gemini assistant.", # ... other agent parameters ) ``` -------------------------------- ### Enable Boolean Confirmation for Tools Source: https://github.com/google/adk-docs/blob/main/docs/tools-custom/confirmation.md Examples demonstrating how to enable simple yes/no boolean confirmation for an ADK Tool across different programming languages. ```python root_agent = Agent( # ... tools = [ # Set require_confirmation to True to require user confirmation # for the tool call. FunctionTool(reimburse, require_confirmation=True), ], # ... ) # This implementation method requires minimal code, but is limited to simple # approvals from the user or confirming system. For a complete example of this # approach, see the following code sample for a more detailed example: # https://github.com/google/adk-python/blob/main/contributing/samples/human_tool_confirmation/agent.py ``` ```go reimburseTool, _ := functiontool.New(functiontool.Config{ Name: "reimburse", Description: "Reimburse an amount", // Set RequireConfirmation to true to require user confirmation // for the tool call. RequireConfirmation: true, }, func(ctx tool.Context, args ReimburseArgs) (ReimburseResult, error) { // actual implementation return ReimburseResult{Status: "ok"}, nil }) rootAgent, _ := llmagent.New(llmagent.Config{ // ... Tools: []tool.Tool{reimburseTool}, }) ``` ```java LlmAgent rootAgent = LlmAgent.builder() // ... .tools( // Set requireConfirmation to true to require user confirmation // for the tool call. FunctionTool.create(myClassInstance, "reimburse", true) ) // ... .build(); ``` -------------------------------- ### Reference for Complete Nested Workflow Example (Go) Source: https://github.com/google/adk-docs/blob/main/docs/graphs/routes.md This entry points to a comprehensive Go example illustrating the full construction of both inner and outer graphs for nested workflows. ```go --8<-- "examples/go/snippets/graphs/routes/main.go:nested-workflows" ``` -------------------------------- ### Dockerfile for Self-Contained Stdio MCP Server (Docker) Source: https://github.com/google/adk-docs/blob/main/docs/tools-custom/mcp-tools.md This Dockerfile example sets up a container environment for an ADK agent that uses npm-based Stdio MCP servers, installing Node.js, npm, and Python dependencies. ```dockerfile # Example for npm-based MCP servers FROM python:3.13-slim # Install Node.js and npm for MCP servers RUN apt-get update && apt-get install -y nodejs npm && rm -rf /var/lib/apt/lists/* # Install your Python dependencies COPY requirements.txt . RUN pip install -r requirements.txt # Copy your agent code COPY . . # Your agent can now use StdioConnectionParams with 'npx' commands CMD ["python", "main.py"] ``` -------------------------------- ### exampleProvider(BaseExampleProvider provider) Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/tools/ExampleTool.Builder.html Sets the `BaseExampleProvider` for the `ExampleTool`, which is responsible for providing examples. ```APIDOC ## Method: exampleProvider ### Description Sets the `BaseExampleProvider` for the `ExampleTool` being built. ### Method Signature `ExampleTool.Builder exampleProvider(com.google.adk.examples.BaseExampleProvider provider)` ### Parameters - **provider** (com.google.adk.examples.BaseExampleProvider) - Required - The example provider. ### Returns `ExampleTool.Builder` - The current builder instance for chaining. ``` -------------------------------- ### Start ADK Web Server with Recording Plugin Source: https://github.com/google/adk-docs/blob/main/docs/evaluate/index.md Start the ADK web server with the recording plugin enabled to allow the generation of baseline interaction data for conformance testing. ```shell adk web -v --extra_plugins=google.adk.cli.plugins.recordings_plugin.RecordingsPlugin /path/to/agents ``` -------------------------------- ### Example Usage Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/cli/index.html Command to start the ADK API server, specifying a session service URI, port, and the directory containing agents. ```bash adk api_server –session_service_uri=[uri] –port=[port] path/to/agents_dir ``` -------------------------------- ### Example.Builder.output(List output) Source: https://github.com/google/adk-docs/blob/main/docs/api-reference/java/com/google/adk/examples/class-use/Example.Builder.html Sets the output content list for the `Example` object being built. This method allows for method chaining. ```APIDOC ## Method: Example.Builder.output(java.util.List output)\n\n### Description\nSets a list of output content for the `Example` object under construction. This method is part of the builder pattern and returns the builder instance for further configuration.\n\n### Signature\n```java\nabstract com.google.adk.examples.Example.Builder Example.Builder.output(java.util.List output)\n```\n\n### Parameters\n- **output** (`java.util.List`) - A list of content objects representing the output for the example.\n\n### Returns\n`com.google.adk.examples.Example.Builder` - The current builder instance, allowing for method chaining. ```