I’m using a trained model of ChatGPT code that works just fine within ChatGPT Playground, but when Iv try to use it with this code I developed I don’t get the same results that I get on the ChatGPT Playground.
This is my code:
package com.em.tatamaster.dev.apichatgpt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApiChatgptApplication {
public static void main(String[] args) {
SpringApplication.run(ApiChatgptApplication.class, args);
}
}
The Coontroller:
package com.em.tatamaster.dev.apichatgpt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ChatController {
@Qualifier("openaiRestTemplate")
@Autowired
private RestTemplate restTemplate;
@Value("${openai.model}")
private String model;
@Value("${openai.api.url}")
private String apiUrl;
@PostMapping("/chat")
public String chat(@RequestParam String prompt) {
ChatRequest request = new ChatRequest(model, prompt);
request.setN(1); // Asegurar que n es al menos 1
ChatResponse response = restTemplate.postForObject(apiUrl, request, ChatResponse.class);
if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) {
return "No response";
}
return response.getChoices().get(0).getMessage().getContent();
}
}
This is the version of the code that i’m not sure if it’s meant to be like this because within it I’m sending a enhanced prompt that uses the prommpt obtained by the other part of the project but my confusion is because When I send the prommpt obtained by the other part of the project, I don’t need to provide the enhancedPrompt but I’m going to leave the code like this so you can understand what I’m trying to obtain.
package com.em.tatamaster.dev.apichatgpt;
import java.util.ArrayList;
import java.util.List;
public class ChatRequest {
private String model;
private List<Message> messages;
private int n = 1; // Valor predeterminado de 1
private double temperature;
public ChatRequest(String model, String prompt) {
this.model = model;
this.messages = new ArrayList<>();
// Agregando el texto adicional al prompt
String enhancedPrompt = prompt + " Retorna el nombre, apellido en el siguiente formato: " +
"{"nombre":"valor", "apellidos":"valor", "genero":"valor", " +
""fechaDeNacimiento":"valor", "fechaDeExpedicion": "valor", "fechaDeExpiracion": "valor", " +
""numeroDui": "valor", "departamento":"valor", "municipio": "valor", "tipoSangre": "valor", " +
""estadoFamiliaar": "valor", "carcteristicasEspeciales": "valor", "profesion": "valor"}";
this.messages.add(new Message("user", enhancedPrompt));
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public List<Message> getMessages() {
return messages;
}
public void setMessages(List<Message> messages) {
this.messages = messages;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public double getTemperature() {
return temperature;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
}
This is the ChatResponse:
package com.em.tatamaster.dev.apichatgpt;
import java.util.List;
public class ChatResponse {
private List<Choice> choices;
public ChatResponse() {
super();
}
public ChatResponse(List<Choice> choices) {
super();
this.choices = choices;
}
public List<Choice> getChoices() {
return choices;
}
public void setChoices(List<Choice> choices) {
this.choices = choices;
}
public static class Choice {
private int index;
private Message message;
public Choice() {
super();
}
public Choice(int index, Message message) {
super();
this.index = index;
this.message = message;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
}
}
This is the Message class:
package com.em.tatamaster.dev.apichatgpt;
public class Message {
private String role;
private String content;
public Message(String role, String content) {
super();
this.role = role;
this.content = content;
}
public Message() {
super();
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
And this is the OpenAIRestTemplateConfig class:
package com.em.tatamaster.dev.apichatgpt;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class OpenAIRestTemplateConfig {
@Value("${openai.api.key}")
private String openaiApiKey;
@Bean
@Qualifier("openaiRestTemplate")
public RestTemplate openaiRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add((request, body, execution) -> {
request.getHeaders().add("Authorization", "Bearer " + openaiApiKey);
return execution.execute(request, body);
});
return restTemplate;
}
}
This is the prompt I get from the other part of the project:
[
“REPUBLICA DE EL SALVADOR”,
“Documento Único de Identidad / ID”,
“Apellidos / Surname”,
“U”,
“LOPEZ AGUILAR”,
“Nombre / Given Names”,
“JOSE ROBERTO”,
“Conocido por / Known by”,
“Genero/Gender Salvadoreño por / Salvadorean by”,
“M”,
“NACIMIENTO”,
“Lugar y Fecha de Nacimiento / Place and Date of Birth”,
“SANTO TOMAS, SAN SALVADOR 20/10/1992”,
“Lugar , Fecha de Expedicion / Place and Date of Issuance”,
“SAN SALVADOR, SAN SALVADOR”,
“20/05/2022”,
“Fecha de Expracion / Date of Expiration”,
“19/05/2030”,
“Número March on ,”,
“JHL”,
“Unique ità number”,
“Firmit @ – Provide”,
“-“,
“04986307-1”,
“Hospital a Signature”,
“- -“,
“Departamento / State”,
“Tipo de sangre / Blood type”,
“NIT”,
“SAN SALVADOR”,
“Municipio / City”,
“Estado familiar / Marital status”,
“TONACATEPEQUE”,
“SOLTERO(A)”,
“Caracteristicas Especiales /”,
“Profesion/Profession”,
“Special Features:”,
“EMPLEADO(A)”,
“IDSLV04986307<<12<<<<<<<<<<<<<“,
“9210206M3005198SLV<<<<<<<<<<<0”,
“LOPEZ<AGUILAR<<JOSE<ROBERTO<<<”
]
And this is what I’m expecting to get with the use of the ChatGPT API:
{
“apellidos”: “LOPEZ AGUILAR”,
“nombre”: “JOSE ROBERTO”,
“conocido(a)Por”: “”,
“genero”: “M”,
“fechaLugarDeNacimiento”: “SANTO TOMAS, SAN SALVADOR 20/10/1992”,
“fechaDeExpedicion”: “SAN SALVADOR, SAN SALVADOR 20/05/2022”,
“fechaDeExpiracion”: “19/05/2030”,
“numeroDUI”: “04986307-1”,
“nit”: “”,
“dirección”: “”,
“departamento”: “SAN SALVADOR”,
“municipio”: “TONACATEPEQUE”,
“tipoSangre”: “-“,
“estadoFamiliar”: “SOLTERO(A)”,
“caracteristicasEspeciales”: “”,
“profesion”: “EMPLEADO(A)”
}
Therefore what I’m trying to do with the use of the ChatGPT API is to arrange the data based on a speciific pattern, and just to make it clear it works just fine on the ChatGPT Playground.