From c5842fd00c26962690c25642a5acc1f2268199de Mon Sep 17 00:00:00 2001 From: DABH Date: Mon, 26 Oct 2026 12:17:15 -0500 Subject: [PATCH 1/5] Document Google ADK Java integration in Public Preview --- docs/develop/java/index.mdx | 1 + docs/develop/java/integrations/google-adk.mdx | 463 ++++++++++++++++++ docs/develop/plugins-guide.mdx | 1 + sidebars.js | 6 +- .../IntegrationsGrid/integrations-data.json | 9 + 5 files changed, 479 insertions(+), 1 deletion(-) create mode 100644 docs/develop/java/integrations/google-adk.mdx diff --git a/docs/develop/java/index.mdx b/docs/develop/java/index.mdx index 8e2b0ada49..de77fdf3aa 100644 --- a/docs/develop/java/index.mdx +++ b/docs/develop/java/index.mdx @@ -84,6 +84,7 @@ From there, you can dive deeper into any of the Temporal primitives to start bui ## [Integrations](/develop/java/integrations) +- [Google ADK integration](/develop/java/integrations/google-adk) - [Parseable integration](https://github.com/parseablehq/temporal-plugin-java/blob/main/INTEGRATION.md) - [Spring AI integration](/develop/java/integrations/spring-ai) - [Spring Boot integration](/develop/java/integrations/spring-boot-integration) diff --git a/docs/develop/java/integrations/google-adk.mdx b/docs/develop/java/integrations/google-adk.mdx new file mode 100644 index 0000000000..9f7e539bdb --- /dev/null +++ b/docs/develop/java/integrations/google-adk.mdx @@ -0,0 +1,463 @@ +--- +id: google-adk +title: Google ADK integration +sidebar_label: Google ADK +slug: /develop/java/integrations/google-adk +toc_max_heading_level: 2 +tags: + - Google ADK + - Integrations + - AI Frameworks +description: Run Google ADK Java agents in Temporal Workflows with retryable model and MCP calls, durable tool approvals, and replayable conversations. +--- + +import { ReleaseNoteHeader } from '@site/src/components'; + +The Temporal [Google ADK Java](https://github.com/google/adk-java) integration runs a native ADK agent inside a +Temporal Workflow. The agent's orchestration and session state stay in the Workflow. Each model call and MCP +operation runs as an Activity, so completed calls are recorded in Event History and aren't repeated during replay. + + + APIs and configuration may change before General Availability. + + +Use `TemporalModel` as the agent's model and build its Runner with `TemporalAdk.runnerBuilder()`. The Runner uses +Workflow time, deterministic identifiers, and Workflow threads for ADK's parallel execution. Register +`GoogleAdkPlugin` on the Temporal Client so its Workers inherit the integration's Activities and payload converter. + +The examples come from the [Java ADK samples](https://github.com/temporalio/samples-java/tree/main/googleadk). +Each scenario can run with a live Gemini model; its tests use a scripted model without provider credentials. + +## Install the integration + +The integration requires Java 17 or later, Google ADK Java 1.12.0 or later, and Temporal Java SDK 1.40.0 or later. +The standalone plugin supplies ADK, but your application must supply the Temporal SDK explicitly. The plugin and SDK +are versioned independently. + +Add the [`io.temporal:google-adk`](https://central.sonatype.com/artifact/io.temporal/google-adk) dependency from Maven +Central alongside the SDK. + +**Maven:** + +```xml + + io.temporal + google-adk + 0.1.0 + + + io.temporal + temporal-sdk + 1.40.0 + +``` + +**Gradle:** + +```groovy +implementation 'io.temporal:google-adk:0.1.0' +implementation 'io.temporal:temporal-sdk:1.40.0' +``` + +The samples use a Gradle version constraint that requires SDK 1.40.0 or later within the 1.x series, preferring +1.40.0. Check your dependency resolution if another dependency supplies an older SDK. + +Before running the samples, [set up your local Java development environment](/develop/java/set-up-your-local-java) +and start a Temporal development server with `temporal server start-dev`. Set `GOOGLE_API_KEY` in the Worker's +environment, or configure the Google GenAI client for Vertex AI. The starter needs no model credentials. + +## Run an agent + +Build the agent with ADK's `LlmAgent` and use `TemporalModel` to route model calls through an Activity. Build the +Runner with `TemporalAdk.runnerBuilder()` and await each turn with `TemporalAdk.run()`: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/basic/BasicWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/basic/BasicWorkflowImpl.java) +```java +@Override +public String ask(String question) { + LlmAgent agent = + LlmAgent.builder() + .name("assistant") + .model(TemporalModel.create(AgentSupport.MODEL)) + .instruction("Answer concisely.") + .build(); + Runner runner = TemporalAdk.runnerBuilder().appName("basic").agent(agent).build(); + List events = + TemporalAdk.run( + runner, + AgentSupport.USER, + AgentSupport.SESSION, + Content.fromParts(Part.fromText(question))); + return AgentSupport.lastText(events); +} +``` + + +`AgentSupport.MODEL` is `gemini-2.5-flash`; `USER` and `SESSION` identify the ADK user and session within this +Workflow. `lastText` returns the last text response among the turn's events. + +On the Worker, register the real model factory and the plugin on the Temporal Client. The plugin automatically +registers model and MCP Activities on Workers created from that Client. Credentials and model clients stay on the +Worker and do not enter Workflow History. Disable the model SDK's native retries so Temporal owns retries: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/SampleWorker.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/SampleWorker.java) +```java +// Client reads GOOGLE_API_KEY or the Vertex AI environment variables on the worker. +// One HTTP attempt disables native retries so Temporal Activities own retries. +Client modelClient = + Client.builder() + .httpOptions( + HttpOptions.builder() + .retryOptions(HttpRetryOptions.builder().attempts(1).build()) + .build()) + .build(); +GoogleAdkPlugin plugin = + GoogleAdkPlugin.newBuilder() + .model( + AgentSupport.MODEL, + () -> Gemini.builder().modelName(AgentSupport.MODEL).apiClient(modelClient).build()) + .mcpToolset("echo", EchoMcpServer::toolset) + .build(); +WorkflowServiceStubs service = WorkflowServiceStubs.newLocalServiceStubs(); +WorkflowClient client = + WorkflowClient.newInstance( + service, WorkflowClientOptions.newBuilder().setPlugins(plugin).build()); +WorkerFactory factory = WorkerFactory.newInstance(client); +Worker worker = factory.newWorker(AgentSupport.TASK_QUEUE); +worker.registerWorkflowImplementationTypes( + BasicWorkflowImpl.class, + ToolsWorkflowImpl.class, + MultiAgentWorkflowImpl.class, + McpWorkflowImpl.class, + ApprovalWorkflowImpl.class, + ChatWorkflowImpl.class); +worker.registerActivitiesImplementations( + new WeatherActivitiesImpl(), new OrderActivitiesImpl()); +factory.start(); +``` + + +This Worker hosts all six samples. Its MCP toolset is created on first use; the other scenarios don't start an MCP +server. Register any Activities exposed as tools, such as `WeatherActivitiesImpl`, alongside the Workflows. + +The starter also registers `GoogleAdkPlugin` on its Client so Signals, Queries, and Workflow payloads use the same +converter. Start a Workflow on the Worker's Task Queue: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/SampleStarter.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/SampleStarter.java) +```java +BasicWorkflow workflow = client.newWorkflowStub(BasicWorkflow.class, options); +System.out.println(workflow.ask("What does Durable Execution mean?")); +``` + + +From the sample repository root, start `./gradlew :googleadk:worker` and then run +`./gradlew :googleadk:starter --args='basic'` in another terminal. + +`TemporalModel.newBuilder(name).activityOptions(...)` customizes model Activity timeouts and retries. The default +start-to-close timeout is two minutes. A heartbeat timeout enables heartbeats while the model call runs. + +## Expose tools as Activities + +Plain ADK function tools run on the Workflow thread. Use them for deterministic operations on agent or Workflow +state. Put network, file, and other I/O in a Temporal Activity and expose the Activity stub with `ActivityTools.create`. + +Declare the tool's schema on the Activity interface: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/tools/WeatherActivities.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/tools/WeatherActivities.java) +```java +@ActivityInterface +public interface WeatherActivities { + @ActivityMethod(name = "GetWeather") + Map getWeather( + @Schema(name = "city", description = "The city to look up") String city); +} +``` + + +Then supply a stub method as an ADK tool: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/tools/ToolsWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/tools/ToolsWorkflowImpl.java) +```java +@Override +public String ask(String question) { + WeatherActivities weather = + Workflow.newActivityStub( + WeatherActivities.class, + ActivityOptions.newBuilder() + .setStartToCloseTimeout(Duration.ofSeconds(30)) + .setRetryOptions(RetryOptions.newBuilder().setMaximumAttempts(3).build()) + .build()); + LlmAgent agent = + LlmAgent.builder() + .name("weather_assistant") + .model(TemporalModel.create(AgentSupport.MODEL)) + .instruction("Use getWeather to answer questions about the weather.") + .tools(ActivityTools.create(weather, "getWeather")) + .build(); + Runner runner = TemporalAdk.runnerBuilder().appName("tools").agent(agent).build(); + return AgentSupport.lastText( + TemporalAdk.run( + runner, + AgentSupport.USER, + AgentSupport.SESSION, + Content.fromParts(Part.fromText(question)))); +} +``` + + +The tool runs as the `GetWeather` Activity with the stub's timeout and retry policy. Its result returns to the agent +as a function response. If the Activity exhausts its retries, `ActivityFailure` propagates to the Workflow. + +Every parameter needs `@Schema(name = ...)` unless the Activity interface is compiled with `-parameters`. The +[tools sample](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/tools) +returns sample weather data; replace the Activity implementation with your provider's HTTP call. + +## Run multiple agents + +ADK's `ParallelAgent` works with the Workflow scheduler supplied by `TemporalAdk.runnerBuilder()`. Its sub-agents +schedule model Activities concurrently while their orchestration stays on Workflow threads: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/multiagent/MultiAgentWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/multiagent/MultiAgentWorkflowImpl.java) +```java +@Override +public List plan(String question) { + LlmAgent planner = + LlmAgent.builder() + .name("planner") + .model(TemporalModel.create(AgentSupport.MODEL)) + .instruction("Propose a short travel itinerary for the user's destination.") + .build(); + LlmAgent reviewer = + LlmAgent.builder() + .name("reviewer") + .model(TemporalModel.create(AgentSupport.MODEL)) + .instruction("List practical travel considerations for the user's destination.") + .build(); + ParallelAgent root = + ParallelAgent.builder().name("travel_team").subAgents(planner, reviewer).build(); + // The runner supplies workflow threads for ADK's parallel fan-out. + Runner runner = TemporalAdk.runnerBuilder().appName("travel").agent(root).build(); + return TemporalAdk.run( + runner, + AgentSupport.USER, + AgentSupport.SESSION, + Content.fromParts(Part.fromText(question))) + .stream() + .flatMap(event -> event.content().stream()) + .map(Content::text) + .filter(text -> text != null && !text.isEmpty()) + .sorted() + .toList(); +} +``` + + +Do not override a `ParallelAgent` scheduler or an `LlmAgent` executor: agent-level settings override the Runner's +scheduler and move execution off Workflow threads. For sequential execution, pass `WorkflowScheduler.sequential()` +to `TemporalAdk.runnerBuilder(...)`. + +## Use MCP tools + +Register a worker-side ADK `McpToolset` under a name, as the Worker example does with `echo`. Reference that name +in the Workflow with `TemporalMcpToolset`: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/mcp/McpWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/mcp/McpWorkflowImpl.java) +```java +@Override +public String echo(String message) { + LlmAgent agent = + LlmAgent.builder() + .name("echo_assistant") + .model(TemporalModel.create(AgentSupport.MODEL)) + .instruction("Call echo with the user's message, then return the echoed text.") + .tools(TemporalMcpToolset.newBuilder("echo").cacheTools(true).build()) + .build(); + Runner runner = TemporalAdk.runnerBuilder().appName("echo").agent(agent).build(); + return AgentSupport.lastText( + TemporalAdk.run( + runner, + AgentSupport.USER, + AgentSupport.SESSION, + Content.fromParts(Part.fromText(message)))); +} +``` + + +The Workflow never connects to the MCP server. Listing tools runs the `googleadk.ListMcpTools` Activity, and calling +one runs `googleadk.CallMcpTool`. By default, tools are listed before each model call; `cacheTools(true)` lists them +once per Workflow Execution. The Worker caches the toolset and closes it during shutdown after in-flight calls finish. + +The [MCP sample](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/mcp) +includes a local Java stdio echo server. No Node installation or separately running MCP service is needed. + +## Wait for human approval + +Pass `true` as the confirmation argument to `ActivityTools.create` to pause before the tool executes. Read pending +requests with `Hitl.pendingConfirmations`, wait for a Signal, and resume the next ADK turn with +`Hitl.confirmationResponse`: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/humanintheloop/ApprovalWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/humanintheloop/ApprovalWorkflowImpl.java) +```java +@Override +public String fulfill(String question) { + OrderActivities orders = + Workflow.newActivityStub( + OrderActivities.class, + ActivityOptions.newBuilder() + .setStartToCloseTimeout(Duration.ofSeconds(30)) + .setRetryOptions(RetryOptions.newBuilder().setMaximumAttempts(3).build()) + .build()); + LlmAgent agent = + LlmAgent.builder() + .name("fulfillment_assistant") + .model(TemporalModel.create(AgentSupport.MODEL)) + .instruction( + "Use shipOrder when asked to ship an order. Respect rejected confirmations.") + .tools(ActivityTools.create(orders, "shipOrder", true)) + .build(); + Runner runner = TemporalAdk.runnerBuilder().appName("approval").agent(agent).build(); + List events = + TemporalAdk.run( + runner, + AgentSupport.USER, + AgentSupport.SESSION, + Content.fromParts(Part.fromText(question))); + pending = Hitl.pendingConfirmations(events); + while (!pending.isEmpty()) { + Workflow.await(() -> decision != null); + Content response = + Hitl.confirmationResponse( + pending.stream() + .map(p -> new Hitl.ConfirmationDecision(p.functionCallId(), decision)) + .toArray(Hitl.ConfirmationDecision[]::new)); + decision = null; + pending = List.of(); + events = TemporalAdk.run(runner, AgentSupport.USER, AgentSupport.SESSION, response); + pending = Hitl.pendingConfirmations(events); + } + return AgentSupport.lastText(events); +} + +``` + + +The [approval sample](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/humanintheloop) +exposes pending tool names and arguments through a Query. A Signal handler sets `decision`. The example applies +that decision to all pending calls from the turn. A confirmed call schedules the shipping Activity; a rejected call +does not. The sample Activity returns mock shipment data and makes no fulfillment request. + +Run `./gradlew :googleadk:starter --args='approval'`, query with `pending WORKFLOW_ID`, and send `decide WORKFLOW_ID true` +or `decide WORKFLOW_ID false` through the same starter task. The [sample README](https://github.com/temporalio/samples-java/blob/main/googleadk/README.md) +has the full commands. + +## Preserve conversations through Continue-As-New + +The Runner's session service lives in the Workflow; replay rebuilds it from Event History. A new Run after +[Continue-As-New](/develop/java/workflows/continue-as-new) starts with an empty session service. Export the ADK session with +`Sessions.exportSession`, carry it in the next Run's input, and restore it with `Sessions.importSession`: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/chat/ChatWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat/ChatWorkflowImpl.java) +```java +@Override +public String chat(ChatInput input) { + LlmAgent agent = + LlmAgent.builder() + .name("chat_assistant") + .model(TemporalModel.create(AgentSupport.MODEL)) + .instruction("Answer concisely, remembering the earlier turns in this conversation.") + .build(); + Runner runner = TemporalAdk.runnerBuilder().appName("chat").agent(agent).build(); + if (input.session() != null) { + Sessions.importSession(runner.sessionService(), input.session()); + } + int turns = 0; + while (!finished || !messages.isEmpty()) { + Workflow.await(() -> finished || !messages.isEmpty()); + if (messages.isEmpty()) { + break; + } + String text = messages.remove(0); + reply = + AgentSupport.lastText( + TemporalAdk.run( + runner, + AgentSupport.USER, + AgentSupport.SESSION, + Content.fromParts(Part.fromText(text)))); + // Use a small threshold to make Continue-As-New easy to observe in this sample. + if (++turns == 3 && !finished) { + Session snapshot = + Sessions.exportSession( + runner.sessionService(), "chat", AgentSupport.USER, AgentSupport.SESSION); + Workflow.continueAsNew(new ChatInput(snapshot, List.copyOf(messages), finished, reply)); + } + } + return reply; +} + +``` + + +The [chat sample](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat) +uses Signals to queue messages and a Query for the latest reply. Its `@WorkflowInit` constructor restores the queue, +completion flag, and last reply before Signal handlers can run. Every three turns, it carries those fields and the +session snapshot into the next Run. A finish Signal drains the queue and completes the Workflow. + +The snapshot preserves session-scoped state and events, including pending confirmations. It does not carry app-, +user-, or temporary-scoped state. Continue-As-New limits each Run's Event History; the conversation snapshot still +grows and must remain within Temporal's [payload limits](/evaluate/cloud/limits#transaction-payload-size-limit). + +## Test and replay without credentials + +Use `io.temporal.googleadk.testing.ScriptedModel` as the worker-side model in `TestWorkflowEnvironment`. Configure +the test environment's Client with the same plugin as a live Worker, then replay the recorded history on a fresh +Worker: + + +[googleadk/src/test/java/io/temporal/samples/googleadk/BasicWorkflowTest.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/test/java/io/temporal/samples/googleadk/BasicWorkflowTest.java) +```java +ScriptedModel model = + ScriptedModel.of(AgentSupport.MODEL, ScriptedModel.text("Hello from ADK")); +try (AdkTestEnvironment test = new AdkTestEnvironment(model, BasicWorkflowImpl.class)) { + test.environment.start(); + BasicWorkflow workflow = test.workflow(BasicWorkflow.class); + + assertEquals("Hello from ADK", workflow.ask("Hello")); + assertEquals( + List.of("googleadk.InvokeModel"), AdkTestEnvironment.activities(test.history(workflow))); + test.replay(test.history(workflow), BasicWorkflowImpl.class); +} +``` + + +The [test helper](https://github.com/temporalio/samples-java/blob/main/googleadk/src/test/java/io/temporal/samples/googleadk/AdkTestEnvironment.java) +registers the plugin through `TestEnvironmentOptions.setWorkflowClientOptions`. Its replay check creates another +Worker with the plugin, replays the history, and verifies the model received no additional requests. + +Run `./gradlew :googleadk:test` without provider credentials or an external Temporal Service. The sample tests cover +Activity retries and results, parallel model scheduling, a real local MCP server, approved and rejected tools, and +session snapshots and queued messages through Continue-As-New. + +## Understand the limitations + +- Streamed model chunks reach the Workflow after the model Activity completes. The integration does not stream + tokens out of a Workflow and does not support live bidirectional connections. +- ADK services that perform I/O, including code execution, memory, and artifact services, cannot run directly inside + a Workflow. Use Activities for I/O. +- Avoid RxJava blocking methods inside a Workflow. Use `TemporalAdk.run` or `TemporalAdk.await` so the Workflow + thread yields while Activities or timers are pending. +- ADK's OpenTelemetry spans are emitted again during replay when a tracing SDK is installed. +- ADK's experimental App resumability and event compaction are not covered by the integration's tests. +- Gemini context caching is inactive because its cache configuration does not cross the Activity boundary. + +See the [integration README](https://github.com/temporalio/ai-integrations/tree/main/java/google-adk) for the complete +API, payload converter configuration, and failure classification. diff --git a/docs/develop/plugins-guide.mdx b/docs/develop/plugins-guide.mdx index 6fc5968a85..8890bf78a7 100644 --- a/docs/develop/plugins-guide.mdx +++ b/docs/develop/plugins-guide.mdx @@ -43,6 +43,7 @@ If you prefer to learn by getting hands-on with code, check out some existing pl - [Temporal client and Worker plugin for Pydantic AI](https://github.com/pydantic/pydantic-ai/blob/d9b4b2540183a4426669b2824c87cdfc36144780/pydantic_ai_slim/pydantic_ai/durable_exec/temporal/__init__.py#L142) - Temporal's TypeScript SDK ships with an [OpenTelemetry Plugin](https://github.com/temporalio/sdk-typescript/blob/main/contrib/interceptors-opentelemetry/src/plugin.ts) +- Temporal maintains a [Google ADK plugin for Java](/develop/java/integrations/google-adk) in Public Preview ## What you can provide to users in a plugin diff --git a/sidebars.js b/sidebars.js index 50ff0e2984..166a308d2f 100644 --- a/sidebars.js +++ b/sidebars.js @@ -495,7 +495,11 @@ const developJavaCategory = { type: 'doc', id: 'develop/java/integrations/index', }, - items: ['develop/java/integrations/spring-boot', 'develop/java/integrations/spring-ai'], + items: [ + 'develop/java/integrations/google-adk', + 'develop/java/integrations/spring-boot', + 'develop/java/integrations/spring-ai', + ], }, ], }; diff --git a/src/components/IntegrationsGrid/integrations-data.json b/src/components/IntegrationsGrid/integrations-data.json index 1678261d77..a0ac99ad3a 100644 --- a/src/components/IntegrationsGrid/integrations-data.json +++ b/src/components/IntegrationsGrid/integrations-data.json @@ -98,6 +98,15 @@ "sdk": "Go", "href": "/develop/go/integrations/google-adk" }, + { + "name": "Google ADK", + "description": "Run Google ADK Java agents as durable Temporal Workflows with retryable model and MCP calls. Public Preview.", + "tags": [ + "Agent framework" + ], + "sdk": "Java", + "href": "/develop/java/integrations/google-adk" + }, { "name": "Google ADK", "description": "Run Google ADK agents as durable Temporal Workflows.", From 9c18e32fa368c708142e901714d192af24d989f1 Mon Sep 17 00:00:00 2001 From: DABH Date: Mon, 26 Oct 2026 23:43:26 -0500 Subject: [PATCH 2/5] Refresh Java ADK guide for expanded sample suite --- docs/develop/java/integrations/google-adk.mdx | 376 +++++++++++++++--- .../IntegrationsGrid/integrations-data.json | 2 +- 2 files changed, 324 insertions(+), 54 deletions(-) diff --git a/docs/develop/java/integrations/google-adk.mdx b/docs/develop/java/integrations/google-adk.mdx index 9f7e539bdb..1aa58045fe 100644 --- a/docs/develop/java/integrations/google-adk.mdx +++ b/docs/develop/java/integrations/google-adk.mdx @@ -8,7 +8,7 @@ tags: - Google ADK - Integrations - AI Frameworks -description: Run Google ADK Java agents in Temporal Workflows with retryable model and MCP calls, durable tool approvals, and replayable conversations. +description: Run Google ADK Java agents in Temporal Workflows with durable conversations, Activity tools, structured output, and resumable tool calls. --- import { ReleaseNoteHeader } from '@site/src/components'; @@ -26,7 +26,23 @@ Workflow time, deterministic identifiers, and Workflow threads for ADK's paralle `GoogleAdkPlugin` on the Temporal Client so its Workers inherit the integration's Activities and payload converter. The examples come from the [Java ADK samples](https://github.com/temporalio/samples-java/tree/main/googleadk). -Each scenario can run with a live Gemini model; its tests use a scripted model without provider credentials. +Run each scenario with live Gemini or a credential-free offline model. Both modes use the same plugin, Worker +registration, Workflows, Activities, and message paths. The MCP scenario starts the same local Java subprocess in +both modes. + +| Category | Sample | What it demonstrates | +| --- | --- | --- | +| Agent Chat | [chat](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat) | Conversation state and queued messages survive Continue-As-New. | +| Tools | [tools](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/tools) | A deterministic function runs in the Workflow; a weather observation runs in an Activity. | +| MCP | [mcp](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/mcp) | List and call a bundled stateless stdio server through Activities. | +| Human in the Loop | [humanintheloop](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/humanintheloop) | A Signal approves or rejects a pending tool call; cancellation ends the wait. | +| Structured Output | [structuredoutput](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/structuredoutput) | Supply an ADK output schema, validate the response, and return a typed result. | +| Multi-Agent | [multiagent](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/multiagent) | ADK schedules two specialist agents' model Activities concurrently. | + +The suite also includes a [single-turn agent](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/basic) +and a [long-running tool](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/longrunning) +that resumes after a callback. Version 0.1.0 does not provide live Workflow Streams, managed agent sandboxes, or +replay-safe ADK tracing. See [the limitations](#understand-the-limitations). ## Install the integration @@ -62,9 +78,9 @@ implementation 'io.temporal:temporal-sdk:1.40.0' The samples use a Gradle version constraint that requires SDK 1.40.0 or later within the 1.x series, preferring 1.40.0. Check your dependency resolution if another dependency supplies an older SDK. -Before running the samples, [set up your local Java development environment](/develop/java/set-up-your-local-java) -and start a Temporal development server with `temporal server start-dev`. Set `GOOGLE_API_KEY` in the Worker's -environment, or configure the Google GenAI client for Vertex AI. The starter needs no model credentials. +Before running the samples, [set up your local Java development environment](/develop/java/set-up-your-local-java). +Offline mode needs no provider credentials. For live Gemini, set `GOOGLE_API_KEY` in the Worker's environment or +configure the Google GenAI client for Vertex AI. Model credentials stay on the Worker. ## Run an agent @@ -97,53 +113,91 @@ public String ask(String question) { `AgentSupport.MODEL` is `gemini-2.5-flash`; `USER` and `SESSION` identify the ADK user and session within this Workflow. `lastText` returns the last text response among the turn's events. -On the Worker, register the real model factory and the plugin on the Temporal Client. The plugin automatically -registers model and MCP Activities on Workers created from that Client. Credentials and model clients stay on the -Worker and do not enter Workflow History. Disable the model SDK's native retries so Temporal owns retries: +On the Worker, register a model factory and a named MCP toolset through `GoogleAdkPlugin`. The sample's `plugin` +helper accepts either a Gemini factory or the offline provider: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/SampleWorker.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/SampleWorker.java) +```java +public static GoogleAdkPlugin plugin(Supplier models) { + return GoogleAdkPlugin.newBuilder() + .model(AgentSupport.MODEL, models) + .mcpToolset("echo", EchoMcpServer::toolset) + .build(); +} + +``` + + +Register the plugin on the Temporal Client so its Workers inherit the model and MCP Activities and payload converter. +The sample reads `ADK_MODEL_MODE` before the following block, defaulting to `live`. It constructs a Gemini client only +in live mode and disables the client's native retries so Temporal owns retries: [googleadk/src/main/java/io/temporal/samples/googleadk/SampleWorker.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/SampleWorker.java) ```java -// Client reads GOOGLE_API_KEY or the Vertex AI environment variables on the worker. -// One HTTP attempt disables native retries so Temporal Activities own retries. Client modelClient = - Client.builder() - .httpOptions( - HttpOptions.builder() - .retryOptions(HttpRetryOptions.builder().attempts(1).build()) - .build()) - .build(); + mode.equals("live") + ? Client.builder() + .httpOptions( + HttpOptions.builder() + .retryOptions(HttpRetryOptions.builder().attempts(1).build()) + .build()) + .build() + : null; GoogleAdkPlugin plugin = - GoogleAdkPlugin.newBuilder() - .model( - AgentSupport.MODEL, - () -> Gemini.builder().modelName(AgentSupport.MODEL).apiClient(modelClient).build()) - .mcpToolset("echo", EchoMcpServer::toolset) - .build(); + plugin( + modelClient == null + ? OfflineModel::new + : () -> + Gemini.builder().modelName(AgentSupport.MODEL).apiClient(modelClient).build()); WorkflowServiceStubs service = WorkflowServiceStubs.newLocalServiceStubs(); WorkflowClient client = WorkflowClient.newInstance( service, WorkflowClientOptions.newBuilder().setPlugins(plugin).build()); WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(AgentSupport.TASK_QUEUE); -worker.registerWorkflowImplementationTypes( - BasicWorkflowImpl.class, - ToolsWorkflowImpl.class, - MultiAgentWorkflowImpl.class, - McpWorkflowImpl.class, - ApprovalWorkflowImpl.class, - ChatWorkflowImpl.class); -worker.registerActivitiesImplementations( - new WeatherActivitiesImpl(), new OrderActivitiesImpl()); +register(worker); factory.start(); ``` -This Worker hosts all six samples. Its MCP toolset is created on first use; the other scenarios don't start an MCP -server. Register any Activities exposed as tools, such as `WeatherActivitiesImpl`, alongside the Workflows. +`register(worker)` hosts all eight scenarios and their Activity implementations. The same registration is used in the +offline tests. The MCP toolset is created on first use; the other scenarios don't start an MCP server. -The starter also registers `GoogleAdkPlugin` on its Client so Signals, Queries, and Workflow payloads use the same -converter. Start a Workflow on the Worker's Task Queue: +Run the following commands from the samples repository root. Start the Temporal development server in one terminal: + +```bash +temporal server start-dev +``` + +Start an offline Worker in a second terminal: + +```bash +ADK_MODEL_MODE=offline ./gradlew :googleadk:worker +``` + +In a third terminal, execute a Workflow on its Task Queue: + +```bash +temporal workflow execute --type BasicWorkflow --task-queue google-adk-samples --input '"Hello"' +``` + +The offline result is `turns=1; latest: Hello`. The scripted provider is limited to these scenarios; weather and +travel examples use fixed Chicago data. It makes no provider requests, but still runs real Temporal Activities. +Offline runs require a running Temporal Service, and the first Gradle build can download dependencies. + +To use Gemini, stop the offline Worker and restart it with live mode: + +```bash +GOOGLE_API_KEY=your_key ADK_MODEL_MODE=live ./gradlew :googleadk:worker +``` + +The Workflow commands and Task Queue remain the same. Inspect model and tool Activities in the Temporal UI at +`http://localhost:8233`. + +To start the same Workflow from Java, register `GoogleAdkPlugin` on the caller's Client too. The existing starter +does this so ADK payload types use the same converter: [googleadk/src/main/java/io/temporal/samples/googleadk/SampleStarter.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/SampleStarter.java) @@ -153,12 +207,93 @@ System.out.println(workflow.ask("What does Durable Execution mean?")); ``` -From the sample repository root, start `./gradlew :googleadk:worker` and then run -`./gradlew :googleadk:starter --args='basic'` in another terminal. +The starter remains available through `./gradlew :googleadk:starter --args='basic'`. Each scenario's README provides +Temporal CLI commands for its inputs, Signals, Queries, and results. `TemporalModel.newBuilder(name).activityOptions(...)` customizes model Activity timeouts and retries. The default start-to-close timeout is two minutes. A heartbeat timeout enables heartbeats while the model call runs. +### Validate structured output + +Set an agent's `outputSchema` to constrain the model response. The structured-output sample describes a travel plan +with a city, one to seven days, and a list of activities: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/structuredoutput/StructuredOutputWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/structuredoutput/StructuredOutputWorkflowImpl.java) +```java +private static final Schema PLAN_SCHEMA = + Schema.builder() + .type("OBJECT") + .properties( + Map.of( + "city", Schema.builder().type("STRING").build(), + "days", Schema.builder().type("INTEGER").minimum(1.0).maximum(7.0).build(), + "activities", + Schema.builder() + .type("ARRAY") + .items(Schema.builder().type("STRING").build()) + .minItems(1L) + .build())) + .required(List.of("city", "days", "activities")) + .build(); + +``` + + +Validate the response at the Workflow boundary before returning a typed `TravelPlan`. The sample rejects malformed +JSON and trailing values, checks field types against ADK's schema, and validates the record's values: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/structuredoutput/StructuredOutputWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/structuredoutput/StructuredOutputWorkflowImpl.java) +```java +@Override +public TravelPlan plan(String request) { + LlmAgent agent = + LlmAgent.builder() + .name("structured_planner") + .model(TemporalModel.create(AgentSupport.MODEL)) + .instruction( + "Return a travel plan as JSON with city, days (1 through 7), and activities.") + .outputSchema(PLAN_SCHEMA) + .build(); + Runner runner = TemporalAdk.runnerBuilder().appName("structured_plan").agent(agent).build(); + String json = + AgentSupport.lastText( + TemporalAdk.run( + runner, + AgentSupport.USER, + AgentSupport.SESSION, + Content.fromParts(Part.fromText(request)))); + try { + ObjectMapper mapper = + new ObjectMapper().enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + Map output = mapper.readValue(json, new TypeReference<>() {}); + if (output == null) { + throw new IllegalArgumentException("A plan must be a JSON object."); + } + SchemaUtils.validateMapOnSchema(output, PLAN_SCHEMA, false); + return mapper.convertValue(output, TravelPlan.class); + } catch (JsonProcessingException | IllegalArgumentException e) { + throw ApplicationFailure.newNonRetryableFailure( + "The model did not return a valid travel plan.", "InvalidTravelPlan"); + } +} +``` + + +`TravelPlan` requires a nonblank city, one to seven days, and at least one nonblank activity. Invalid model output +fails the Workflow with a non-retryable `InvalidTravelPlan` failure. This prevents invalid output from repeatedly +failing a Workflow Task. + +With either Worker mode running, execute the sample: + +```bash +temporal workflow execute --type StructuredOutputWorkflow --task-queue google-adk-samples --input '"Plan two days in Chicago."' +``` + +Offline mode returns a two-day Chicago plan with a lakefront walk and a museum visit. Live Gemini supplies its own +plan with the same schema. The model call is an Activity; validation and the typed return value stay in the Workflow. + ## Expose tools as Activities Plain ADK function tools run on the Workflow thread. Use them for deterministic operations on agent or Workflow @@ -178,7 +313,19 @@ public interface WeatherActivities { ``` -Then supply a stub method as an ADK tool: +Define a deterministic function tool for calculations that need no I/O: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/tools/TemperatureTools.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/tools/TemperatureTools.java) +```java +public static Map toFahrenheit( + @Schema(name = "celsius", description = "Temperature in degrees Celsius") double celsius) { + return Map.of("fahrenheit", celsius * 9 / 5 + 32); +} +``` + + +Supply both the Activity stub and the function as ADK tools: [googleadk/src/main/java/io/temporal/samples/googleadk/tools/ToolsWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/tools/ToolsWorkflowImpl.java) @@ -196,8 +343,12 @@ public String ask(String question) { LlmAgent.builder() .name("weather_assistant") .model(TemporalModel.create(AgentSupport.MODEL)) - .instruction("Use getWeather to answer questions about the weather.") - .tools(ActivityTools.create(weather, "getWeather")) + .instruction( + "Use getWeather for conditions and Celsius temperature, then toFahrenheit to" + + " convert the temperature. Report the conditions and both temperatures.") + .tools( + ActivityTools.create(weather, "getWeather"), + FunctionTool.create(TemperatureTools.class, "toFahrenheit")) .build(); Runner runner = TemporalAdk.runnerBuilder().appName("tools").agent(agent).build(); return AgentSupport.lastText( @@ -210,12 +361,101 @@ public String ask(String question) { ``` -The tool runs as the `GetWeather` Activity with the stub's timeout and retry policy. Its result returns to the agent -as a function response. If the Activity exhausts its retries, `ActivityFailure` propagates to the Workflow. +`getWeather` runs as the `GetWeather` Activity with the stub's timeout and retry policy. Its result returns to the +agent as a function response. `toFahrenheit` runs directly on the Workflow thread and schedules no Activity. +If the weather Activity exhausts its retries or returns a non-retryable failure, `ActivityFailure` propagates to the +Workflow. Every parameter needs `@Schema(name = ...)` unless the Activity interface is compiled with `-parameters`. The [tools sample](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/tools) -returns sample weather data; replace the Activity implementation with your provider's HTTP call. +returns illustrative weather data and reads `Instant.now()` inside the Activity. The host timestamp demonstrates +why the observation needs an Activity. Replace that implementation with your provider's HTTP call for real weather. + +### Resume a long-running tool + +Use `ActivityTools.createLongRunning` when a tool starts an operation whose result will arrive later. The report +sample submits a job as an Activity and returns a pending status: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/longrunning/ReportActivities.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/longrunning/ReportActivities.java) +```java +@ActivityInterface +public interface ReportActivities { + @ActivityMethod(name = "StartReport") + Map startReport( + @Schema(name = "name", description = "The report to prepare") String name); +} +``` + + +After the ADK turn, use `Hitl.longRunningCalls` to find the pending function call. Wait for its result through a +Signal, then resume the original call with `Hitl.functionResponse`: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/longrunning/LongRunningWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/longrunning/LongRunningWorkflowImpl.java) +```java +@Override +public String prepare(String request) { + ReportActivities reports = + Workflow.newActivityStub( + ReportActivities.class, + ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(30)).build()); + LlmAgent agent = + LlmAgent.builder() + .name("report_assistant") + .model(TemporalModel.create(AgentSupport.MODEL)) + .instruction("Start exactly one report with startReport. Wait for its final result.") + .tools(ActivityTools.createLongRunning(reports, "startReport")) + .build(); + Runner runner = TemporalAdk.runnerBuilder().appName("reports").agent(agent).build(); + List events = + TemporalAdk.run( + runner, + AgentSupport.USER, + AgentSupport.SESSION, + Content.fromParts(Part.fromText(request))); + List pending = Hitl.longRunningCalls(events); + if (pending.size() != 1) { + throw ApplicationFailure.newNonRetryableFailure( + "Expected exactly one pending report.", "InvalidReportRequest"); + } + FunctionCall call = pending.get(0); + callId = call.id().orElseThrow(); + Workflow.await(() -> result != null); + events = + TemporalAdk.run( + runner, + AgentSupport.USER, + AgentSupport.SESSION, + Hitl.functionResponse(call, Map.of("status", "done", "result", result))); + callId = ""; + return AgentSupport.lastText(events); +} + +``` + + +The sample's `pendingCall` Query returns the function-call identifier. Its `complete` Signal accepts that identifier +and a result. Start a report and query the pending call: + +```bash +temporal workflow start --workflow-id adk-report --type LongRunningWorkflow --task-queue google-adk-samples --input '"Prepare a sales report."' +temporal workflow query --workflow-id adk-report --name pendingCall +``` + +Repeat the Query until the identifier is nonempty. Replace `CALL_ID` with that value before sending the callback: + +```bash +temporal workflow signal --workflow-id adk-report --name complete --input '"CALL_ID"' --input '"Revenue grew 10%."' +temporal workflow result --workflow-id adk-report +``` + +While waiting, the Signal handler ignores premature callbacks and wrong identifiers; the first matching result wins. +Offline mode returns `Report complete: Revenue grew 10%.`. + +The Activity simulates report submission. The Workflow's wait needs no polling Activity or open model connection, +and replay does not submit the report again. Use a new Workflow ID for another run. A real report service must store +the callback correlation and send the Signal when its work finishes. ## Run multiple agents @@ -354,9 +594,24 @@ exposes pending tool names and arguments through a Query. A Signal handler sets that decision to all pending calls from the turn. A confirmed call schedules the shipping Activity; a rejected call does not. The sample Activity returns mock shipment data and makes no fulfillment request. -Run `./gradlew :googleadk:starter --args='approval'`, query with `pending WORKFLOW_ID`, and send `decide WORKFLOW_ID true` -or `decide WORKFLOW_ID false` through the same starter task. The [sample README](https://github.com/temporalio/samples-java/blob/main/googleadk/README.md) -has the full commands. +Use the Temporal CLI to start and query an approval Workflow: + +```bash +temporal workflow start --workflow-id adk-approval --type ApprovalWorkflow --task-queue google-adk-samples --input '"Ship order demo-order, after confirmation."' +temporal workflow query --workflow-id adk-approval --name pendingConfirmations +``` + +Repeat the Query until a pending request appears. Then send a decision and wait for the result: + +```bash +temporal workflow signal --workflow-id adk-approval --name decide --input true +temporal workflow result --workflow-id adk-approval +``` + +Use `--input false` to reject a pending request on a fresh execution. Premature Signals are ignored, and the first +decision for the pending batch wins. Offline results are `Order shipped.` and `Order rejected.`. To cancel the wait +instead, run `temporal workflow cancel --workflow-id adk-approval`. A cancellation before approval schedules no +shipping Activity. ## Preserve conversations through Continue-As-New @@ -412,6 +667,10 @@ uses Signals to queue messages and a Query for the latest reply. Its `@WorkflowI completion flag, and last reply before Signal handlers can run. Every three turns, it carries those fields and the session snapshot into the next Run. A finish Signal drains the queue and completes the Workflow. +Use the [chat README](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat) +for the Signal and Query commands. Offline replies show the conversation's turn count, including turns restored +after Continue-As-New. Live Gemini receives the imported conversation as context. + The snapshot preserves session-scoped state and events, including pending confirmations. It does not carry app-, user-, or temporary-scoped state. Continue-As-New limits each Run's Event History; the conversation snapshot still grows and must remain within Temporal's [payload limits](/evaluate/cloud/limits#transaction-payload-size-limit). @@ -443,19 +702,30 @@ The [test helper](https://github.com/temporalio/samples-java/blob/main/googleadk registers the plugin through `TestEnvironmentOptions.setWorkflowClientOptions`. Its replay check creates another Worker with the plugin, replays the history, and verifies the model received no additional requests. -Run `./gradlew :googleadk:test` without provider credentials or an external Temporal Service. The sample tests cover -Activity retries and results, parallel model scheduling, a real local MCP server, approved and rejected tools, and -session snapshots and queued messages through Continue-As-New. +Run the suite without provider credentials or an external Temporal Service: + +```bash +./gradlew :googleadk:test :googleadk:spotlessCheck :googleadk:build +``` + +The tests verify Activity retries and non-retryable failures, deterministic function results, parallel model +scheduling, a real local MCP server, approval/rejection and cancellation, invalid structured output, correlated +callbacks, and session/queue recovery through Continue-As-New. `OfflineSamplesTest` also runs every scenario with +the same `OfflineModel` and `SampleWorker.register` used by the runnable Worker. Each scenario's README includes a +targeted test command. ## Understand the limitations -- Streamed model chunks reach the Workflow after the model Activity completes. The integration does not stream - tokens out of a Workflow and does not support live bidirectional connections. +- In version 0.1.0, streamed model chunks reach the Workflow after the model Activity completes. The integration has + no live Workflow Streams publisher and does not support live bidirectional connections. - ADK services that perform I/O, including code execution, memory, and artifact services, cannot run directly inside - a Workflow. Use Activities for I/O. + a Workflow. Use Activities for I/O. The plugin does not durably manage an agent-facing code execution environment. - Avoid RxJava blocking methods inside a Workflow. Use `TemporalAdk.run` or `TemporalAdk.await` so the Workflow thread yields while Activities or timers are pending. -- ADK's OpenTelemetry spans are emitted again during replay when a tracing SDK is installed. +- ADK uses global OpenTelemetry providers. The plugin has no replay suppression for ADK tracing, so an installed + tracing SDK emits duplicate spans during replay. Temporal Activity history and UI inspection remain available. +- Canceling an approval or callback wait does not undo a shipment or cancel an external job that already started. + A real backend needs an explicit cancellation Activity. - ADK's experimental App resumability and event compaction are not covered by the integration's tests. - Gemini context caching is inactive because its cache configuration does not cross the Activity boundary. diff --git a/src/components/IntegrationsGrid/integrations-data.json b/src/components/IntegrationsGrid/integrations-data.json index a0ac99ad3a..1970503294 100644 --- a/src/components/IntegrationsGrid/integrations-data.json +++ b/src/components/IntegrationsGrid/integrations-data.json @@ -100,7 +100,7 @@ }, { "name": "Google ADK", - "description": "Run Google ADK Java agents as durable Temporal Workflows with retryable model and MCP calls. Public Preview.", + "description": "Run Google ADK Java agents with durable conversations, tools, and structured output. Public Preview.", "tags": [ "Agent framework" ], From 2dca294d39098e313d2bc53ecc4c8128eeb40282 Mon Sep 17 00:00:00 2001 From: DABH Date: Wed, 28 Oct 2026 00:18:27 -0500 Subject: [PATCH 3/5] Use chat, buffered streaming, and tracing in Java ADK guide --- docs/develop/java/integrations/google-adk.mdx | 369 +++++++++++++----- 1 file changed, 269 insertions(+), 100 deletions(-) diff --git a/docs/develop/java/integrations/google-adk.mdx b/docs/develop/java/integrations/google-adk.mdx index 1aa58045fe..2e9c8ef06d 100644 --- a/docs/develop/java/integrations/google-adk.mdx +++ b/docs/develop/java/integrations/google-adk.mdx @@ -35,14 +35,17 @@ both modes. | Agent Chat | [chat](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat) | Conversation state and queued messages survive Continue-As-New. | | Tools | [tools](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/tools) | A deterministic function runs in the Workflow; a weather observation runs in an Activity. | | MCP | [mcp](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/mcp) | List and call a bundled stateless stdio server through Activities. | +| Streaming | [streaming](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/streaming) | Deliver buffered ADK partial/final events through Workflow Streams and finish with or without a subscriber. | | Human in the Loop | [humanintheloop](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/humanintheloop) | A Signal approves or rejects a pending tool call; cancellation ends the wait. | | Structured Output | [structuredoutput](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/structuredoutput) | Supply an ADK output schema, validate the response, and return a typed result. | | Multi-Agent | [multiagent](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/multiagent) | ADK schedules two specialist agents' model Activities concurrently. | +| Observability | [observability](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/observability) | Export linked model and tool Activity spans with OpenTelemetry and suppress replayed Workflow spans. | +| Sandboxes | [Limitations](#understand-the-limitations) | Plugin 0.1.0 does not manage agent-facing code execution environments. | -The suite also includes a [single-turn agent](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/basic) -and a [long-running tool](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/longrunning) -that resumes after a callback. Version 0.1.0 does not provide live Workflow Streams, managed agent sandboxes, or -replay-safe ADK tracing. See [the limitations](#understand-the-limitations). +The suite also includes a [long-running tool](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/longrunning) +that resumes after a callback. Agent Chat is the introductory example. The streaming example publishes buffered SSE +output after the model Activity completes; it does not forward live tokens. The observability example traces +Temporal operations without enabling native ADK's global tracing provider. ## Install the integration @@ -84,35 +87,60 @@ configure the Google GenAI client for Vertex AI. Model credentials stay on the W ## Run an agent -Build the agent with ADK's `LlmAgent` and use `TemporalModel` to route model calls through an Activity. Build the -Runner with `TemporalAdk.runnerBuilder()` and await each turn with `TemporalAdk.run()`: +Start with Agent Chat. Signals queue user messages, a Query exposes the latest reply, and a finish Signal drains the +queue. Build its agent with ADK's `LlmAgent`, use `TemporalModel` for Activity-based model calls, and drive each turn +with `TemporalAdk.run()` and a Runner built by `TemporalAdk.runnerBuilder()`: - -[googleadk/src/main/java/io/temporal/samples/googleadk/basic/BasicWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/basic/BasicWorkflowImpl.java) + +[googleadk/src/main/java/io/temporal/samples/googleadk/chat/ChatWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat/ChatWorkflowImpl.java) ```java @Override -public String ask(String question) { +public String chat(ChatInput input) { LlmAgent agent = LlmAgent.builder() - .name("assistant") + .name("chat_assistant") .model(TemporalModel.create(AgentSupport.MODEL)) - .instruction("Answer concisely.") + .instruction("Answer concisely, remembering the earlier turns in this conversation.") .build(); - Runner runner = TemporalAdk.runnerBuilder().appName("basic").agent(agent).build(); - List events = - TemporalAdk.run( - runner, - AgentSupport.USER, - AgentSupport.SESSION, - Content.fromParts(Part.fromText(question))); - return AgentSupport.lastText(events); + Runner runner = TemporalAdk.runnerBuilder().appName("chat").agent(agent).build(); + if (input.session() != null) { + Sessions.importSession(runner.sessionService(), input.session()); + } + int turns = 0; + while (!finished || !messages.isEmpty()) { + Workflow.await(() -> finished || !messages.isEmpty()); + if (messages.isEmpty()) { + break; + } + String text = messages.remove(0); + reply = + AgentSupport.lastText( + TemporalAdk.run( + runner, + AgentSupport.USER, + AgentSupport.SESSION, + Content.fromParts(Part.fromText(text)))); + // Use a small threshold to make Continue-As-New easy to observe in this sample. + if (++turns == 3 && !finished) { + Session snapshot = + Sessions.exportSession( + runner.sessionService(), "chat", AgentSupport.USER, AgentSupport.SESSION); + Workflow.continueAsNew(new ChatInput(snapshot, List.copyOf(messages), finished, reply)); + } + } + return reply; } + ``` `AgentSupport.MODEL` is `gemini-2.5-flash`; `USER` and `SESSION` identify the ADK user and session within this Workflow. `lastText` returns the last text response among the turn's events. +For plugin 0.1.0, use the provider's model name for both registration and `TemporalModel`, as this example does. +An arbitrary registration alias can reach Gemini or Claude as the requested provider model name. Model names also +affect ADK's Workflow-side capability checks. + On the Worker, register a model factory and a named MCP toolset through `GoogleAdkPlugin`. The sample's `plugin` helper accepts either a Gemini factory or the offline provider: @@ -155,14 +183,21 @@ WorkflowServiceStubs service = WorkflowServiceStubs.newLocalServiceStubs(); WorkflowClient client = WorkflowClient.newInstance( service, WorkflowClientOptions.newBuilder().setPlugins(plugin).build()); -WorkerFactory factory = WorkerFactory.newInstance(client); +SampleTelemetry telemetry = + "console".equals(System.getenv("ADK_TRACING")) ? SampleTelemetry.console() : null; +WorkerFactory factory = + WorkerFactory.newInstance( + client, + telemetry == null + ? WorkerFactoryOptions.newBuilder().build() + : telemetry.workerOptions()); Worker worker = factory.newWorker(AgentSupport.TASK_QUEUE); register(worker); factory.start(); ``` -`register(worker)` hosts all eight scenarios and their Activity implementations. The same registration is used in the +`register(worker)` hosts all nine scenarios and their Activity implementations. The same registration is used in the offline tests. The MCP toolset is created on first use; the other scenarios don't start an MCP server. Run the following commands from the samples repository root. Start the Temporal development server in one terminal: @@ -180,10 +215,20 @@ ADK_MODEL_MODE=offline ./gradlew :googleadk:worker In a third terminal, execute a Workflow on its Task Queue: ```bash -temporal workflow execute --type BasicWorkflow --task-queue google-adk-samples --input '"Hello"' +temporal workflow start --workflow-id adk-chat --type ChatWorkflow --task-queue google-adk-samples --input '{"session":null,"messages":[],"finished":false,"lastReply":""}' +temporal workflow signal --workflow-id adk-chat --name message --input '"Hello"' +temporal workflow query --workflow-id adk-chat --name lastReply +``` + +Repeat the Query until the reply appears. Offline mode returns `turns=1; latest: Hello`. Send more messages to +continue the conversation, or finish and wait for its result: + +```bash +temporal workflow signal --workflow-id adk-chat --name finish +temporal workflow result --workflow-id adk-chat ``` -The offline result is `turns=1; latest: Hello`. The scripted provider is limited to these scenarios; weather and +Use a new Workflow ID for another conversation. The scripted provider is limited to these scenarios; weather and travel examples use fixed Chicago data. It makes no provider requests, but still runs real Temporal Activities. Offline runs require a running Temporal Service, and the first Gradle build can download dependencies. @@ -202,12 +247,13 @@ does this so ADK payload types use the same converter: [googleadk/src/main/java/io/temporal/samples/googleadk/SampleStarter.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/SampleStarter.java) ```java -BasicWorkflow workflow = client.newWorkflowStub(BasicWorkflow.class, options); -System.out.println(workflow.ask("What does Durable Execution mean?")); +ChatWorkflow chat = client.newWorkflowStub(ChatWorkflow.class, options); +WorkflowClient.start(chat::chat, ChatInput.empty()); +System.out.println("Workflow ID: " + id); ``` -The starter remains available through `./gradlew :googleadk:starter --args='basic'`. Each scenario's README provides +The starter defaults to Agent Chat: run `./gradlew :googleadk:starter` without arguments. Each scenario's README provides Temporal CLI commands for its inputs, Signals, Queries, and results. `TemporalModel.newBuilder(name).activityOptions(...)` customizes model Activity timeouts and retries. The default @@ -457,6 +503,41 @@ The Activity simulates report submission. The Workflow's wait needs no polling A and replay does not submit the report again. Use a new Workflow ID for another run. A real report service must store the callback correlation and send the Signal when its work finishes. +### Use MCP tools + +Register a worker-side ADK `McpToolset` under a name, as the Worker example does with `echo`. Reference that name +in the Workflow with `TemporalMcpToolset`: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/mcp/McpWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/mcp/McpWorkflowImpl.java) +```java +@Override +public String echo(String message) { + LlmAgent agent = + LlmAgent.builder() + .name("echo_assistant") + .model(TemporalModel.create(AgentSupport.MODEL)) + .instruction("Call echo with the user's message, then return the echoed text.") + .tools(TemporalMcpToolset.newBuilder("echo").cacheTools(true).build()) + .build(); + Runner runner = TemporalAdk.runnerBuilder().appName("echo").agent(agent).build(); + return AgentSupport.lastText( + TemporalAdk.run( + runner, + AgentSupport.USER, + AgentSupport.SESSION, + Content.fromParts(Part.fromText(message)))); +} +``` + + +The Workflow never connects to the MCP server. Listing tools runs the `googleadk.ListMcpTools` Activity, and calling +one runs `googleadk.CallMcpTool`. By default, tools are listed before each model call; `cacheTools(true)` lists them +once per Workflow Execution. The Worker caches the toolset and closes it during shutdown after in-flight calls finish. + +The [MCP sample](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/mcp) +includes a local Java stdio echo server. No Node installation or separately running MCP service is needed. + ## Run multiple agents ADK's `ParallelAgent` works with the Workflow scheduler supplied by `TemporalAdk.runnerBuilder()`. Its sub-agents @@ -502,40 +583,166 @@ Do not override a `ParallelAgent` scheduler or an `LlmAgent` executor: agent-lev scheduler and move execution off Workflow threads. For sequential execution, pass `WorkflowScheduler.sequential()` to `TemporalAdk.runnerBuilder(...)`. -## Use MCP tools +## Stream and observe model calls -Register a worker-side ADK `McpToolset` under a name, as the Worker example does with `echo`. Reference that name -in the Workflow with `TemporalMcpToolset`: +### Publish buffered model output - -[googleadk/src/main/java/io/temporal/samples/googleadk/mcp/McpWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/mcp/McpWorkflowImpl.java) +ADK Java supports SSE responses. In plugin 0.1.0, one model Activity collects all chunks before returning them to +the Workflow. Select `RunConfig.StreamingMode.SSE`, then publish the recorded partial and final events through +Workflow Streams: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/streaming/StreamingWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/streaming/StreamingWorkflowImpl.java) ```java @Override -public String echo(String message) { +public List stream(String prompt) { LlmAgent agent = LlmAgent.builder() - .name("echo_assistant") + .name("streaming_assistant") .model(TemporalModel.create(AgentSupport.MODEL)) - .instruction("Call echo with the user's message, then return the echoed text.") - .tools(TemporalMcpToolset.newBuilder("echo").cacheTools(true).build()) + .instruction("Answer concisely.") .build(); - Runner runner = TemporalAdk.runnerBuilder().appName("echo").agent(agent).build(); + Runner runner = TemporalAdk.runnerBuilder().appName("streaming").agent(agent).build(); + List events = + TemporalAdk.run( + runner, + AgentSupport.USER, + AgentSupport.SESSION, + Content.fromParts(Part.fromText(prompt)), + RunConfig.builder() + .streamingMode(RunConfig.StreamingMode.SSE) + .autoCreateSession(true) + .build()); + List chunks = + events.stream() + .filter(event -> event.content().isPresent()) + .map( + event -> + new ModelChunk( + event.partial().orElse(false) ? "partial" : "final", + event.content().map(Content::text).orElse(""))) + .toList(); + for (ModelChunk chunk : chunks) output.topic("model").publish(chunk); + output.topic("model").publish(new ModelChunk("complete", AgentSupport.lastText(events))); + Workflow.await(Duration.ofSeconds(10), () -> acknowledged); + return chunks; +} + +``` + + +Workflow Streams is an experimental SDK module. This example publishes model chunks after the model Activity +completes. Live token forwarding while that Activity is running requires an integration change. Start a subscriber +with the sample's client: + +```bash +./gradlew :googleadk:starter --args='streaming' +``` + +Offline mode emits two partial chunks, a final `Hello from ADK`, and a `complete` event. The subscriber acknowledges +completion. Without a subscriber, the Workflow returns after a ten-second acknowledgement deadline. To exercise +that path, use `temporal workflow execute --type StreamingWorkflow --task-queue google-adk-samples --input '"Say hello."'`. +Subscribe when starting the Workflow; the sample serves stream items while the Workflow is open. + +### Export OpenTelemetry spans + +The observability sample traces the Temporal Workflow and its model/tool Activities through the SDK's tracing +interceptor and OpenTracing-to-OpenTelemetry bridge. It uses an instance-scoped OpenTelemetry SDK with W3C trace +propagation: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/observability/SampleTelemetry.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/observability/SampleTelemetry.java) +```java +public SampleTelemetry(SpanExporter exporter) { + telemetry = + OpenTelemetrySdk.builder() + .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance())) + .setTracerProvider( + SdkTracerProvider.builder() + .addSpanProcessor( + SimpleSpanProcessor.create(new ReplayAwareSpanExporter(exporter))) + .build()) + .build(); + options = + OpenTracingOptions.newBuilder() + .setTracer(OpenTracingShim.createTracerShim(telemetry)) + .setSpanContextCodec(OpenTracingSpanContextCodec.TEXT_MAP_CODEC) + .build(); +} + +public WorkerFactoryOptions workerOptions() { + return WorkerFactoryOptions.newBuilder() + .setWorkerInterceptors(new OpenTracingWorkerInterceptor(options)) + .build(); +} + +``` + + +The synchronous processor checks replay before forwarding spans to the chosen exporter. This suppresses duplicate +Workflow spans from history replay while retaining Query spans: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/observability/ReplayAwareSpanExporter.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/observability/ReplayAwareSpanExporter.java) +```java +@Override +public CompletableResultCode export(Collection spans) { + if (WorkflowUnsafe.isWorkflowThread() && WorkflowUnsafe.isReplaying()) { + spans = spans.stream().filter(span -> span.getName().startsWith("HandleQuery:")).toList(); + } + return spans.isEmpty() ? CompletableResultCode.ofSuccess() : delegate.export(spans); +} + +``` + + +Keep the replay filter on the Workflow thread, before asynchronous export. Enable console export when starting +the Worker: + +```bash +ADK_MODEL_MODE=offline ADK_TRACING=console ./gradlew :googleadk:worker +``` + +Then run the observed model/tool interaction: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/observability/ObservabilityWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/observability/ObservabilityWorkflowImpl.java) +```java +@Override +public String observe(String prompt) { + WeatherActivities weather = + Workflow.newActivityStub( + WeatherActivities.class, + ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(30)).build()); + LlmAgent agent = + LlmAgent.builder() + .name("observed_assistant") + .model(TemporalModel.create(AgentSupport.MODEL)) + .instruction("Use getWeather and summarize its result.") + .tools(ActivityTools.create(weather, "getWeather")) + .build(); + Runner runner = TemporalAdk.runnerBuilder().appName("observability").agent(agent).build(); return AgentSupport.lastText( TemporalAdk.run( runner, AgentSupport.USER, AgentSupport.SESSION, - Content.fromParts(Part.fromText(message)))); + Content.fromParts(Part.fromText(prompt)))); } ``` -The Workflow never connects to the MCP server. Listing tools runs the `googleadk.ListMcpTools` Activity, and calling -one runs `googleadk.CallMcpTool`. By default, tools are listed before each model call; `cacheTools(true)` lists them -once per Workflow Execution. The Worker caches the toolset and closes it during shutdown after in-flight calls finish. +```bash +temporal workflow execute --type ObservabilityWorkflow --task-queue google-adk-samples --input '"What is the weather in Chicago?"' +``` -The [MCP sample](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/mcp) -includes a local Java stdio echo server. No Node installation or separately running MCP service is needed. +Offline mode returns `Chicago is sunny.`. Console spans include the Workflow, two model Activity executions, and +the weather Activity, linked into one trace. Real Activity retries produce another attempt span. Replace the console +exporter with another `SpanExporter` to send these spans to an OpenTelemetry backend. The tests use an in-memory +exporter and verify failures, retries, trace linkage, and replay without extra exported spans. + +This sample exports Temporal operation spans. It does not install a global ADK telemetry provider; native ADK +agent-internal tracing in plugin 0.1.0 still lacks replay suppression. ## Wait for human approval @@ -615,52 +822,9 @@ shipping Activity. ## Preserve conversations through Continue-As-New -The Runner's session service lives in the Workflow; replay rebuilds it from Event History. A new Run after +The Agent Chat example above keeps the Runner's session service in the Workflow; replay rebuilds it from Event History. A new Run after [Continue-As-New](/develop/java/workflows/continue-as-new) starts with an empty session service. Export the ADK session with -`Sessions.exportSession`, carry it in the next Run's input, and restore it with `Sessions.importSession`: - - -[googleadk/src/main/java/io/temporal/samples/googleadk/chat/ChatWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat/ChatWorkflowImpl.java) -```java -@Override -public String chat(ChatInput input) { - LlmAgent agent = - LlmAgent.builder() - .name("chat_assistant") - .model(TemporalModel.create(AgentSupport.MODEL)) - .instruction("Answer concisely, remembering the earlier turns in this conversation.") - .build(); - Runner runner = TemporalAdk.runnerBuilder().appName("chat").agent(agent).build(); - if (input.session() != null) { - Sessions.importSession(runner.sessionService(), input.session()); - } - int turns = 0; - while (!finished || !messages.isEmpty()) { - Workflow.await(() -> finished || !messages.isEmpty()); - if (messages.isEmpty()) { - break; - } - String text = messages.remove(0); - reply = - AgentSupport.lastText( - TemporalAdk.run( - runner, - AgentSupport.USER, - AgentSupport.SESSION, - Content.fromParts(Part.fromText(text)))); - // Use a small threshold to make Continue-As-New easy to observe in this sample. - if (++turns == 3 && !finished) { - Session snapshot = - Sessions.exportSession( - runner.sessionService(), "chat", AgentSupport.USER, AgentSupport.SESSION); - Workflow.continueAsNew(new ChatInput(snapshot, List.copyOf(messages), finished, reply)); - } - } - return reply; -} - -``` - +`Sessions.exportSession`, carry it in the next Run's input, and restore it with `Sessions.importSession`. The [chat sample](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat) uses Signals to queue messages and a Query for the latest reply. Its `@WorkflowInit` constructor restores the queue, @@ -681,19 +845,21 @@ Use `io.temporal.googleadk.testing.ScriptedModel` as the worker-side model in `T the test environment's Client with the same plugin as a live Worker, then replay the recorded history on a fresh Worker: - -[googleadk/src/test/java/io/temporal/samples/googleadk/BasicWorkflowTest.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/test/java/io/temporal/samples/googleadk/BasicWorkflowTest.java) + +[googleadk/src/test/java/io/temporal/samples/googleadk/ChatWorkflowTest.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/test/java/io/temporal/samples/googleadk/ChatWorkflowTest.java) ```java ScriptedModel model = - ScriptedModel.of(AgentSupport.MODEL, ScriptedModel.text("Hello from ADK")); -try (AdkTestEnvironment test = new AdkTestEnvironment(model, BasicWorkflowImpl.class)) { + ScriptedModel.of( + AgentSupport.MODEL, + ScriptedModel.text("First reply"), + ScriptedModel.text("Last reply")); +try (AdkTestEnvironment test = new AdkTestEnvironment(model, ChatWorkflowImpl.class)) { test.environment.start(); - BasicWorkflow workflow = test.workflow(BasicWorkflow.class); - - assertEquals("Hello from ADK", workflow.ask("Hello")); + ChatWorkflow workflow = test.workflow(ChatWorkflow.class); assertEquals( - List.of("googleadk.InvokeModel"), AdkTestEnvironment.activities(test.history(workflow))); - test.replay(test.history(workflow), BasicWorkflowImpl.class); + "Last reply", workflow.chat(new ChatInput(null, List.of("one", "two"), true, ""))); + assertEquals(2, model.requests().size()); + test.replay(test.history(workflow), ChatWorkflowImpl.class); } ``` @@ -710,20 +876,23 @@ Run the suite without provider credentials or an external Temporal Service: The tests verify Activity retries and non-retryable failures, deterministic function results, parallel model scheduling, a real local MCP server, approval/rejection and cancellation, invalid structured output, correlated -callbacks, and session/queue recovery through Continue-As-New. `OfflineSamplesTest` also runs every scenario with +callbacks, session/queue recovery through Continue-As-New, buffered streaming with and without a subscriber, and +OpenTelemetry trace linkage without duplicate replay exports. `OfflineSamplesTest` also runs every scenario with the same `OfflineModel` and `SampleWorker.register` used by the runnable Worker. Each scenario's README includes a targeted test command. ## Understand the limitations -- In version 0.1.0, streamed model chunks reach the Workflow after the model Activity completes. The integration has - no live Workflow Streams publisher and does not support live bidirectional connections. +- In version 0.1.0, streamed model chunks reach the Workflow after the model Activity completes. The streaming sample + publishes those recorded chunks through Workflow Streams. Live token forwarding and live bidirectional + connections remain unsupported by the plugin. - ADK services that perform I/O, including code execution, memory, and artifact services, cannot run directly inside a Workflow. Use Activities for I/O. The plugin does not durably manage an agent-facing code execution environment. - Avoid RxJava blocking methods inside a Workflow. Use `TemporalAdk.run` or `TemporalAdk.await` so the Workflow thread yields while Activities or timers are pending. - ADK uses global OpenTelemetry providers. The plugin has no replay suppression for ADK tracing, so an installed - tracing SDK emits duplicate spans during replay. Temporal Activity history and UI inspection remain available. + tracing SDK emits duplicate spans during replay. The observability sample instruments Temporal operations through + the SDK instead of enabling global native ADK telemetry. - Canceling an approval or callback wait does not undo a shipment or cancel an external job that already started. A real backend needs an explicit cancellation Activity. - ADK's experimental App resumability and event compaction are not covered by the integration's tests. From 18bcae25cad3c51dd3cd5dce8f3cc8d14b1e038b Mon Sep 17 00:00:00 2001 From: DABH Date: Wed, 28 Oct 2026 11:43:36 -0500 Subject: [PATCH 4/5] Document Java ADK streaming and native tracing gaps --- docs/develop/java/integrations/google-adk.mdx | 194 ++---------------- 1 file changed, 12 insertions(+), 182 deletions(-) diff --git a/docs/develop/java/integrations/google-adk.mdx b/docs/develop/java/integrations/google-adk.mdx index 2e9c8ef06d..81e38ee6dd 100644 --- a/docs/develop/java/integrations/google-adk.mdx +++ b/docs/develop/java/integrations/google-adk.mdx @@ -35,17 +35,16 @@ both modes. | Agent Chat | [chat](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat) | Conversation state and queued messages survive Continue-As-New. | | Tools | [tools](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/tools) | A deterministic function runs in the Workflow; a weather observation runs in an Activity. | | MCP | [mcp](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/mcp) | List and call a bundled stateless stdio server through Activities. | -| Streaming | [streaming](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/streaming) | Deliver buffered ADK partial/final events through Workflow Streams and finish with or without a subscriber. | +| Streaming | Unsupported | Plugin 0.1.0 buffers SSE responses until the model Activity completes; it cannot deliver output while the Activity is running. | | Human in the Loop | [humanintheloop](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/humanintheloop) | A Signal approves or rejects a pending tool call; cancellation ends the wait. | | Structured Output | [structuredoutput](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/structuredoutput) | Supply an ADK output schema, validate the response, and return a typed result. | | Multi-Agent | [multiagent](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/multiagent) | ADK schedules two specialist agents' model Activities concurrently. | -| Observability | [observability](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/observability) | Export linked model and tool Activity spans with OpenTelemetry and suppress replayed Workflow spans. | +| Observability | Unsupported | Native ADK tracing has no replay suppression and can export duplicate spans during replay. | | Sandboxes | [Limitations](#understand-the-limitations) | Plugin 0.1.0 does not manage agent-facing code execution environments. | The suite also includes a [long-running tool](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/longrunning) -that resumes after a callback. Agent Chat is the introductory example. The streaming example publishes buffered SSE -output after the model Activity completes; it does not forward live tokens. The observability example traces -Temporal operations without enabling native ADK's global tracing provider. +that resumes after a callback. Agent Chat is the introductory example. See [the limitations](#understand-the-limitations) +for streaming, native ADK tracing, and agent sandbox support. ## Install the integration @@ -183,21 +182,14 @@ WorkflowServiceStubs service = WorkflowServiceStubs.newLocalServiceStubs(); WorkflowClient client = WorkflowClient.newInstance( service, WorkflowClientOptions.newBuilder().setPlugins(plugin).build()); -SampleTelemetry telemetry = - "console".equals(System.getenv("ADK_TRACING")) ? SampleTelemetry.console() : null; -WorkerFactory factory = - WorkerFactory.newInstance( - client, - telemetry == null - ? WorkerFactoryOptions.newBuilder().build() - : telemetry.workerOptions()); +WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(AgentSupport.TASK_QUEUE); register(worker); factory.start(); ``` -`register(worker)` hosts all nine scenarios and their Activity implementations. The same registration is used in the +`register(worker)` hosts all seven scenarios and their Activity implementations. The same registration is used in the offline tests. The MCP toolset is created on first use; the other scenarios don't start an MCP server. Run the following commands from the samples repository root. Start the Temporal development server in one terminal: @@ -583,167 +575,6 @@ Do not override a `ParallelAgent` scheduler or an `LlmAgent` executor: agent-lev scheduler and move execution off Workflow threads. For sequential execution, pass `WorkflowScheduler.sequential()` to `TemporalAdk.runnerBuilder(...)`. -## Stream and observe model calls - -### Publish buffered model output - -ADK Java supports SSE responses. In plugin 0.1.0, one model Activity collects all chunks before returning them to -the Workflow. Select `RunConfig.StreamingMode.SSE`, then publish the recorded partial and final events through -Workflow Streams: - - -[googleadk/src/main/java/io/temporal/samples/googleadk/streaming/StreamingWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/streaming/StreamingWorkflowImpl.java) -```java -@Override -public List stream(String prompt) { - LlmAgent agent = - LlmAgent.builder() - .name("streaming_assistant") - .model(TemporalModel.create(AgentSupport.MODEL)) - .instruction("Answer concisely.") - .build(); - Runner runner = TemporalAdk.runnerBuilder().appName("streaming").agent(agent).build(); - List events = - TemporalAdk.run( - runner, - AgentSupport.USER, - AgentSupport.SESSION, - Content.fromParts(Part.fromText(prompt)), - RunConfig.builder() - .streamingMode(RunConfig.StreamingMode.SSE) - .autoCreateSession(true) - .build()); - List chunks = - events.stream() - .filter(event -> event.content().isPresent()) - .map( - event -> - new ModelChunk( - event.partial().orElse(false) ? "partial" : "final", - event.content().map(Content::text).orElse(""))) - .toList(); - for (ModelChunk chunk : chunks) output.topic("model").publish(chunk); - output.topic("model").publish(new ModelChunk("complete", AgentSupport.lastText(events))); - Workflow.await(Duration.ofSeconds(10), () -> acknowledged); - return chunks; -} - -``` - - -Workflow Streams is an experimental SDK module. This example publishes model chunks after the model Activity -completes. Live token forwarding while that Activity is running requires an integration change. Start a subscriber -with the sample's client: - -```bash -./gradlew :googleadk:starter --args='streaming' -``` - -Offline mode emits two partial chunks, a final `Hello from ADK`, and a `complete` event. The subscriber acknowledges -completion. Without a subscriber, the Workflow returns after a ten-second acknowledgement deadline. To exercise -that path, use `temporal workflow execute --type StreamingWorkflow --task-queue google-adk-samples --input '"Say hello."'`. -Subscribe when starting the Workflow; the sample serves stream items while the Workflow is open. - -### Export OpenTelemetry spans - -The observability sample traces the Temporal Workflow and its model/tool Activities through the SDK's tracing -interceptor and OpenTracing-to-OpenTelemetry bridge. It uses an instance-scoped OpenTelemetry SDK with W3C trace -propagation: - - -[googleadk/src/main/java/io/temporal/samples/googleadk/observability/SampleTelemetry.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/observability/SampleTelemetry.java) -```java -public SampleTelemetry(SpanExporter exporter) { - telemetry = - OpenTelemetrySdk.builder() - .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance())) - .setTracerProvider( - SdkTracerProvider.builder() - .addSpanProcessor( - SimpleSpanProcessor.create(new ReplayAwareSpanExporter(exporter))) - .build()) - .build(); - options = - OpenTracingOptions.newBuilder() - .setTracer(OpenTracingShim.createTracerShim(telemetry)) - .setSpanContextCodec(OpenTracingSpanContextCodec.TEXT_MAP_CODEC) - .build(); -} - -public WorkerFactoryOptions workerOptions() { - return WorkerFactoryOptions.newBuilder() - .setWorkerInterceptors(new OpenTracingWorkerInterceptor(options)) - .build(); -} - -``` - - -The synchronous processor checks replay before forwarding spans to the chosen exporter. This suppresses duplicate -Workflow spans from history replay while retaining Query spans: - - -[googleadk/src/main/java/io/temporal/samples/googleadk/observability/ReplayAwareSpanExporter.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/observability/ReplayAwareSpanExporter.java) -```java -@Override -public CompletableResultCode export(Collection spans) { - if (WorkflowUnsafe.isWorkflowThread() && WorkflowUnsafe.isReplaying()) { - spans = spans.stream().filter(span -> span.getName().startsWith("HandleQuery:")).toList(); - } - return spans.isEmpty() ? CompletableResultCode.ofSuccess() : delegate.export(spans); -} - -``` - - -Keep the replay filter on the Workflow thread, before asynchronous export. Enable console export when starting -the Worker: - -```bash -ADK_MODEL_MODE=offline ADK_TRACING=console ./gradlew :googleadk:worker -``` - -Then run the observed model/tool interaction: - - -[googleadk/src/main/java/io/temporal/samples/googleadk/observability/ObservabilityWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/observability/ObservabilityWorkflowImpl.java) -```java -@Override -public String observe(String prompt) { - WeatherActivities weather = - Workflow.newActivityStub( - WeatherActivities.class, - ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(30)).build()); - LlmAgent agent = - LlmAgent.builder() - .name("observed_assistant") - .model(TemporalModel.create(AgentSupport.MODEL)) - .instruction("Use getWeather and summarize its result.") - .tools(ActivityTools.create(weather, "getWeather")) - .build(); - Runner runner = TemporalAdk.runnerBuilder().appName("observability").agent(agent).build(); - return AgentSupport.lastText( - TemporalAdk.run( - runner, - AgentSupport.USER, - AgentSupport.SESSION, - Content.fromParts(Part.fromText(prompt)))); -} -``` - - -```bash -temporal workflow execute --type ObservabilityWorkflow --task-queue google-adk-samples --input '"What is the weather in Chicago?"' -``` - -Offline mode returns `Chicago is sunny.`. Console spans include the Workflow, two model Activity executions, and -the weather Activity, linked into one trace. Real Activity retries produce another attempt span. Replace the console -exporter with another `SpanExporter` to send these spans to an OpenTelemetry backend. The tests use an in-memory -exporter and verify failures, retries, trace linkage, and replay without extra exported spans. - -This sample exports Temporal operation spans. It does not install a global ADK telemetry provider; native ADK -agent-internal tracing in plugin 0.1.0 still lacks replay suppression. - ## Wait for human approval Pass `true` as the confirmation argument to `ActivityTools.create` to pause before the tool executes. Read pending @@ -876,23 +707,22 @@ Run the suite without provider credentials or an external Temporal Service: The tests verify Activity retries and non-retryable failures, deterministic function results, parallel model scheduling, a real local MCP server, approval/rejection and cancellation, invalid structured output, correlated -callbacks, session/queue recovery through Continue-As-New, buffered streaming with and without a subscriber, and -OpenTelemetry trace linkage without duplicate replay exports. `OfflineSamplesTest` also runs every scenario with +callbacks, and session/queue recovery through Continue-As-New. `OfflineSamplesTest` also runs every scenario with the same `OfflineModel` and `SampleWorker.register` used by the runnable Worker. Each scenario's README includes a targeted test command. ## Understand the limitations -- In version 0.1.0, streamed model chunks reach the Workflow after the model Activity completes. The streaming sample - publishes those recorded chunks through Workflow Streams. Live token forwarding and live bidirectional - connections remain unsupported by the plugin. +- In version 0.1.0, streamed model chunks reach the Workflow after the model Activity completes. Delivery through + Workflow Streams while the Activity is running is tracked in [#257](https://github.com/temporalio/ai-integrations/issues/257). + Live bidirectional connections are also unsupported. - ADK services that perform I/O, including code execution, memory, and artifact services, cannot run directly inside a Workflow. Use Activities for I/O. The plugin does not durably manage an agent-facing code execution environment. - Avoid RxJava blocking methods inside a Workflow. Use `TemporalAdk.run` or `TemporalAdk.await` so the Workflow thread yields while Activities or timers are pending. - ADK uses global OpenTelemetry providers. The plugin has no replay suppression for ADK tracing, so an installed - tracing SDK emits duplicate spans during replay. The observability sample instruments Temporal operations through - the SDK instead of enabling global native ADK telemetry. + tracing SDK emits duplicate spans during replay. Replay-safe native ADK tracing is tracked in + [#258](https://github.com/temporalio/ai-integrations/issues/258). - Canceling an approval or callback wait does not undo a shipment or cancel an external job that already started. A real backend needs an explicit cancellation Activity. - ADK's experimental App resumability and event compaction are not covered by the integration's tests. From 1eba3ab855c51719e4112db222d7318f5587bed2 Mon Sep 17 00:00:00 2001 From: DABH Date: Thu, 29 Oct 2026 21:45:05 -0500 Subject: [PATCH 5/5] Document Java ADK chat with Workflow Updates --- docs/develop/java/integrations/google-adk.mdx | 183 ++++++++++++------ 1 file changed, 126 insertions(+), 57 deletions(-) diff --git a/docs/develop/java/integrations/google-adk.mdx b/docs/develop/java/integrations/google-adk.mdx index 81e38ee6dd..a9748c58b6 100644 --- a/docs/develop/java/integrations/google-adk.mdx +++ b/docs/develop/java/integrations/google-adk.mdx @@ -32,15 +32,15 @@ both modes. | Category | Sample | What it demonstrates | | --- | --- | --- | -| Agent Chat | [chat](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat) | Conversation state and queued messages survive Continue-As-New. | +| Agent Chat | [chat](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat) | Updates return each turn's reply and conversation state survives Continue-As-New. | | Tools | [tools](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/tools) | A deterministic function runs in the Workflow; a weather observation runs in an Activity. | | MCP | [mcp](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/mcp) | List and call a bundled stateless stdio server through Activities. | -| Streaming | Unsupported | Plugin 0.1.0 buffers SSE responses until the model Activity completes; it cannot deliver output while the Activity is running. | +| Streaming | Unsupported | Plugin 0.1.1 buffers SSE responses until the model Activity completes; it cannot deliver output while the Activity is running. | | Human in the Loop | [humanintheloop](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/humanintheloop) | A Signal approves or rejects a pending tool call; cancellation ends the wait. | | Structured Output | [structuredoutput](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/structuredoutput) | Supply an ADK output schema, validate the response, and return a typed result. | | Multi-Agent | [multiagent](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/multiagent) | ADK schedules two specialist agents' model Activities concurrently. | | Observability | Unsupported | Native ADK tracing has no replay suppression and can export duplicate spans during replay. | -| Sandboxes | [Limitations](#understand-the-limitations) | Plugin 0.1.0 does not manage agent-facing code execution environments. | +| Sandboxes | [Limitations](#understand-the-limitations) | Plugin 0.1.1 does not manage agent-facing code execution environments. | The suite also includes a [long-running tool](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/longrunning) that resumes after a callback. Agent Chat is the introductory example. See [the limitations](#understand-the-limitations) @@ -61,7 +61,7 @@ Central alongside the SDK. io.temporal google-adk - 0.1.0 + 0.1.1 io.temporal @@ -73,7 +73,7 @@ Central alongside the SDK. **Gradle:** ```groovy -implementation 'io.temporal:google-adk:0.1.0' +implementation 'io.temporal:google-adk:0.1.1' implementation 'io.temporal:temporal-sdk:1.40.0' ``` @@ -86,59 +86,123 @@ configure the Google GenAI client for Vertex AI. Model credentials stay on the W ## Run an agent -Start with Agent Chat. Signals queue user messages, a Query exposes the latest reply, and a finish Signal drains the -queue. Build its agent with ADK's `LlmAgent`, use `TemporalModel` for Activity-based model calls, and drive each turn -with `TemporalAdk.run()` and a Runner built by `TemporalAdk.runnerBuilder()`: +Start with Agent Chat. The `message` Update returns the reply to each user message. A `finish` Signal stops new +messages and lets accepted Updates finish. The optional `lastReply` Query inspects the latest completed reply: + + +[googleadk/src/main/java/io/temporal/samples/googleadk/chat/ChatWorkflow.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat/ChatWorkflow.java) +```java +@WorkflowInterface +public interface ChatWorkflow { + @WorkflowMethod + String chat(ChatInput input); + + @UpdateMethod + String message(String text); + + @UpdateValidatorMethod(updateName = "message") + void validateMessage(String text); + + @SignalMethod + void finish(); + + @QueryMethod + String lastReply(); +} +``` + + +Build the agent with ADK's `LlmAgent`, use `TemporalModel` for Activity-based model calls, and drive each turn with +`TemporalAdk.run()` and a Runner built by `TemporalAdk.runnerBuilder()`. `@WorkflowInit` restores the session before +message handlers run. A `WorkflowLock` keeps concurrent turns from interleaving on the shared session: [googleadk/src/main/java/io/temporal/samples/googleadk/chat/ChatWorkflowImpl.java](https://github.com/temporalio/samples-java/blob/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat/ChatWorkflowImpl.java) ```java -@Override -public String chat(ChatInput input) { - LlmAgent agent = - LlmAgent.builder() - .name("chat_assistant") - .model(TemporalModel.create(AgentSupport.MODEL)) - .instruction("Answer concisely, remembering the earlier turns in this conversation.") - .build(); - Runner runner = TemporalAdk.runnerBuilder().appName("chat").agent(agent).build(); - if (input.session() != null) { - Sessions.importSession(runner.sessionService(), input.session()); - } - int turns = 0; - while (!finished || !messages.isEmpty()) { - Workflow.await(() -> finished || !messages.isEmpty()); - if (messages.isEmpty()) { - break; +public class ChatWorkflowImpl implements ChatWorkflow { + private final WorkflowLock turnLock = Workflow.newWorkflowLock(); + private final Runner runner; + private boolean finished; + private String reply; + private int turns; + + @WorkflowInit + public ChatWorkflowImpl(ChatInput input) { + reply = input.lastReply(); + LlmAgent agent = + LlmAgent.builder() + .name("chat_assistant") + .model(TemporalModel.create(AgentSupport.MODEL)) + .instruction("Answer concisely, remembering the earlier turns in this conversation.") + .build(); + runner = TemporalAdk.runnerBuilder().appName("chat").agent(agent).build(); + if (input.session() != null) { + Sessions.importSession(runner.sessionService(), input.session()); } - String text = messages.remove(0); - reply = - AgentSupport.lastText( - TemporalAdk.run( - runner, - AgentSupport.USER, - AgentSupport.SESSION, - Content.fromParts(Part.fromText(text)))); - // Use a small threshold to make Continue-As-New easy to observe in this sample. - if (++turns == 3 && !finished) { + } + + @Override + public String chat(ChatInput input) { + Workflow.await( + () -> + finished || turns >= 3 || (turns > 0 && Workflow.getInfo().isContinueAsNewSuggested())); + Workflow.await(Workflow::isEveryHandlerFinished); + if (!finished) { Session snapshot = Sessions.exportSession( runner.sessionService(), "chat", AgentSupport.USER, AgentSupport.SESSION); - Workflow.continueAsNew(new ChatInput(snapshot, List.copyOf(messages), finished, reply)); + Workflow.continueAsNew(new ChatInput(snapshot, reply)); + } + return reply; + } + + @Override + public String message(String text) { + turnLock.lock(); + try { + reply = + AgentSupport.lastText( + TemporalAdk.run( + runner, + AgentSupport.USER, + AgentSupport.SESSION, + Content.fromParts(Part.fromText(text)))); + turns++; + return reply; + } finally { + turnLock.unlock(); } } - return reply; -} + @Override + public void validateMessage(String text) { + if (finished) { + throw new IllegalStateException("The conversation is finishing."); + } + if (text == null || text.isBlank()) { + throw new IllegalArgumentException("The message must not be blank."); + } + } + + @Override + public void finish() { + finished = true; + } + + @Override + public String lastReply() { + return reply; + } +} ``` `AgentSupport.MODEL` is `gemini-2.5-flash`; `USER` and `SESSION` identify the ADK user and session within this Workflow. `lastText` returns the last text response among the turn's events. -For plugin 0.1.0, use the provider's model name for both registration and `TemporalModel`, as this example does. -An arbitrary registration alias can reach Gemini or Claude as the requested provider model name. Model names also -affect ADK's Workflow-side capability checks. +The example uses the provider's model name for both registration and `TemporalModel`. ADK's Workflow-side +capability checks use the `TemporalModel` name. Plugin 0.1.1 resolves registration aliases to the worker-side +provider model name for model calls, while preserving explicit before-model callback overrides. On the Worker, register a model factory and a named MCP toolset through `GoogleAdkPlugin`. The sample's `plugin` helper accepts either a Gemini factory or the offline provider: @@ -207,13 +271,12 @@ ADK_MODEL_MODE=offline ./gradlew :googleadk:worker In a third terminal, execute a Workflow on its Task Queue: ```bash -temporal workflow start --workflow-id adk-chat --type ChatWorkflow --task-queue google-adk-samples --input '{"session":null,"messages":[],"finished":false,"lastReply":""}' -temporal workflow signal --workflow-id adk-chat --name message --input '"Hello"' -temporal workflow query --workflow-id adk-chat --name lastReply +temporal workflow start --workflow-id adk-chat --type ChatWorkflow --task-queue google-adk-samples --input '{"session":null,"lastReply":""}' +temporal workflow update execute --workflow-id adk-chat --name message --input '"Hello"' ``` -Repeat the Query until the reply appears. Offline mode returns `turns=1; latest: Hello`. Send more messages to -continue the conversation, or finish and wait for its result: +The Update waits for its own reply. Offline mode returns `turns=1; latest: Hello`. Send more Updates to continue +the conversation, or finish and wait for its result: ```bash temporal workflow signal --workflow-id adk-chat --name finish @@ -246,7 +309,7 @@ System.out.println("Workflow ID: " + id); The starter defaults to Agent Chat: run `./gradlew :googleadk:starter` without arguments. Each scenario's README provides -Temporal CLI commands for its inputs, Signals, Queries, and results. +Temporal CLI commands for its inputs, Updates, Signals, Queries, and results. `TemporalModel.newBuilder(name).activityOptions(...)` customizes model Activity timeouts and retries. The default start-to-close timeout is two minutes. A heartbeat timeout enables heartbeats while the model call runs. @@ -658,12 +721,14 @@ The Agent Chat example above keeps the Runner's session service in the Workflow; `Sessions.exportSession`, carry it in the next Run's input, and restore it with `Sessions.importSession`. The [chat sample](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat) -uses Signals to queue messages and a Query for the latest reply. Its `@WorkflowInit` constructor restores the queue, -completion flag, and last reply before Signal handlers can run. Every three turns, it carries those fields and the -session snapshot into the next Run. A finish Signal drains the queue and completes the Workflow. +serializes message Updates on the shared ADK session. After three completed turns, or when Temporal suggests +Continue-As-New, the main Workflow waits for `Workflow.isEveryHandlerFinished()`, exports the session, and carries +the snapshot and last reply into the next Run. `@WorkflowInit` imports the snapshot before Update handlers run. +Continue-As-New runs in the main Workflow method after accepted Updates finish. A `finish` Signal rejects new +messages, drains accepted Updates, and completes the Workflow. Use the [chat README](https://github.com/temporalio/samples-java/tree/main/googleadk/src/main/java/io/temporal/samples/googleadk/chat) -for the Signal and Query commands. Offline replies show the conversation's turn count, including turns restored +for the Update and finish commands. Offline replies show the conversation's turn count, including turns restored after Continue-As-New. Live Gemini receives the imported conversation as context. The snapshot preserves session-scoped state and events, including pending confirmations. It does not carry app-, @@ -687,8 +752,12 @@ ScriptedModel model = try (AdkTestEnvironment test = new AdkTestEnvironment(model, ChatWorkflowImpl.class)) { test.environment.start(); ChatWorkflow workflow = test.workflow(ChatWorkflow.class); - assertEquals( - "Last reply", workflow.chat(new ChatInput(null, List.of("one", "two"), true, ""))); + WorkflowClient.start(workflow::chat, ChatInput.empty()); + + assertEquals("First reply", workflow.message("one")); + assertEquals("Last reply", workflow.message("two")); + workflow.finish(); + assertEquals("Last reply", WorkflowStub.fromTyped(workflow).getResult(String.class)); assertEquals(2, model.requests().size()); test.replay(test.history(workflow), ChatWorkflowImpl.class); } @@ -707,13 +776,13 @@ Run the suite without provider credentials or an external Temporal Service: The tests verify Activity retries and non-retryable failures, deterministic function results, parallel model scheduling, a real local MCP server, approval/rejection and cancellation, invalid structured output, correlated -callbacks, and session/queue recovery through Continue-As-New. `OfflineSamplesTest` also runs every scenario with -the same `OfflineModel` and `SampleWorker.register` used by the runnable Worker. Each scenario's README includes a -targeted test command. +callbacks, concurrent Update replies, shutdown with accepted Updates, and session recovery through Continue-As-New. +`OfflineSamplesTest` also runs every scenario with the same `OfflineModel` and `SampleWorker.register` used by the +runnable Worker. Each scenario's README includes a targeted test command. ## Understand the limitations -- In version 0.1.0, streamed model chunks reach the Workflow after the model Activity completes. Delivery through +- In version 0.1.1, streamed model chunks reach the Workflow after the model Activity completes. Delivery through Workflow Streams while the Activity is running is tracked in [#257](https://github.com/temporalio/ai-integrations/issues/257). Live bidirectional connections are also unsupported. - ADK services that perform I/O, including code execution, memory, and artifact services, cannot run directly inside