com.xlrit.gears.plugin.chatgpt.ChatGptTaskHandler Maven / Gradle / Ivy
package com.xlrit.gears.plugin.chatgpt;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import com.cjcrafter.openai.OpenAI;
import com.cjcrafter.openai.chat.ChatMessage;
import com.cjcrafter.openai.chat.ChatRequest;
import com.cjcrafter.openai.chat.ChatResponse;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xlrit.gears.engine.task.TaskHandler;
import lombok.RequiredArgsConstructor;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.jetbrains.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnExpression("${gears.chatgpt.enabled:true}")
@RequiredArgsConstructor
public class ChatGptTaskHandler implements TaskHandler {
private static final Logger LOG = LoggerFactory.getLogger(ChatGptTaskHandler.class);
private final ChatGptProperties properties;
private final ObjectMapper objectMapper;
@Override
public boolean canHandle(String roleId, TaskEntity task) {
return Objects.equals(roleId, properties.getRole());
}
@Override
public TaskHandler.Action handle(String roleId, TaskEntity task, JsonNode form) {
JsonNode basedOnJson = form.at("/values/__basedOn");
LOG.info("basedOnJson={}", basedOnJson);
ChatGptBasedOn basedOn = objectMapper.convertValue(basedOnJson, ChatGptBasedOn.class);
LOG.info("basedOn={}", basedOn);
String content = handle(basedOn);
ObjectNode values = objectMapper.createObjectNode();
values.put("content", content);
return new SubmitAction(values);
}
@VisibleForTesting
public String handle(ChatGptBasedOn basedOn) {
OpenAI openai = OpenAI.builder()
.apiKey(properties.getKey())
.build();
List messages = new ArrayList<>();
messages.add(ChatMessage.toSystemMessage("Help the user with questions regarding " + basedOn.subject()));
for (ChatMessage message : basedOn.history()) {
if (message.getRole() != null && message.getContent() != null)
messages.add(message);
}
// Here you can change the model's settings, add tools, and more.
ChatRequest request = ChatRequest.builder()
.model(properties.getModel())
.messages(messages)
.build();
ChatResponse response = openai.createChatCompletion(request);
return response.getChoices().isEmpty() ? "" : response.getChoices().get(0).getMessage().getContent();
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy