diff --git a/examples/workflows/LoopWorkflow.java b/examples/workflows/LoopWorkflow.java new file mode 100644 index 000000000..9b5cffd9a --- /dev/null +++ b/examples/workflows/LoopWorkflow.java @@ -0,0 +1,149 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.example.workflows; + +import com.google.adk.agents.AgentMode; +import com.google.adk.agents.Context; +import com.google.adk.agents.LlmAgent; +import com.google.adk.apps.App; +import com.google.adk.runner.Runner; +import com.google.adk.workflow.FunctionNodes; +import com.google.adk.workflow.Node; +import com.google.adk.workflow.Route; +import com.google.adk.workflow.Workflow; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.genai.types.Content; +import com.google.genai.types.Part; +import com.google.genai.types.Schema; +import com.google.genai.types.Type; + +/** + * A port of adk-python's {@code loop} workflow sample: an agent writes a headline about the user's + * topic, a second agent grades whether it is about technology, and the workflow loops back with the + * grader's feedback until it is. + */ +public final class LoopWorkflow { + + private static final String DEFAULT_MODEL = "gemini-3.8-flash"; + private static final String USER_ID = "user"; + + /** Builds the workflow, with both agents on {@code model}. */ + public static Workflow create(String model) { + LlmAgent generateHeadline = generateHeadlineAgent(model); + // START hands the first node the user's message as Content. + Node processInput = + FunctionNodes.of("process_input", Content.class, Void.class, LoopWorkflow::processInput); + Node routeHeadline = + FunctionNodes.of("route_headline", Feedback.class, Void.class, LoopWorkflow::routeHeadline); + return Workflow.builder() + .name("loop") + .edges(g -> + g.fromStart() + .chain(processInput, generateHeadline, evaluateHeadlineAgent(model), routeHeadline) + .route(r -> r.on("unrelated").then(generateHeadline))) + .build(); + } + + /** + * Runs the workflow on one topic and prints each headline and grade. It calls Gemini, so it needs + * the credentials the README describes; the first argument, if any, overrides the model. + */ + public static void main(String[] args) { + String model = args.length > 0 ? args[0] : DEFAULT_MODEL; + App app = App.builder().name("loop").rootNode(create(model)).build(); + Runner runner = Runner.builder().app(app).build(); + String sessionId = + runner.sessionService().createSession(app.name(), USER_ID).blockingGet().id(); + runner + .runAsync(USER_ID, sessionId, Content.fromParts(Part.fromText("flower"))) + .blockingForEach(event -> { + String text = event.stringifyContent(); + if (!text.isBlank()) { + System.out.println("[" + event.author() + "] " + text); + } + }); + } + + /** Stores the user's topic in state, where the headline agent's instruction reads it. */ + private static Void processInput(Context context, Content message) { + context.state().put("topic", message.text()); + return null; + } + + /** Routes on the grade; no edge matches {@code tech-related}, so that grade ends the loop. */ + private static Void routeHeadline(Context context, Feedback feedback) { + context.routes(ImmutableList.of(new Route.Tag(feedback.grade()))); + return null; + } + + /** The grader's structured answer, with the fields of adk-python's {@code Feedback} model. */ + private record Feedback(String grade, String feedback) {} + + /** The schema of {@link Feedback}, which the grader's answer must match. */ + private static final Schema FEEDBACK_SCHEMA = + Schema.builder() + .type(Type.Known.OBJECT) + .properties( + ImmutableMap.of( + "grade", + Schema.builder() + .type(Type.Known.STRING) + .enum_("tech-related", "unrelated") + .description( + "Decide if the headline is related to technology or software" + + " engineering.") + .build(), + "feedback", + Schema.builder() + .type(Type.Known.STRING) + .description( + "If the headline is unrelated to technology, provide feedback on how to" + + " make it more tech-focused.") + .build())) + .required("grade", "feedback") + .build(); + + private static LlmAgent generateHeadlineAgent(String model) { + return LlmAgent.builder() + .name("generate_headline") + .model(model) + .instruction( + """ + Write a headline about the topic "{topic}". + If feedback is provided, take it into account. + The feedback: {feedback?} + """) + // Outputs its headline, which the grader takes as its user turn. + .mode(AgentMode.SINGLE_TURN) + .build(); + } + + private static LlmAgent evaluateHeadlineAgent(String model) { + return LlmAgent.builder() + .name("evaluate_headline") + .model(model) + .instruction("Grade whether the headline is related to technology or software engineering.") + .outputSchema(FEEDBACK_SCHEMA) + // Stores the grade and feedback for the headline agent's next attempt. + .outputKey("feedback") + // Takes the headline as its user turn and outputs the parsed grade. + .mode(AgentMode.SINGLE_TURN) + .build(); + } + + private LoopWorkflow() {} +} diff --git a/examples/workflows/MessageTriageWorkflow.java b/examples/workflows/MessageTriageWorkflow.java new file mode 100644 index 000000000..de6b80902 --- /dev/null +++ b/examples/workflows/MessageTriageWorkflow.java @@ -0,0 +1,137 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.example.workflows; + +import static com.google.common.collect.ImmutableList.toImmutableList; + +import com.google.adk.agents.AgentMode; +import com.google.adk.agents.Context; +import com.google.adk.agents.LlmAgent; +import com.google.adk.apps.App; +import com.google.adk.events.Event; +import com.google.adk.runner.Runner; +import com.google.adk.workflow.FunctionNodes; +import com.google.adk.workflow.Node; +import com.google.adk.workflow.Route; +import com.google.adk.workflow.Workflow; +import com.google.common.base.CharMatcher; +import com.google.common.base.Splitter; +import com.google.genai.types.Content; +import com.google.genai.types.Part; +import java.util.Locale; + +/** + * A port of ADK Kotlin's message-triage workflow sample, the graph from the ADK docs: an agent + * labels a message as a bug, a customer-support request, a logistics question, or several of these, + * and a function node emits one route per label so each matching handler runs. + */ +public final class MessageTriageWorkflow { + + private static final String DEFAULT_MODEL = "gemini-3.8-flash"; + private static final String USER_ID = "user"; + + /** The characters the model may wrap a label in. */ + private static final CharMatcher LABEL_TRIM = + CharMatcher.whitespace().or(CharMatcher.anyOf("\"'.")); + + /** Builds the workflow, with the classifier on {@code model}. */ + public static Workflow create(String model) { + return Workflow.builder() + .name("routing_workflow") + .edges(g -> + g.fromStart() + .chain( + processMessageAgent(model), + FunctionNodes.of( + "message_categories", + String.class, + Void.class, + MessageTriageWorkflow::messageCategories)) + .route(r -> { + r.on("BUG").then(responder("response_1_bug", "Handling bug...")); + r.on("CUSTOMER_SUPPORT") + .then(responder("response_2_support", "Handling customer support...")); + r.on("LOGISTICS") + .then(responder("response_3_logistics", "Handling logistics...")); + })) + .build(); + } + + /** + * Runs the workflow on one message and prints each reply. It calls Gemini, so it needs the + * credentials the README describes; the first argument, if any, overrides the model. + */ + public static void main(String[] args) { + String model = args.length > 0 ? args[0] : DEFAULT_MODEL; + App app = App.builder().name("routing_workflow").rootNode(create(model)).build(); + Runner runner = Runner.builder().app(app).build(); + String sessionId = + runner.sessionService().createSession(app.name(), USER_ID).blockingGet().id(); + Content message = + Content.fromParts( + Part.fromText("The app crashes when I open my order, and my parcel is late.")); + runner + .runAsync(USER_ID, sessionId, message) + .blockingForEach(event -> { + String text = event.stringifyContent(); + if (!text.isBlank()) { + System.out.println("[" + event.author() + "] " + text); + } + }); + } + + /** Emits a route for each label in the classifier's answer; several routes fan out. */ + private static Void messageCategories(Context context, String labels) { + // Normalizes each label, since the model may quote, punctuate or lowercase it. + context.routes( + Splitter.on(',') + .trimResults(LABEL_TRIM) + .splitToStream(labels) + .map(label -> new Route.Tag(label.toUpperCase(Locale.ROOT).replace(' ', '_'))) + .collect(toImmutableList())); + return null; + } + + /** Returns a node that tells the user the message is being handled. */ + private static Node responder(String name, String reply) { + return FunctionNodes.of( + name, + Object.class, + Event.class, + (context, input) -> + Event.builder() + .id(context.invocationContext().newUuid()) + .content(Content.builder().role("model").parts(Part.fromText(reply)).build()) + .build()); + } + + private static LlmAgent processMessageAgent(String model) { + return LlmAgent.builder() + .name("process_message") + .model(model) + // Outputs its labels, which the next node turns into routes. + .mode(AgentMode.SINGLE_TURN) + .instruction( + """ + Classify user message into either "BUG", "CUSTOMER_SUPPORT", + or "LOGISTICS". If you think a message applies to more than one category, + reply with a comma separated list of categories. + """) + .build(); + } + + private MessageTriageWorkflow() {} +} diff --git a/examples/workflows/NestedWorkflow.java b/examples/workflows/NestedWorkflow.java new file mode 100644 index 000000000..0737a2088 --- /dev/null +++ b/examples/workflows/NestedWorkflow.java @@ -0,0 +1,176 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.example.workflows; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.adk.agents.AgentMode; +import com.google.adk.agents.Context; +import com.google.adk.agents.LlmAgent; +import com.google.adk.apps.App; +import com.google.adk.events.Event; +import com.google.adk.runner.Runner; +import com.google.adk.workflow.FunctionNodes; +import com.google.adk.workflow.JoinNode; +import com.google.adk.workflow.Node; +import com.google.adk.workflow.Workflow; +import com.google.genai.types.Content; +import com.google.genai.types.Part; +import io.reactivex.rxjava3.core.Flowable; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.jspecify.annotations.Nullable; + +/** + * A port of adk-python's {@code nested_workflow} sample: for the year the user names, a nested + * workflow finds a famous person born that year and writes their bio while an agent describes an + * event from that year, and a {@link JoinNode} waits for both branches before one message combines + * them. + */ +public final class NestedWorkflow { + + private static final String DEFAULT_MODEL = "gemini-3.8-flash"; + private static final String USER_ID = "user"; + private static final Pattern YEAR = Pattern.compile("\\b\\d{4}\\b"); + + /** Builds the workflow, with every agent on {@code model}. */ + public static Workflow create(String model) { + // A Workflow is a Node, so a whole workflow can be one branch of another. + Workflow findFamousPerson = + Workflow.builder() + .name("find_famous_person") + .edges(g -> g.fromStart().chain(findNameAgent(model), generateBioAgent(model))) + .build(); + Node aggregateResults = + FunctionNodes.of( + "aggregate_results", + new TypeReference>() {}, + Event.class, + NestedWorkflow::aggregateResults); + return Workflow.builder() + .name("nested_workflow") + .edges(g -> + g.fromStart() + .then(new ProcessInput()) + .then(findFamousPerson, findHistoricalEventAgent(model)) + .joinTo(JoinNode.create("join_for_aggregation")) + .then(aggregateResults)) + .build(); + } + + /** + * Runs the workflow on one year and prints each reply. It calls Gemini, so it needs the + * credentials the README describes; the first argument, if any, overrides the model. + */ + public static void main(String[] args) { + String model = args.length > 0 ? args[0] : DEFAULT_MODEL; + App app = App.builder().name("nested_workflow").rootNode(create(model)).build(); + Runner runner = Runner.builder().app(app).build(); + String sessionId = + runner.sessionService().createSession(app.name(), USER_ID).blockingGet().id(); + runner + .runAsync(USER_ID, sessionId, Content.fromParts(Part.fromText("1984"))) + .blockingForEach(event -> { + String text = event.stringifyContent(); + if (!text.isBlank()) { + System.out.println("[" + event.author() + "] " + text); + } + }); + } + + /** + * Stores the year from the user's message in state, and fails the run if there is none. It is a + * {@link Node} rather than a function node because it sends a message before it fails. + */ + private static final class ProcessInput implements Node { + @Override + public String name() { + return "process_input"; + } + + @Override + public Flowable runNode(Context context, @Nullable Object nodeInput) { + // START hands the first node the user's message as Content. + Matcher year = YEAR.matcher(((Content) nodeInput).text()); + if (!year.find()) { + return Flowable.just(message(context, "Please provide a valid 4-digit year (e.g., 1955).")) + .concatWith(Flowable.error(new IllegalArgumentException("Invalid year format."))); + } + context.state().put("year", year.group()); + return Flowable.empty(); + } + } + + /** Combines both branches' answers, which the join passes on keyed by branch name. */ + private static Event aggregateResults(Context context, Map answers) { + return message( + context, + "# Year: " + + context.state().get("year") + + "\n\n## Famous Person Bio:\n\n" + + answers.get("find_famous_person") + + "\n\n## Historical Event:\n\n" + + answers.get("find_historical_event")); + } + + /** A user-facing message from a node, with {@code text} as its content. */ + private static Event message(Context context, String text) { + return Event.builder() + .id(context.invocationContext().newUuid()) + .content(Content.builder().role("model").parts(Part.fromText(text)).build()) + .build(); + } + + private static LlmAgent findNameAgent(String model) { + return LlmAgent.builder() + .name("find_name") + .model(model) + .instruction( + """ + Find the name of one famous person who was born in this year: {year}. + Return ONLY their name, nothing else. + """) + // Outputs the name, which generate_bio takes as its user turn. + .mode(AgentMode.SINGLE_TURN) + .build(); + } + + private static LlmAgent generateBioAgent(String model) { + return LlmAgent.builder() + .name("generate_bio") + .model(model) + .instruction("Write a short, engaging 3-sentence biography for the specified person.") + // Its answer, as the last node's output, is the nested workflow's output. + .mode(AgentMode.SINGLE_TURN) + .build(); + } + + private static LlmAgent findHistoricalEventAgent(String model) { + return LlmAgent.builder() + .name("find_historical_event") + .model(model) + .instruction( + """ + Describe one highly significant historical event that occurred in this year: {year}. + Keep the description to 2 sentences. + """) + // Outputs its description, which the join collects. + .mode(AgentMode.SINGLE_TURN) + .build(); + } + + private NestedWorkflow() {} +} diff --git a/examples/workflows/NodeOutputWorkflow.java b/examples/workflows/NodeOutputWorkflow.java new file mode 100644 index 000000000..0c682ce7c --- /dev/null +++ b/examples/workflows/NodeOutputWorkflow.java @@ -0,0 +1,155 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.example.workflows; + +import com.google.adk.agents.AgentMode; +import com.google.adk.agents.Context; +import com.google.adk.agents.LlmAgent; +import com.google.adk.apps.App; +import com.google.adk.events.Event; +import com.google.adk.runner.Runner; +import com.google.adk.workflow.FunctionNodes; +import com.google.adk.workflow.NodeInfo; +import com.google.adk.workflow.Workflow; +import com.google.common.collect.ImmutableMap; +import com.google.genai.types.Content; +import com.google.genai.types.Part; +import com.google.genai.types.Schema; +import com.google.genai.types.Type; + +/** + * A port of adk-python's {@code node_output} workflow sample: a function node's return value + * becomes its output, a returned {@link Event} passes through as is, and an agent with an output + * schema answers with structured data, which the next node receives decoded into a record. + */ +public final class NodeOutputWorkflow { + + private static final String DEFAULT_MODEL = "gemini-3.8-flash"; + private static final String USER_ID = "user"; + + /** Builds the workflow, with the agent on {@code model}. */ + public static Workflow create(String model) { + return Workflow.builder() + .name("node_output") + .edges(g -> + g.fromStart() + .chain( + // START hands the first node the user's message as Content. + FunctionNodes.of( + "generate_string_output", + Content.class, + String.class, + NodeOutputWorkflow::generateStringOutput), + FunctionNodes.of( + "generate_event_output", + String.class, + Event.class, + NodeOutputWorkflow::generateEventOutput), + topicAgent(model), + FunctionNodes.of( + "consume_structured_output", + TopicDetails.class, + String.class, + NodeOutputWorkflow::consumeStructuredOutput))) + .build(); + } + + /** + * Runs the workflow on one topic and prints what each node produced. It calls Gemini, so it needs + * the credentials the README describes; the first argument, if any, overrides the model. + */ + public static void main(String[] args) { + String model = args.length > 0 ? args[0] : DEFAULT_MODEL; + App app = App.builder().name("node_output").rootNode(create(model)).build(); + Runner runner = Runner.builder().app(app).build(); + String sessionId = + runner.sessionService().createSession(app.name(), USER_ID).blockingGet().id(); + runner + .runAsync(USER_ID, sessionId, Content.fromParts(Part.fromText("cyberpunk future"))) + .blockingForEach(event -> { + String path = event.nodeInfo().map(NodeInfo::path).orElse(null); + String text = event.stringifyContent(); + if (!text.isBlank()) { + System.out.println("[" + path + "] " + text); + } else { + event.output().ifPresent(output -> System.out.println("[" + path + "] " + output)); + } + }); + } + + /** Returns a string, which becomes the node's output. */ + private static String generateStringOutput(Context context, Content message) { + return "Processed input: " + message.text(); + } + + /** Returns an {@link Event}, which passes through as is and could also carry routes or state. */ + private static Event generateEventOutput(Context context, String text) { + return Event.builder() + .id(context.invocationContext().newUuid()) + .output("Event wrapped output: " + text) + .build(); + } + + /** Formats the agent's structured answer, decoded from the node input into a record. */ + private static String consumeStructuredOutput(Context context, TopicDetails topic) { + return "Received structured output!\nTitle: " + + topic.title() + + "\nDescription: " + + topic.description() + + "\nCategory: " + + topic.category(); + } + + private static LlmAgent topicAgent(String model) { + return LlmAgent.builder() + .name("generate_structured_output") + .model(model) + // Takes the previous node's output as its user turn and outputs the parsed topic. + .mode(AgentMode.SINGLE_TURN) + .instruction("Generate a creative topic based on the following input.") + .outputSchema(TOPIC_SCHEMA) + .build(); + } + + /** The agent's structured answer, with the fields of adk-python's {@code TopicDetails} model. */ + private record TopicDetails(String title, String description, String category) {} + + /** The schema of {@link TopicDetails}, which the agent's answer must match. */ + private static final Schema TOPIC_SCHEMA = + Schema.builder() + .type(Type.Known.OBJECT) + .properties( + ImmutableMap.of( + "title", + Schema.builder() + .type(Type.Known.STRING) + .description("The title of the generated topic.") + .build(), + "description", + Schema.builder() + .type(Type.Known.STRING) + .description("A short description of the topic.") + .build(), + "category", + Schema.builder() + .type(Type.Known.STRING) + .description("The broad category of the topic.") + .build())) + .required("title", "description", "category") + .build(); + + private NodeOutputWorkflow() {} +} diff --git a/examples/workflows/README.md b/examples/workflows/README.md index ae9629ea5..813adeee0 100644 --- a/examples/workflows/README.md +++ b/examples/workflows/README.md @@ -9,8 +9,12 @@ an adk-python workflow sample. | `ClassifierNodeWorkflow` | A classifier node routes a support ticket to the team that handles it, and a second classifier node decides whether a technical ticket is urgent. | Yes | | `FanOutFanInWorkflow` | Three nodes transform the user's text concurrently, and a join combines their outputs. | No | | `LoopSelfWorkflow` | A node routes back to itself until it guesses the user's number. | No | +| `LoopWorkflow` | An agent writes a headline, a grader agent with an output schema judges it, and a node routes on the grader's output back to the writer until it passes. | Yes | +| `MessageTriageWorkflow` | An agent labels a message, and a node emits a route per label so several handlers run. | Yes | | `MessageWorkflow` | Nodes send text, an inline image, several messages, and a streamed sentence. | No | | `MultiTriggersWorkflow` | Three nodes transform the user's text concurrently, and each one triggers its own run of the same node. | No | +| `NestedWorkflow` | A nested workflow of two agents runs beside a third agent, and a join hands both branches' answers to a node that combines them. | Yes | +| `NodeOutputWorkflow` | Nodes output a string and an event, an agent with an output schema outputs structured data, and the last node reads it as a record. | Yes | | `OrderProcessingWorkflow` | Nested workflows and a tool check an order concurrently, then a node routes it based on an agent's risk decision: charge, review, or freeze as fraud. | Yes | | `RequestInputAdvancedWorkflow` | A node asks a manager to decide, sending a payload and asking for an answer that matches a schema. | Yes | | `RequestInputRerunWorkflow` | The `RequestInputWorkflow` review in one node, which reruns when the human answers. | Yes | @@ -19,7 +23,9 @@ an adk-python workflow sample. | `RetryWorkflow` | A retry policy reruns a failing node before the next node reports its result. | No | | `ReturnsWorkflow` | Function tools run as graph steps, and a routing map matches groups of statuses with `anyOf`. | No | | `RouteWorkflow` | An agent classifies the input, and a node routes it to the agent or node that handles it. | Yes | +| `SequenceWorkflow` | One agent names a fruit, and the next agent receives that answer as its input and tells a health benefit of it. | Yes | | `StateWorkflow` | Nodes write session state through the context and through an event, then read it back. | No | +| `SupportTriageWorkflow` | An agent classifies a support request, a routing map sends it to a specialist agent that uses a function tool, and a summarizer agent writes the reply. | Yes | ## Project Layout diff --git a/examples/workflows/SequenceWorkflow.java b/examples/workflows/SequenceWorkflow.java new file mode 100644 index 000000000..de1ce5c1f --- /dev/null +++ b/examples/workflows/SequenceWorkflow.java @@ -0,0 +1,85 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.example.workflows; + +import com.google.adk.agents.AgentMode; +import com.google.adk.agents.LlmAgent; +import com.google.adk.apps.App; +import com.google.adk.runner.Runner; +import com.google.adk.workflow.Workflow; +import com.google.genai.types.Content; +import com.google.genai.types.Part; + +/** + * A port of adk-python's {@code sequence} workflow sample: one agent names a random fruit, and the + * next agent receives that answer as its input and tells a health benefit of the fruit. + */ +public final class SequenceWorkflow { + + private static final String DEFAULT_MODEL = "gemini-3.8-flash"; + private static final String USER_ID = "user"; + + /** Builds the workflow, with both agents on {@code model}. */ + public static Workflow create(String model) { + return Workflow.builder() + .name("sequence") + .edges(g -> g.fromStart().chain(generateFruitAgent(model), generateBenefitAgent(model))) + .build(); + } + + /** + * Runs the workflow once and prints each agent's answer. It calls Gemini, so it needs the + * credentials the README describes; the first argument, if any, overrides the model. + */ + public static void main(String[] args) { + String model = args.length > 0 ? args[0] : DEFAULT_MODEL; + App app = App.builder().name("sequence").rootNode(create(model)).build(); + Runner runner = Runner.builder().app(app).build(); + String sessionId = + runner.sessionService().createSession(app.name(), USER_ID).blockingGet().id(); + // The workflow needs no input, so any message starts it. + runner + .runAsync(USER_ID, sessionId, Content.fromParts(Part.fromText("go"))) + .blockingForEach(event -> { + String text = event.stringifyContent(); + if (!text.isBlank()) { + System.out.println("[" + event.author() + "] " + text); + } + }); + } + + private static LlmAgent generateFruitAgent(String model) { + return LlmAgent.builder() + .name("generate_fruit_agent") + .model(model) + // Outputs the fruit, which the next agent takes as its user turn. + .mode(AgentMode.SINGLE_TURN) + .instruction("Return the name of a random fruit.\nReturn only the name, nothing else.") + .build(); + } + + private static LlmAgent generateBenefitAgent(String model) { + return LlmAgent.builder() + .name("generate_benefit_agent") + .model(model) + // Takes the fruit as its user turn. + .mode(AgentMode.SINGLE_TURN) + .instruction("Tell me a health benefit about the specified fruit.") + .build(); + } + + private SequenceWorkflow() {} +} diff --git a/examples/workflows/SupportTriageWorkflow.java b/examples/workflows/SupportTriageWorkflow.java new file mode 100644 index 000000000..8be4d33f9 --- /dev/null +++ b/examples/workflows/SupportTriageWorkflow.java @@ -0,0 +1,247 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.example.workflows; + +import com.google.adk.agents.AgentMode; +import com.google.adk.agents.Context; +import com.google.adk.agents.LlmAgent; +import com.google.adk.agents.RunConfig; +import com.google.adk.apps.App; +import com.google.adk.runner.Runner; +import com.google.adk.tools.Annotations; +import com.google.adk.tools.FunctionTool; +import com.google.adk.workflow.FunctionNodes; +import com.google.adk.workflow.Node; +import com.google.adk.workflow.NodeInfo; +import com.google.adk.workflow.Route; +import com.google.adk.workflow.Workflow; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.genai.types.Content; +import com.google.genai.types.Part; +import com.google.genai.types.Schema; +import com.google.genai.types.Type; +import java.util.Map; + +/** + * A port of ADK Kotlin's support-triage workflow sample. A classifier labels the request, a routing + * map sends it to a billing or tech specialist who looks up the facts with a tool, and a summarizer + * writes the reply. Any other request goes straight to the summarizer through {@code otherwise}. + */ +public final class SupportTriageWorkflow { + + private static final String DEFAULT_MODEL = "gemini-3.8-flash"; + private static final String USER_ID = "user"; + + /** + * Builds the workflow, with every agent on {@code model}. The billing specialist reads the + * customer's account ID from the {@code account_id} session state key, so pass it with each + * request. + */ + public static Workflow create(String model) { + LlmAgent billing = billingAgent(model); + LlmAgent tech = techAgent(model); + LlmAgent summarize = summaryAgent(model); + // START hands the first node the user's message as Content. + Node saveRequest = + FunctionNodes.of( + "save_request", Content.class, String.class, SupportTriageWorkflow::saveRequest); + Node requestCategory = + FunctionNodes.of( + "request_category", Triage.class, Void.class, SupportTriageWorkflow::requestCategory); + return Workflow.builder() + .name("support_triage") + .edges(g -> { + // An LlmAgent is a Node, so it goes straight into the graph. + g.fromStart() + .chain(saveRequest, classifierAgent(model), requestCategory) + .route(r -> { + r.on("billing").then(billing); + r.on("tech").then(tech); + r.otherwise(summarize); + }); + g.from(billing).then(summarize); + g.from(tech).then(summarize); + }) + .build(); + } + + /** + * Runs the workflow on one request from a signed-in customer and prints what each node said. It + * calls Gemini, so it needs the credentials the README describes; the first argument, if any, + * overrides the model. + */ + public static void main(String[] args) { + String model = args.length > 0 ? args[0] : DEFAULT_MODEL; + App app = App.builder().name("support_triage").rootNode(create(model)).build(); + Runner runner = Runner.builder().app(app).build(); + String sessionId = + runner.sessionService().createSession(app.name(), USER_ID).blockingGet().id(); + Content request = + Content.fromParts(Part.fromText("I was charged twice for my subscription this month.")); + // The support app knows who is signed in, so it passes the account ID as session state. + Map account = ImmutableMap.of("account_id", "ACC-1042"); + runner + .runAsync(USER_ID, sessionId, request, RunConfig.builder().build(), account) + .blockingForEach(event -> { + String text = event.stringifyContent(); + // Skips the specialists' tool calls and results, printing only what nodes said. + if (!text.isBlank() + && event.functionCalls().isEmpty() + && event.functionResponses().isEmpty()) { + System.out.println( + "[" + event.nodeInfo().map(NodeInfo::path).orElse(null) + "] " + text); + } + }); + } + + /** A charge on a customer's account. */ + public record Charge( + String id, String date, String description, int amountCents, String currency) {} + + /** A mock billing backend that the billing specialist queries through a tool. */ + public static final class BillingSystem { + + /** Lists the charges on an account from the last 60 days, newest first. */ + @Annotations.Schema( + description = "Lists the charges on an account from the last 60 days, newest first.") + public ImmutableList listRecentCharges( + @Annotations.Schema( + name = "accountId", + description = "The customer's account ID, such as ACC-1042") + String accountId) { + if (!accountId.equals("ACC-1042")) { + return ImmutableList.of(); + } + return ImmutableList.of( + new Charge("ch_302", "2026-09-01", "Pro plan, monthly", 1200, "USD"), + new Charge("ch_301", "2026-09-01", "Pro plan, monthly", 1200, "USD"), + new Charge("ch_214", "2026-08-01", "Pro plan, monthly", 1200, "USD")); + } + } + + /** A mock status page that the support engineer checks through a tool. */ + public static final class StatusPage { + + /** Returns the current status of each service. */ + @Annotations.Schema(description = "Returns the current status of each service.") + public ImmutableMap getServiceStatus() { + return ImmutableMap.of( + "sync", "Degraded since 09:10 UTC. A fix is rolling out.", + "login", "Operational", + "billing", "Operational"); + } + } + + /** + * Stores the customer's request in state so the specialists and the summarizer can read it. After + * a specialist runs, the summarizer sees only that specialist's notes. + */ + private static String saveRequest(Context context, Content message) { + String request = message.text(); + context.state().put("request", request); + return request; + } + + /** Routes on the category the classifier returned, since an agent node emits no route. */ + private static Void requestCategory(Context context, Triage triage) { + // No edge matches "other", so otherwise takes the request. + context.routes(ImmutableList.of(new Route.Tag(triage.category()))); + return null; + } + + private static LlmAgent classifierAgent(String model) { + return LlmAgent.builder() + .name("classifier") + .model(model) + // Takes the request as its user turn and outputs the parsed category. + .mode(AgentMode.SINGLE_TURN) + .instruction("Classify the customer's latest message.") + .outputSchema(TRIAGE_SCHEMA) + .build(); + } + + private static LlmAgent billingAgent(String model) { + return LlmAgent.builder() + .name("billing") + .model(model) + // Outputs its notes, which the summarizer takes as its user turn. + .mode(AgentMode.SINGLE_TURN) + .instruction( + """ + You are a billing specialist. The customer's account ID is {account_id}. + The customer wrote: {request} + Look up their recent charges, then note in two bullets what happened and how to fix it. + """) + .tools(FunctionTool.create(new BillingSystem(), "listRecentCharges")) + .build(); + } + + private static LlmAgent techAgent(String model) { + return LlmAgent.builder() + .name("tech") + .model(model) + // Outputs its notes, which the summarizer takes as its user turn. + .mode(AgentMode.SINGLE_TURN) + .instruction( + """ + You are a support engineer. + The customer wrote: {request} + Check the service status, then note in two bullets the likely cause and the fix or + workaround. + """) + .tools(FunctionTool.create(new StatusPage(), "getServiceStatus")) + .build(); + } + + private static LlmAgent summaryAgent(String model) { + return LlmAgent.builder() + .name("summary") + .model(model) + // Takes a specialist's notes as its user turn, or the request if reached via otherwise. + .mode(AgentMode.SINGLE_TURN) + .instruction( + """ + The customer wrote: {request} + Write the reply in at most four sentences, based on any specialist notes you are given; + without notes, say that a support agent will follow up. Do not mention internal tools or + IDs other than the customer's. + """) + .build(); + } + + /** The classifier's structured answer, which matches {@link #TRIAGE_SCHEMA}. */ + private record Triage(String category) {} + + /** The schema of {@link Triage}, so routing never depends on parsing free text. */ + private static final Schema TRIAGE_SCHEMA = + Schema.builder() + .type(Type.Known.OBJECT) + .properties( + ImmutableMap.of( + "category", + Schema.builder() + .type(Type.Known.STRING) + .enum_("billing", "tech", "other") + .description( + "billing: charges, refunds or plans. tech: errors, outages or app" + + " problems. other: anything else.") + .build())) + .required("category") + .build(); + + private SupportTriageWorkflow() {} +}