0% found this document useful (0 votes)
52 views9 pages

Add Generative AI in Your Spring Boot Application - Spring AI - by Zeeshan Adil - Nov, 2023 - Level Up Coding

Add Generative AI in your Spring Boot Application -Spring AI _ by Zeeshan Adil _ Nov, 2023 _ Level Up Coding

Uploaded by

h2oo2h
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views9 pages

Add Generative AI in Your Spring Boot Application - Spring AI - by Zeeshan Adil - Nov, 2023 - Level Up Coding

Add Generative AI in your Spring Boot Application -Spring AI _ by Zeeshan Adil _ Nov, 2023 _ Level Up Coding

Uploaded by

h2oo2h
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

2023. 12. 18.

10:37 Add Generative AI in your Spring Boot Application -Spring AI | by Zeeshan Adil | Nov, 2023 | Level Up Coding

Add Generative AI in your Spring Boot Application


-Spring AI
Zeeshan Adil · Follow
Published in Level Up Coding

6 min read · Nov 20

In this tutorial, we’ll be putting AI to work in some fascinating scenarios using Spring
Boot.

Think of Spring AI as a toolkit for making AI applications. It gives you basic building
blocks that can be easily swapped out with different options. This flexibility lets you tweak
and customize your AI program without having to do a lot of complicated reprogramming.

Apart from the basic building blocks, Spring AI wants to offer extra features to handle
everyday situations like “asking questions about your documents” or “having a
conversation with your documents.” As the tasks become more complicated, Spring AI will
work together with other projects in the Spring family, like Spring Integration, Spring
Batch, and Spring Data.

Spring-AI is extremely fresh and currently lacks a stable version. However, we anticipate
the release of a stable version in the future.

Spring AI introduces the AiClient interface with implementations for OpenAI and Azure
OpenAI.

To know more about OpenAI action in spring boot. Check out my below article:

OpenAI in Action : ChatGPT Integration with Spring Boot

Let’s start coding.. 😊


Dependencies required in pom.xml
To use Spring AI, include the following repository. Keep in mind that it’s an experimental
project, and only snapshot releases are available at this stage.

https://levelup.gitconnected.com/add-generative-ai-in-your-spring-boot-application-spring-ai-12561b1adf08 1/9
2023. 12. 18. 10:37 Add Generative AI in your Spring Boot Application -Spring AI | by Zeeshan Adil | Nov, 2023 | Level Up Coding

<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>

When incorporating OpenAI, you can utilize the following dependency:

<dependency>
<groupId>org.springframework.experimental.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>0.2.0-SNAPSHOT</version>
</dependency>

To employ Azure OpenAI instead of OpenAI, you can include the following dependency:

<dependency>
<groupId>org.springframework.experimental.ai</groupId>
<artifactId>spring-ai-azure-openai-spring-boot-starter</artifactId>
<version>0.2.0-SNAPSHOT</version>
</dependency>

We will use OpenAI in this article.

Create OpenAI API Key


For Spring AI to function, it’s essential to provide the API Key to establish a connection
with OpenAI.

Sign up & create your own OpenAI API key here.

https://levelup.gitconnected.com/add-generative-ai-in-your-spring-boot-application-spring-ai-12561b1adf08 2/9
2023. 12. 18. 10:37 Add Generative AI in your Spring Boot Application -Spring AI | by Zeeshan Adil | Nov, 2023 | Level Up Coding

Add API Key and OpenAI Image Generator URL in application. properties file:

spring.ai.openai.apikey=REPLACE_WITH_YOUR_API_KEY
spring.ai.openai.imageUrl=https://api.openai.com/v1/images/generations

Project Structure :

https://levelup.gitconnected.com/add-generative-ai-in-your-spring-boot-application-spring-ai-12561b1adf08 3/9
2023. 12. 18. 10:37 Add Generative AI in your Spring Boot Application -Spring AI | by Zeeshan Adil | Nov, 2023 | Level Up Coding

Create SpringAIService under services package:

@Service
public class SpringAIService {

@Autowired
AiClient aiClient;

@Value("{spring.ai.openai.apikey}")
private String apiKey;

@Value("{spring.ai.openai.imageUrl}")
private String openAIImageUrl;

https://levelup.gitconnected.com/add-generative-ai-in-your-spring-boot-application-spring-ai-12561b1adf08 4/9
2023. 12. 18. 10:37 Add Generative AI in your Spring Boot Application -Spring AI | by Zeeshan Adil | Nov, 2023 | Level Up Coding
public String getJoke(String topic){
PromptTemplate promptTemplate = new PromptTemplate("""
Crafting a compilation of programming jokes for my website. Would you like me to create a joke about {t
""");
promptTemplate.add("topic", topic);
return this.aiClient.generate(promptTemplate.create()).getGeneration().getText();
}

public String getBestBook(String category, String year) {


PromptTemplate promptTemplate = new PromptTemplate("""
I want to research some books. How about you give me a book about {category} in {year} to get started?
But pick the best best you can think of. I'm a book critic, after all. Ratings are a good place to star
And who wrote it? And who help it? Can you give me a short plot summary and also it's name?
But don't give me too much information. I want to be surprised.
And please give me these details in the following JSON format: category, year, bookName, author, review
""");
Map.of("category", category, "year", year).forEach(promptTemplate::add);
AiResponse generate = this.aiClient.generate(promptTemplate.create());
return generate.getGeneration().getText();
}

public InputStreamResource getImage(@RequestParam(name = "topic") String topic) throws URISyntaxException {


PromptTemplate promptTemplate = new PromptTemplate("""
I am really board from online memes. Can you create me a prompt about {topic}.
Elevate the given topic. Make it classy.
Make a resolution of 256x256, but ensure that it is presented in json.
I desire only one creation. Give me as JSON format: prompt, n, size.
""");
promptTemplate.add("topic", topic);
String imagePrompt = this.aiClient.generate(promptTemplate.create()).getGeneration().getText();

RestTemplate restTemplate = new RestTemplate();


HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + apiKey);
headers.add("Content-Type", "application/json");
HttpEntity<String> httpEntity = new HttpEntity<>(imagePrompt,headers);

String imageUrl = restTemplate.exchange(openAIImageUrl, HttpMethod.POST, httpEntity, GeneratedImage.class)


.getBody().getData().get(0).getUrl();
byte[] imageBytes = restTemplate.getForObject(new URI(imageUrl), byte[].class);
assert imageBytes != null;
return new InputStreamResource(new java.io.ByteArrayInputStream(imageBytes));
}
}

