Table of Contents
1 Introduction to Spring AI
2 Create a Spring Boot project and write an OpenAI controller example
3 Use the Prompt class to build prompt information
4 Testing the application
Home Technology peripherals AI A new programming paradigm, when Spring Boot meets OpenAI

A new programming paradigm, when Spring Boot meets OpenAI

Feb 01, 2024 pm 09:18 PM
ai spring openai

In 2023, AI technology has become a hot topic and has had a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception.

With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "Spring AI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "Spring AI", developers can more easily build applications with AI functions, making them easier to use and operate. This not only helps improve development efficiency, but also accelerates the popularization and application of AI technology. In short, "Spring AI" brings new possibilities to the development of AI applications, providing developers with simpler and more intuitive tools and frameworks.

This article will briefly introduce the Spring AI framework and some engineering tips for using the framework. Developers can use these tips to better structure prompt information and fully utilize the capabilities of Spring AI.

1 Introduction to Spring AI

编程新范式,当Spring Boot遇上OpenAISpring AI is created and written by M K Pavan Kumar

Spring AI is a tool designed to simplify AI applications Developed project inspired by the Python projects LangChain and LlamaIndex. However, Spring AI is not a simple copy. Its core idea is to open generative AI applications to users of various programming languages, not just Python language enthusiasts. This means developers can build AI applications using a language they are familiar with without having to learn the Python language. With Spring AI, developers can more easily harness the power of AI to solve a variety of problems, regardless of which programming language they use. This will facilitate broader AI application development and provide developers with more flexibility and choice.

The core goal of Spring AI is to provide the basic building blocks for building AI-driven applications. These building blocks are highly flexible and components can be easily swapped with virtually no modifications to the code. One example is that Spring AI introduces a component called the ChatClient interface, which is compatible with OpenAI and Azure OpenAI technologies. This allows developers to switch between different AI service providers without changing the code, making development and integration more convenient.

At its core, Spring AI provides reliable building blocks for developing artificial intelligence-based applications. The elasticity of these modules enables smooth swapping of components without requiring extensive modifications to the coding. One example is Spring AI's introduction of the ChatClient interface, which is compatible with OpenAI and Azure OpenAI, allowing developers to easily talk to both platforms. This compatibility allows developers to choose the appropriate platform based on actual needs without having to rewrite code. With Spring AI, developers can build AI-driven applications more efficiently.

Spring AI goes beyond basic building blocks and focuses on providing more advanced solutions. For example, it can support typical scenarios such as "questions and answers about one's own documents" or "interactive chat using documents". As application needs grow, Spring AI plans to work closely with other components of the Spring ecosystem such as Spring Integration, Spring Batch and Spring Data to meet more complex business needs.

2 Create a Spring Boot project and write an OpenAI controller example

First generate the Spring Boot project in the IDE and keep the following content in the application.properties file:

spring.ai.openai.api-key=<YOUR\_OPENAI\_API\_KEY>
Copy after login

Below Write a controller named OpenAIController.java:

package com.vas.springai.controller;import org.springframework.ai.client.AiClient;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/api/v1")public class OpenAIController {private final AiClient aiClient;public OpenAIController(AiClient aiClient) {this.aiClient = aiClient;}}
Copy after login

3 Use the Prompt class to build prompt information

The prompt class is a structured holder of a sequence of message objects, each message represents a prompt a part of. These messages have different roles and purposes in the prompt, and their content varies. Includes user questions, AI-generated responses, relevant contextual details, and more. This setup facilitates complex and sophisticated human-computer interactions since the prompt consists of multiple messages with specific functions.

@GetMapping("/completion")public String completion(@RequestParam(value = "message") String message){return this.aiClient.generate(message);}
Copy after login

However, aiClient's generate method does not only accept plain text as a parameter, it can also accept objects of the Prompt class as parameters, as shown below. Now, this method returns an instance of type AiResponse, not simple text.

@GetMapping("/completion")public AiResponse completion(@RequestParam(value = "message") String message){ PromptTemplate promptTemplate = new PromptTemplate("translate the given english sentence sentence into french {query}"); Prompt prompt = promptTemplate.create(Map.of("query", message)); return this.aiClient.generate(prompt);}
Copy after login

In addition, the Prompt class also provides an overloaded constructor that can accept a sequence of Message type instances with different roles and intentions as parameters. This can better organize and manage prompt information and facilitate subsequent processing and use. Below is a sample code showing how to use this overloaded constructor to merge everything.

package com.vas.springai.controller;import org.springframework.ai.client.AiClient;import org.springframework.ai.client.Generation;import org.springframework.ai.prompt.Prompt;import org.springframework.ai.prompt.PromptTemplate;import org.springframework.ai.prompt.SystemPromptTemplate;import org.springframework.ai.prompt.messages.Message;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import java.util.List;import java.util.Map;@RestController@RequestMapping("/api/v1")public class OpenAIController {private final AiClient aiClient;public OpenAIController(AiClient aiClient) {this.aiClient = aiClient;}@GetMapping("/completion")public List<Generation> completion(@RequestParam(value = "message") String message) {String systemPrompt = """You are a helpful AI assistant that helps people translate given text from english to french.Your name is TranslateProYou should reply to the user's request with your name and also in the style of a professional.""";SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPrompt);Message systemMessage = systemPromptTemplate.createMessage();PromptTemplate promptTemplate = new PromptTemplate("translate the given english sentence sentence into french {query}");Message userMessage = promptTemplate.createMessage(Map.of("query", message));Prompt prompt = new Prompt(List.of(systemMessage, userMessage));return this.aiClient.generate(prompt).getGenerations();}}
Copy after login

4 Testing the application

You can use any open tool available on the market to test the application, such as postman, insomnia, Httpie, etc.

编程新范式,当Spring Boot遇上OpenAI picture

The above is the detailed content of A new programming paradigm, when Spring Boot meets OpenAI. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to create an oracle database How to create an oracle database How to create an oracle database How to create an oracle database Apr 11, 2025 pm 02:33 PM

Creating an Oracle database is not easy, you need to understand the underlying mechanism. 1. You need to understand the concepts of database and Oracle DBMS; 2. Master the core concepts such as SID, CDB (container database), PDB (pluggable database); 3. Use SQL*Plus to create CDB, and then create PDB, you need to specify parameters such as size, number of data files, and paths; 4. Advanced applications need to adjust the character set, memory and other parameters, and perform performance tuning; 5. Pay attention to disk space, permissions and parameter settings, and continuously monitor and optimize database performance. Only by mastering it skillfully requires continuous practice can you truly understand the creation and management of Oracle databases.

How to create oracle database How to create oracle database How to create oracle database How to create oracle database Apr 11, 2025 pm 02:36 PM

To create an Oracle database, the common method is to use the dbca graphical tool. The steps are as follows: 1. Use the dbca tool to set the dbName to specify the database name; 2. Set sysPassword and systemPassword to strong passwords; 3. Set characterSet and nationalCharacterSet to AL32UTF8; 4. Set memorySize and tablespaceSize to adjust according to actual needs; 5. Specify the logFile path. Advanced methods are created manually using SQL commands, but are more complex and prone to errors. Pay attention to password strength, character set selection, tablespace size and memory

How to write oracle database statements How to write oracle database statements Apr 11, 2025 pm 02:42 PM

The core of Oracle SQL statements is SELECT, INSERT, UPDATE and DELETE, as well as the flexible application of various clauses. It is crucial to understand the execution mechanism behind the statement, such as index optimization. Advanced usages include subqueries, connection queries, analysis functions, and PL/SQL. Common errors include syntax errors, performance issues, and data consistency issues. Performance optimization best practices involve using appropriate indexes, avoiding SELECT *, optimizing WHERE clauses, and using bound variables. Mastering Oracle SQL requires practice, including code writing, debugging, thinking and understanding the underlying mechanisms.

How to add, modify and delete MySQL data table field operation guide How to add, modify and delete MySQL data table field operation guide Apr 11, 2025 pm 05:42 PM

Field operation guide in MySQL: Add, modify, and delete fields. Add field: ALTER TABLE table_name ADD column_name data_type [NOT NULL] [DEFAULT default_value] [PRIMARY KEY] [AUTO_INCREMENT] Modify field: ALTER TABLE table_name MODIFY column_name data_type [NOT NULL] [DEFAULT default_value] [PRIMARY KEY]

What are the integrity constraints of oracle database tables? What are the integrity constraints of oracle database tables? Apr 11, 2025 pm 03:42 PM

The integrity constraints of Oracle databases can ensure data accuracy, including: NOT NULL: null values ​​are prohibited; UNIQUE: guarantee uniqueness, allowing a single NULL value; PRIMARY KEY: primary key constraint, strengthen UNIQUE, and prohibit NULL values; FOREIGN KEY: maintain relationships between tables, foreign keys refer to primary table primary keys; CHECK: limit column values ​​according to conditions.

Detailed explanation of nested query instances in MySQL database Detailed explanation of nested query instances in MySQL database Apr 11, 2025 pm 05:48 PM

Nested queries are a way to include another query in one query. They are mainly used to retrieve data that meets complex conditions, associate multiple tables, and calculate summary values ​​or statistical information. Examples include finding employees above average wages, finding orders for a specific category, and calculating the total order volume for each product. When writing nested queries, you need to follow: write subqueries, write their results to outer queries (referenced with alias or AS clauses), and optimize query performance (using indexes).

How to configure Debian Apache log format How to configure Debian Apache log format Apr 12, 2025 pm 11:30 PM

This article describes how to customize Apache's log format on Debian systems. The following steps will guide you through the configuration process: Step 1: Access the Apache configuration file The main Apache configuration file of the Debian system is usually located in /etc/apache2/apache2.conf or /etc/apache2/httpd.conf. Open the configuration file with root permissions using the following command: sudonano/etc/apache2/apache2.conf or sudonano/etc/apache2/httpd.conf Step 2: Define custom log formats to find or

What does oracle do What does oracle do Apr 11, 2025 pm 06:06 PM

Oracle is the world's largest database management system (DBMS) software company. Its main products include the following functions: relational database management system (Oracle database) development tools (Oracle APEX, Oracle Visual Builder) middleware (Oracle WebLogic Server, Oracle SOA Suite) cloud service (Oracle Cloud Infrastructure) analysis and business intelligence (Oracle Analytics Cloud, Oracle Essbase) blockchain (Oracle Blockchain Pla

See all articles