Tags: spring boot
In this blog, we'll explore how to create a simple Spring Boot application that leverages Spring AI for generating responses. We'll build a BooksApi application that can tell us which book won the booker prize for a given year.
Go to start.spring.io
Name your project as BooksApi
Add the dependencies: Spring Web, Spring Boot Dev Tools
Snapshot repositories store development versions of artifacts. The Spring Snapshot Repository contains the latest updates. Add this to your build.gradle
to access the Spring Snapshot Repository and Spring AI dependency:
Add your API key to src/main/resources/application.properties
:
spring.ai.openai.api-key=YOUR_API_KEY
Create controller/BooksController.java
`:
In the above code, openAiClient
is injected through constructor injection, which is a preferred method in Spring for dependency injection. The @Autowired annotation is not required when using constructor injection.
Quick Quiz: What's @RequestMapping Annotation?
PromptTemplate is useful for dynamically constructing prompts with variables. It ensures cleaner code and easier manipulation of the prompt string.
If you go to : http://localhost:8080/books/booker/2003
, it will output something like
The book that won the Booker Prize in 2003 is "Vernon God Little" by DBC Pierre.
Quick Quiz: What's @PathVariable Annotation?
A record class in Java is a concise way to create immutable data objects.
BeanOutputParser is a utility in Spring AI that helps in parsing the output from AI into a Java Bean (in our case, BookerWinner).
parser.getFormat()
returns a string that represents the format in which the AI should return the data, making it easier to parse into the BookerWinner object.
If you go to : http://localhost:8080/books/booker/2003
, it will output something like
{
"title": "Vernon God Little",
"author": "DBC Pierre",
"year": "2003"
}