48 lines
1.7 KiB
Java
48 lines
1.7 KiB
Java
package com.example.chatbot;
|
|
|
|
import java.util.List;
|
|
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.stereotype.Service;
|
|
|
|
import com.theokanning.openai.completion.CompletionRequest;
|
|
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
|
|
import com.theokanning.openai.completion.chat.ChatMessage;
|
|
import com.theokanning.openai.service.OpenAiService;
|
|
|
|
@Service
|
|
public class OpenAiServiceWrapper {
|
|
|
|
private final OpenAiService service;
|
|
|
|
@Value("${openai.model}")
|
|
private String openAiModel;
|
|
|
|
@Value("${weaviate.url}")
|
|
private String weaviateUrl;
|
|
|
|
public OpenAiServiceWrapper(@Value("${openai.api-key}") String openAiApiKey) {
|
|
this.service = new OpenAiService(openAiApiKey);
|
|
}
|
|
|
|
public String processQuestion2(String question) {
|
|
CompletionRequest request = CompletionRequest.builder().model(this.openAiModel).prompt(
|
|
"You are a helpful assistant for interpreting database questions.\nQuestion: " + question).maxTokens(
|
|
150).temperature(0.7).build();
|
|
|
|
return service.createCompletion(request).getChoices().get(0).getText().trim();
|
|
}
|
|
|
|
public String processQuestion(String question, List<String> context) {
|
|
String fullPrompt = "Answer the question based on the context below.\n\n" + "Context:\n"
|
|
+ String.join("\n", context) + "\n\n" + "Question: " + question;
|
|
|
|
ChatMessage system = new ChatMessage("system", "You are a helpful assistant.");
|
|
ChatMessage user = new ChatMessage("user", fullPrompt);
|
|
|
|
ChatCompletionRequest request = ChatCompletionRequest.builder().model(openAiModel).messages(
|
|
List.of(system, user)).temperature(0.7).build();
|
|
|
|
return service.createChatCompletion(request).getChoices().get(0).getMessage().getContent().trim();
|
|
}
|
|
}
|