Skip to main content

Spring 5 and Spring AI

warning

This guide applies to Spring AI 1.x. Spring AI 2.0 requires Spring Boot 4.0 / Spring Framework 7.0 and cannot be loaded in a Spring 5 or Spring Boot 3 context at all, so none of the workarounds below apply if you need Spring AI 2.0.

If your project is using Spring 6 and Spring Boot 3, then the life is much easier when integrating with Spring AI 1.x. However, if you are stuck with Spring 5 and Spring Boot 2 for whatever reasons, then it's not that easy to using Spring AI. Here are some tips.

No Spring Boot Starters​

Don't use Spring Boot starters provided by Spring AI. They will include too many dependencies and cause conflicts with existing libraries. Just use spring-ai-core and other modules.

OpenAI ChatModel and EmbeddingModel​

The ChatModel and EmbeddingModel for OpenAI provided by Spring AI uses RestClient, which is only available in Spring 6.

Use my ChatModel implementation for OpenAI. See more details at here.

Prompt from Resource​

When building a Prompt, the user method accepts a Spring Resource as the content. In the implementation, the getContentAsString method of Resource is used to get content. However, this getContentAsString method is only available starting Spring 6.0.5.

In Spring 5, we can copy the implementation of getContentAsString method to the loadResourceContent method shown below. For a Resource, use loadResourceContent to get its content, then pass the text content to user method.

public static String loadResourceContent(Resource resource, Charset charset) {
return FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream(), charset));
}