This blog post will integrate the Spring AI framework into a Java application. We’ll use a simple project that includes a ChatService
and a ChatController
to demonstrate using the Spring AI framework to generate text & image responses and horoscopes based on user input.
Prerequisites
Before we start, make sure you have the following:
- Java Development Kit (JDK) installed
- Familiarity with Spring Framework
- Basic understanding of RESTful APIs
- An OpenAI API key
Obtaining an OpenAI API Key
To use the OpenAI API, you’ll need to sign up for an API key:
- Go to the OpenAI website.
- Sign up for an account if you don’t already have one.
- Navigate to the API section and generate a new API key.
Once you have your API key, you must set it up in your Spring application. The sample code I have in Git has a placeholder where you will need to enter in the API key.
Setting Up the Project
First, let’s set up our project. Create a new Spring Boot project and add the necessary dependencies for Spring AI.
Maven Dependencies
Add the following dependencies to your pom.xml:
1 2 3 4 5 6 7 |
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Add other necessary dependencies here --> </dependencies> |
Configuring the API Key
Add your OpenAI API key to the application.properties file:
1 |
spring.ai.openai.api-key=your_openai_api_key_here |
Replace your_openai_api_key_here
with your actual OpenAI API key.
Implementing the ChatService
The ChatService
class contains methods to process AI prompts and generate horoscopes. Here’s the complete implementation:
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 |
import java.util.Map; import org.springframework.ai.image.ImageModel; import org.springframework.ai.image.ImagePrompt; import org.springframework.ai.openai.OpenAiChatOptions; import org.springframework.ai.openai.OpenAiImageOptions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ChatService { @Autowired private ChatClient chatClient; @Autowired private ImageModel imageModel; public String processPrompt(String prompt, String gptModelName, double temperature) { if (prompt == null || prompt.trim().isEmpty()) { throw new IllegalArgumentException("Prompt cannot be null or empty"); } return chatClient.prompt(new Prompt( prompt, OpenAiChatOptions.builder() .withModel(gptModelName) .withTemperature(temperature) .build() )) .call() .content(); } public String getMyHoroscope(String zodiacSign, int days, String gptModelName, double temperature) { String template = "I am a fortune teller. I can predict your future. Given your zodiac sign {zodiacSign} please tell me my future for the next {days} days?"; PromptTemplate promptTemplate = new PromptTemplate(template); Map<String, Object> params = Map.of( "zodiacSign", zodiacSign, "days", days ); return chatClient.prompt(new Prompt( promptTemplate.render(params), OpenAiChatOptions.builder() .withModel(gptModelName) .withTemperature(temperature) .build() )) .call() .content(); } public String generateImage(String message) { ImagePrompt imagePrompt = new ImagePrompt(message); return imageModel.generate(imagePrompt, OpenAiImageOptions.builder().build()); } } |
processPrompt: This method takes a prompt, model name, and temperature as parameters and returns the AI-generated text response.
getMyHoroscope
: This method generates a horoscope based on the user’s zodiac sign and the specified number of days for which you want to know your future. Note: I do not have to say this, but I will — this is a generic response and nothing to do with your real life or what you should expect in future (just saying!)lgenerateImage
: This method generates an image based on the provided message. It returns the URL where you can view the generated image.
Implementing the ChatController
The ChatController
class exposes REST endpoints to interact with the ChatService
. Here’s the complete implementation:
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 |
package com.tryout.ai; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class ChatController { @Autowired private ChatService chatService; @PostMapping("/chat") public ResponseEntity<ChatResponse> chat(@RequestBody ChatRequest request) { try { String response = chatService.processPrompt(request.getPrompt(), "gpt-4o", 0.7); return ResponseEntity.ok(new ChatResponse(response)); } catch (IllegalArgumentException e) { return ResponseEntity.badRequest() .body(new ChatResponse(e.getMessage())); } } @GetMapping("/image/gen") public String generateImage(@RequestParam String message) { return chatService.generateImage(message); } @PostMapping("/horoscope") public String getMyHoroscope(@RequestBody HoroscopeRequest request) { return chatService.getMyHoroscope(request.zodiacSign(), request.days(), "gpt-4o", 0.7); } } |
Running the Application
To run the application, use the following command:
1 |
./mvnw spring-boot:run |
Using tools like Postman, Insomnia, or cURL, you can test the endpoints.
Conclusion
In this blog post, we demonstrated how to integrate the Spring AI framework into a Java application. We created a ChatService to handle AI prompts and horoscope generation and exposed REST endpoints through a ChatController
. This should give you a good starting point for building more advanced AI-powered Spring AI applications. The code is at https://github.com/thomasma/spring-ai