Repository navigation
Expand file tree
/
Copy pathRouteWorkflow.java
More file actions
167 lines (153 loc) · 6.29 KB
/
Copy pathRouteWorkflow.java
File metadata and controls
167 lines (153 loc) · 6.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/*
* 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.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 route} workflow sample: an agent classifies the user's input as a
* question, a statement, or something else, and a node routes it to the agent or node that handles
* that category.
*/
public final class RouteWorkflow {
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}. */
public static Workflow create(String model) {
Node processInput =
FunctionNodes.of("process_input", String.class, Void.class, RouteWorkflow::processInput);
Node routeOnCategory =
FunctionNodes.of(
"route_on_category", InputCategory.class, Void.class, RouteWorkflow::routeOnCategory);
Node handleOther =
FunctionNodes.of("handle_other", Void.class, Event.class, RouteWorkflow::handleOther);
return Workflow.builder()
.name("route")
.edges(g ->
g.fromStart()
.chain(processInput, classifyInputAgent(model), routeOnCategory)
.route(r -> {
r.on("question").then(answerQuestionAgent(model));
r.on("statement").then(commentOnStatementAgent(model));
r.on("other").then(handleOther);
}))
.build();
}
/**
* Runs the workflow on a question, a statement, and a request, each in its own session, 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("route").rootNode(create(model)).build();
Runner runner = Runner.builder().app(app).build();
ImmutableList<String> inputs =
ImmutableList.of(
"What is the capital of France?",
"The weather is very nice today.",
"Translate bonjour to english");
for (String input : inputs) {
System.out.println("\n=== " + input);
String sessionId =
runner.sessionService().createSession(app.name(), USER_ID).blockingGet().id();
runner
.runAsync(USER_ID, sessionId, Content.fromParts(Part.fromText(input)))
.blockingForEach(
event -> {
String text = event.stringifyContent();
if (!text.isBlank()) {
System.out.println("[" + event.author() + "] " + text);
}
});
}
}
/** Stores the user's input in state, where the agents' instructions read it. */
private static Void processInput(Context context, String input) {
context.state().put("input", input);
return null;
}
/** Routes on the classifier's category. */
private static Void routeOnCategory(Context context, InputCategory category) {
context.routes(ImmutableList.of(new Route.Tag(category.category())));
return null;
}
private static Event handleOther(Context context, Void unused) {
String reply = "Sorry I can only answer questions or comment on statements.";
return Event.builder()
.id(context.invocationContext().newUuid())
.content(Content.builder().role("model").parts(Part.fromText(reply)).build())
.build();
}
/** The classifier's structured answer, with the field of adk-python's {@code InputCategory}. */
private record InputCategory(String category) {}
/** The schema of {@link InputCategory}, which the classifier's answer must match. */
private static final Schema INPUT_CATEGORY_SCHEMA =
Schema.builder()
.type(Type.Known.OBJECT)
.properties(
ImmutableMap.of(
"category",
Schema.builder()
.type(Type.Known.STRING)
.enum_("question", "statement", "other")
.build()))
.required("category")
.build();
private static LlmAgent classifyInputAgent(String model) {
return LlmAgent.builder()
.name("classify_input")
.model(model)
// Takes the user's message as its user turn and outputs the parsed category.
.mode(AgentMode.SINGLE_TURN)
.instruction("Based on this input, decide which category it belongs to: {input}")
.outputSchema(INPUT_CATEGORY_SCHEMA)
.outputKey("category")
.build();
}
private static LlmAgent answerQuestionAgent(String model) {
return LlmAgent.builder()
.name("answer_question")
.model(model)
// Takes the user's message as its user turn and outputs its reply.
.mode(AgentMode.SINGLE_TURN)
.instruction("Answer the question: {input}")
.build();
}
private static LlmAgent commentOnStatementAgent(String model) {
return LlmAgent.builder()
.name("comment_on_statement")
.model(model)
// Takes the user's message as its user turn and outputs its reply.
.mode(AgentMode.SINGLE_TURN)
.instruction("Comment on the statement: {input}")
.build();
}
private RouteWorkflow() {}
}