Let’s understand the code step by step.

1. Autowired Dependencies:

The class uses the @Autowired annotation to inject an instance of the AiClient class.

AiClient is an interface that communicates with OpenAI service.


Open in app Sign up Sign in

2. getJoke Method:

There’s a method named getJoke that takes a topic as a parameter.

It creates a PromptTemplate object with a predefined template for crafting


programming jokes.
https://levelup.gitconnected.com/add-generative-ai-in-your-spring-boot-application-spring-ai-12561b1adf08 5/9
2023. 12. 18. 10:37 Add Generative AI in your Spring Boot Application -Spring AI | by Zeeshan Adil | Nov, 2023 | Level Up Coding

The {topic} placeholder in the template is replaced with the actual topic parameter.

The AI client generates a response based on this prompt, and the text of the response
is returned.

3. getBestBook Method:

Another method named getBestBook takes category and year parameters.

It follows a similar pattern, using a template to request information about the best
book in a certain category and year.

The placeholders {category} and {year} are replaced with the provided parameters.

The AI client generates a response, and the text of the response is returned.

4. getImage Method:

It takes a topic as a parameter and request an image related to that topic.

It uses a prompt template to form a request for image creation, replacing {topic} with
the actual topic.

The generated prompt is sent to an AI service using AiClient , and the resulting image
URL is obtained.

The image is then fetched from the URL and converted into an InputStreamResource for
further processing.

Create GeneratedImage entity under models package:

public class GeneratedImage {


private List<ImageUrl> data;

public List<ImageUrl> getData() {


return data;
}

public void setData(List<ImageUrl> data) {


this.data = data;
}

public static class ImageUrl {


private String url;

public String getUrl() {


return url;
}

https://levelup.gitconnected.com/add-generative-ai-in-your-spring-boot-application-spring-ai-12561b1adf08 6/9
2023. 12. 18. 10:37 Add Generative AI in your Spring Boot Application -Spring AI | by Zeeshan Adil | Nov, 2023 | Level Up Coding
public void setUrl(String url) {
this.url = url;
}
}
}

Create SpringAIController under controllers package:

@RestController
@RequestMapping("/api/v1")
public class SpringAIController {

@Autowired
SpringAIService aiService;

@GetMapping("/joke")
public String getJoke(@RequestParam String topic) {
return aiService.getJoke(topic);
}

@GetMapping("/book")
public String getBook(@RequestParam(name = "category") String category, @RequestParam(name = "year") String year) {
return aiService.getBestBook(category, year);
}

@GetMapping(value = "/image", produces = "image/jpeg")


public ResponseEntity<InputStreamResource> getImage(@RequestParam(name = "topic") String topic) throws URISyntaxExc
return ResponseEntity.ok().body(aiService.getImage(topic));
}
}

In controller class, I’ve created 3 endpoints —

1. /api/v1/joke : It will give joke based on your topic provided. (Spring AI in action)

https://levelup.gitconnected.com/add-generative-ai-in-your-spring-boot-application-spring-ai-12561b1adf08 7/9
2023. 12. 18. 10:37 Add Generative AI in your Spring Boot Application -Spring AI | by Zeeshan Adil | Nov, 2023 | Level Up Coding

2. /api/v1/book : It will give you a book details based on category and year provided by you
(Spring Ai in Action)

😊
3. /api/v1/image : It will generate an image for you what you have asked from AI. (Spring
AI in Action Again … )

https://levelup.gitconnected.com/add-generative-ai-in-your-spring-boot-application-spring-ai-12561b1adf08 8/9
2023. 12. 18. 10:37 Add Generative AI in your Spring Boot Application -Spring AI | by Zeeshan Adil | Nov, 2023 | Level Up Coding

👏
Spring AI is awesome. If you find this article informative and beneficial, please consider
showing your appreciation by giving it a clap . Feel free to share this article with your
peers. Your support and knowledge sharing within the developer community are highly
valued.

You can find the source code here…

GitHub - zees007/spring-ai-in-action
Contribute to zees007/spring-ai-in-action development by creating an
account on GitHub.
github.com

https://levelup.gitconnected.com/add-generative-ai-in-your-spring-boot-application-spring-ai-12561b1adf08 9/9

You might also like