DEV Community

superhandsomeg
superhandsomeg

Posted on

3 1 1 1 2

Spring Boot conformity Spring AI Implement project access to chatgpt

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:

<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>
Enter fullscreen mode Exit fullscreen mode

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

application.yml:

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 
Enter fullscreen mode Exit fullscreen mode

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

@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);
    }
}
Enter fullscreen mode Exit fullscreen mode

4. API calls

OpenAiChatService.java

public interface OpenAiChatService {
    String easyChat(String message);
}
Enter fullscreen mode Exit fullscreen mode

OpenAiChatServiceImpl.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();
    }
}
Enter fullscreen mode Exit fullscreen mode

ChatController.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);
    }
}
Enter fullscreen mode Exit fullscreen mode

5. Demonstration of the results

Image description

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (1)

Collapse
 
roc9universe profile image
roc9-universe

Finally found the desired resource

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay