Building Your First Chatbot
Create a fully functional AI chatbot with Spring AI in just 5 simple steps. No prior AI experience required!
In this tutorial, you'll learn how to build a production-ready AI chatbot using Spring AI and OpenAI's GPT models. Spring AI is the official Spring project that brings the power of generative AI to Java developers, providing a familiar programming model that integrates seamlessly with the Spring ecosystem you already know and love.
Unlike building AI applications in Python, Spring AI leverages Java's enterprise-grade features including dependency injection, declarative configuration, and battle-tested patterns. This means you can focus on building intelligent features while Spring handles the boilerplate code for API communication, error handling, and resource management.
Prerequisites
Why Spring AI?
Spring AI provides a portable API that works across multiple AI providers (OpenAI, Azure OpenAI, Anthropic, Google Vertex AI, and more). This means you can switch providers without changing your application code—just update your configuration. Additionally, Spring AI integrates with Spring's dependency injection, making it easy to test and maintain your AI-powered applications.
Create a New Spring Boot Project
Start by creating a new Spring Boot project with the required dependencies. The easiest way is to useSpring Initializrand select "Spring Web" along with your preferred build tool.
<!-- pom.xml --><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-openai-spring-boot-starter</artifactId></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-bom</artifactId><version>1.0.0-M4</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>Tip: The Spring AI BOM (Bill of Materials) manages all Spring AI dependency versions for you, preventing version conflicts and ensuring compatibility.
Configure Your API Key
Add your OpenAI API key to the application properties. Spring AI uses this key to authenticate with OpenAI's servers and make requests to their language models. The temperature setting controls response creativity—lower values produce more deterministic outputs, while higher values increase randomness.
# application.propertiesspring.ai.openai.api-key=${OPENAI_API_KEY}spring.ai.openai.chat.options.model=gpt-4o-minispring.ai.openai.chat.options.temperature=0.7Security Warning: Never commit API keys to version control! Use environment variables or a secrets manager. Set your key via export OPENAI_API_KEY=your-key-here before running.
Create the Chat Controller
This is where the magic happens. The ChatClient is Spring AI's primary abstraction for interacting with language models. It follows a fluent builder pattern that makes it intuitive to construct prompts and process responses.
@RestController@RequestMapping("/api/chat")publicclassChatController{privatefinalChatClient chatClient;publicChatController(ChatClient.Builder chatClientBuilder){this.chatClient = chatClientBuilder
.defaultSystem("You are a helpful assistant. Be concise and friendly.").build();}@PostMappingpublicStringchat(@RequestBodyMap<String,String> request){String userMessage = request.get("message");return chatClient.prompt().user(userMessage).call().content();}}Understanding the Code
ChatClient.BuilderInjected automatically by Spring's dependency injection. It's pre-configured with your OpenAI settings from application.properties.
.defaultSystem()Sets a system prompt that defines the AI's personality and behavior. This is sent with every request to guide the model's responses.
.prompt().user().call().content()The fluent API chain: create a prompt, add user message, call the model, and extract the text content from the response.
Create a Simple Frontend
While you could test with curl or Postman, a simple HTML interface makes interaction much more enjoyable. This basic frontend uses vanilla JavaScript and the Fetch API to communicate with your backend. Place this file in your project's static resources folder.
<!DOCTYPEhtml><html><head><title>My First Chatbot</title><style>
body { font-family: system-ui; max-width: 600px; margin: 50px auto; padding: 20px; }
#chat { border: 1px solid #ddd; height: 400px; overflow-y: auto; padding: 10px; margin-bottom: 10px; border-radius: 8px; }
.message { padding: 10px 14px; margin: 8px 0; border-radius: 12px; max-width: 80%; }
.user { background: #007bff; color: white; margin-left: auto; }
.bot { background: #f1f1f1; margin-right: auto; }
.input-group { display: flex; gap: 10px; }
input { flex: 1; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 16px; }
button { padding: 12px 24px; background: #007bff; color: white; border: none; border-radius: 8px; cursor: pointer; }
button:hover { background: #0056b3; }
</style></head><body><h1>🤖 My First Chatbot</h1><divid="chat"></div><divclass="input-group"><inputtype="text"id="message"placeholder="Type a message..."onkeypress="if(event.key==='Enter')send()"><buttononclick="send()">Send</button></div><script>
async function send() {
const input = document.getElementById('message');
const chat = document.getElementById('chat');
const message = input.value.trim();
if (!message) return;
chat.innerHTML += '<divclass="message user">' + message + '</div>';
input.value = '';
try {
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message })
});
const reply = await response.text();
chat.innerHTML += '<divclass="message bot">' + reply + '</div>';
} catch (error) {
chat.innerHTML += '<divclass="message bot"style="color:red;">Error: Unable to connect</div>';
}
chat.scrollTop = chat.scrollHeight;
}
</script></body></html>Note: Spring Boot automatically serves files from src/main/resources/static/. Just place your HTML file there and it will be accessible at the root URL.
Run and Test Your Chatbot
You're ready to launch! Start your application and watch your AI chatbot come to life. The first request might take a few seconds as the connection to OpenAI is established.
# Run the application
./mvnw spring-boot:run
# Or with Gradle
./gradlew bootRun
# Test with curlcurl-X POST http://localhost:8080/api/chat \-H"Content-Type: application/json"\-d'{"message": "Hello! What can you do?"}'Expected Results
- ✓Open
http://localhost:8080to see the chat interface - ✓Type a message and press Enter or click Send
- ✓Watch as the AI responds with helpful, contextual answers
🎉 Congratulations!
You've successfully built your first AI chatbot with Spring AI! Your chatbot can now have intelligent conversations using OpenAI's powerful language models. But this is just the beginning—there's so much more you can do.
What you've built is a stateless chatbot—each message is processed independently without memory of previous exchanges. In the real world, conversations require context. In the next tutorial, we'll add conversation memory so your chatbot can remember what was discussed and provide more coherent, personalized responses.