Skip to content

Commit bca0591

Browse files
Rafal Glowinskicopybara-github
authored andcommitted
feat: add a Spring Boot chat app backed by an ADK agent
PiperOrigin-RevId: 1009593322
1 parent c2ab2e3 commit bca0591

9 files changed

Lines changed: 392 additions & 0 deletions

File tree

‎examples/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,5 @@ contains more complete end-to-end samples for customers to use or modify.
1919
prime-checking tools.
2020
- [`mcpfilesystem`](mcpfilesystem/README.md): an agent that uses the MCP
2121
filesystem server as a toolset.
22+
- [`spring_chat`](spring_chat/README.md): a Spring Boot chat page backed by an
23+
agent that calls its model through Spring AI.

‎examples/pom.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,5 +37,6 @@
3737
<module>contextcaching</module>
3838
<module>helloworld</module>
3939
<module>mcpfilesystem</module>
40+
<module>spring_chat</module>
4041
</modules>
4142
</project>

‎examples/spring_chat/README.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Spring Chat Sample
2+
3+
A minimal Spring Boot web app with a browser chat window backed by an ADK agent.
4+
The agent calls its model through Spring AI, using the ADK Spring AI integration
5+
(`google-adk-spring-ai`).
6+
7+
## How it fits together
8+
9+
- `spring-ai-starter-model-google-genai` creates a Spring AI `ChatModel`.
10+
- The ADK Spring AI auto-configuration wraps it in a `SpringAI` bean, which is
11+
an ADK `BaseLlm`.
12+
- `AgentConfig` builds an `LlmAgent` on that model and an `InMemoryRunner`.
13+
- `ChatController` exposes `POST /api/chat`, and `static/index.html` is the
14+
chat page. Each page load gets its own ADK session, so the agent remembers
15+
the conversation until you reload. Sessions are kept in memory until the app
16+
stops.
17+
18+
To use another provider, replace the Google GenAI starter in `pom.xml` with any
19+
other Spring AI chat model starter (OpenAI, Anthropic, Ollama, ...) and set its
20+
`spring.ai.*` properties.
21+
22+
## Prerequisites
23+
24+
- Java 17+
25+
- A Google Cloud project with Vertex AI enabled, and Application Default
26+
Credentials (`gcloud auth application-default login`).
27+
28+
The app uses Vertex AI by default. Set `GOOGLE_CLOUD_PROJECT`, and optionally
29+
`GOOGLE_CLOUD_LOCATION` (default `global`) and `GEMINI_MODEL`. To use the Gemini
30+
Developer API instead, set `GOOGLE_GENAI_USE_VERTEXAI=false` and
31+
`GOOGLE_API_KEY`.
32+
33+
## Run
34+
35+
From the repository root:
36+
37+
```bash
38+
export GOOGLE_CLOUD_PROJECT=your-project-id
39+
./mvnw install -DskipTests -pl examples/spring_chat -am
40+
./mvnw spring-boot:run -pl examples/spring_chat
41+
```
42+
43+
Then open http://localhost:8080. The chat endpoint has no authentication, so the
44+
app listens on `localhost` only, which keeps other machines out. Set
45+
`SERVER_ADDRESS=0.0.0.0` to accept connections from other hosts. Don't expose it
46+
beyond a trusted environment without adding authentication.

