Spring Boot conformity Spring AI Implement project access to chatgpt
Tags: springboot, spring, springai, java
Published: 2024-03-12 13:26:26

## preface

With the rapid development of AI technology, more and more applications are starting to integrate AI capabilities to provide a smarter, more personalized experience. The advent of open large language models such as ChatGPT has made the development of natural language processing and dialogue systems easier and more popular. These technologies have shown great potential in social media, customer service, education, and more, and are essential for improving user experience and productivity.

## advantage	

In the past, open ai has provided a corresponding Java integration solution: <https://github.com/TheoKanning/openai-java>, but the release of the beta version of Spring AI has provided us with a new integration direction, compared with the original method, Spring AI has the following advantages:

1. **Faster development cycles：** Spring AI's native ecosystem encapsulation enables developers to integrate AI capabilities faster and accelerate project iteration cycles.

2. **Seamless integration with existing technology stacks:** If your project is already built on Spring Boot, it will be easier to use Spring AI without introducing an additional technology stack and making better use of the technology and resources you already have.

3. **Strong Community Support:** Spring Framework has a large community of support and an active developer community, which can provide more technical support and solutions for developers.

## Brief introduction

The purpose of this article is to provide readers with a basic use case to help learn how to integrate Spring AI into a Spring Boot application to implement intelligent functionality. Through this article, readers will learn how to leverage existing AI technologies to add automation and intelligence to their applications, thereby improving the user experience and the value of the application. Next, we will introduce in detail how to configure and use Spring AI in your Spring Boot project to bring you a more intelligent application experience.

## Preparation

- jdk 17
- Spring Boot 3.2.0
- maven 3.9

## steps

### 1. Import dependencies

pom.xml Write the following：

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

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>0.8.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
```

### 2. Configure your own api-key and base-url

application.yml：

```yaml
server:
  port: 9876

spring:
  ai:
    openai:
      api-key: sk-xxx # The api-key of the application
      base-url: https://api.openai.com/ # default
      chat:
        # Specifying an API Configuration (Overriding the Global Configuration)
        api-key: sk-xxx
        base-url: https://api.openai.com/
        options:
          model: gpt-3.5-turbo 
```

### 3. Configure your own OpenAI chat client

It should be noted here that after the api-key and base-url have been configured in the application.yml file, they can be automatically assembled directly at the service layer, but only one parameter type of client can be configured< Reference](https://docs.spring.io/spring-ai/reference/api/clients/openai-chat.html#_chat_properties)>

OpenAiChatConfig.java

```java
@Configuration
public class OpenAiChatConfig {

    @Value("${spring.ai.openai.chat.api-key}")
    private String apiKey;
    @Value("${spring.ai.openai.chat.base-url}")
    private String baseUrl;
    
    @Bean("myOpenAiChatClient")
    public OpenAiChatClient myOpenAiChatClient(){
        OpenAiApi openAiApi = new OpenAiApi(baseUrl, apiKey);
        return new OpenAiChatClient(openAiApi);
    }
}
```

### 4. API calls

OpenAiChatService.java

```java
public interface OpenAiChatService {
    String easyChat(String message);
}
```

OpenAiChatServiceImpl.java

```java
@Service
public class OpenAiChatServiceImpl implements OpenAiChatService {
    @Resource(name = "myOpenAiChatClient")
    private OpenAiChatClient chatClient;
    
    @Override
    public String easyChat(String message) {
        Prompt prompt = new Prompt(message);
        return chatClient.call(prompt).getResult().getOutput().getContent();
    }
}
```

ChatController.java

```java
@RestController
@RequestMapping("/ai")
public class ChatController {
    @Resource
    private OpenAiChatService openAiChatService;

    @GetMapping(value = "/easyChat",params = "message")
    public String easyChat(@RequestParam String message){
        return openAiChatService.easyChat(message);
    }
}
```

### 5. Demonstration of the results

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u9qn651gzwxx2xw19yel.png)

## summary
Spring AI is a native encapsulation designed to provide a solution for Spring Boot applications to quickly integrate AI capabilities. With perfect integration with the Spring framework, Spring AI can take advantage of the dependency injection provided by Spring, making it easier and more flexible to integrate AI capabilities. With Spring AI, development teams are able to implement intelligent applications faster and provide users with a better experience.