Conectar Spring Boot con Chat GPT

ChatGPT es un modelo de lenguaje artificial desarrollado por OpenAI, basado en la arquitectura GPT-3.5 (Ya disponible por estos días as con GPT-4). Es capaz de generar respuestas coherentes y contextualizadas a partir de las entradas de texto que recibe. ChatGPT puede ser utilizado en diversos contextos, como asistentes virtuales, chatbots y sistemas de recomendación personalizados, entre otros. Además, su capacidad para procesar y comprender el lenguaje natural lo convierte en una herramienta útil para tareas de análisis de texto y procesamiento de lenguaje natural en general.

En este artículo veremos cómo desarrollar una API usando Spring Boot y conectarla con ChatGPT, el resultado final será una aplicación web que ofrecerá un API REST con los endpoints necesarios para interactuar con ChatGPT. Esto abre un mundo de posibilidades para luego conectar cualquier frontend como páginas web y/o aplicaciones móviles con esta tecnología.

Toda la explicación esta disponible acá:

Dependencias del proyecto

Hemos creado un proyecto Spring Boot basado en Maven, las dependencias son:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.sacavix.chatgpt</groupId>
	<artifactId>springboot-chatgpt</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot-chatgpt</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>io.github.flashvayne</groupId>
			<artifactId>chatgpt-spring-boot-starter</artifactId>
			<version>1.0.0</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>

	</build>

</project>

De las dependencias anteriores resaltar la biblioteca: chatgpt-spring-boot-starter, un starter comunitario que permite conectar con chat-gpt, es simplemente una clase que se encarga de hacer las llamadas http/rest por nosotros a la API de OpenAI.

Código principal

Una vez que agregamos la biblioteca, por el mecanismo de configuración de Spring Boot ya se crea en el contexto de Spring el bean chatGPTService, el cual podemos inyectar donde deseemos para comenzar a usarlo.

@RestController
@RequestMapping("/chatboot")
public class HelloGPTController implements InitializingBean {

    @Autowired
    private ChatgptService chatgptService;

    @Override
    public void afterPropertiesSet() {
        System.out.println(" ===== Starting Chat GPT Boot ==== ");
    }

    @GetMapping("/chat")
    public String chatWith(@RequestParam String message) {
        System.out.println(message);
        return chatgptService.sendMessage(message);
    }

    @GetMapping("/prompt")
    public ChatResponse prompt(@RequestParam String message) {

        //The maximum number of tokens to generate in the completion.The token count of your prompt plus max_tokens cannot exceed the model's context length. Most models have a context length of 2048 tokens (except for the newest models, which support 4096).
        Integer maxTokens = 300;

        // GPT-3 models can understand and generate natural language. We offer four main models with different levels of power suitable for different tasks. Davinci is the most capable model, and Ada is the fastest.
        String model = "text-davinci-003";

        // What sampling temperature to use. Higher values means the model will take more risks. Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer.We generally recommend altering this or top_p but not both.
        Double temperature = 0.5;

        //An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.We generally recommend altering this or temperature but not both.
        Double topP = 1.0;

        ChatRequest chatRequest = new ChatRequest(model, message, maxTokens,temperature,topP);
        ChatResponse res =  chatgptService.sendChatRequest(chatRequest);
        System.out.println("Response was: " + res.toString());
        return res;

    }
}
Footer

Adicionalmente, necesitamos settear algunas configuraciones, especialmente la api key que nos permite conectarnos a ChatGPT, para ello puedes fijarte en el fichero de configuración.

Todo el código esta disponible acá: https://github.com/yoandypv/springboot-chatgpt

Espero te sea útil el articulo.