Spring AI
Ahmed Abdelaziz
Software Engineer Team Leader at IST Networks | Java Champion ??| Java and Web technologies Expert |Solutions Architect | Spring Boot Expert | Microservices | Databases | Expert in GENESYS,CISCO and Sprinklr CC solutions
Spring AI supports ChatGPT, the AI language model by OpenAI. ChatGPT has been instrumental in sparking interest in AI-driven text generation, thanks to its creation of industry-leading text generation models and embeddings.
Prerequisites
You will need to create an API with OpenAI to access ChatGPT models. Create an account at OpenAI signup page and generate the token on the API Keys page. The Spring AI project defines a configuration property named spring.ai.openai.api-key that you should set to the value of the API Key obtained from openai.com. Exporting an environment variable is one way to set that configuration property:
spring.ai.openai.api-key= your key
spring.ai.openai.chat.options.model=gpt-4o
Add Repositories and BOM
Spring AI artifacts are published in Spring Milestone and Snapshot repositories. Refer to the Repositories section to add these repositories to your build system.
To help with dependency management, Spring AI provides a BOM (bill of materials) to ensure that a consistent version of Spring AI is used throughout the entire project. Refer to the Dependency Management section to add the Spring AI BOM to your build system.
Auto-configuration
Spring AI provides Spring Boot auto-configuration for the OpenAI Chat Client. To enable it add the following dependency to your project’s Maven pom.xml file:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
or to your Gradle build.gradle build file.
dependencies {
implementation 'org.springframework.ai:spring-ai-openai-spring-boot-starter'
}
package com.zizo.ai.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
@RestController
@RequestMapping("ai/v1")
public class AiController {
private final ChatClient chatclient ;
public AiController(ChatClient.Builder chatClientBuilder) {
super();
this.chatclient = chatClientBuilder.build();
}
@GetMapping("/film2/{actor}")
public ActorFilms openAIfilm2(@PathVariable String actor) {
return chatclient.prompt().user(u->u.text("best five film for ").param("actor",actor))
.call()
.entity(ActorFilms.class);
}
record ActorFilms (String actor,List<String> movies) {}
}
Response