‎examples/spring_chat/pom.xml‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
Copyright 2026 Google LLC
4+
5+
Licensed under the Apache License, Version 2.0 (the "License");
6+
you may not use this file except in compliance with the License.
7+
You may obtain a copy of the License at
8+
9+
http://www.apache.org/licenses/LICENSE-2.0
10+
11+
Unless required by applicable law or agreed to in writing, software
12+
distributed under the License is distributed on an "AS IS" BASIS,
13+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
See the License for the specific language governing permissions and
15+
limitations under the License.
16+
-->
17+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
18+
<modelVersion>4.0.0</modelVersion>
19+
20+
<parent>
21+
<groupId>com.google.adk</groupId>
22+
<artifactId>google-adk-examples</artifactId>
23+
<version>1.13.0</version><!-- {x-version-update:google-adk:current} -->
24+
<relativePath>..</relativePath>
25+
</parent>
26+
27+
<groupId>com.google.adk.samples</groupId>
28+
<artifactId>google-adk-sample-spring-chat</artifactId>
29+
<name>Google ADK - Sample - Spring Chat</name>
30+
<description>
31+
A Spring Boot web app with a chat page backed by an ADK agent that calls its model through
32+
Spring AI.
33+
</description>
34+
<packaging>jar</packaging>
35+
36+
<properties>
37+
<spring-ai.version>2.0.1</spring-ai.version>
38+
</properties>
39+
40+
<dependencyManagement>
41+
<dependencies>
42+
<dependency>
43+
<groupId>org.springframework.ai</groupId>
44+
<artifactId>spring-ai-bom</artifactId>
45+
<version>${spring-ai.version}</version>
46+
<type>pom</type>
47+
<scope>import</scope>
48+
</dependency>
49+
</dependencies>
50+
</dependencyManagement>
51+
52+
<dependencies>
53+
<dependency>
54+
<groupId>com.google.adk</groupId>
55+
<artifactId>google-adk</artifactId>
56+
<version>${project.version}</version>
57+
</dependency>
58+
<dependency>
59+
<groupId>com.google.adk</groupId>
60+
<artifactId>google-adk-spring-ai</artifactId>
61+
<version>${project.version}</version>
62+
</dependency>
63+
<dependency>
64+
<groupId>org.springframework.boot</groupId>
65+
<artifactId>spring-boot-starter-webmvc</artifactId>
66+
</dependency>
67+
<!-- Any Spring AI chat model starter works; swap this one to change providers. -->
68+
<dependency>
69+
<groupId>org.springframework.ai</groupId>
70+
<artifactId>spring-ai-starter-model-google-genai</artifactId>
71+
</dependency>
72+
</dependencies>
73+
74+
<build>
75+
<plugins>
76+
<plugin>
77+
<groupId>org.springframework.boot</groupId>
78+
<artifactId>spring-boot-maven-plugin</artifactId>
79+
<version>${spring-boot.version}</version>
80+
</plugin>
81+
<plugin>
82+
<!-- Like the contextcaching demo, this example is not released to Maven. -->
83+
<groupId>org.apache.maven.plugins</groupId>
84+
<artifactId>maven-deploy-plugin</artifactId>
85+
<configuration>
86+
<skip>true</skip>
87+
</configuration>
88+
</plugin>
89+
</plugins>
90+
</build>
91+
</project>
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
* Copyright 2026 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.springchat;
18+
19+
import com.google.adk.agents.BaseAgent;
20+
import com.google.adk.agents.LlmAgent;
21+
import com.google.adk.models.springai.SpringAI;
22+
import com.google.adk.runner.InMemoryRunner;
23+
import com.google.adk.runner.Runner;
24+
import org.springframework.context.annotation.Bean;
25+
import org.springframework.context.annotation.Configuration;
26+
27+
/** Spring configuration for the ADK agent and runner. */
28+
@Configuration(proxyBeanMethods = false)
29+
class AgentConfig {
30+
31+
private static final String APP_NAME = "spring-chat";
32+
33+
/**
34+
* Returns the chat agent. Its {@link SpringAI} model is auto-configured by the ADK Spring AI
35+
* integration from whichever Spring AI {@code ChatModel} starter is on the classpath.
36+
*/
37+
@Bean
38+
BaseAgent chatAgent(SpringAI model) {
39+
return LlmAgent.builder()
40+
.name("spring_chat_agent")
41+
.description("A friendly general-purpose chat assistant.")
42+
.model(model)
43+
.instruction("You are a friendly, concise assistant. Answer the user's questions clearly.")
44+
.build();
45+
}
46+
47+
@Bean
48+
Runner runner(BaseAgent chatAgent) {
49+
return new InMemoryRunner(chatAgent, APP_NAME);
50+
}
51+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
* Copyright 2026 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.springchat;
18+
19+
import com.google.adk.agents.RunConfig;
20+
import com.google.adk.events.Event;
21+
import com.google.adk.runner.Runner;
22+
import com.google.genai.types.Content;
23+
import com.google.genai.types.Part;
24+
import java.util.stream.Collectors;
25+
import org.jspecify.annotations.Nullable;
26+
import org.springframework.http.HttpStatus;
27+
import org.springframework.web.bind.annotation.PostMapping;
28+
import org.springframework.web.bind.annotation.RequestBody;
29+
import org.springframework.web.bind.annotation.RestController;
30+
import org.springframework.web.server.ResponseStatusException;
31+
32+
/** REST endpoint that forwards chat messages from the browser to the ADK runner. */
33+
@RestController
34+
class ChatController {
35+
36+
// The sample has no login, so every browser tab shares one user and keeps its own session.
37+
private static final String USER_ID = "spring-chat-user";
38+
39+
private static final RunConfig RUN_CONFIG = RunConfig.builder().autoCreateSession(true).build();
40+
41+
private final Runner runner;
42+
43+
ChatController(Runner runner) {
44+
this.runner = runner;
45+
}
46+
47+
/** A message from the browser; {@code sessionId} is generated client-side once per page load. */
48+
private record ChatRequest(@Nullable String sessionId, @Nullable String message) {}
49+
50+
private record ChatResponse(String reply) {}
51+
52+
@PostMapping("/api/chat")
53+
ChatResponse chat(@RequestBody ChatRequest request) {
54+
if (isBlank(request.sessionId()) || isBlank(request.message())) {
55+
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
56+
}
57+
// The session service trims ids it creates, so look them up trimmed too.
58+
String sessionId = request.sessionId().trim();
59+
Content userMessage = Content.fromParts(Part.fromText(request.message()));
60+
String reply =
61+
runner
62+
.runAsync(USER_ID, sessionId, userMessage, RUN_CONFIG)
63+
.filter(Event::finalResponse)
64+
.map(ChatController::replyText)
65+
.collect(Collectors.joining("\n"))
66+
.blockingGet();
67+
return new ChatResponse(reply.strip());
68+
}
69+
70+
/** Returns the event's text, followed by why the model stopped, if it ended early. */
71+
private static String replyText(Event event) {
72+
String text = event.stringifyContent();
73+
return event.errorMessage().map(error -> text + "\n[" + error + "]").orElse(text);
74+
}
75+
76+
private static boolean isBlank(@Nullable String s) {
77+
return s == null || s.trim().isEmpty();
78+
}
79+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
* Copyright 2026 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.springchat;
18+
19+
import org.springframework.boot.SpringApplication;
20+
import org.springframework.boot.autoconfigure.SpringBootApplication;
21+
22+
/** Spring Boot entry point for the chat sample. */
23+
@SpringBootApplication
24+
public class SpringChatApplication {
25+
26+
public static void main(String[] args) {
27+
SpringApplication.run(SpringChatApplication.class, args);
28+
}
29+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Spring AI Google GenAI chat model. Vertex AI with Application Default Credentials is the default:
2+
# set GOOGLE_CLOUD_PROJECT (and optionally GOOGLE_CLOUD_LOCATION). To use the Gemini Developer API
3+
# instead, set GOOGLE_GENAI_USE_VERTEXAI=false and GOOGLE_API_KEY.
4+
spring.ai.google.genai.vertex-ai=${GOOGLE_GENAI_USE_VERTEXAI:true}
5+
spring.ai.google.genai.project-id=${GOOGLE_CLOUD_PROJECT:}
6+
spring.ai.google.genai.location=${GOOGLE_CLOUD_LOCATION:global}
7+
spring.ai.google.genai.api-key=${GOOGLE_API_KEY:}
8+
spring.ai.google.genai.chat.model=${GEMINI_MODEL:gemini-3.8-flash}
9+
10+
# The chat endpoint has no authentication, so listen on loopback only unless told otherwise.
11+
server.address=${SERVER_ADDRESS:localhost}

0 commit comments

Comments
 (0)