Streamlining Language Translation with Spring Boot and ChatGPT API Integration

What is ChatGPT?

ChatGPT is a large language model developed by OpenAI. It is a deep learning-based model that has been trained on a large corpus of text data and can be used to generate text in a variety of styles and formats.

ChatGPT is part of the GPT (Generative Pretrained Transformer) series of models developed by OpenAI, which are designed to generate text that is semantically and stylistically similar to text in a given context. ChatGPT is specifically designed for chatbot applications and has been trained to respond to natural language inputs in a conversational manner.

Overall, ChatGPT represents a significant advance in the field of natural language processing and has the potential to revolutionize the way we interact with computers using natural language.

In this article we are going to integrate ChatGPT’s Language translation API with Springboot.

In order to use ChatGPT’s API, first we need to create an API Key. (Click here to generate API key).

Project Structure:

First, Let us create model classes for sending request and receiving response from ChatGPT API.

Note: Variables declared in model classes are already defined by ChatGPT, not custom variables. Please do use same variables.

OpenAIRequest.java

package com.javainfinite.openai.model;

import java.util.List;

public class OpenAIRequest {

    private String model;
    private String prompt;
    private Integer temperature;
    private Integer max_tokens;
    private Integer top_p;
    private Integer frequency_penalty;
    private Integer presence_penalty;
    private List<String> stop;

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getPrompt() {
        return prompt;
    }

    public void setPrompt(String prompt) {
        this.prompt = prompt;
    }

    public Integer getTemperature() {
        return temperature;
    }

    public void setTemperature(Integer temperature) {
        this.temperature = temperature;
    }

    public Integer getMax_tokens() {
        return max_tokens;
    }

    public void setMax_tokens(Integer max_tokens) {
        this.max_tokens = max_tokens;
    }

    public Integer getTop_p() {
        return top_p;
    }

    public void setTop_p(Integer top_p) {
        this.top_p = top_p;
    }

    public Integer getFrequency_penalty() {
        return frequency_penalty;
    }

    public void setFrequency_penalty(Integer frequency_penalty) {
        this.frequency_penalty = frequency_penalty;
    }

    public Integer getPresence_penalty() {
        return presence_penalty;
    }

    public void setPresence_penalty(Integer presence_penalty) {
        this.presence_penalty = presence_penalty;
    }

    public List<String> getStop() {
        return stop;
    }

    public void setStop(List<String> stop) {
        this.stop = stop;
    }
}

OpenAIResponse.java

package com.javainfinite.openai.model;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Date;
import java.util.List;

public class OpenAIResponse {

    private String id;
    private String object;
    private Date creation;
    private String model;
    @JsonProperty("choices")
    private List<Choices> choicesList;
    @JsonProperty("usage")
    private Usage usage;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getObject() {
        return object;
    }

    public void setObject(String object) {
        this.object = object;
    }

    public Date getCreation() {
        return creation;
    }

    public void setCreation(Date creation) {
        this.creation = creation;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public List<Choices> getChoicesList() {
        return choicesList;
    }

    public void setChoicesList(List<Choices> choicesList) {
        this.choicesList = choicesList;
    }

    public Usage getUsage() {
        return usage;
    }

    public void setUsage(Usage usage) {
        this.usage = usage;
    }
}

Choices.java

package com.javainfinite.openai.model;

public class Choices {

    private String text;
    private int index;
    private String logprobs;
    private String finish_reason;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public String getLogprobs() {
        return logprobs;
    }

    public void setLogprobs(String logprobs) {
        this.logprobs = logprobs;
    }

    public String getFinish_reason() {
        return finish_reason;
    }

    public void setFinish_reason(String finish_reason) {
        this.finish_reason = finish_reason;
    }
}

Usage.java

package com.javainfinite.openai.model;

public class Usage {

    private int prompt_tokens;
    private int completion_tokens;
    private int total_tokens;

    public int getPrompt_tokens() {
        return prompt_tokens;
    }

    public void setPrompt_tokens(int prompt_tokens) {
        this.prompt_tokens = prompt_tokens;
    }

    public int getCompletion_tokens() {
        return completion_tokens;
    }

    public void setCompletion_tokens(int completion_tokens) {
        this.completion_tokens = completion_tokens;
    }

    public int getTotal_tokens() {
        return total_tokens;
    }

    public void setTotal_tokens(int total_tokens) {
        this.total_tokens = total_tokens;
    }
}

Now let us create an utility class that holds all our constants,

package com.javainfinite.openai.util;

public class OpenAIConstants {

    public static final String TOKEN = "Bearer "+{{Use the API key generated from link above in the first Section}};
    public static final String MODEL = "text-davinci-003";
    public static final String AUTHORIZATION = "Authorization";
    public static final String TRANSLATE = "Translate this into 1.";

}

OpenAITranslationService.java

package com.javainfinite.openai.service;

import com.javainfinite.openai.model.OpenAIRequest;
import com.javainfinite.openai.model.OpenAIResponse;
import com.javainfinite.openai.util.OpenAIConstants;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class OpenAITranslationService {

    private RestTemplate restTemplate;

    public OpenAITranslationService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public OpenAIResponse translate(String language, String text) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(OpenAIConstants.AUTHORIZATION, OpenAIConstants.TOKEN);

        OpenAIRequest ai = new OpenAIRequest();
        ai.setModel(OpenAIConstants.MODEL);
        ai.setPrompt(OpenAIConstants.TRANSLATE + language + ": " + text);
        ai.setFrequency_penalty(0);
        ai.setPresence_penalty(0);
        HttpEntity entity = new HttpEntity(ai, headers);

        ResponseEntity<OpenAIResponse> data = restTemplate.exchange("https://api.openai.com/v1/completions", HttpMethod.POST, entity, OpenAIResponse.class);
        return data.getBody();
    }
}

Prompt should be exactly in same format with “:” followed by the text that needs to be translated.

OpenAIController.java

package com.javainfinite.openai.controller;

import com.javainfinite.openai.model.Choices;
import com.javainfinite.openai.model.OpenAIResponse;
import com.javainfinite.openai.service.OpenAITranslationService;

import org.springframework.web.bind.annotation.PostMapping;
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.stream.Collectors;

@RestController
@RequestMapping("/openai")
public class OpenAIController {

    private OpenAITranslationService service;

    public OpenAIController(OpenAITranslationService service) {
        this.service = service;
    }



    @PostMapping("/translate")
    public List<String> translate(@RequestParam String language, @RequestParam String text) {
        OpenAIResponse response = service.translate(language, text);
        return response.getChoicesList().stream().map(Choices::getText).collect(Collectors.toList());
    }

}

Now our main application,

package com.javainfinite.openai;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class OpenaiApplication {

	public static void main(String[] args) {
		SpringApplication.run(OpenaiApplication.class, args);
	}

	@Bean
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}
}

Now let us try to run this application and check the output with Postman,

First lets try Spanish,

Lets try French,

German,

We have successfully integrated ChatGPT’s language translation API with our Springboot application!

By Sri

Leave a Reply

Your email address will not be published. Required fields are marked *