code
stringlengths 419
138k
| apis
sequencelengths 1
8
| extract_api
stringlengths 67
7.3k
|
---|---|---|
package bobo.commands.ai;
import com.theokanning.openai.OpenAiHttpException;
import com.theokanning.openai.image.CreateImageRequest;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.Commands;
import java.awt.*;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
public class ImageCommand extends AbstractAI {
/**
* Creates a new image command.
*/
public ImageCommand() {
super(Commands.slash("image", "Uses OpenAI (DALL-E 3) to generate an image of the given prompt.")
.addOption(OptionType.STRING, "prompt", "Image to generate", true));
}
@Override
protected void handleAICommand() {
event.deferReply().queue();
var currentHook = hook;
String prompt = Objects.requireNonNull(event.getOption("prompt")).getAsString();
CreateImageRequest createImageRequest = CreateImageRequest.builder()
.model("dall-e-3")
.prompt(prompt)
.build();
CompletableFuture.supplyAsync(() -> {
try {
return service.createImage(createImageRequest)
.getData()
.get(0)
.getUrl();
} catch (Exception e) {
throw new RuntimeException(e);
}
}).thenAccept(imageUrl -> {
Member member = event.getMember();
assert member != null;
MessageEmbed embed = new EmbedBuilder()
.setAuthor(member.getUser().getGlobalName(), "https://discord.com/users/" + member.getId(), member.getEffectiveAvatarUrl())
.setTitle(prompt.substring(0, Math.min(prompt.length(), 256)))
.setColor(Color.red)
.setImage(imageUrl)
.build();
currentHook.editOriginalEmbeds(embed).queue();
}).exceptionally(e -> {
Throwable cause = e.getCause();
if (cause instanceof OpenAiHttpException exception) {
if (exception.statusCode == 429) {
currentHook.editOriginal("DALL-E 3 rate limit reached. Please try again in a few seconds.").queue();
} else {
currentHook.editOriginal(cause.getMessage()).queue();
e.printStackTrace();
}
} else {
currentHook.editOriginal(cause.getMessage()).queue();
e.printStackTrace();
}
return null;
});
}
@Override
public String getName() {
return "image";
}
} | [
"com.theokanning.openai.image.CreateImageRequest.builder"
] | [((630, 804), 'net.dv8tion.jda.api.interactions.commands.build.Commands.slash'), ((959, 1022), 'java.util.Objects.requireNonNull'), ((1073, 1193), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((1073, 1168), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((1073, 1136), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((1204, 2738), 'java.util.concurrent.CompletableFuture.supplyAsync'), ((1204, 2099), 'java.util.concurrent.CompletableFuture.supplyAsync')] |
package utilities;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionRequest;
import java.util.ArrayList;
public class GPT3Impl {
private static OpenAiService service = new OpenAiService(Config.OPENAI_KEY);
private static final String genericQuestionPrompt = "I am a highly intelligent question answering bot. If you ask me a question that is rooted in truth, I will give you the answer. If you ask me a question that is nonsense, trickery, or has no clear answer, I will respond with \"Unknown\".\n" +
"Q: What is human life expectancy in the United States?\n" +
"A: Human life expectancy in the United States is 78 years.\n" +
"Q: Who was president of the United States in 1955?\n" +
"A: Dwight D. Eisenhower was president of the United States in 1955.\n" +
"Q: Which party did he belong to?\n" +
"A: He belonged to the Republican Party.\n" +
"Q: What is the square root of banana?\n" +
"A: Unknown\n" +
"Q: How does a telescope work?\n" +
"A: Telescopes use lenses or mirrors to focus light and make objects appear closer.\n" +
"Q: Where were the 1992 Olympics held?\n" +
"A: The 1992 Olympics were held in Barcelona, Spain.\n" +
"Q: How many squigs are in a bonk?\n" +
"A: Unknown\n" +
"Q: ";
private static final String friendlyChatResponse = "The following is a conversation with an AI assistant. The assistant is funny and helpful.\n";
public static String getGenericAnswer(String genericQuestion) {
genericQuestion += "\nA: ";
genericQuestion = genericQuestionPrompt + genericQuestion;
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt(genericQuestion)
.echo(true)
.maxTokens(100)
.topP(1.0)
.stop(new ArrayList<>(){{add("\n");}})
.temperature(0.0)
.build();
for(CompletionChoice choice : service.createCompletion("davinci", completionRequest).getChoices()) {
return choice.getText().substring(choice.getText().lastIndexOf("A:")).replace("A: ", "");
}
return "Unknown";
}
public static String getFriendResponse(String input){
input = friendlyChatResponse + "Human: " + input + "\nAI: ";
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt(input)
.echo(true)
.maxTokens(150)
.topP(1.0)
.stop(new ArrayList<>(){{add("\n"); add("Human:"); add("AI:");}})
.temperature(0.9)
.presencePenalty(0.6)
.build();
for(CompletionChoice choice : service.createCompletion("davinci", completionRequest).getChoices()) {
return choice.getText().substring(choice.getText().lastIndexOf("AI:")).replace("AI: ", "");
}
return "Unknown";
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((1860, 2129), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1860, 2104), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1860, 2070), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1860, 2015), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1860, 1988), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1860, 1956), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1860, 1928), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2881), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2856), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2818), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2784), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2702), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2675), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2643), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2615), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package egovframework.example.sample.web;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.embedding.EmbeddingRequest;
import com.theokanning.openai.service.OpenAiService;
import egovframework.example.API.*;
@RestController
@RequestMapping("/restapi")
public class restapitest {
@ResponseBody
@GetMapping("/{name}")
public String sayHello(@PathVariable String name){
String result = "Hello eGovFramework! name: " + name;
return result;
}
//embedding model: text-embedding-ada-002
@PostMapping("/postMethod")
public ResponseEntity<?> sendQuestion(@RequestBody Map<String, String> list){
OpenAiService service = new OpenAiService(Keys.OPENAPI_KEY ,Duration.ofMinutes(9999));
System.out.println(list.get("Q"));
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt(list.get("Q"))
.model("gpt-3.5-turbo")
.echo(true)
.maxTokens(8191)
.temperature((double) 1.0f)
.build();
service.createCompletion(completionRequest).getChoices().forEach(System.out::println);
return ResponseEntity.ok(service.createCompletion(completionRequest).getChoices());
//did some work on project
}
@PostMapping("/postEmbedd")
public ResponseEntity<?> sendEmbedding(@RequestBody Map<String,String> list) {
OpenAiService service = new OpenAiService(Keys.OPENAPI_KEY,Duration.ofMinutes(9999));
List<String> inpStr = new ArrayList<String>();
inpStr.add(list.get("Q"));
new EmbeddingRequest();
EmbeddingRequest emb = EmbeddingRequest.builder()
.input(inpStr)
.model("text-embedding-ada-002")
.build();
service.createEmbeddings(emb).getData().forEach(System.out::println);
return ResponseEntity.ok(service.createEmbeddings(emb).getData());
}
@PostMapping("/postEmbedd2")
public ResponseEntity<?> fromSingleton2(@RequestBody Map<String,String> list){
List<String> input = new ArrayList<String>();
input.add(list.get("Q"));
return ResponseEntity.ok(OAISingleton.getInstance()
.getEmbeddingData(input));
}
}
| [
"com.theokanning.openai.embedding.EmbeddingRequest.builder",
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((1458, 1695), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1458, 1670), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1458, 1626), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1458, 1592), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1458, 1564), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1458, 1524), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2355), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((2260, 2342), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((2260, 2305), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')] |
package com.victorborzaquel.whatsprompt.game;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.image.CreateImageRequest;
import com.theokanning.openai.service.OpenAiService;
import com.victorborzaquel.whatsprompt.api.controllers.GameController;
import com.victorborzaquel.whatsprompt.api.dto.CompleteGameResponse;
import com.victorborzaquel.whatsprompt.api.dto.CreateGameResponse;
import com.victorborzaquel.whatsprompt.api.dto.RankingResponse;
import com.victorborzaquel.whatsprompt.enums.FilterDates;
import com.victorborzaquel.whatsprompt.enums.Languages;
import com.victorborzaquel.whatsprompt.exceptions.GameCompletedException;
import com.victorborzaquel.whatsprompt.exceptions.GameNotFoundException;
import com.victorborzaquel.whatsprompt.utils.ScoreUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.PagedModel;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.UUID;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
@Service
@RequiredArgsConstructor
public class GameService {
private final GameRepository repository;
private final OpenAiService openAiService;
private final PagedResourcesAssembler<RankingResponse> assembler;
public PagedModel<EntityModel<RankingResponse>> getRanking(Pageable pageable, Languages language, FilterDates date) {
Page<Game> pageGame = repository.findAllByRanking(pageable, language, date.getDate());
Page<RankingResponse> pageResponse = pageGame.map(RankingResponse::fromGame);
PagedModel<EntityModel<RankingResponse>> pageModel = methodOn(GameController.class).ranking(pageable.getPageNumber(), pageable.getPageSize(), language, date);
Link link = linkTo(pageModel).withSelfRel();
return assembler.toModel(pageResponse, link);
}
public Game findById(UUID id) {
return repository.findById(id).orElseThrow(GameNotFoundException::new);
}
public CreateGameResponse createGame(Languages language, String nickname) {
String translatedPrompt = getTranslatedPromptToRandomText(language);
String promptToGenerateImage = generateRandomPromptToGenerateImage(translatedPrompt);
String imageUrl = generateImageUrl(promptToGenerateImage);
Game game = Game.builder()
.userNickName(nickname)
.language(language)
.correctAnswer(promptToGenerateImage)
.imageUrl(imageUrl)
.build();
Game repositoryGame = repository.save(game);
return CreateGameResponse.builder()
.id(repositoryGame.getId())
.imageUrl(repositoryGame.getImageUrl())
.build();
}
public CompleteGameResponse completeGame(UUID gameId, String answer) {
Game game = findById(gameId);
if (game.getUserAnswer() != null || game.getCompletedAt() != null) {
throw new GameCompletedException();
}
final int score = ScoreUtils.generateScore(game.getCorrectAnswer(), answer);
game.setUserAnswer(answer);
game.setScore(score);
game.setCompletedAt(LocalDateTime.now());
repository.save(game);
return CompleteGameResponse.builder()
.imageUrl(game.getImageUrl())
.correctAnswer(game.getCorrectAnswer())
.userAnswer(game.getUserAnswer())
.score(game.getScore())
.build();
}
private String generateImageUrl(String prompt) {
CreateImageRequest createImageRequest = CreateImageRequest.builder()
.prompt(prompt)
.responseFormat("url")
.n(1)
.size("256x256")
.build();
return openAiService.createImage(createImageRequest).getData().get(0).getUrl();
}
private String generateRandomPromptToGenerateImage(String prompt) {
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt(prompt)
.model("text-davinci-003")
// .temperature(1.5)
.maxTokens(100)
.build();
String text = openAiService.createCompletion(completionRequest).getChoices().get(0).getText();
return text.replaceAll("[\n\"\r.]", "");
}
private String getTranslatedPromptToRandomText(Languages language) {
return switch (language) {
case EN_US -> "generate a english random prompt for DALL-E to generate an image from.";
case PT_BR -> "gerar um prompt em português aleatório para o DALL-E gerar uma imagem.";
};
}
}
| [
"com.theokanning.openai.image.CreateImageRequest.builder",
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((3117, 3294), 'com.victorborzaquel.whatsprompt.api.dto.CreateGameResponse.builder'), ((3117, 3261), 'com.victorborzaquel.whatsprompt.api.dto.CreateGameResponse.builder'), ((3117, 3197), 'com.victorborzaquel.whatsprompt.api.dto.CreateGameResponse.builder'), ((3895, 4182), 'com.victorborzaquel.whatsprompt.api.dto.CompleteGameResponse.builder'), ((3895, 4149), 'com.victorborzaquel.whatsprompt.api.dto.CompleteGameResponse.builder'), ((3895, 4101), 'com.victorborzaquel.whatsprompt.api.dto.CompleteGameResponse.builder'), ((3895, 4043), 'com.victorborzaquel.whatsprompt.api.dto.CompleteGameResponse.builder'), ((3895, 3979), 'com.victorborzaquel.whatsprompt.api.dto.CompleteGameResponse.builder'), ((4308, 4527), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4308, 4494), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4308, 4453), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4308, 4423), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4308, 4376), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4767, 5002), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4767, 4969), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4767, 4885), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4767, 4834), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package com.copybot.bonappcopybot.openai;
import com.copybot.bonappcopybot.model.entity.topic.Topic;
import com.copybot.bonappcopybot.model.entity.topic.TopicCopy;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;
public class TopicCopyAI {
static TopicCopyAI obj = new TopicCopyAI();
private TopicCopyAI(){}
public static TopicCopyAI getInstance(){return obj;}
public String getCopy(Topic topic, TopicCopy copy){
String APIKey = "APIKEY";
OpenAiService service = new OpenAiService(APIKey);
String prompt = createPrompt(topic, copy);
System.out.println(prompt);
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt(prompt)
.temperature(0.9)
.maxTokens(150)
.topP(1.0)
.frequencyPenalty(1.0)
.presencePenalty(0.3)
.echo(false)
.build();
String copyResult = service.createCompletion("text-davinci-001", completionRequest).getChoices().get(0).getText();
System.out.println(copyResult);
copyResult = copyResult.replaceFirst("\\n\\n", "");
String lang = copy.getLang();
if (lang.equals("English") || lang.equals("english") || lang.equals("en") || lang.equals("EN")){
return copyResult;
}else {
String translated = translateCopy(copyResult, lang);
return translated;
}
}
private String createPrompt(Topic topic, TopicCopy copy){
String prompt = "Write an engaging add for " + topic.getTopic() + " food for the occassion of " + copy.getOccasion() + " in "+ copy.getLang() +"->";
return prompt;
}
private String translateCopy(String originalCopy, String lang){
String APIKey = "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";
OpenAiService service = new OpenAiService(APIKey);
String prompt = "Translate the following text to " + lang + ": " + originalCopy;
System.out.println(prompt);
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt(prompt)
.temperature(0.9)
.maxTokens(150)
.topP(1.0)
.frequencyPenalty(1.0)
.presencePenalty(0.3)
.echo(false)
.build();
String copyResult = service.createCompletion("text-davinci-001", completionRequest).getChoices().get(0).getText();
copyResult = copyResult.replaceFirst("\\n\\n", "");
return copyResult;
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((719, 1002), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((719, 977), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((719, 948), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((719, 910), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((719, 871), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((719, 844), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((719, 812), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((719, 778), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2447), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2422), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2393), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2355), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2316), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2289), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2257), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2223), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package br.com.alura.screenmatch.service;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
public class ConsultaChatGPT {
public static String obterTraducao(String texto) {
OpenAiService service = new OpenAiService(System.getenv("OPENAI_APIKEY"));
CompletionRequest requisicao = CompletionRequest.builder()
.model("text-davinci-003")
.prompt("traduza para o português o texto: " + texto)
.maxTokens(1000)
.temperature(0.7)
.build();
var resposta = service.createCompletion(requisicao);
return resposta.getChoices().get(0).getText();
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((367, 600), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 575), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 541), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 508), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 437), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package dingov2.bot.services;
import com.theokanning.openai.ListSearchParameters;
import com.theokanning.openai.OpenAiResponse;
import com.theokanning.openai.assistants.Assistant;
import com.theokanning.openai.messages.Message;
import com.theokanning.openai.messages.MessageContent;
import com.theokanning.openai.messages.MessageRequest;
import com.theokanning.openai.runs.CreateThreadAndRunRequest;
import com.theokanning.openai.service.OpenAiService;
import com.theokanning.openai.threads.ThreadRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.CoreSubscriber;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class DingoOpenAIQueryService implements OpenAIQueryService {
private String apiKey;
public static final List<String> runningStates = Arrays.asList("queued", "in_progress");
public static final List<String> failedStates = Arrays.asList("requires_action", "failed", "expired", "cancelled", "cancelling");
private Logger logger;
public DingoOpenAIQueryService(String apiKey){
this.apiKey = apiKey;
logger = LoggerFactory.getLogger(DingoOpenAIQueryService.class);
}
public static void main(String[] args){
Logger logger2 = LoggerFactory.getLogger(DingoOpenAIQueryService.class);
new DingoOpenAIQueryService("")
.sendChatMessage("who is jerry seinfeld?")
.subscribe(logger2::info);
}
@Override
public Flux<String> sendChatMessage(String chatMessage){
return Flux.create(emitter -> {
logger.info("processing chat message");
OpenAiService service = new OpenAiService(apiKey);
OpenAiResponse<Assistant> test = service.listAssistants(ListSearchParameters.builder().build());
Assistant dingoAssistant = test.getData().stream().filter(assistant -> assistant
.getName()
.toLowerCase()
.contains("dingo"))
.findFirst()
.orElseThrow();
MessageRequest messageRequest = MessageRequest.builder().content(chatMessage).build();
ThreadRequest threadRequest = ThreadRequest.builder()
.messages(Collections.singletonList(messageRequest))
.build();
CreateThreadAndRunRequest createThreadAndRunRequest = CreateThreadAndRunRequest
.builder()
.thread(threadRequest)
.assistantId(dingoAssistant.getId())
.build();
var createThreadAndRunResponse = service.createThreadAndRun(createThreadAndRunRequest);
var runResponse = service.retrieveRun(createThreadAndRunResponse.getThreadId(), createThreadAndRunResponse.getId());
while (runningStates.contains(runResponse.getStatus().toLowerCase())) {
logger.info("waiting for response");
Mono.delay(Duration.ofSeconds(1)).block();
runResponse = service.retrieveRun(runResponse.getThreadId(), runResponse.getId());
}
if(failedStates.contains(runResponse.getStatus())){
String errorMessage = "Run stopped unexpectedly... Reason: " + runResponse.getStatus() + " " + runResponse.toString();
logger.error(errorMessage);
emitter.next(errorMessage);
emitter.complete();
return;
}
var messages = service.listMessages(createThreadAndRunResponse.getThreadId());
for (Message m : messages.getData()) {
for (MessageContent c :
m.getContent()) {
if(!m.getRole().equalsIgnoreCase("user")){
emitter.next(c.getText().getValue());
logger.info(c.getText().getValue());
}
}
}
emitter.complete();
});
}
}
| [
"com.theokanning.openai.threads.ThreadRequest.builder",
"com.theokanning.openai.ListSearchParameters.builder",
"com.theokanning.openai.messages.MessageRequest.builder"
] | [((1958, 1996), 'com.theokanning.openai.ListSearchParameters.builder'), ((2344, 2397), 'com.theokanning.openai.messages.MessageRequest.builder'), ((2344, 2389), 'com.theokanning.openai.messages.MessageRequest.builder'), ((2442, 2569), 'com.theokanning.openai.threads.ThreadRequest.builder'), ((2442, 2539), 'com.theokanning.openai.threads.ThreadRequest.builder'), ((3216, 3257), 'reactor.core.publisher.Mono.delay')] |
package com.thirty.smartnotify.services;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.ListMessagesResponse;
import com.google.api.services.gmail.model.Message;
import com.google.api.services.gmail.model.MessagePartHeader;
import com.google.api.services.gmail.model.ModifyMessageRequest;
import com.theokanning.openai.OpenAiHttpException;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.service.OpenAiService;
import com.thirty.smartnotify.domain.Application;
import com.thirty.smartnotify.model.StatusEnum;
import com.thirty.smartnotify.repositories.ApplicationRepository;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
@Service
public class GmailService {
private final Gmail gmail;
private final ApplicationRepository applicationRepository;
public GmailService(Gmail gmail, ApplicationRepository applicationRepository) {
this.gmail = gmail;
this.applicationRepository = applicationRepository;
}
public String parseNewestMessage() {
try {
String err = "";
Message newMsg = getNewestMessage();
if (! isMessageUnread(newMsg)) {
return "There is no new message in the mailbox";
}
err = markMessageRead(newMsg);
if (!err.isEmpty()) {
return err;
}
err = parseMessage(newMsg);
if (err.equals("Didn't contain keywords")) {
//TODO query if sender's email exists in db, if this is the case its either
// 1. a promotion (advertisement) 2. a followup email regarding application
String senderEmail = getSenderEmail(newMsg.getPayload().getHeaders());
List<Application> application = applicationRepository.findApplicationBySenderEmail(senderEmail);
//first querying by email (instead of company name) to limit api calls to gpt. (need to call api to parse for company name)
if (!application.isEmpty()) {
String body = newMsg.getPayload().getParts().get(0).getBody().getData();
String companyName = getCompanyName(body);
if (companyName.equals("NULL")) {
return "Couldn't parse mail";
}
if (body.contains(companyName)) {
//updateStatus contains # rows updated
int updateStatus = applicationRepository.updateApplicationBySenderEmail(senderEmail, StatusEnum.PENDING);
}
}
}
} catch (IOException e) {
System.out.println(e);
}
return "Could not parse message";
}
public String parseMessage(Message msg) throws IOException {
if (msg == null) {
return "Could not find new message";
}
List<MessagePartHeader> headers = msg.getPayload().getHeaders();
String sender = getSenderEmail(headers);
String contents = msg.getPayload().getParts().get(0).getBody().getData();
if (contents == null) {
return "Mail has no body";
}
String decodedContent = new String(Base64.getDecoder().decode(contents), StandardCharsets.UTF_8);
if (! containsJobApplicationKeywords(decodedContent.toLowerCase())) {
return "Didn't contain keywords";
}
String companyName = getCompanyName(contents);
if (companyName.equals("NULL")) {
return "Could not find company name in text";
}
//storing data (sender email, company name, application status) in db.
Application newApp = new Application(sender, companyName, StatusEnum.APPLIED);
try {
applicationRepository.save(newApp);
} catch (DataIntegrityViolationException | ConstraintViolationException e) {
System.out.println(e);
}
return "";
}
/**
* Second layer of filtering, uses openai's gpt-3.5-turbo model to extract, if present, the company name from the email.
* @param body The text portion of a given email.
* @return The name of the company if found; NULL if not found.
*/
public String getCompanyName(String body) {
OpenAiService service = new OpenAiService(System.getenv("OPENAI_API_KEY"));
String context = "Your job is to extract the company name from the provided text. The output should only contain the company name, or \"NULL\" if there is no company name in the text";
ChatMessage config = new ChatMessage("system", context);
ChatMessage prompt = new ChatMessage("user", body);
List<ChatMessage> gptInput = List.of(config, prompt);
String res = "";
try {
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
.messages(gptInput)
.model("gpt-3.5-turbo")
.maxTokens(100)
.build();
ChatCompletionChoice output = service.createChatCompletion(chatCompletionRequest).getChoices().get(0);
res = output.getMessage().getContent();
} catch (OpenAiHttpException e) {
System.out.println(e);
}
return res;
}
/**
* First layer of filtering, to get rid of unrelated emails. This is to reduce the amount of calls to openai's api/token usage.
* @param body String containing the text portion of the email.
* @return True if the text contains certain buzzwords. False if it is deemed to be an unrelated email.
*/
public Boolean containsJobApplicationKeywords(String body) {
String[] keywords = {"apply", "application", "applying", "interview"};
for (String keyword: keywords) {
if (body.contains(keyword)) {
return true;
}
}
return false;
}
public String getSenderEmail(List<MessagePartHeader> headers) {
String sender = "";
for (MessagePartHeader h: headers) {
if (h.getName().equals("X-Google-Sender-Delegation")) {
sender = h.getValue();
}
}
return sender;
}
public Message getNewestMessage() {
try {
ListMessagesResponse a = gmail.users().messages().list("me").execute();
List<Message> messages = a.getMessages();
if (messages != null && !messages.isEmpty()) {
return gmail.users().messages().get("me", messages.get(0).getId()).execute();
}
} catch (IOException e) {
System.out.println(e);
}
return null;
}
/**
* Verifies that the message has already been read or not, based on the presence of the "UNREAD" label.
* @param msg The Message object that we want to validate.
* @return Boolean: True if Message contains the label "UNREAD". False if not.
*/
private Boolean isMessageUnread(Message msg) {
List<String> labels = msg.getLabelIds();
return labels.contains("UNREAD");
}
public String markMessageRead(Message msg) {
try {
gmail.users().messages().modify(
"me",
msg.getId(),
new ModifyMessageRequest().setRemoveLabelIds(Collections.singletonList("UNREAD")))
.execute();
return "";
} catch (IOException e) {
return "Failed to delete Label.";
}
}
public String testMethod(String x) {
String y = "";
System.out.println("hello");
return y;
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((3667, 3703), 'java.util.Base64.getDecoder'), ((5288, 5468), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5288, 5439), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5288, 5403), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5288, 5359), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.contrib.llm.internal;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.apache.hc.core5.http.HttpEntity;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.InstantiationStrategy;
import org.xwiki.component.descriptor.ComponentInstantiationStrategy;
import org.xwiki.contrib.llm.ChatMessage;
import org.xwiki.contrib.llm.ChatModel;
import org.xwiki.contrib.llm.ChatRequest;
import org.xwiki.contrib.llm.ChatResponse;
import org.xwiki.contrib.llm.GPTAPIConfig;
import org.xwiki.contrib.llm.RequestError;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.theokanning.openai.OpenAiResponse;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
/**
* Chat model implementation that uses the OpenAI API.
*
* @version $Id$
* @since 0.3
*/
@Component(roles = { OpenAIChatModel.class })
@InstantiationStrategy(ComponentInstantiationStrategy.PER_LOOKUP)
public class OpenAIChatModel implements ChatModel
{
@Inject
private RequestHelper requestHelper;
private GPTAPIConfig config;
private String model;
/**
* Initialize the model.
*
* @param config the API configuration
* @param model the model to use
*/
public void initialize(GPTAPIConfig config, String model)
{
this.config = config;
this.model = model;
}
@Override
public void processStreaming(ChatRequest request, Consumer<ChatResponse> consumer) throws RequestError
{
// TODO: Implement this once JAX-RS 2.1 with real streaming is available. For now, fall back to non-streaming.
// With JAX-RS 2.1, use real streaming if the model supports it, otherwise fall back to non-streaming.
consumer.accept(process(request));
}
@Override
public ChatResponse process(ChatRequest request) throws RequestError
{
List<com.theokanning.openai.completion.chat.ChatMessage> messages = request.getMessages().stream()
.map(message ->
new com.theokanning.openai.completion.chat.ChatMessage(message.getRole(), message.getContent()))
.collect(Collectors.toList());
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
.model(this.model)
.temperature(request.getParameters().getTemperature())
.messages(messages)
.build();
try {
return this.requestHelper.post(this.config,
"/chat/completions",
chatCompletionRequest,
response -> {
if (response.getCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
ObjectMapper objectMapper = new ObjectMapper();
OpenAiResponse<ChatCompletionResult> modelOpenAiResponse =
objectMapper.readValue(inputStream,
new TypeReference<OpenAiResponse<ChatCompletionResult>>()
{
});
List<ChatCompletionChoice> chatCompletionChoices =
modelOpenAiResponse.getData().get(0).getChoices();
ChatCompletionChoice chatCompletionChoice = chatCompletionChoices.get(0);
com.theokanning.openai.completion.chat.ChatMessage resultMessage =
chatCompletionChoice.getMessage();
return new ChatResponse(chatCompletionChoice.getFinishReason(),
new ChatMessage(resultMessage.getRole(), resultMessage.getContent()));
} else {
throw new IOException("Response is empty.");
}
} else {
throw new IOException("Response code is " + response.getCode());
}
});
} catch (Exception e) {
throw new RequestError(500, e.getMessage());
}
/*
// TODO: don't recreate the client every time. However, the client is also not thread-safe so we can't just
// use a single client for all requests. We could use a thread-local client but that would require us to
// handle cleanup, which is not trivial. An object pool might be a better solution.
Client client = ClientBuilder.newClient();
Invocation.Builder completionRequest = client.target(config.getURL())
.path("chat/completions")
.request(MediaType.APPLICATION_JSON)
.header(AUTHORIZATION, BEARER + config.getToken());
GenericType<OpenAiResponse<ChatCompletionResult>> chatCompletionResponseType = new GenericType<>()
{
};
try {
// TODO: change this to use jax-rs 2.0 where we can get a response object and then read different types
// of entities depending on the success/error.
OpenAiResponse<ChatCompletionResult> modelOpenAiResponse =
completionRequest.post(Entity.entity(chatCompletionRequest, MediaType.APPLICATION_JSON_TYPE),
chatCompletionResponseType);
// TODO: Better error handling.
List<ChatCompletionChoice> chatCompletionChoices = modelOpenAiResponse.getData().get(0).getChoices();
ChatCompletionChoice chatCompletionChoice = chatCompletionChoices.get(0);
com.theokanning.openai.completion.chat.ChatMessage resultMessage = chatCompletionChoice.getMessage();
return new ChatResponse(chatCompletionChoice.getFinishReason(),
new ChatMessage(resultMessage.getRole(), resultMessage.getContent()));
} catch (WebApplicationException e) {
throw new RequestError(e.getResponse().getStatus(), e.getMessage());
}
*/
}
@Override
public boolean supportsStreaming()
{
return this.config.getCanStream();
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((3439, 3621), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3439, 3600), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3439, 3568), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3439, 3501), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package com.timoxino.interview.tamer.service;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class OpenAiService implements CompletionService {
final static String PROMPT_TEMPLATE_EVALUATE_SENIORITY_LEVEL = """
Identify seniority level of the candidate \
applying for the technical role of {role} \
with the following CV delimited with triple backticks.\
Seniority levels can be determined based on number of java frameworks mentioned \
and years of experience and can be the following:
1. Junior
2. Middle
3. Senior
4. Lead
Provide a single-digit answer that corresponds to the level identified.
CV: '''{cv}'''
""";
final static String PROMPT_TEMPLATE_DETECT_SKILLS = """
Identify key technical skills which the following CV has \
for the role of {role} \
in the following CV delimited with triple backticks. \
Provide the list of skill names only separated by comma. \
CV: '''{cv}'''
""";
@Autowired
com.theokanning.openai.service.OpenAiService openAiClient;
@Override
public Integer evaluateSeniorityLevel(String cv, String role) {
String prompt = PROMPT_TEMPLATE_EVALUATE_SENIORITY_LEVEL.replace("{role}", role).replace("{cv}", cv);
return Integer.valueOf(initiateCompletion(prompt));
}
@Override
public List<String> detectSkills(String cv, String role) {
String prompt = PROMPT_TEMPLATE_DETECT_SKILLS.replace("{role}", role).replace("{cv}", cv);
return Arrays.asList(initiateCompletion(prompt).split(","));
}
private String initiateCompletion(String prompt) {
log.info("Completion initiation for the prompt '{}'", prompt);
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder().model("gpt-3.5-turbo")
.temperature(0.0).n(1).messages(Arrays.asList(new ChatMessage("user", prompt)))
.build();
log.info("Completion request created");
ChatCompletionResult completion = openAiClient.createChatCompletion(chatCompletionRequest);
log.info("Completion finished");
return completion.getChoices().get(0).getMessage().getContent();
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((2260, 2435), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2260, 2410), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2260, 2353), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2260, 2348), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2260, 2314), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package br.com.lucasts.screenmatch.service;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
public class ConsultaChatGPT {
public static String obterTraducao(String texto) {
OpenAiService service = new OpenAiService(System.getenv("OPENAI_APIKEY"));
CompletionRequest requisicao = CompletionRequest.builder()
.model("gpt-3.5-turbo")
.prompt("traduza para o português o texto: " + texto)
.maxTokens(1000)
.temperature(0.7)
.build();
var resposta = service.createCompletion(requisicao);
return resposta.getChoices().get(0).getText();
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((369, 599), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((369, 574), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((369, 540), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((369, 507), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((369, 436), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package br.com.danilo.ecommerce;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.Duration;
import java.util.Arrays;
import java.util.stream.Collectors;
// --> Analisador de Sentimentos de Avaliações de Produtos
public class FeelingsAnalysis {
public static void main(String[] args) {
try {
var promptSystem = """
Você é um analisador de sentimentos de avaliações de produtos.
Escreva um parágrafo com até 50 palavras resumindo as avaliações e depois atribua qual o sentimento geral para o produto.
Identifique também 3 pontos fortes e 3 pontos fracos identificados a partir das avaliações.
#### Formato de saída
Nome do produto:
Resumo das avaliações: [resuma em até 50 palavras]
Sentimento geral: [deve ser: POSITIVO, NEUTRO ou NEGATIVO]
Pontos fortes: [3 bullets points]
Pontos fracos: [3 bullets points]
""";
var productDirectory = Path.of("src/main/resources/customerReviews/"); // --> Diretório dos produtos
var userReviewFiles = Files
.walk(productDirectory, 1)
.filter(path -> path.toString().endsWith(".txt"))
.collect(Collectors.toList());
for (Path file : userReviewFiles) {
System.out.println(" Iniciando análise do produto: | Starting product analysis: " + file.getFileName()); // --> Imprime o nome do arquivo
var promptUser = loadFileReviews(file);
String modelOpenAI = "gpt-3.5-turbo"; // --> Modelo do OpenAI a ser utilizado
var request = ChatCompletionRequest
.builder()
.model(modelOpenAI) // --> Modelo do OpenAI a ser utilizado
.messages(Arrays.asList(
new ChatMessage(
ChatMessageRole.SYSTEM.value(),
promptSystem),
new ChatMessage(
ChatMessageRole.USER.value(),
promptUser)))
.build();
var keyToken = System.getenv("OPENAI_API_KEY");
var serviceOpenAI = new OpenAiService(keyToken, Duration.ofSeconds(60));
var answers = serviceOpenAI
.createChatCompletion(request)
.getChoices().get(0).getMessage().getContent();
saveCustomerAnalysis(file.getFileName().toString(). // --> Salvar somente o nome do arquivo
replace(".txt", ""), // --> Remover o .txt do nome do arquivo
answers);
System.out.println(" Analise Finalizada | Analysis Finished" + "\n");
}
} catch (Exception errorWhenParsingFiles) {
System.out.println("Erro ao analisar o produto! | Error analyzing product!");
}
}
// --> Carrega os clientes do arquivo
private static String loadFileReviews(Path file) {
try {
return Files.readAllLines(file).toString();
} catch (Exception errorLoadFile) {
throw new RuntimeException("Erro ao carregar o arquivo! | Error loading file!", errorLoadFile);
}
}
// --> Salva a análise do produto
private static void saveCustomerAnalysis(String file, String analise) {
try {
var path = Path.of("src/main/resources/savedCustomerReviews" + file + ".txt");
Files.writeString(path, analise, StandardOpenOption.CREATE_NEW);
} catch (Exception errorSaveAnalysis) {
throw new RuntimeException("Erro ao salvar o arquivo! | Error saving file!", errorSaveAnalysis);
}
}
} | [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value"
] | [((2477, 2507), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((2653, 2681), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((3762, 3797), 'java.nio.file.Files.readAllLines')] |
package br.com.rodrigo.screenmatch.service;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
public class ChatGPTQuery {
public static String getTranslation(String texto) {
OpenAiService service = new OpenAiService(System.getenv("OPENAI_API_KEY"));
CompletionRequest request = CompletionRequest.builder()
.model("text-davinci-003")
.prompt("traduza para o português o texto: " + texto)
.maxTokens(1000)
.temperature(0.7)
.build();
var response = service.createCompletion(request);
return response.getChoices().get(0).getText();
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((364, 597), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((364, 572), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((364, 538), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((364, 505), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((364, 434), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package com.jentsch.voicegpt;
import static com.jentsch.voicegpt.SettingsActivity.MAX_TOKENS;
import static com.jentsch.voicegpt.SettingsActivity.OPENAI_API_KEY;
import android.content.Context;
import android.content.SharedPreferences;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionChunk;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.service.OpenAiService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import io.reactivex.functions.Consumer;
public class OpenAI
{
public static synchronized void doAsyncChatCompletionRequest(SharedPreferences prefs, List<ChatMessage> messages, ChatCompletionChunkResponseListener listener)
{
String token = prefs.getString(OPENAI_API_KEY, null);
int maxTokens = prefs.getInt(MAX_TOKENS, 500);
Thread t = new Thread() {
@Override
public void run() {
try {
ArrayList<ChatCompletionChunk> chatCompletionChunks = OpenAI.doChatCompletionRequest(token, maxTokens, messages);
if (listener != null) {
String content = "";
for (ChatCompletionChunk chatCompletionChunk : chatCompletionChunks) {
List<ChatCompletionChoice> choices = chatCompletionChunk.getChoices();
if (choices != null) {
ChatCompletionChoice choice = choices.get(0);
if (choice != null) {
ChatMessage message = choice.getMessage();
if (message != null) {
if (message.getContent() != null) {
content += message.getContent();
}
}
}
}
}
listener.publishResponse (content);
}
} catch (Exception e) {
if (listener != null) {
listener.publishResponse (e.getMessage());
}
}
}
};
t.start();
}
private static ArrayList<ChatCompletionChunk> doChatCompletionRequest(String token, int maxTokens, List<ChatMessage> messages)
{
ArrayList<ChatCompletionChunk> ret = new ArrayList<>();
OpenAiService service = new OpenAiService(token);
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
.model("gpt-3.5-turbo")
.messages(messages)
.maxTokens(maxTokens)
.temperature(0.8)
.logitBias(new HashMap<>())
.n(1)
.build();
Consumer<? super ChatCompletionChunk> appendResult = new Consumer<ChatCompletionChunk>() {
@Override
public void accept(ChatCompletionChunk chatCompletionChunk) throws Exception {
ret.add(chatCompletionChunk);
}
};
service.streamChatCompletion(chatCompletionRequest)
.doOnError(Throwable::printStackTrace)
.blockingForEach(appendResult);
service.shutdownExecutor();
return ret;
}
public interface ChatCompletionChunkResponseListener {
void publishResponse(String content);
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((2794, 3064), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2794, 3039), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2794, 3017), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2794, 2973), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2794, 2939), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2794, 2901), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2794, 2865), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package org.wishlistapp.client;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
import io.github.cdimascio.dotenv.Dotenv;
import org.springframework.stereotype.Component;
@Component
public class AiClient {
private final OpenAiService client;
public AiClient() {
String secretKey = getTheKey();
client = new OpenAiService(secretKey);
}
private String getTheKey() throws IllegalStateException {
Dotenv dotenv = Dotenv.load();
// Retrieve the secret key
String secretKey = dotenv.get("OPENAI_SECRET_KEY");
if (secretKey == null || secretKey.isEmpty()) {
throw new IllegalStateException("OPENAI_SECRET_KEY is not set in the .env file.");
}
return secretKey;
}
public String getResponse(String prompt) {
String instructions = "Find a suitable title for the product described in provided comments. Keep it short. Use simple words. If it's a book, then book title is enough. If it's vacation somewhere, just 'Vacation in Somewhere'. If it's a piece of clothing, then type and color as title are enough, etc.\n";
String complete_prompt = instructions + "COMMENTS: " + prompt;
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt(complete_prompt)
.model("gpt-3.5-turbo-instruct")
.maxTokens(64)
.build();
StringBuilder response = new StringBuilder();
client.createCompletion(completionRequest).getChoices().forEach(choice -> {
response.append(choice.getText());
});
return response.toString().strip();
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((1301, 1474), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1449), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1418), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1369), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package ru.itzstonlex.desktop.chatbotmessenger.form.feed.controller;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import lombok.Getter;
import lombok.NonNull;
import lombok.SneakyThrows;
import ru.itzstonlex.desktop.chatbotmessenger.api.chatbot.ChatBotAssistant;
import ru.itzstonlex.desktop.chatbotmessenger.api.chatbot.type.request.ChatBotRequest;
import ru.itzstonlex.desktop.chatbotmessenger.api.form.AbstractSceneForm;
import ru.itzstonlex.desktop.chatbotmessenger.api.form.ApplicationFormKeys;
import ru.itzstonlex.desktop.chatbotmessenger.api.form.controller.AbstractComponentController;
import ru.itzstonlex.desktop.chatbotmessenger.api.form.observer.ObserveBy;
import ru.itzstonlex.desktop.chatbotmessenger.form.feed.FeedForm;
import ru.itzstonlex.desktop.chatbotmessenger.form.feed.controller.ChatBotHeaderController.TypingStatus;
import ru.itzstonlex.desktop.chatbotmessenger.form.feed.function.FeedFormFunctionReleaser;
import ru.itzstonlex.desktop.chatbotmessenger.form.feed.view.FeedFormFrontView;
import ru.itzstonlex.desktop.chatbotmessenger.form.feed.view.FeedFormFrontViewConfiguration;
import ru.itzstonlex.desktop.chatbotmessenger.form.message.MessageForm;
import ru.itzstonlex.desktop.chatbotmessenger.form.message.function.MessageFormFunctionReleaser.SenderType;
import ru.itzstonlex.desktop.chatbotmessenger.observer.FooterButtonSendClickObserver;
import ru.itzstonlex.desktop.chatbotmessenger.observer.FooterMessageInputEnterObserver;
public final class BothMessagesReceiveController extends AbstractComponentController<FeedForm> {
@ObserveBy(FooterMessageInputEnterObserver.class)
private TextField inputMessageField;
@ObserveBy(FooterButtonSendClickObserver.class)
private Button messageSendButton;
@Getter
private final List<Node> messageNodesList = new ArrayList<>();
@Getter
private final ChatBotAssistant chatBotAssistant;
public BothMessagesReceiveController(FeedForm form, ChatBotAssistant chatBotAssistant) {
super(form);
this.chatBotAssistant = chatBotAssistant;
}
@Override
protected void configureController() {
this.inputMessageField = getForm().getView().find(FeedFormFrontViewConfiguration.INPUT_MESSAGE_FIELD);
this.messageSendButton = getForm().getView().find(FeedFormFrontViewConfiguration.MESSAGE_SEND_BUTTON);
}
private String reformatMessage(String text) {
return text.replace("<br>", "\n");
}
private final OpenAiService chatGPT = new OpenAiService("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", 5);
public void onMessageReceive(@NonNull String receivedMessage) {
ChatBotHeaderController chatBotHeaderController = getForm().getController(ChatBotHeaderController.class);
// send question
fireFunction(FeedFormFunctionReleaser.SEND, receivedMessage);
chatBotHeaderController.setTypingStatus(TypingStatus.TYPING);
// send answer
CompletableFuture.supplyAsync(() -> chatGPT.createCompletion(CompletionRequest.builder()
.model("text-davinci-003")
.prompt(receivedMessage)
.temperature(0.9)
.maxTokens(500)
.topP(1.0)
.frequencyPenalty(0.0)
.presencePenalty(0.6)
.build()))
.whenCompleteAsync((completionResult, error) -> fireFunction(FeedFormFunctionReleaser.REPLY,
completionResult.getChoices().get(0).getText()));
// ChatBotRequest chatBotRequest = new ChatBotRequest(receivedMessage);
// chatBotAssistant.requestBestSuggestion(chatBotRequest)
// .thenAccept(response -> fireFunction(FeedFormFunctionReleaser.REPLY, response.getMessageText()));
// hide suggestions.
FooterSuggestionsController footerSuggestionsController = getForm().getController(FooterSuggestionsController.class);
footerSuggestionsController.setSuggestionsVisible(false);
}
@SneakyThrows
private Node createMessageNode(SenderType senderType, String msg) {
AbstractSceneForm<?> messageForm = getForm().getSceneLoader()
.loadUncachedForm(ApplicationFormKeys.MESSAGE);
// todo - replace to function MessageFormFunctionReleaser.UPDATE_MESSAGE_TEXT
((MessageForm) messageForm).updateMessageText(senderType, msg);
return messageForm.getJavafxNode();
}
private void addMessageChildren(ObservableList<Node> childrenList, Node messageNode) {
FeedFormFrontView view = getForm().getView();
Node wrappedMessageNode = view.createWrappedMessageNode(messageNode);
childrenList.add(wrappedMessageNode);
childrenList.add(view.createMessageEmptySeparator(10));
messageNodesList.add(wrappedMessageNode);
}
public void addMessage(SenderType senderType, String text) {
VBox messagesBox = getForm().getView().find(FeedFormFrontViewConfiguration.MESSAGES_DISPLAY_BOX);
Node messageNode = createMessageNode(senderType, reformatMessage(text));
addMessageChildren(messagesBox.getChildren(), messageNode);
AnchorPane noMessagesPanel = getForm().getView().find(FeedFormFrontViewConfiguration.NO_MESSAGES_PANEL);
if (noMessagesPanel.isVisible()) {
noMessagesPanel.setVisible(false);
}
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((3303, 3802), 'java.util.concurrent.CompletableFuture.supplyAsync'), ((3364, 3638), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3364, 3617), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3364, 3583), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3364, 3548), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3364, 3525), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3364, 3497), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3364, 3467), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3364, 3430), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package com.springboot.chatgptbot.config.bot;
import com.springboot.chatgptbot.domain.Ticket;
import com.springboot.chatgptbot.service.LogService;
import com.springboot.chatgptbot.service.TicketService;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.commands.SetMyCommands;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.*;
import org.telegram.telegrambots.meta.api.objects.commands.BotCommand;
import org.telegram.telegrambots.meta.api.objects.commands.scope.BotCommandScopeDefault;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Component
@Slf4j
public class TelegramBot extends TelegramLongPollingBot {
private final TicketService ticketService;
private final LogService logService;
private final TelegramBotConfig config;
private boolean waitingForQuestion = false;
private long waitingChatId;
private String waitingUserName;
public TelegramBot(TelegramBotConfig config, LogService logService, TicketService ticketService) {
this.config = config;
this.logService = logService;
this.ticketService = ticketService;
List<BotCommand> listOfCommands = new ArrayList<>();
listOfCommands.add(new BotCommand("/start", "Nice to meet you."));
listOfCommands.add(new BotCommand("/help", "Ask questions."));
try {
this.execute(new SetMyCommands(listOfCommands, new BotCommandScopeDefault(), null));
} catch (TelegramApiException e) {
log.error(Arrays.toString(e.getStackTrace()));
}
}
@Override
public void onUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) {
long chatId = update.getMessage().getChatId();
String messageText = update.getMessage().getText();
if (waitingForQuestion && chatId == waitingChatId) {
answerAfterQuestion(update);
} else if (messageText.equals("/help")) {
sendMessage("What is your question?", chatId);
waitingForQuestion = true;
waitingChatId = chatId;
waitingUserName = update.getMessage().getFrom().getUserName();
} else {
handleUserMessage(update);
}
}
}
private void answerAfterQuestion(Update update) {
String userQuestion = update.getMessage().getText();
sendMessage("Wait, they will answer you soon.", waitingChatId);
LocalDateTime timestamp = LocalDateTime.now();
saveTicket(waitingUserName, userQuestion, timestamp, waitingChatId);
waitingForQuestion = false;
}
public void sendSyncMessage(String textToSend, long chatId) {
SendMessage message = new SendMessage();
message.setChatId(String.valueOf(chatId));
if (!textToSend.isEmpty()) {
message.setText(textToSend);
}
try {
execute(message);
} catch (TelegramApiException e) {
log.error("Error sending message: {}", e.getMessage());
}
}
public void saveAnswerToTicket(Long ticketId, String answer, Long chatId) {
ticketService.saveAnswer(ticketId, answer, chatId);
sendMessageToTicketOwner(ticketId, answer);
}
private void sendMessageToTicketOwner(Long ticketId, String answer) {
Ticket ticket = ticketService.findByTicketId(ticketId);
if (ticket != null) {
long userChatId = ticket.getChatId();
if (answer != null && !answer.isEmpty()) {
sendSyncMessage(answer, userChatId);
} else {
sendSyncMessage("Sorry, the answer to this question is not ready yet.", userChatId);
}
} else {
log.error("Ticket not found for ID: {}", ticketId);
}
}
private void handleUserMessage(Update update) {
Message message = update.getMessage();
if (message != null && message.hasText()) {
String userMessage = message.getText();
long chatId = message.getChatId();
String botResponse = generateBotResponse(userMessage);
saveLog(update.getMessage().getFrom().getUserName(), userMessage, botResponse);
sendMessage(botResponse, chatId);
}
}
private void saveLog(String username, String message, String botResponse) {
LocalDateTime timestamp = LocalDateTime.now();
logService.saveLog(username, message, botResponse, timestamp);
}
public void saveTicket(String username, String question, LocalDateTime timestamp, Long chatId) {
Ticket ticket = new Ticket(username, question, timestamp);
ticket.setChatId(chatId);
ticketService.saveTicket(ticket);
}
private String generateBotResponse(String userMessage) {
OpenAiService service = new OpenAiService("your-openai-token");
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt(userMessage)
.model("text-davinci-003")
.maxTokens(255)
.build();
return service.createCompletion(completionRequest).getChoices().get(0).getText();
}
private void sendMessage(String textToSend, long chatId) {
SendMessage message = new SendMessage();
message.setChatId(String.valueOf(chatId));
if (!textToSend.isEmpty()) {
message.setText(textToSend);
}
send(message);
}
private void send(SendMessage sendMessage) {
try {
execute(sendMessage);
} catch (TelegramApiException e) {
log.error(Arrays.toString(e.getStackTrace()));
}
}
@Override
public String getBotUsername() {
return config.getBotUsername();
}
@Override
public String getBotToken() {
return config.getBotToken();
}
} | [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((5383, 5547), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((5383, 5522), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((5383, 5490), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((5383, 5447), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package com.erzbir.numeron.plugin.openai.config;
import com.erzbir.numeron.api.NumeronImpl;
import com.erzbir.numeron.utils.ConfigReadException;
import com.erzbir.numeron.utils.ConfigWriteException;
import com.erzbir.numeron.utils.JsonUtil;
import com.theokanning.openai.completion.CompletionRequest;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* @author Erzbir
* @Date: 2023/3/3 23:52
*/
public class CompletionConfig implements Serializable {
private static final Object key = new Object();
private static final String configFile = NumeronImpl.INSTANCE.getPluginWorkDir() + "chatgpt/config/completion.json";
private static volatile CompletionConfig INSTANCE;
private String model = "text-davinci-003";
private int max_tokens = 1024;
private double temperature = 1.0;
private double top_p = 1.0;
private double presence_penalty = 0.0;
private double frequency_penalty = 0.0;
private int number = 1;
private boolean echo = false;
private List<String> stop = null;
private int best_of = 1;
private Map<String, Integer> logit_bias = null;
private String suffix = null;
private CompletionConfig() {
}
public static CompletionConfig getInstance() {
if (INSTANCE == null) {
synchronized (key) {
if (INSTANCE == null) {
try {
INSTANCE = JsonUtil.load(configFile, CompletionConfig.class);
} catch (ConfigReadException e) {
throw new RuntimeException(e);
}
}
}
}
if (INSTANCE == null) {
synchronized (key) {
if (INSTANCE == null) {
INSTANCE = new CompletionConfig();
try {
JsonUtil.dump(configFile, INSTANCE, CompletionConfig.class);
} catch (ConfigWriteException e) {
throw new RuntimeException(e);
}
}
}
}
return INSTANCE;
}
public CompletionRequest load() {
return CompletionRequest.builder()
.maxTokens(max_tokens)
.model(model)
.n(number)
.presencePenalty(presence_penalty)
.topP(top_p)
.frequencyPenalty(frequency_penalty)
.bestOf(best_of)
.logitBias(logit_bias)
.suffix(suffix)
.echo(echo)
.suffix(suffix)
.stop(stop)
.build();
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getMax_tokens() {
return max_tokens;
}
public void setMax_tokens(int max_tokens) {
this.max_tokens = max_tokens;
}
public double getTemperature() {
return temperature;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
public double getTop_p() {
return top_p;
}
public void setTop_p(double top_p) {
this.top_p = top_p;
}
public double getPresence_penalty() {
return presence_penalty;
}
public void setPresence_penalty(double presence_penalty) {
this.presence_penalty = presence_penalty;
}
public double getFrequency_penalty() {
return frequency_penalty;
}
public void setFrequency_penalty(double frequency_penalty) {
this.frequency_penalty = frequency_penalty;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public boolean isEcho() {
return echo;
}
public void setEcho(boolean echo) {
this.echo = echo;
}
public List<String> getStop() {
return stop;
}
public void setStop(List<String> stop) {
this.stop = stop;
}
public int getBest_of() {
return best_of;
}
public void setBest_of(int best_of) {
this.best_of = best_of;
}
public Map<String, Integer> getLogit_bias() {
return logit_bias;
}
public void setLogit_bias(Map<String, Integer> logit_bias) {
this.logit_bias = logit_bias;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((582, 621), 'com.erzbir.numeron.api.NumeronImpl.INSTANCE.getPluginWorkDir'), ((2180, 2653), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2628), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2600), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2568), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2540), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2508), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2469), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2436), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2383), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2354), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2303), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2276), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2246), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
/*
* Copyright (c) 2023 Mariusz Bernacki <[email protected]>
* SPDX-License-Identifier: Apache-2.0
*/
package com.didalgo.intellij.chatgpt.chat;
import com.didalgo.intellij.chatgpt.text.TextContent;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import java.util.List;
public class DefaultChatMessageComposer implements ChatMessageComposer {
@Override
public ChatMessage compose(ConversationContext ctx, String prompt) {
return new ChatMessage(ChatMessageRole.USER.value(), prompt);
}
@Override
public ChatMessage compose(ConversationContext ctx, String prompt, List<? extends TextContent> textContents) {
if (textContents.isEmpty()) {
return compose(ctx, prompt);
}
textContents = ChatMessageUtils.composeExcept(textContents, ctx.getLastPostedCodeFragments(), prompt);
if (!textContents.isEmpty()) {
ctx.setLastPostedCodeFragments(textContents);
return compose(ctx, ChatMessageUtils.composeAll(prompt, textContents));
}
return compose(ctx, prompt);
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value"
] | [((547, 575), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')] |
package com.company.project.controllers;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
public class ChatCompletionController {
/**
* The version of AI model we'll send requests.
* This example uses gpt-4
* Other versions: https://platform.openai.com/docs/models/model-endpoint-compatibility
*/
@Value("${openai.model}")
private String model;
/**
* API key to access OpenAI API
*/
@Value("${openai.api.key}")
private String openaiApiKey;
/**
* Creates a chat request and sends it to the OpenAI API
* Returns the first message from the API response
*
* @param prompt the prompt to send to the API
* @return first message from the API response
*/
@PostMapping("/ai-chat")
public String chat(@RequestBody String prompt) {
OpenAiService service = new OpenAiService(openaiApiKey);
final List<ChatMessage> messages = new ArrayList<>();
final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.USER.value(), prompt);
messages.add(systemMessage);
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
.builder()
.model(model)
.messages(messages)
.maxTokens(250)
.build();
List<ChatCompletionChoice> choices = service.createChatCompletion(chatCompletionRequest).getChoices();
if (choices == null || choices.isEmpty()) {
return "No response";
}
return choices.get(0).getMessage().getContent();
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value"
] | [((1581, 1609), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')] |
package edu.sjsu.articlevisualisationbackend.service;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import edu.sjsu.articlevisualisationbackend.service.exception.InvalidChatGptGeneration;
import io.github.cdimascio.dotenv.Dotenv;
import org.json.JSONObject;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ChatGptDiagramGenerator {
private OpenAiService service;
private ChatCompletionRequest chatCompletionRequest;
private List<ChatMessage> messageRecord = new ArrayList<>();
private String pdfText;
private JSONObject chatGptPrompt;
private final String OPERATION_USR_MSG_JSON_KEY = "prompt_msg";
private final String OPERATION_FEW_SHOT_JSON_KEY = "few_shot";
private final String OPERATION_FEW_SHOT_PROMPT_JSON_KEY = "prompt_msg";
private final String OPERATION_FEW_SHOT_RESPONSE_JSON_KEY = "response";
public ChatGptDiagramGenerator(String pdfText) throws IOException {
this.initOpenAiService();
this.initChatCompletionRequest();
this.loadJsonPrompt();
this.initSystemMessage();
this.pdfText = pdfText;
}
public void setPdfText(String pdfText) {
this.pdfText = pdfText;
}
private void initOpenAiService() {
String apiKey = getApiKeyFromEnv();
this.service = new OpenAiService(
this.getApiKey()
);
}
private String getApiKey(){
String apiKey;
try{
apiKey = getApiKeyFromEnvFile();
} catch (Exception e) {
System.out.println("Error reading from env file");
apiKey = getApiKeyFromEnv();
}
return apiKey;
}
private String getApiKeyFromEnv(){
final String OPENAI_KEY_ENV_VAR = "OPENAI_KEY";
return System.getenv(OPENAI_KEY_ENV_VAR);
}
private String getApiKeyFromEnvFile() {
final String OPENAI_KEY_ENV_VAR = "OPENAI_KEY";
final String ENV_FILE_PATH = "src/main/resources/.env";
Dotenv dotenv = Dotenv.configure()
.filename(ENV_FILE_PATH)
.load();
return dotenv.get(OPENAI_KEY_ENV_VAR);
}
private void initChatCompletionRequest(){
final String CHAT_GPT_MODEL = "gpt-3.5-turbo";
this.chatCompletionRequest = ChatCompletionRequest
.builder()
.model(CHAT_GPT_MODEL)
.build();
}
private void loadJsonPrompt() throws IOException {
String jsonContent;
ClassPathResource resource = new ClassPathResource("prompt.json");
try (InputStream inputStream = resource.getInputStream()) {
jsonContent = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
}
this.chatGptPrompt = new JSONObject(jsonContent);
}
private void initSystemMessage(){
final String MESSAGE_JSON_KEY = "system_msg";
ChatMessage chatMessage = new ChatMessage(
ChatMessageRole.SYSTEM.value(),
this.chatGptPrompt.get(MESSAGE_JSON_KEY).toString()
);
this.messageRecord.add(chatMessage);
}
private void addNormalChatMessage(
String promptMessage,
String promptMessageAppendix
) {
ChatMessage chatUserMessage = new ChatMessage(
ChatMessageRole.USER.value(),
promptMessage + promptMessageAppendix
);
this.messageRecord.add(chatUserMessage);
}
private void addFewShotChatMessage(
String promptMessage,
String templateResponse
){
ChatMessage chatUserMessage = new ChatMessage(
ChatMessageRole.USER.value(),
promptMessage
);
ChatMessage chatAssistantMessage = new ChatMessage(
ChatMessageRole.ASSISTANT.value(),
templateResponse
);
this.messageRecord.add(chatUserMessage);
this.messageRecord.add(chatAssistantMessage);
}
private String sendAPIRequest(){
ChatMessage responseMessage = this.service.createChatCompletion(this.chatCompletionRequest).getChoices().get(0).getMessage();
return responseMessage.getContent();
}
private String makeRequest(
String operationJsonKey,
String promptMessageAppendix,
boolean isHasFewShotResponse
){
final JSONObject OPERATION_JSON_OBJECT = this.chatGptPrompt.getJSONObject(operationJsonKey);
if (isHasFewShotResponse) {
final JSONObject fewShotObject = OPERATION_JSON_OBJECT.getJSONObject(OPERATION_FEW_SHOT_JSON_KEY);
final String promptMessage = fewShotObject.getString(OPERATION_FEW_SHOT_PROMPT_JSON_KEY);
final String templateResponse = fewShotObject.getString(OPERATION_FEW_SHOT_RESPONSE_JSON_KEY);
this.addFewShotChatMessage(promptMessage, templateResponse);
}
this.addNormalChatMessage(
OPERATION_JSON_OBJECT.getString(OPERATION_USR_MSG_JSON_KEY),
promptMessageAppendix
);
this.chatCompletionRequest.setMessages(this.messageRecord);
return this.sendAPIRequest();
}
private String makeKeywordsRequest(){
final String OPERATION_JSON_KEY = "get_keyword_from_pdf";
return this.makeRequest(
OPERATION_JSON_KEY,
this.pdfText,
true
);
}
private String makeMermaidCodeRequest(String keywordText) {
final String OPERATION_JSON_KEY = "generate_mermaid_using_keyword";
return this.makeRequest(
OPERATION_JSON_KEY,
keywordText,
false
);
}
private String removeMermaidCodeHeadFoot(String mermaidCode){
final String MERMAID_CODE_HEAD = "```mermaid";
final String MERMAID_CODE_FOOT = "```";
return mermaidCode.replace(MERMAID_CODE_HEAD, "").replace(MERMAID_CODE_FOOT, "");
}
private boolean validateMermaidCode(String mermaidCode){
MermaidValidationApiCaller mermaidValidationApiCaller = new MermaidValidationApiCaller(mermaidCode);
return mermaidValidationApiCaller.validate();
}
private String generateReliableMermaidCode(String keywords) throws InvalidChatGptGeneration {
final int MAX_ATTEMPT_COUNT = 3;
int attemptCount = 0;
boolean isMermaidValid = false;
String mermaidCode;
do {
mermaidCode = this.makeMermaidCodeRequest(keywords);
mermaidCode = this.removeMermaidCodeHeadFoot(mermaidCode);
isMermaidValid = this.validateMermaidCode(mermaidCode);
attemptCount++;
} while (!isMermaidValid && attemptCount < MAX_ATTEMPT_COUNT);
if (isMermaidValid) {
return mermaidCode;
} else {
throw new InvalidChatGptGeneration("Failed to generate mermaid code");
}
}
public String generateMermaidCode() throws InvalidChatGptGeneration {
final String KEYWORDS_FROM_PDF = this.makeKeywordsRequest();
final String MERMAID_CODE = this.generateReliableMermaidCode(KEYWORDS_FROM_PDF);
return this.removeMermaidCodeHeadFoot(MERMAID_CODE);
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value"
] | [((2511, 2594), 'io.github.cdimascio.dotenv.Dotenv.configure'), ((2511, 2570), 'io.github.cdimascio.dotenv.Dotenv.configure'), ((3464, 3494), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3821, 3849), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((4161, 4189), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((4309, 4342), 'com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value')] |
package com.ramesh.openai;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
/***
* This project demonstrates a simple multi prompts usage
***/
class MultipleChatCompletion {
public static void main(String... args) {
// Set the Open AI Token & Model
String token = "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";
String model = "gpt-3.5-turbo";
// service handle for calling OpenAI APIs
OpenAiService service = new OpenAiService(token, Duration.ofSeconds(30));
// multiple prompts example
// Change these and run again and again
String[] prompts = new String[3];
prompts[0] = "Capital of India?";
prompts[1] = "No. of States in India?";
prompts[2] = "Prime Minister of India?";
// Loop through each prompt
for (int i = 0; i < 3; i++) {
String prompt = prompts[i];
// create the chat message
final List<ChatMessage> messages = new ArrayList<>();
final ChatMessage assistantMessage = new ChatMessage(ChatMessageRole.ASSISTANT.value(), prompt);
messages.add(assistantMessage);
// create the request object
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
.model(model)
.messages(messages)
.n(1)
.temperature(.1)
.maxTokens(50)
.logitBias(new HashMap<>())
.build();
// get the response from chat gpt
System.out.println("Prompt=" + prompt);
System.out.print("ChatGPT response=");
service.createChatCompletion(chatCompletionRequest).getChoices().forEach((c) -> {
System.out.println(c.getMessage().getContent());
});
System.out.println("--------------------------------");
}
service.shutdownExecutor();
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value",
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((1296, 1329), 'com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value'), ((1457, 1709), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1457, 1684), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1457, 1640), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1457, 1609), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1457, 1576), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1457, 1554), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1457, 1518), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package com.github.tornado2023team5.kanjichan.util;
import com.github.tornado2023team5.kanjichan.model.function.FunctionCallingBase;
import com.theokanning.openai.completion.chat.ChatFunctionCall;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
@RequiredArgsConstructor
@Service
public class FunctionCallUtil {
private final OpenAiService service;
public <T> T call(String text, FunctionCallingBase base) {
var executor = base.getExecutor();
var request = base.getRequest(executor);
request.setMessages(Arrays.asList(new ChatMessage(ChatMessageRole.SYSTEM.value(), base.getBaseMessages()), new ChatMessage(ChatMessageRole.USER.value(), text)));
ChatMessage responseMessage = service.createChatCompletion(request).getChoices().get(0).getMessage();
ChatFunctionCall functionCall = responseMessage.getFunctionCall();
return executor.execute(functionCall);
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value"
] | [((830, 860), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((903, 931), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')] |
package org.zhong.chatgpt.wechat.bot.msgprocess;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.yaml.snakeyaml.Yaml;
import org.zhong.chatgpt.wechat.bot.builder.OpenAiServiceBuilder;
import org.zhong.chatgpt.wechat.bot.config.BotConfig;
import org.zhong.chatgpt.wechat.bot.consts.BotConst;
import org.zhong.chatgpt.wechat.bot.model.BotMsg;
import org.zhong.chatgpt.wechat.bot.model.WehchatMsgQueue;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
import cn.zhouyafeng.itchat4j.beans.BaseMsg;
/**
* 使用普通OpenAI接口进行回复
* @author zhong
*
*/
public class OpenAIReplyProcessor implements MsgProcessor{
private static OpenAiService service = OpenAiServiceBuilder.build(BotConfig.getAppKey(), Duration.ofSeconds(300));
private static String model = "text-davinci-003";
private static Double temperature = 0.9;
private static Integer maxTokens = 2000;
private static Double topP = 1d;
private static Double frequencyPenalty = 0.2;
private static Double presencePenalty = 0.6;
private static List<String> stops = new ArrayList<String>();
static {
final Yaml yaml = new Yaml();
Map<String, Object> yamlMap = yaml.load(BotConfig.class.getResourceAsStream("/application.yml"));
String stopsStr = (String) yamlMap.get("bot.openai.completio.stop");
model = yamlMap.get("bot.openai.completio.model").toString();
temperature = Double.valueOf( yamlMap.get("bot.openai.completio.temperature").toString());
maxTokens = Integer.valueOf( yamlMap.get("bot.openai.completio.max_tokens").toString());
topP = Double.valueOf( yamlMap.get("bot.openai.completio.top_p").toString());
frequencyPenalty = Double.valueOf( yamlMap.get("bot.openai.completio.frequency_penalty").toString());
presencePenalty = Double.valueOf( yamlMap.get("bot.openai.completio.presence_penalty").toString());
if(StringUtils.isNotEmpty(stopsStr)) {
stops = Arrays.asList(stopsStr.split(","));
}
}
@Override
public void process(BotMsg botMsg) {
BaseMsg baseMsg = botMsg.getBaseMsg();
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt(baseMsg.getContent())
.model(model)
.maxTokens(maxTokens)
.temperature(temperature)
.topP(topP)
.frequencyPenalty(frequencyPenalty)
.presencePenalty(presencePenalty)
.echo(true)
.user(botMsg.getUserName())
.build();
try {
String text = service.createCompletion(completionRequest).getChoices().get(0).getText();
botMsg.setReplyMsg(text);
WehchatMsgQueue.pushSendMsg(botMsg);
}catch (Exception e) {
e.printStackTrace();
botMsg.setRetries(botMsg.getRetries() + 1);
if(botMsg.getRetries() < 5) {
WehchatMsgQueue.pushReplyMsg(botMsg);
}else {
String recontent = baseMsg.getContent();
if(recontent.length() > 20) {
recontent = recontent.substring(0, 17) + "...\n";
}
botMsg.setReplyMsg(recontent+ "该提问已失效,请重新提问");
WehchatMsgQueue.pushSendMsg(botMsg);
}
}
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((1358, 1413), 'org.zhong.chatgpt.wechat.bot.config.BotConfig.class.getResourceAsStream'), ((2260, 2568), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2555), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2523), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2507), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2469), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2429), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2413), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2383), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2351), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2327), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package biz.readmylegal.backend;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import com.theokanning.openai.completion.chat.ChatCompletionChunk;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
public class GPTBackend {
private OpenAiService service;
private List<String> currentResponse;
public GPTBackend(String apiKey) {
this.service = new OpenAiService(apiKey, Duration.ofSeconds(30));
this.currentResponse = new LinkedList<>();
}
final static String audioInstructions =
"Give a small, succinct, and basic summary of the following audio transcript. " +
"It is not known in these instructions what the transcript formatting or contents " +
"are beyond that it involves some discussion of law and legal processes such as " +
"an interview between lawyer and client, some presentation discussing laws, etc. " +
"Give the summary in the form of a singular short paragraph, discuss what information " +
"was exchanged. Ignore any transcripts which make no mention of law or any legal " +
"process or do not appear to be transcripts of human conversation, and simply state " +
"that the given transcript does not fit the requirements for processing.";
final static String legalInstructions =
"Give a small, succinct, and basic analysis of the following legal document " +
"in a such a way that someone inexperienced with legal terms can understand it. " +
"Do so in the following format: a section which shows the legal rights and " +
"responsibilities of the person/party submitting the document in bulleted form, " +
"a section which shows the legal rights and responsibilities of the person/party " +
"who wrote, created, or provided the document to the aforementioned person/party " +
"in bulleted form, and finally a small paragraph summary of other aspects of the " +
" document which are important or should otherwise be noted if the prior two " +
"categories aren't sufficient. If the provided document or text has nothing to do" +
"with any kind of legal agreement or notice, simply express that it's not a legal " +
"document and don't attempt any further analysis.";
// Awaits response from gpt-3.5-turbo based on given prompt
// Blocks until the response is given
public synchronized String promptAwaitResponse(String prompt, String type) {
System.out.println("Processing prompt.");
String instructions;
if (type.equals("document"))
instructions = legalInstructions;
else if (type.equals("transcript"))
instructions = audioInstructions;
else
return "Invalid processing typing given \"" + type + "\"";
final List<ChatMessage> messages = new ArrayList<>();
final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), instructions);
final ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), prompt);
messages.add(systemMessage);
messages.add(userMessage);
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
.builder()
.model("gpt-3.5-turbo")
.messages(messages)
.n(1)
.maxTokens(512)
.logitBias(new HashMap<>())
.build();
service.streamChatCompletion(chatCompletionRequest)
.doOnError(Throwable::printStackTrace)
.blockingForEach(this::addChunk);
System.out.println("Finished processing prompt.");
String response = currentResponseAsString();
currentResponse.clear();
return response;
}
public void stop() {
service.shutdownExecutor();
}
private String currentResponseAsString() {
StringBuilder response = new StringBuilder();
for(String s : currentResponse) {
response.append(s);
}
return response.toString();
}
private void addChunk(ChatCompletionChunk chunk) {
if (chunk.getChoices().isEmpty() || chunk.getChoices().get(0).getMessage().getContent() == null)
return;
String chunkString = chunk.getChoices().get(0).getMessage().getContent();
currentResponse.add(chunkString);
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value"
] | [((3285, 3315), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3388, 3416), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')] |
package net.anotheria.anosite.cms.translation;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import net.anotheria.anosite.config.LocalizationAutoTranslationTokenConfig;
import net.anotheria.anosite.gen.shared.service.BasicService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
public class IASGTranslationTranslationServiceImpl extends BasicService implements IASGTranslationService {
private static IASGTranslationTranslationServiceImpl instance;
private static final Logger log = LoggerFactory.getLogger(IASGTranslationTranslationServiceImpl.class);
private static final String PROMPT = "You will get a localizations in format 'key'='translation'. Translate it from %s to %s without any explanations.\n" +
"Localizations:\n \"\"\"\n%s\n\"\"\"";
private LocalizationAutoTranslationTokenConfig config;
private OpenAiService openAiService;
public IASGTranslationTranslationServiceImpl() {
this.config = LocalizationAutoTranslationTokenConfig.getInstance();
this.openAiService = new OpenAiService(config.getToken(), Duration.ofSeconds(240));
}
@Override
public String translate(String originLanguage, String targetLanguage, String bundleContent) {
String result = "";
String formattedPrompt = String.format(PROMPT, originLanguage, targetLanguage, bundleContent);
List<ChatMessage> chatMessageList = new ArrayList<>();
chatMessageList.add(new ChatMessage(ChatMessageRole.SYSTEM.value(), formattedPrompt));
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
.model("gpt-3.5-turbo")
.messages(chatMessageList)
.user("testing")
.temperature(0.0)
.build();
int maxAttempts = 15;
int currentAttempt = 1;
while (currentAttempt <= maxAttempts) {
try {
List<ChatCompletionChoice> choices = openAiService.createChatCompletion(chatCompletionRequest).getChoices();
if (!choices.isEmpty()) {
for (ChatCompletionChoice choice : choices) {
return choice.getMessage().getContent();
}
}
} catch (RuntimeException ex) {
if (ex.getMessage().toLowerCase().contains("http") || ex.getMessage().toLowerCase().contains("timeout") || ex.getMessage().toLowerCase().contains("that model is currently overloaded with other requests")) {
log.error("Cannot translate localizations. Exception: {}.\n Attempt #{}", ex.getMessage(), currentAttempt);
currentAttempt++; // request to openAI can often fail. So will try one more time. There are only 15 attempts.
} else {
log.error("Cannot translate localizations. Exception: {}.", ex.getMessage());
break;
}
}
}
return result;
}
static IASGTranslationTranslationServiceImpl getInstance() {
if (instance == null) {
instance = new IASGTranslationTranslationServiceImpl();
}
return instance;
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value",
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((1812, 1842), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((1918, 2124), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1918, 2099), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1918, 2065), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1918, 2032), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1918, 1989), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package de.ja.view.explanation.text;
import com.ibm.icu.text.RuleBasedNumberFormat;
import com.ibm.icu.text.SimpleDateFormat;
import com.knuddels.jtokkit.api.ModelType;
import com.theokanning.openai.OpenAiHttpException;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import de.ja.view.ExplainerFrame;
import de.ja.view.explanation.text.textinfo.GeneratedTextsPanel;
import de.swa.gc.GraphCode;
import net.miginfocom.swing.MigLayout;
import org.jdesktop.swingx.JXTaskPane;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.List;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
public class TextPanel extends JPanel implements ActionListener {
// API-Key.
private static String key;
// Textfeld für die generierte Prompt.
private final JTextArea promptArea;
private final JSpinner temperatureSpinner;
private final JSpinner topPSpinner;
// Anzahl zu generierender Texte.
private final JSpinner nSpinner;
private final JSpinner maxTokensSpinner;
private final JSpinner presencePenaltySpinner;
private final JSpinner frequencyPenaltySpinner;
private final JComboBox<String> modelTypeComboBox;
private final JButton generateChatCompletions;
// Nachrichten, die die Prompt darstellen.
private List<ChatMessage> messages = new ArrayList<>();
// Panel für alle generierten Texte.
private final GeneratedTextsPanel generatedTextsPanel;
// Referenz.
private final ExplainerFrame reference;
public TextPanel(ExplainerFrame reference) {
this.reference = reference;
key = System.getenv("OpenAI-Key");
// Layout definieren.
MigLayout imagePanelMigLayout = new MigLayout("" , "[fill, grow]", "10[12.5%][][fill,57.5%][fill,30%]"); //1. 12.5%
setLayout(imagePanelMigLayout);
// Textfeld für die Prompt initialisieren und konfigurieren.
promptArea = new JTextArea();
promptArea.setLineWrap(true);
promptArea.setWrapStyleWord(true);
promptArea.setEditable(false);
JScrollPane promptSP = new JScrollPane(promptArea);
promptSP.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
promptSP.setBorder(new TitledBorder("Generated Prompt"));
add(promptSP, "cell 0 3, growx, height ::30%, aligny top");
// Ästhetische Eigenschaften für erweiterte Optionen einstellen...
UIManager.put("TaskPane.animate", Boolean.FALSE);
UIManager.put("TaskPane.titleOver", new Color(200, 200, 200));
UIManager.put("TaskPane.titleForeground", new Color(187, 187, 187));
UIManager.put("TaskPane.titleBackgroundGradientStart", new Color(85, 88, 89));
UIManager.put("TaskPane.titleBackgroundGradientEnd", new Color(85, 88, 89));
UIManager.put("TaskPane.background", new Color(76, 80, 82));
UIManager.put("TaskPane.borderColor", new Color(94, 96, 96));
// Erweiterte Optionen initialisieren und konfigurieren.
JXTaskPane advancedOptions = new JXTaskPane();
advancedOptions.setCollapsed(true);
advancedOptions.setTitle("Advanced Options");
add(advancedOptions, "cell 0 0, growx, aligny top");
// Layout für die Optionen in den erweiterten Optionen definieren.
MigLayout advancedOptionsMigLayout = new MigLayout("", "0[]5[]10[]5[]0", "0[]0");
advancedOptions.setLayout(advancedOptionsMigLayout);
// Erweiterte Optionen definieren.
JLabel temperatureLabel = new JLabel("Temperature:");
temperatureLabel.setHorizontalTextPosition(SwingConstants.CENTER);
temperatureLabel.setHorizontalAlignment(SwingConstants.CENTER);
temperatureSpinner = new JSpinner();
SpinnerNumberModel temperatureSpinnerModel = new SpinnerNumberModel(0, 0, 2, 0.1);
temperatureSpinner.setModel(temperatureSpinnerModel);
JLabel topPLabel = new JLabel("Top P:");
topPLabel.setHorizontalTextPosition(SwingConstants.CENTER);
topPLabel.setHorizontalAlignment(SwingConstants.CENTER);
topPSpinner = new JSpinner();
SpinnerNumberModel topPSpinnerModel = new SpinnerNumberModel(0, 0, 1, 0.01);
topPSpinner.setModel(topPSpinnerModel);
JLabel nLabel = new JLabel("N:");
nLabel.setHorizontalTextPosition(SwingConstants.CENTER);
nLabel.setHorizontalAlignment(SwingConstants.CENTER);
nSpinner = new JSpinner();
SpinnerNumberModel nSpinnerModel = new SpinnerNumberModel(1, 1, 10, 1);
nSpinner.setModel(nSpinnerModel);
JLabel maxTokensLabel = new JLabel("Max Tokens:");
maxTokensLabel.setHorizontalTextPosition(SwingConstants.CENTER);
maxTokensLabel.setHorizontalAlignment(SwingConstants.CENTER);
maxTokensSpinner = new JSpinner();
SpinnerNumberModel maxTokensSpinnerModel = new SpinnerNumberModel(256, 0, 8192, 1);
maxTokensSpinner.setModel(maxTokensSpinnerModel);
JLabel presencePenaltyLabel = new JLabel("Presence Penalty:");
presencePenaltyLabel.setHorizontalTextPosition(SwingConstants.CENTER);
presencePenaltyLabel.setHorizontalAlignment(SwingConstants.CENTER);
presencePenaltySpinner = new JSpinner();
SpinnerNumberModel presencePenaltySpinnerModel = new SpinnerNumberModel(0, -2, 2, 0.1);
presencePenaltySpinner.setModel(presencePenaltySpinnerModel);
JLabel frequencyPenaltyLabel = new JLabel("Frequency Penalty:");
frequencyPenaltyLabel.setHorizontalTextPosition(SwingConstants.CENTER);
frequencyPenaltyLabel.setHorizontalAlignment(SwingConstants.CENTER);
frequencyPenaltySpinner = new JSpinner();
SpinnerNumberModel frequencyPenaltySpinnerModel = new SpinnerNumberModel(0, -2, 2, 0.1);
frequencyPenaltySpinner.setModel(frequencyPenaltySpinnerModel);
JLabel modelTypeLabel = new JLabel("Model Type:");
modelTypeLabel.setHorizontalTextPosition(SwingConstants.CENTER);
modelTypeLabel.setHorizontalAlignment(SwingConstants.CENTER);
modelTypeComboBox = new JComboBox<>();
for(ModelType type : ModelType.values()) {
modelTypeComboBox.addItem(type.getName());
}
advancedOptions.add(temperatureLabel);
advancedOptions.add(temperatureSpinner);
advancedOptions.add(topPLabel);
advancedOptions.add(topPSpinner);
advancedOptions.add(nLabel);
advancedOptions.add(nSpinner, "wrap");
advancedOptions.add(maxTokensLabel);
advancedOptions.add(maxTokensSpinner);
advancedOptions.add(presencePenaltyLabel);
advancedOptions.add(presencePenaltySpinner);
advancedOptions.add(frequencyPenaltyLabel);
advancedOptions.add(frequencyPenaltySpinner, "wrap");
advancedOptions.add(modelTypeLabel);
advancedOptions.add(modelTypeComboBox, "width ::84px");
// Knopf zum Generieren von Texten.
generateChatCompletions = new JButton("Generate Chat-Completion(s)");
generateChatCompletions.addActionListener(this);
add(generateChatCompletions, "cell 0 1, width ::190px, aligny top");
// Modell der generativen KI.
generatedTextsPanel = new GeneratedTextsPanel();
add(generatedTextsPanel, "cell 0 2, growx, aligny top");
}
/**
* Graph Code verarbeiten
* @param graphCode Ausgewählter Graph Code.
*/
public void setGraphCode(GraphCode graphCode) {
if(graphCode != null) {
String prompt = setUpPrompt(graphCode);
promptArea.setText(prompt);
} else {
promptArea.setText(null);
}
}
/**
* Prompt vorbereiten und aus Graph Code
* generieren.
* @param graphCode Ausgewählter Graph Code.
* @return Generierte Prompt.
*/
private String setUpPrompt(GraphCode graphCode) {
String s = graphCode.getFormattedTerms();
messages = new ArrayList<>();
messages.add(new ChatMessage(ChatMessageRole.SYSTEM.value(),
"You are an assistant, who is able to generate cohesive textual explanations based on a collection of words."));
messages.add(new ChatMessage(
ChatMessageRole.SYSTEM.value(),
"The collection of words represents a dictionary. The dictionary contains so-called feature " +
"vocabulary terms. Additionally some of these terms are connected through a relationship. " +
"These relationships will be noted as <i_t> - <i_t1,...,i_tn>, where i_t denotes the index of a feature " +
"vocabulary term in the given collection."));
messages.add(new ChatMessage(
ChatMessageRole.SYSTEM.value(),
"Using these terms, we can create a coherent explanation that accurately " +
"describes the terms and its relations.\n" +
"\n" +
"An example could be: The image shows water, the sky, and clouds. " +
"We can imagine a scene with clouds floating in the sky above."));
messages.add(new ChatMessage(
ChatMessageRole.USER.value(),
"The collections of words is as follows: " + graphCode.listTerms() + ". Only respect these terms and its relations: " + s + ", and ignore all others. " +
"Do not create an explanation regarding the dictionary. Only generate a text containing " +
"the terms of the dictionary like in the example above."));
messages.add(new ChatMessage(
ChatMessageRole.ASSISTANT.value(),
"Based on the dictionary, here is a cohesive text " +
"containing the terms from the dictionary:"));
// Nachrichten zusammenfügen.
return messages.stream().map(ChatMessage::getContent).collect(Collectors.joining("\n"));
}
@Override
public void actionPerformed(ActionEvent e) {
// Tabs zurücksetzen.
generatedTextsPanel.reset();
// Anbindung zur Schnittstelle.
OpenAiService service = new OpenAiService(key, Duration.ofSeconds(60));
if(key.isEmpty()) {
reference.getExplainerConsoleModel().insertText("OpenAI-Key is missing, abort process. Must be set in launch-config: OpenAI-Key=...");
return;
}
// Prozess erstellen.
ExecutorService executor = Executors.newSingleThreadExecutor();
Thread t = new Thread(() -> {
// Textanfrage initialisieren und parametrisieren.
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
.messages(messages)
.model((String) modelTypeComboBox.getSelectedItem())
.temperature((Double) temperatureSpinner.getValue())
.topP((Double) topPSpinner.getValue())
.n((Integer) nSpinner.getValue())
.maxTokens((Integer) maxTokensSpinner.getValue())
.presencePenalty((Double) presencePenaltySpinner.getValue())
.frequencyPenalty((Double) frequencyPenaltySpinner.getValue())
.build();
try {
// Cursor auf Warten setzen.
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
// Knopf deaktivieren.
generateChatCompletions.setEnabled(false);
// Info in der Konsole ausgeben.
RuleBasedNumberFormat numberFormat = new RuleBasedNumberFormat(Locale.US, RuleBasedNumberFormat.SPELLOUT);
reference.getExplainerConsoleModel()
.insertText(String.format("Generating %s textual explanation%s!",
numberFormat.format(nSpinner.getValue()),
(int) nSpinner.getValue() > 1 ? "s" : ""));
// Textanfrage an Endpunkt senden.
ChatCompletionResult chatCompletionResult = service.createChatCompletion(chatCompletionRequest);
// Anhand des Ergebnisses Tabs hinzufügen.
Optional<ModelType> model = ModelType.fromName((String) modelTypeComboBox.getSelectedItem());
ModelType modelType = ModelType.GPT_4;
if(model.isPresent()) {
modelType = model.get();
}
generatedTextsPanel.addTabsFromResult(chatCompletionResult, modelType);
// Texte speichern.
for(int i = 0; i < chatCompletionResult.getChoices().size(); i++) {
Files.createDirectories(Paths.get(System.getProperty("user.dir") + "/explanations/text/"));
String content = chatCompletionResult.getChoices().get(i).getMessage().getContent();
String timeStamp = new SimpleDateFormat("dd-MM-yyyy_HHmmss").format(new Date());
String fileName = String.format("explanations/text/%s-text-%s.txt", timeStamp, i + 1);
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(content);
writer.close();
}
} catch(OpenAiHttpException openAiHttpException) {
if(openAiHttpException.statusCode == 401) {
JOptionPane.showMessageDialog(null,
"You provided an invalid API-Key!",
"Authentication Error", JOptionPane.ERROR_MESSAGE);
reference.getExplainerConsoleModel().insertText("You provided an invalid API-Key!");
}
} catch (Exception ex) {
ex.printStackTrace();
// Fehler in Konsole ausgeben.
reference.getExplainerConsoleModel().insertText(ex.getMessage());
} finally {
// Cursor auf Standard zurücksetzen.
setCursor(Cursor.getDefaultCursor());
// Knopf reaktivieren.
generateChatCompletions.setEnabled(true);
}
});
// Prozess ausführen und beenden.
executor.execute(t);
executor.shutdown();
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value",
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((8619, 8649), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((8834, 8864), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((9352, 9382), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((9816, 9844), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((10270, 10303), 'com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value'), ((11306, 11899), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11870), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11787), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11706), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11636), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11582), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11523), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11450), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11377), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package org.example.chatgpt.service;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.theokanning.openai.OpenAiApi;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import retrofit2.Retrofit;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.theokanning.openai.service.OpenAiService.*;
/**
* 会话服务
*
* @author lijiatao
* 时间: 2023/12/6
*/
@Service
public class ChatService {
private static final Logger LOG = LoggerFactory.getLogger(ChatService.class);
String token = "sk-xxx";
String proxyHost = "127.0.0.1";
int proxyPort = 7890;
/**
* 流式对话
* 注:必须使用异步处理(否则发送消息不会及时返回前端)
*
* @param prompt 输入消息
* @param sseEmitter SSE对象
*/
@Async
public void streamChatCompletion(String prompt, SseEmitter sseEmitter) {
LOG.info("发送消息:" + prompt);
final List<ChatMessage> messages = new ArrayList<>();
final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), prompt);
messages.add(systemMessage);
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
.builder()
.model("gpt-3.5-turbo")
.messages(messages)
.n(1)
// .maxTokens(500)
.logitBias(new HashMap<>())
.build();
//流式对话(逐Token返回)
StringBuilder receiveMsgBuilder = new StringBuilder();
OpenAiService service = buildOpenAiService(token, proxyHost, proxyPort);
service.streamChatCompletion(chatCompletionRequest)
//正常结束
.doOnComplete(() -> {
LOG.info("连接结束");
//发送连接关闭事件,让客户端主动断开连接避免重连
sendStopEvent(sseEmitter);
//完成请求处理
sseEmitter.complete();
})
//异常结束
.doOnError(throwable -> {
LOG.error("连接异常", throwable);
//发送连接关闭事件,让客户端主动断开连接避免重连
sendStopEvent(sseEmitter);
//完成请求处理携带异常
sseEmitter.completeWithError(throwable);
})
//收到消息后转发到浏览器
.blockingForEach(x -> {
ChatCompletionChoice choice = x.getChoices().get(0);
LOG.debug("收到消息:" + choice);
if (StrUtil.isEmpty(choice.getFinishReason())) {
//未结束时才可以发送消息(结束后,先调用doOnComplete然后还会收到一条结束消息,因连接关闭导致发送消息失败:ResponseBodyEmitter has already completed)
sseEmitter.send(choice.getMessage());
}
String content = choice.getMessage().getContent();
content = content == null ? StrUtil.EMPTY : content;
receiveMsgBuilder.append(content);
});
LOG.info("收到的完整消息:" + receiveMsgBuilder);
}
/**
* 发送连接关闭事件,让客户端主动断开连接避免重连
*
* @param sseEmitter
* @throws IOException
*/
private static void sendStopEvent(SseEmitter sseEmitter) throws IOException {
sseEmitter.send(SseEmitter.event().name("stop").data(""));
}
/**
* 构建OpenAiService
*
* @param token API_KEY
* @param proxyHost 代理域名
* @param proxyPort 代理端口号
* @return OpenAiService
*/
private OpenAiService buildOpenAiService(String token, String proxyHost, int proxyPort) {
//构建HTTP代理
Proxy proxy = null;
if (StrUtil.isNotBlank(proxyHost)) {
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
}
//构建HTTP客户端
OkHttpClient client = defaultClient(token, Duration.of(60, ChronoUnit.SECONDS))
.newBuilder()
.proxy(proxy)
.build();
ObjectMapper mapper = defaultObjectMapper();
Retrofit retrofit = defaultRetrofit(client, mapper);
OpenAiApi api = retrofit.create(OpenAiApi.class);
OpenAiService service = new OpenAiService(api, client.dispatcher().executorService());
return service;
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value"
] | [((1799, 1829), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((4341, 4381), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((4341, 4372), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event')] |
package com.beginner.techies.chatgptintegration.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.beginner.techies.chatgptintegration.dto.ChatMessagePrompt;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.service.OpenAiService;
@RestController
public class ChatGPTController {
@GetMapping("/getChat/{prompt}")
public String getPrompt(@PathVariable String prompt) {
// /v1/completion -> text-davinci-003, text-davinci-002, text-curie-001,
// text-babbage-001, text-ada-001
OpenAiService service = new OpenAiService("ADD_YOUR_SECRET_KEY_HERE");
CompletionRequest completionRequest = CompletionRequest.builder().prompt(prompt).model("text-davinci-003")
.echo(true).build();
return service.createCompletion(completionRequest).getChoices().get(0).getText();
}
@PostMapping("/chat")
public String getChatMessages(@RequestBody ChatMessagePrompt prompt) {
// /v1/chat/completions ->
// gpt-4, gpt-4-0613, gpt-4-32k, gpt-4-32k-0613, gpt-3.5-turbo,
// gpt-3.5-turbo-0613, gpt-3.5-turbo-16k, gpt-3.5-turbo-16k-0613
OpenAiService service = new OpenAiService("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");
ChatCompletionRequest completionRequest = ChatCompletionRequest.builder().messages(prompt.getChatMessage())
.model("gpt-3.5-turbo-16k").build();
return service.createChatCompletion(completionRequest).getChoices().get(0).getMessage().getContent();
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder",
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((983, 1075), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((983, 1067), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((983, 1051), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((983, 1025), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1568, 1673), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1568, 1665), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1568, 1633), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package com.github.pablwoaraujo;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Arrays;
import com.knuddels.jtokkit.Encodings;
import com.knuddels.jtokkit.api.ModelType;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
public class ProfileIdentifier {
public static void main(String[] args) {
var promptSistema = """
Identifique o perfil de compra de cada cliente.
A resposta deve ser:
Cliente - descreva o perfil do cliente em três palavras
""";
var clientes = loadCustomersFromFile();
var quantidadeTokens = countTokens(clientes);
var modelo = "gpt-3.5-turbo";
var tamanhoRespostaEsperada = 2048;
if (quantidadeTokens > 4096 - tamanhoRespostaEsperada) {
modelo = "gpt-3.5-turbo-16k";
}
System.out.println("QTD TOKENS: " + quantidadeTokens);
System.out.println("Modelo escolhido: " + modelo);
var request = ChatCompletionRequest
.builder()
.model(modelo)
.maxTokens(tamanhoRespostaEsperada)
.messages(Arrays.asList(
new ChatMessage(
ChatMessageRole.SYSTEM.value(),
promptSistema),
new ChatMessage(
ChatMessageRole.SYSTEM.value(),
clientes)))
.build();
var key = System.getenv("OPENAI_API_KEY");
var service = new OpenAiService(key, Duration.ofSeconds(60));
System.out.println(
service
.createChatCompletion(request)
.getChoices().get(0).getMessage().getContent());
}
private static String loadCustomersFromFile() {
try {
var path = Path.of(ClassLoader
.getSystemResource("lista_de_compras_10_clientes.csv")
.toURI());
return Files.readAllLines(path).toString();
} catch (Exception e) {
throw new RuntimeException("Erro ao carregar o arquivo!", e);
}
}
private static int countTokens(String prompt) {
var registry = Encodings.newDefaultEncodingRegistry();
var enc = registry.getEncodingForModel(ModelType.GPT_3_5_TURBO);
return enc.countTokens(prompt);
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value"
] | [((1472, 1502), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((1625, 1655), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((2271, 2306), 'java.nio.file.Files.readAllLines')] |
package tech.ailef.jpromptmanager.completion;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import com.theokanning.openai.OpenAiHttpException;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.service.OpenAiService;
import tech.ailef.jpromptmanager.exceptions.JPromptManagerException;
/**
* An implementation of the LLMConnector that allows to make requests
* to the ChatGPT OpenAI endpoints.
*
*/
public class OpenAIChatGPTConnector implements LLMConnector {
private OpenAiService service;
private String model;
private String systemPrompt;
private int maxRetries;
/**
* Builds the connector to ChatGPT with the required parameters.
* @param apiKey OpenAI secret key
* @param timeout timeout for requests, 0 means no timeout
* @param model the OpenAI model to use (this setting will be overridden if an individual `<step>` tag provides a different value),
* @param systemPrompt the system prompt
*/
public OpenAIChatGPTConnector(String apiKey, int timeout, String model, String systemPrompt) {
this(apiKey, timeout, 0, model, systemPrompt);
}
/**
* Builds the connector to ChatGPT with the required parameters.
* @param apiKey OpenAI secret key
* @param timeout timeout for requests, 0 means no timeout
* @param model the OpenAI model to use (this setting will be overridden if an individual `<step>` tag provides a different value),
*/
public OpenAIChatGPTConnector(String apiKey, int timeout, String model) {
this(apiKey, timeout, 0, model, "You are a helpful assistant.");
}
/**
* Builds the connector to ChatGPT with the required parameters.
* @param apiKey OpenAI secret key
* @param timeout timeout for requests, 0 means no timeout
* @param model the OpenAI model to use (this setting will be overridden if an individual `<step>` tag provides a different value)
* @param maxRetries the number of times to retry a request that fails, default 0
*/
public OpenAIChatGPTConnector(String apiKey, int timeout, int maxRetries, String model) {
this(apiKey, timeout, maxRetries, model, "You are a helpful assistant.");
}
/**
* Builds the connector to ChatGPT with the required parameters.
* @param apiKey OpenAI secret key
* @param timeout timeout for requests, 0 means no timeout
* @param model the OpenAI model to use (this setting will be overridden if an individual `<step>` tag provides a different value),
* @param systemPrompt the initial system prompt that gets prepended to each conversation (see https://platform.openai.com/docs/guides/chat)
*/
public OpenAIChatGPTConnector(String apiKey, int timeout, int maxRetries, String model, String systemPrompt) {
service = new OpenAiService(apiKey, Duration.ofSeconds(timeout));
this.maxRetries = maxRetries;
if (model == null)
throw new JPromptManagerException("Must specify which OpenAI model to use");
this.model = model;
this.systemPrompt = systemPrompt;
}
/**
* Requests a completion for the given text/params to OpenAI.
*/
@Override
public String complete(String prompt, Map<String, String> params) {
int maxTokens = Integer.parseInt(params.get("maxTokens"));
double temperature = Double.parseDouble(params.get("temperature"));
String[] messages = prompt.split("(" + LLMConnector.PROMPT_TOKEN + ")|(" + LLMConnector.COMPLETION_TOKEN + ")");
AtomicInteger count = new AtomicInteger(0);
List<ChatMessage> chatMessages = Arrays.asList(messages).stream().filter(x -> x.trim().length() > 0)
.map(x -> x.trim())
.map(x -> {
if (count.get() % 2 == 0) {
return new ChatMessage("user", x);
} else {
return new ChatMessage("assistant", x);
}
})
.collect(Collectors.toList());
chatMessages.add(0, new ChatMessage("system", systemPrompt));
int tries = 1;
while (tries <= maxRetries) {
try {
ChatCompletionRequest completionRequest = ChatCompletionRequest.builder()
.messages(chatMessages)
.maxTokens(maxTokens)
.temperature(temperature)
.model(model)
.build();
ChatCompletionResult chatCompletion = service.createChatCompletion(completionRequest);
ChatCompletionChoice choice = chatCompletion.getChoices().get(0);
return choice.getMessage().getContent();
} catch (OpenAiHttpException e) {
System.err.println("On try " + tries + ", got exception: " + e.getMessage());
tries++;
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
throw new RuntimeException(e);
}
}
}
throw new RuntimeException("Request failed after " + tries + " retries");
}
@Override
public Map<String, String> getDefaultParams() {
Map<String, String> params = new HashMap<>();
params.put("model", model);
params.put("temperature", "0");
params.put("maxTokens", "256");
return params;
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((3817, 4097), 'java.util.Arrays.asList'), ((3817, 4064), 'java.util.Arrays.asList'), ((3817, 3907), 'java.util.Arrays.asList'), ((3817, 3884), 'java.util.Arrays.asList'), ((3817, 3849), 'java.util.Arrays.asList'), ((4270, 4421), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4270, 4407), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4270, 4388), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4270, 4357), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4270, 4330), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package com.archeruu.ai.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.theokanning.openai.OpenAiApi;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.service.OpenAiService;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import retrofit2.Retrofit;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import static com.theokanning.openai.service.OpenAiService.*;
/**
* 调用openai API
*
* 确保7890接口可以访问国外网
*
* @author Archer
*/
public class ChatApiLocalProxyUtil {
public static String chatApi(String content) {
String key = "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";
// 配置 V2ray 代理
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890));
OkHttpClient client = defaultClient(key, Duration.ofMinutes(1))
.newBuilder()
.proxy(proxy)
.build();
// 创建 OpenAiService
ObjectMapper mapper = defaultObjectMapper();
Retrofit retrofit = defaultRetrofit(client, mapper);
OpenAiApi api = retrofit.create(OpenAiApi.class);
OpenAiService service = new OpenAiService(api);
// 创建 ChatCompletionRequest
ChatMessage chatMessage = new ChatMessage("user", content);
List<ChatMessage> chatMessageList = new ArrayList<>();
chatMessageList.add(chatMessage);
ChatCompletionRequest completionRequest = ChatCompletionRequest.builder()
.messages(chatMessageList)
.model("gpt-3.5-turbo")
.maxTokens(500)
.temperature(0.2)
.build();
// 调用 OpenAiService
ChatCompletionResult completionResult = service.createChatCompletion(completionRequest);
String result = completionResult.getChoices().get(0).getMessage().getContent();
if (result.startsWith("{")) {
String error = "出了点小问题呢,换个问题试试。";
return error;
}
return result.trim();
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((1754, 1960), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1754, 1935), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1754, 1901), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1754, 1868), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1754, 1828), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package com.wy.chatting.domain.chatgpt.service.dto.request;
import java.util.List;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class GPTCompletionChatRequest {
private String model;
private String role;
private String message;
private Integer maxTokens;
public static ChatCompletionRequest of(GPTCompletionChatRequest request) {
return ChatCompletionRequest.builder()
.model(request.getModel())
.messages(convertChatMessage(request))
.maxTokens(request.getMaxTokens())
.build();
}
private static List<ChatMessage> convertChatMessage(GPTCompletionChatRequest request) {
return List.of(new ChatMessage(request.getRole(), request.getMessage()));
}
} | [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((600, 805), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((600, 780), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((600, 729), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((600, 674), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package com.lazzy.base.openai;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
/**
* open ai 三方库集成demo
*/
public class ChatGPTIntegration {
public static void main(String[] args) {
new ChatGPTIntegration().chat("中医与西医相比有什么区别");
}
public void chat(String question) {
OpenAiService service = new OpenAiService("openai key");
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt("Somebody once told me the world is gonna roll me")
.model("gpt-3.5-turbo")
.echo(true)
.build();
service.createCompletion(completionRequest).getChoices().forEach(System.out::println);
}
} | [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((499, 695), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((499, 670), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((499, 642), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((499, 602), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package com.erzbir.numeron.plugin.openai.config;
import com.erzbir.numeron.api.NumeronImpl;
import com.erzbir.numeron.utils.ConfigReadException;
import com.erzbir.numeron.utils.ConfigWriteException;
import com.erzbir.numeron.utils.JsonUtil;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import java.io.Serializable;
/**
* @author Erzbir
* @Date: 2023/3/3 23:54
*/
public class QuestionConfig implements Serializable {
private static final Object key = new Object();
private static final String configFile = NumeronImpl.INSTANCE.getPluginWorkDir() + "chatgpt/config/question.json";
private static volatile QuestionConfig INSTANCE;
private String model = "gpt-3.5-turbo";
private int max_tokens = 2048;
private double temperature = 0.0;
private double top_p = 1.0;
private double presence_penalty = 0.0;
private double frequency_penalty = 0.0;
private int n = 1;
private QuestionConfig() {
}
public static QuestionConfig getInstance() {
if (INSTANCE == null) {
synchronized (key) {
if (INSTANCE == null) {
try {
INSTANCE = JsonUtil.load(configFile, QuestionConfig.class);
} catch (ConfigReadException e) {
throw new RuntimeException(e);
}
}
}
}
if (INSTANCE == null) {
synchronized (key) {
if (INSTANCE == null) {
INSTANCE = new QuestionConfig();
try {
JsonUtil.dump(configFile, INSTANCE, QuestionConfig.class);
} catch (ConfigWriteException e) {
throw new RuntimeException(e);
}
}
}
}
return INSTANCE;
//return new QuestionConfig();
}
public ChatCompletionRequest load() {
return ChatCompletionRequest.builder()
.maxTokens(max_tokens)
.model(model)
.n(n)
.presencePenalty(presence_penalty)
.topP(top_p)
.frequencyPenalty(frequency_penalty)
.build();
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getMax_tokens() {
return max_tokens;
}
public void setMax_tokens(int max_tokens) {
this.max_tokens = max_tokens;
}
public double getTemperature() {
return temperature;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
public double getTop_p() {
return top_p;
}
public void setTop_p(double top_p) {
this.top_p = top_p;
}
public double getPresence_penalty() {
return presence_penalty;
}
public void setPresence_penalty(double presence_penalty) {
this.presence_penalty = presence_penalty;
}
public double getFrequency_penalty() {
return frequency_penalty;
}
public void setFrequency_penalty(double frequency_penalty) {
this.frequency_penalty = frequency_penalty;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((544, 583), 'com.erzbir.numeron.api.NumeronImpl.INSTANCE.getPluginWorkDir'), ((1976, 2256), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1976, 2231), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1976, 2178), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1976, 2149), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1976, 2098), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1976, 2076), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1976, 2046), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package com.coremedia.labs.plugins.feedbackhub.openai.jobs;
import com.coremedia.labs.plugins.feedbackhub.openai.OpenAISettings;
import com.coremedia.labs.plugins.feedbackhub.openai.OpenAISettingsProvider;
import com.coremedia.labs.plugins.feedbackhub.openai.api.OpenAIClientProvider;
import com.coremedia.rest.cap.jobs.GenericJobErrorCode;
import com.coremedia.rest.cap.jobs.Job;
import com.coremedia.rest.cap.jobs.JobContext;
import com.coremedia.rest.cap.jobs.JobExecutionException;
import com.google.gson.annotations.SerializedName;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public class GenerateTextJob implements Job {
private static final Logger LOG = LoggerFactory.getLogger(GenerateTextJob.class);
public static final String ACTION_SUMMARIZE = "summarize";
public static final String ACTION_GENERATE_TITLE = "title";
public static final String ACTION_GENERATE_HEADLINE = "headline";
public static final String ACTION_GENERATE_METADATA = "metadata";
public static final String ACTION_EXTRACT_KEYWORDS = "keywords";
public static final int CHAT_GPT_MAX_MSG_LENGTH = 4096;
private String prompt;
private String contentId;
private String siteId;
private String groupId;
private String actionId;
private final OpenAISettingsProvider settingsProvider;
public GenerateTextJob(OpenAISettingsProvider settingsProvider) {
this.settingsProvider = settingsProvider;
}
@SerializedName("prompt")
public void setPrompt(String prompt) {
this.prompt = prompt;
}
@SerializedName("contentId")
public void setContentId(String contentId) {
this.contentId = contentId;
}
@SerializedName("siteId")
public void setSiteId(String siteId) {
this.siteId = siteId;
}
@SerializedName("groupId")
public void setGroupId(String groupId) {
this.groupId = groupId;
}
@SerializedName("actionId")
public void setActionId(String actionId) {
this.actionId = actionId;
}
@Nullable
@Override
public Object call(@NonNull JobContext jobContext) throws JobExecutionException {
String model = null;
String text = null;
OpenAISettings settings = getSettings();
String updatedPrompt = applyUserAction(settings, prompt, actionId);
String sanitized = sanitizePrompt(updatedPrompt);
try {
model = settings.getLanguageModel();
Integer timeoutInSeconds = settings.getTimeoutInSeconds() != null ? settings.getTimeoutInSeconds() : 30;
OpenAiService client;
String baseUrl = settings.getBaseUrl();
if (isNotBlank(baseUrl)) {
client = OpenAIClientProvider.getClient(baseUrl, settings.getApiKey(), Duration.ofSeconds(timeoutInSeconds));
} else {
client = OpenAIClientProvider.getClient(settings.getApiKey(), Duration.ofSeconds(timeoutInSeconds));
}
int temparature = (settings.getTemperature() != null ? settings.getTemperature() : 30) / 100;
int maxTokens = settings.getMaxTokens() != null ? settings.getMaxTokens() : 1000;
if (model.contains("4") || model.contains("3.5")) {
List<ChatMessage> messages = new ArrayList<>();
ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), sanitized);
messages.add(userMessage);
ChatCompletionRequest request = ChatCompletionRequest.builder()
.messages(messages)
.model(model)
.user(String.valueOf(contentId))
.maxTokens(maxTokens)
.temperature((double) temparature)
.build();
ChatCompletionChoice chatCompletionChoice = client.createChatCompletion(request).getChoices().get(0);
text = chatCompletionChoice.getMessage().getContent();
} else {
CompletionRequest request = CompletionRequest.builder()
.prompt(sanitized)
.model(model)
.user(String.valueOf(contentId))
.maxTokens(maxTokens)
.temperature((double) temparature)
.echo(false)
.build();
Optional<CompletionChoice> first = client.createCompletion(request).getChoices().stream().findFirst();
if (first.isPresent()) {
CompletionChoice completionChoice = first.get();
if (completionChoice.getFinish_reason() != null && !completionChoice.getFinish_reason().equals("stop")) {
LOG.info("Text generation stopped, reason: " + completionChoice.getFinish_reason());
}
text = completionChoice.getText().trim();
if (StringUtils.isEmpty(text)) {
LOG.info("Text generation was empty, finish reason: " + completionChoice.getFinish_reason());
}
}
}
return text.trim();
} catch (Exception e) {
LOG.error("Failed to generate text with language model \"{}\" for given prompt: \"{}\" on content {}: {}", model, prompt, contentId, e.getMessage());
throw new JobExecutionException(GenericJobErrorCode.FAILED, e.getMessage());
}
}
/**
* Ensure that the max message length is not exceeded.
* Otherwise the message "overflow" would be sent with the next chat message.
*
* @param updatedPrompt the user prompt, may be already customized depending on the actionId
* @return the sanitized user prompt
*/
private String sanitizePrompt(String updatedPrompt) {
if (updatedPrompt.length() > CHAT_GPT_MAX_MSG_LENGTH) {
updatedPrompt = updatedPrompt.substring(0, CHAT_GPT_MAX_MSG_LENGTH);
if (updatedPrompt.contains(".")) {
updatedPrompt = updatedPrompt.substring(0, updatedPrompt.lastIndexOf("."));
}
}
return updatedPrompt;
}
/**
* Depending on the user action, we do a little prompt engineering to customize the output.
*
* @param settings
* @param prompt the question the user has entered OR the text OpenAI has generated for the original question
* @param actionId an action if the user has already entered a question or null if the first AI is given
* @return the modified prompt with optional additional commands
*/
private String applyUserAction(OpenAISettings settings, String prompt, String actionId) {
if (StringUtils.isEmpty(actionId)) {
prompt = "Answer with less than 500 words or 4000 characters: " + prompt;
return prompt;
}
String promptPrefix = null;
switch (actionId) {
case ACTION_SUMMARIZE: {
promptPrefix = !StringUtils.isEmpty(settings.getSummaryPrompt()) ? settings.getSummaryPrompt() : "Summarize the following text";
break;
}
case ACTION_EXTRACT_KEYWORDS: {
promptPrefix = !StringUtils.isEmpty(settings.getKeywordsPrompt()) ? settings.getKeywordsPrompt() : "Extract the keywords from the following text with a total maximum length of 255 characters";
break;
}
case ACTION_GENERATE_HEADLINE: {
promptPrefix = !StringUtils.isEmpty(settings.getHeadlinePrompt()) ? settings.getHeadlinePrompt() : "Create an article headline from the following text";
break;
}
case ACTION_GENERATE_METADATA: {
promptPrefix = !StringUtils.isEmpty(settings.getMetadataPrompt()) ? settings.getMetadataPrompt() : "Summarize the following text in one sentence";
break;
}
case ACTION_GENERATE_TITLE: {
promptPrefix = !StringUtils.isEmpty(settings.getTitlePrompt()) ? settings.getTitlePrompt() : "Generate a title from the following text with a maximum length of 60 characters";
break;
}
default: {
throw new UnsupportedOperationException("Invalid actionId '" + actionId + "'");
}
}
return formatActionPrompt(promptPrefix) + prompt;
}
private OpenAISettings getSettings() {
return settingsProvider.getSettings(groupId, siteId);
}
private String formatActionPrompt(String prompt) {
if (prompt != null && !prompt.endsWith(":")) {
prompt += ":\n\n";
}
return prompt;
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder",
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value",
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((3899, 3927), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((4017, 4241), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4017, 4222), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4017, 4177), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4017, 4145), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4017, 4102), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4017, 4078), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4468, 4710), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4468, 4691), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4468, 4668), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4468, 4623), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4468, 4591), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4468, 4548), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4468, 4524), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package ru.goncharenko.kekita.bot.handlers.meme.generators.chatgpt;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Update;
import ru.goncharenko.kekita.bot.handlers.meme.generators.MemeGenerator;
import java.util.List;
@Component
@ConditionalOnProperty(
prefix = "bot.handlers.meme.ai",
name = "enabled",
havingValue = "true",
matchIfMissing = false
)
public class AiGenerator implements MemeGenerator {
Logger logger = LoggerFactory.getLogger(AiGenerator.class);
private final AiConfig config;
private final OpenAiService openAiService;
public AiGenerator(AiConfig config, OpenAiService openAiService) {
this.openAiService = openAiService;
this.config = config;
}
@Override
public BotApiMethod<?> generate(Update update) {
logger.info("Use AiGenerator for generate meme response");
final var chatCompletionRequest = generateAiRequest(update.getMessage().getText());
final var completionResult = openAiService.createChatCompletion(chatCompletionRequest);
return SendMessage.builder()
.chatId(update.getMessage().getChatId())
.text(completionResult.getChoices().getFirst().getMessage().getContent())
.replyToMessageId(update.getMessage().getMessageId())
.build();
}
private ChatCompletionRequest generateAiRequest(String message) {
final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), config.promt());
final ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), message);
return ChatCompletionRequest.builder()
.model(config.model())
.messages(List.of(systemMessage, userMessage))
.n(1)
.maxTokens(512)
.build();
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value",
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((1642, 1905), 'org.telegram.telegrambots.meta.api.methods.send.SendMessage.builder'), ((1642, 1880), 'org.telegram.telegrambots.meta.api.methods.send.SendMessage.builder'), ((1642, 1810), 'org.telegram.telegrambots.meta.api.methods.send.SendMessage.builder'), ((1642, 1720), 'org.telegram.telegrambots.meta.api.methods.send.SendMessage.builder'), ((2042, 2072), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((2147, 2175), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((2202, 2414), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2202, 2389), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2202, 2357), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2202, 2335), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2202, 2272), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package jasper.component;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.theokanning.openai.OpenAiHttpException;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.image.CreateImageRequest;
import com.theokanning.openai.image.ImageResult;
import com.theokanning.openai.service.OpenAiService;
import jasper.client.dto.RefDto;
import jasper.config.Props;
import jasper.errors.NotFoundException;
import jasper.repository.PluginRepository;
import jasper.repository.RefRepository;
import okhttp3.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.List;
import static jasper.repository.spec.QualifiedTag.selector;
@Profile("ai")
@Component
public class OpenAi {
private static final Logger logger = LoggerFactory.getLogger(OpenAi.class);
public static final MediaType TEXT = MediaType.parse("text/plain; charset=utf-8");
@Autowired
Props props;
@Autowired
RefRepository refRepository;
@Autowired
PluginRepository pluginRepository;
@Autowired
ObjectMapper objectMapper;
public CompletionResult completion(String systemPrompt, String prompt) {
var key = refRepository.findAll(selector("_openai/key" + props.getLocalOrigin()).refSpec());
if (key.isEmpty()) {
throw new NotFoundException("requires openai api key");
}
var service = new OpenAiService(key.get(0).getComment(), Duration.ofSeconds(200));
var completionRequest = CompletionRequest.builder()
.model("text-davinci-003")
.maxTokens(1024)
.prompt(systemPrompt + "\n\n" +
"Prompt: " + prompt + "\n\n" +
"Reply:")
.stop(List.of("Prompt:", "Reply:"))
.build();
try {
return service.createCompletion(completionRequest);
} catch (OpenAiHttpException e) {
if ("context_length_exceeded".equals(e.code)) {
completionRequest.setMaxTokens(400);
try {
return service.createCompletion(completionRequest);
} catch (OpenAiHttpException second) {
if ("context_length_exceeded".equals(second.code)) {
completionRequest.setMaxTokens(20);
try {
return service.createCompletion(completionRequest);
} catch (OpenAiHttpException third) {
throw e;
}
}
throw e;
}
}
throw e;
}
}
public ChatCompletionResult chatCompletion(String prompt, AiConfig config) {
var key = refRepository.findAll(selector("_openai/key" + props.getLocalOrigin()).refSpec());
if (key.isEmpty()) {
throw new NotFoundException("requires openai api key");
}
var service = new OpenAiService(key.get(0).getComment(), Duration.ofSeconds(200));
var completionRequest = ChatCompletionRequest
.builder()
.model(config.model)
.maxTokens(config.maxTokens)
.messages(List.of(
cm("system", config.systemPrompt),
cm("user", prompt)
))
.build();
return service.createChatCompletion(completionRequest);
}
public ImageResult dale(String prompt, DalleConfig config) {
var key = refRepository.findAll(selector("_openai/key" + props.getLocalOrigin()).refSpec());
if (key.isEmpty()) {
throw new NotFoundException("requires openai api key");
}
var service = new OpenAiService(key.get(0).getComment(), Duration.ofSeconds(200));
var imageRequest = CreateImageRequest.builder()
.prompt(prompt)
.responseFormat("b64_json")
.model(config.model)
.size(config.size)
.quality(config.quality)
.style(config.style)
.build();
return service.createImage(imageRequest);
}
public ChatCompletionResult chat(List<ChatMessage> messages, AiConfig config) {
var key = refRepository.findAll(selector("_openai/key" + props.getLocalOrigin()).refSpec());
if (key.isEmpty()) {
throw new NotFoundException("requires openai api key");
}
OpenAiService service = new OpenAiService(key.get(0).getComment(), Duration.ofSeconds(200));
ChatCompletionRequest completionRequest = ChatCompletionRequest
.builder()
.model(config.model)
.maxTokens(config.maxTokens)
.messages(messages)
.build();
return service.createChatCompletion(completionRequest);
}
public static ChatMessage cm(String origin, String role, String title, String content, ObjectMapper om) {
var result = new ChatMessage();
result.setRole(role);
result.setContent(ref(origin, role, title, content, om));
return result;
}
public static ChatMessage cm(String role, String content) {
var result = new ChatMessage();
result.setRole(role);
result.setContent(content);
return result;
}
public static String ref(String origin, String role, String title, String content, ObjectMapper om) {
var result = new RefDto();
result.setOrigin(origin);
result.setTitle(title);
result.setComment(content);
if (role.equals("system")) {
result.setUrl("system:instructions");
result.setTags(List.of("system", "internal", "notes", "+plugin/openai"));
} else {
result.setUrl("system:user-instructions");
result.setTags(List.of("dm", "internal", "plugin/thread"));
}
try {
return om.writeValueAsString(result);
} catch (JsonProcessingException e) {
logger.error("Cannot write content to Ref {}", content, e);
throw new RuntimeException(e);
}
}
public static class AiConfig {
public String model = "gpt-4-turbo-preview";
public List<String> fallback;
public int maxTokens = 4096;
public int maxContext = 7;
public String systemPrompt;
}
public static class DalleConfig {
public String size = "1024x1024";
public String model = "dall-e-3";
public String quality = "hd";
public String style = "vivid";
}
}
| [
"com.theokanning.openai.image.CreateImageRequest.builder",
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((1947, 2159), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1947, 2147), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1947, 2108), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1947, 2024), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1947, 2004), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3729, 3917), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3729, 3905), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3729, 3881), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3729, 3853), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3729, 3831), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3729, 3807), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3729, 3776), 'com.theokanning.openai.image.CreateImageRequest.builder')] |
package run.halo.live2d.chat.client.openai;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import java.util.List;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import run.halo.app.infra.utils.JsonUtils;
import run.halo.app.plugin.ReactiveSettingFetcher;
import run.halo.live2d.chat.ChatResult;
import run.halo.live2d.chat.WebClientFactory;
import run.halo.live2d.chat.client.ChatClient;
@Slf4j
@Component
public class OpenAiChatClient implements ChatClient {
public final static String DEFAULT_OPEN_AI_API_URL = "https://api.openai.com";
public final static String CHAT_COMPLETION_PATH = "/v1/chat/completions";
public final static String DEFAULT_MODEL = "gpt-3.5-turbo";
private final ReactiveSettingFetcher reactiveSettingFetcher;
private final WebClientFactory webClientFactory;
public OpenAiChatClient(WebClientFactory webClientFactory,
ReactiveSettingFetcher reactiveSettingFetcher) {
this.webClientFactory = webClientFactory;
this.reactiveSettingFetcher = reactiveSettingFetcher;
}
@Override
public Flux<ServerSentEvent<ChatResult>> generate(List<ChatMessage> messages) {
return reactiveSettingFetcher.fetch("aichat", OpenAiConfig.class)
.filter(openAiConfig -> openAiConfig.openAiSetting.isOpenAi)
.flatMapMany(openAiConfig -> {
var webClient = webClientFactory
.createWebClientBuilder()
.map(build -> build.baseUrl(openAiConfig.openAiSetting.openAiBaseUrl)
.defaultHeader(HttpHeaders.AUTHORIZATION,
"Bearer " + openAiConfig.openAiSetting.openAiToken)
.build()
);
var request = ChatCompletionRequest.builder()
.model(openAiConfig.openAiSetting.openAiModel)
.messages(messages)
.stream(true)
.build();
return webClient.flatMapMany(client -> client.post()
.uri(CHAT_COMPLETION_PATH)
.accept(MediaType.TEXT_EVENT_STREAM)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(JsonUtils.objectToJson(request))
.retrieve()
.bodyToFlux(String.class))
.flatMap(data -> {
if (StringUtils.equals("[DONE]", data)) {
return Mono.just(ServerSentEvent.builder(ChatResult.finish()).build());
}
var chatCompletionResult =
JsonUtils.jsonToObject(data, ChatCompletionResult.class);
if (Objects.nonNull(chatCompletionResult.getChoices())) {
var choice = chatCompletionResult.getChoices().get(0);
if (StringUtils.isNotBlank(choice.getFinishReason())) {
return Flux.empty();
}
if (Objects.isNull(choice.getMessage())
|| StringUtils.isEmpty(choice.getMessage().getContent())
) {
return Flux.empty();
} else {
return Mono.just(
ServerSentEvent.builder(
ChatResult.ok(choice.getMessage().getContent()))
.build()
);
}
}
return Mono.just(ServerSentEvent.builder(ChatResult.finish()).build());
})
.onTerminateDetach()
.doOnCancel(() -> {
// 在中止事件时执行逻辑
log.info("Client manually canceled the SSE stream.");
});
});
}
@Override
public Mono<Boolean> supports() {
return reactiveSettingFetcher.fetch("aichat", OpenAiConfig.class)
.filter((openAiConfig) -> openAiConfig.openAiSetting.isOpenAi)
.hasElement();
}
record OpenAiConfig(OpenAiSetting openAiSetting){
}
record OpenAiSetting(boolean isOpenAi, String openAiToken, String openAiBaseUrl, String openAiModel) {
OpenAiSetting {
if (isOpenAi) {
if (StringUtils.isBlank(openAiToken)) {
throw new IllegalArgumentException("OpenAI token must not be blank");
}
if (StringUtils.isBlank(openAiBaseUrl)) {
openAiBaseUrl = DEFAULT_OPEN_AI_API_URL;
}
if (StringUtils.isBlank(openAiModel)) {
openAiModel = DEFAULT_MODEL;
}
}
}
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((2227, 2428), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2227, 2399), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2227, 2365), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2227, 2325), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2982, 3034), 'org.springframework.http.codec.ServerSentEvent.builder'), ((3899, 4065), 'org.springframework.http.codec.ServerSentEvent.builder'), ((4198, 4250), 'org.springframework.http.codec.ServerSentEvent.builder')] |
package org.example.chatgpt.service;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.theokanning.openai.OpenAiApi;
import com.theokanning.openai.service.OpenAiService;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.theokanning.openai.service.OpenAiService.*;
import static org.example.chatgpt.service.ChatService.sendStopEvent;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import retrofit2.Retrofit;
import java.io.IOException;
import javabean.LogForDB;
/**
* 会话服务
*
* @author lijiatao
* 时间: 2023/12/6
*/
@Service
public class ASTEService {
private static final Logger LOG = LoggerFactory.getLogger(ChatService.class);
//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
// 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
// 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
String token = "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";
String proxyHost = "127.0.0.1";
int proxyPort = 7890;
String prompt_extract = "属性情感三元组抽取(Aspect Sentiment Triplet Extraction ,ASTE)任务是在AAAI 2020里被提出的一个新任务,被划为属性级情感分析(Aspect-based sentiment analysis ,ABSA)任务的一个子任务。ASTE的定义是抽取出其中包含的三元组<属性,情感,观点>,其目的是从句子中获得全面的信息,用于情感分析。在这里,属性(aspect)指评价的对象,情感(sentiment)是指对象在上下文中的整体情感,一般包括正向,中性,负向和冲突(conflict),观点(opinion)则是评论对象时用到的描述词。比如,对于一个句子“这盘空心菜很好吃,但是不好看\",ASTE则会抽取出两个三元组:<空心菜,冲突,好吃> 和 <空心菜,冲突,不好看>。" +
"现在请你执行三元组抽取任务:给定一段文本,抽取其中的三元组。输出的格式为" +
"属性-情感-观点" +
"请严格遵循格式,并除此以外不要输出其它任何内容。文本如下:";
@Async
public void asteCompletion(String prompt, SseEmitter sseEmitter) throws IOException {
LogForDB logForDB = new LogForDB();
LOG.info("发送消息:" + prompt);
String prompt1 = prompt_extract + prompt;
final List<ChatMessage> messages = new ArrayList<>();
final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), prompt1);
messages.add(systemMessage);
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
.builder()
.model("gpt-3.5-turbo")
.messages(messages)
.n(1)
.maxTokens(500)
.logitBias(new HashMap<>())
.build();
//完整对话
StringBuilder receiveMsgBuilder = new StringBuilder();
OpenAiService service = buildOpenAiService(token, proxyHost, proxyPort);
service.createChatCompletion(chatCompletionRequest)
.getChoices()
.forEach(x-> {
try {
sseEmitter.send(x.getMessage().getContent());
} catch (IOException e) {
throw new RuntimeException(e);
}
String content = x.getMessage().getContent();
content = content == null ? StrUtil.EMPTY : content;
receiveMsgBuilder.append(content);
});
LOG.info("收到的完整消息:" + receiveMsgBuilder);
sendStopEvent(sseEmitter);
service.shutdownExecutor();
LOG.info("连接结束");
logForDB.log2DB("ASTE", prompt, String.valueOf(receiveMsgBuilder));
}
/**
* 构建OpenAiService
*
* @param token API_KEY
* @param proxyHost 代理域名
* @param proxyPort 代理端口号
* @return OpenAiService
*/
private OpenAiService buildOpenAiService(String token, String proxyHost, int proxyPort) {
//构建HTTP代理
Proxy proxy = null;
if (StrUtil.isNotBlank(proxyHost)) {
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
}
//构建HTTP客户端
OkHttpClient client = defaultClient(token, Duration.of(60, ChronoUnit.SECONDS))
.newBuilder()
.proxy(proxy)
.build();
ObjectMapper mapper = defaultObjectMapper();
Retrofit retrofit = defaultRetrofit(client, mapper);
OpenAiApi api = retrofit.create(OpenAiApi.class);
return new OpenAiService(api, client.dispatcher().executorService());
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value"
] | [((3100, 3130), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value')] |
package org.lambda.framework.openai.service.chat;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.lambda.framework.common.exception.EventException;
import org.lambda.framework.openai.OpenAiContract;
import org.lambda.framework.openai.OpenAiConversation;
import org.lambda.framework.openai.OpenAiConversations;
import org.lambda.framework.openai.OpenAiReplying;
import org.lambda.framework.openai.enums.OpenAiModelEnum;
import org.lambda.framework.openai.enums.OpenaiExceptionEnum;
import org.lambda.framework.openai.service.chat.param.OpenAiChatParam;
import org.lambda.framework.openai.service.chat.response.OpenAiChatReplied;
import org.lambda.framework.redis.operation.ReactiveRedisOperation;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.LinkedList;
import java.util.List;
import static org.lambda.framework.openai.OpenAiContract.currentTime;
import static org.lambda.framework.openai.OpenAiContract.encoding;
@Component
public class OpenAiChatService implements OpenAiChatFunction {
@Resource(name = "openAiChatRedisOperation")
private ReactiveRedisOperation openAiChatRedisOperation;
@Override
public Mono<OpenAiReplying<OpenAiChatReplied>> execute(OpenAiChatParam param) {
//参数校验
param.verify();
String uniqueId = OpenAiContract.uniqueId(param.getUserId(),param.getUniqueParam().getUniqueTime());
return openAiChatRedisOperation.get(uniqueId)
.onErrorResume(e->Mono.error(new EventException(OpenaiExceptionEnum.ES_OPENAI_007)))
.defaultIfEmpty(Mono.empty())
.flatMap(e->{
List<ChatMessage> chatMessage = null;
List<OpenAiChatReplied> openAiChatReplied = null;
List<OpenAiConversation<OpenAiChatReplied>> openAiConversation = null;
OpenAiConversations<OpenAiChatReplied> openAiConversations = null;
Integer tokens = 0;
if(e.equals(Mono.empty())){
//没有历史聊天记录,第一次对话,装载AI人设
chatMessage = new LinkedList<>();
openAiChatReplied = new LinkedList<>();
if(StringUtils.isNotBlank(param.getPersona())){
chatMessage.add(new ChatMessage(ChatMessageRole.SYSTEM.value(),param.getPersona()));
openAiChatReplied.add(new OpenAiChatReplied(ChatMessageRole.SYSTEM.value(),param.getPersona(),currentTime()));
tokens = tokens + encoding(param.getPersona());
}
chatMessage.add(new ChatMessage(ChatMessageRole.USER.value(),param.getPrompt()));
openAiChatReplied.add(new OpenAiChatReplied(ChatMessageRole.USER.value(),param.getPrompt(),currentTime()));
tokens = tokens + encoding(param.getPrompt());
openAiConversation = new LinkedList<>();
OpenAiConversation<OpenAiChatReplied> _openAiConversation = new OpenAiConversation<OpenAiChatReplied>();
_openAiConversation.setConversation(openAiChatReplied);
openAiConversation.add(_openAiConversation);
openAiConversations = new OpenAiConversations<OpenAiChatReplied>();
openAiConversations.setOpenAiConversations(openAiConversation);
}else {
List<ChatMessage> _chatMessage = new LinkedList<>();
openAiConversations = new ObjectMapper().convertValue(e, new TypeReference<>(){});
openAiConversations.getOpenAiConversations().forEach(_conversations->{
_conversations.getConversation().forEach(message->{
_chatMessage.add(new ChatMessage(message.getRole(),message.getContent()));
});
});
chatMessage = _chatMessage;
chatMessage.add(new ChatMessage(ChatMessageRole.USER.value(),param.getPrompt()));
openAiChatReplied = new LinkedList<>();
openAiChatReplied.add(new OpenAiChatReplied(ChatMessageRole.USER.value(),param.getPrompt(),currentTime()));
tokens = tokens + encoding(param.getPrompt());
OpenAiConversation<OpenAiChatReplied> _openAiConversation = new OpenAiConversation<>();
_openAiConversation.setConversation(openAiChatReplied);
openAiConversations.getOpenAiConversations().add(_openAiConversation);
//多轮对话要计算所有的tokens
tokens = Math.toIntExact(tokens + openAiConversations.getTotalTokens());
}
limitVerify(param.getQuota(),param.getMaxTokens(),tokens);
limitVerifyByModel(OpenAiModelEnum.TURBO,param.getQuota(),param.getMaxTokens(),tokens);
OpenAiService service = new OpenAiService(param.getApiKey(),Duration.ofSeconds(param.getTimeOut()));
ChatCompletionRequest request = ChatCompletionRequest.builder()
.model(OpenAiModelEnum.TURBO.getModel())
.messages(chatMessage)
.temperature(param.getTemperature())
.topP(param.getTopP())
.n(param.getN())
.stream(param.getStream())
.maxTokens(param.getMaxTokens())
.presencePenalty(param.getPresencePenalty())
.frequencyPenalty(param.getFrequencyPenalty())
.build();
OpenAiConversations<OpenAiChatReplied> finalOpenAiConversations = openAiConversations;
return Mono.fromCallable(() -> service.createChatCompletion(request))
.onErrorMap(throwable -> new EventException(OpenaiExceptionEnum.ES_OPENAI_006, throwable.getMessage()))
.flatMap(chatCompletionResult -> {
ChatMessage _chatMessage = chatCompletionResult.getChoices().get(0).getMessage();
OpenAiConversation<OpenAiChatReplied> _openAiConversation = finalOpenAiConversations.getOpenAiConversations().get(finalOpenAiConversations.getOpenAiConversations().size()-1);
_openAiConversation.setPromptTokens(chatCompletionResult.getUsage().getPromptTokens());
_openAiConversation.setCompletionTokens(chatCompletionResult.getUsage().getCompletionTokens());
_openAiConversation.setTotalTokens(chatCompletionResult.getUsage().getTotalTokens());
_openAiConversation.getConversation().add(new OpenAiChatReplied(_chatMessage.getRole(),_chatMessage.getContent(), OpenAiContract.currentTime()));
finalOpenAiConversations.setTotalTokens(finalOpenAiConversations.getTotalTokens() + chatCompletionResult.getUsage().getTotalTokens());
finalOpenAiConversations.setTotalPromptTokens(finalOpenAiConversations.getTotalPromptTokens() + chatCompletionResult.getUsage().getPromptTokens());
finalOpenAiConversations.setTotalCompletionTokens(finalOpenAiConversations.getTotalCompletionTokens() + chatCompletionResult.getUsage().getCompletionTokens());
openAiChatRedisOperation.set(uniqueId, finalOpenAiConversations).subscribe();
return Mono.just(_openAiConversation);
})
.flatMap(current->{
OpenAiReplying<OpenAiChatReplied> openAiReplying = new OpenAiReplying<OpenAiChatReplied>();
openAiReplying.setReplying(current.getConversation().get(current.getConversation().size()-1));
openAiReplying.setPromptTokens(current.getPromptTokens());
openAiReplying.setCompletionTokens(current.getCompletionTokens());
openAiReplying.setTotalTokens(current.getTotalTokens());
return Mono.just(openAiReplying);
});
});
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value",
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((2799, 2829), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((2924, 2954), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3149, 3177), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((3267, 3295), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((4587, 4615), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((4769, 4797), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((5735, 6388), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 6347), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 6268), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 6191), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 6126), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 6067), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 6018), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 5963), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 5894), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 5839), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5806, 5838), 'org.lambda.framework.openai.enums.OpenAiModelEnum.TURBO.getModel'), ((6525, 9074), 'reactor.core.publisher.Mono.fromCallable'), ((6525, 8398), 'reactor.core.publisher.Mono.fromCallable'), ((6525, 6719), 'reactor.core.publisher.Mono.fromCallable')] |
package com.nashss.se.yodaservice.activity;
import com.nashss.se.yodaservice.activity.requests.AiRequest;
import com.nashss.se.yodaservice.activity.results.AiResult;
import com.nashss.se.yodaservice.dynamodb.PHRDAO;
import com.nashss.se.yodaservice.dynamodb.models.PHR;
import com.nashss.se.yodaservice.prompt.PromptStandard;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import javax.inject.Inject;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AiActivity {
private final OpenAiService openAiService;
private final PHRDAO phrdao;
@Inject
public AiActivity(OpenAiService openAiService1, PHRDAO phrdao) {
this.openAiService = openAiService1;
this.phrdao = phrdao;
}
public AiResult handleRequest(final AiRequest request) {
try {
PHR existingPhr = phrdao.getPHR(request.getPhrId(), request.getDate());
PromptStandard prompt = new PromptStandard(existingPhr.getComprehendData(), existingPhr.getTranscription());
List<ChatMessage> messages = new ArrayList<>();
ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(),prompt.toString());
messages.add(userMessage);
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
.model("gpt-4")
.messages(messages)
.logitBias(new HashMap<>())
.build();
try {
System.out.println("Completion initiated");
String completion = openAiService.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage().getContent();
try {
List<String> pastAi = existingPhr.getAiDifferentials();
pastAi.add(completion);
existingPhr.setAiDifferentials(pastAi);
phrdao.savePHR(existingPhr);
} catch (NullPointerException npe) {
List<String> pastAi = new ArrayList<>();
pastAi.add(completion);
existingPhr.setAiDifferentials(pastAi);
phrdao.savePHR(existingPhr);
}
return AiResult.builder()
.withDifferential(completion)
.build();
} catch (RuntimeException RE) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
RE.printStackTrace(pw);
throw new RuntimeException("Error while creating chat completion with OpenAI service: \n" + sw);
}
} catch (Exception RE) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
RE.printStackTrace(pw);
throw new RuntimeException("Error while receiving completion data: \n" + sw);
}
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value",
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((1400, 1428), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((1546, 1730), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1546, 1701), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1546, 1653), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1546, 1613), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2510, 2615), 'com.nashss.se.yodaservice.activity.results.AiResult.builder'), ((2510, 2582), 'com.nashss.se.yodaservice.activity.results.AiResult.builder')] |
package com.couchbase.intellij.tree.iq.chat;
import com.didalgo.gpt3.ChatFormatDescriptor;
import com.didalgo.gpt3.GPT3Tokenizer;
import com.didalgo.gpt3.ModelType;
import com.couchbase.intellij.tree.iq.core.TextSubstitutor;
import com.couchbase.intellij.tree.iq.text.TextContent;
import com.intellij.openapi.application.ApplicationInfo;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import static com.couchbase.intellij.tree.iq.chat.ChatMessageUtils.countTokens;
import static com.couchbase.intellij.tree.iq.chat.ChatMessageUtils.isRoleSystem;
public class ChatLinkState implements ConversationContext {
private final LinkedList<ChatMessage> chatMessages = new LinkedList<>();
private volatile List<? extends TextContent> lastSentTextFragments = List.of();
private volatile TextSubstitutor textSubstitutor = TextSubstitutor.NONE;
private final ConfigurationPage configuration;
public ChatLinkState(ConfigurationPage configuration) {
this.configuration = configuration;
}
public ConfigurationPage getModelConfiguration() {
var configuration = this.configuration;
if (configuration == null)
throw new UnsupportedOperationException("ModelConfiguration is not supported by this ChatLink instance");
return configuration;
}
public void setTextSubstitutor(TextSubstitutor textSubstitutor) {
this.textSubstitutor = Objects.requireNonNull(textSubstitutor);
}
public final TextSubstitutor getTextSubstitutor() {
return textSubstitutor;
}
public Supplier<String> getSystemPrompt() {
return getModelConfiguration().getSystemPrompt();
}
@Override
public List<? extends TextContent> getLastPostedCodeFragments() {
return lastSentTextFragments;
}
@Override
public void setLastPostedCodeFragments(List<? extends TextContent> textContents) {
Objects.requireNonNull(textContents);
this.lastSentTextFragments = textContents;
}
@Override
public void addChatMessage(ChatMessage message) {
if (message.getContent() == null)
message = new ChatMessage(message.getRole(), "");
synchronized (chatMessages) {
if (!chatMessages.isEmpty()) {
if (message.getRole() == null || isRoleSystem(chatMessages.getLast()) && isRoleSystem(message)) {
ChatMessage last = chatMessages.removeLast();
message = new ChatMessage(last.getRole(), last.getContent() + message.getContent());
}
else if (Objects.equals(chatMessages.getLast().getRole(), message.getRole()))
chatMessages.removeLast();
}
chatMessages.add(message);
}
}
@Override
public ModelType getModelType() {
String modelName = getModelConfiguration().getModelName();
return ModelType.forModel(modelName).orElseThrow();
}
@Override
public List<ChatMessage> getChatMessages(ModelType model, ChatMessage userMessage) {
var chatMessages = new LinkedList<ChatMessage>();
// Add the rest of messages in the chat
synchronized (this.chatMessages) {
if (!this.chatMessages.isEmpty())
this.chatMessages.stream()
.filter(chatMessage -> !ChatMessageRole.SYSTEM.value().equals(chatMessage.getRole()))
.forEach(chatMessages::add);
// Substitute template placeholders
substitutePlaceholders(chatMessages);
// add the system prompt
var systemMessage = getSystemPrompt().get();
if (!systemMessage.isBlank()) {
systemMessage = systemMessage.stripTrailing()
+ "\n\nCurrent IDE: " + ApplicationInfo.getInstance().getFullApplicationName()
+ "\nOS: " + System.getProperty("os.name");
chatMessages.add(0, new ChatMessage(ChatMessageRole.SYSTEM.value(), systemMessage));
}
// Trim messages if exceeding token limit
//int maxTokens = model.maxTokens();
// hard-coded as I couldn't find API to set it
int maxTokens = 4097;
var tokenizer = model.getTokenizer();
var chatFormatDescriptor = model.getChatFormatDescriptor();
int removed = dropOldestMessagesToStayWithinTokenLimit(chatMessages, maxTokens, tokenizer, chatFormatDescriptor);
while (removed-- > 0)
this.chatMessages.remove(0);
return chatMessages;
}
}
public void substitutePlaceholders(List<ChatMessage> chatMessages) {
ChatMessageUtils.substitutePlaceholders(chatMessages, getTextSubstitutor());
}
public int dropOldestMessagesToStayWithinTokenLimit(List<ChatMessage> messages, int maxTokens, GPT3Tokenizer tokenizer, ChatFormatDescriptor formatDescriptor) {
// here we assume ratio at most 2/3 available tokens for input prompt with context history,
// and at least 1/3 tokens for output
int tokenLimit = maxTokens*2/3;
int tokenCount;
int removed = 0;
boolean hasSystemMessage = !messages.isEmpty() && isRoleSystem(messages.get(0));
int oldestMessageIndex = hasSystemMessage? 1: 0;
while ((tokenCount = countTokens(messages, tokenizer, formatDescriptor)) > tokenLimit && oldestMessageIndex < messages.size() - 1) {
messages.remove(oldestMessageIndex);
removed++;
}
if (tokenCount > tokenLimit) {
var lastMessage = messages.get(oldestMessageIndex);
// TODO: calculation is currently wrong
var lastMsgCutoff = lastMessage.getContent().length() - tokenLimit;
if (lastMsgCutoff > 0)
messages.set(oldestMessageIndex,
new ChatMessage(lastMessage.getRole(), "[...] " + lastMessage.getContent().substring(lastMsgCutoff)));
}
return removed;
}
@Override
public String getModelPage() {
return getModelConfiguration().getModelPage();
}
@Override
public void clear() {
chatMessages.clear();
setLastPostedCodeFragments(List.of());
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value"
] | [((3089, 3132), 'com.didalgo.gpt3.ModelType.forModel'), ((3532, 3592), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3532, 3562), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((4003, 4057), 'com.intellij.openapi.application.ApplicationInfo.getInstance'), ((4178, 4208), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value')] |
package com.wy.chatting.domain.chatgpt.service.dto.request;
import com.theokanning.openai.completion.CompletionRequest;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class GPTCompletionRequest {
private String model;
private String prompt;
private Integer maxToken;
public static CompletionRequest of(GPTCompletionRequest restRequest) {
return CompletionRequest.builder()
.model(restRequest.getModel())
.prompt(restRequest.getPrompt())
.maxTokens(restRequest.getMaxToken())
.build();
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((472, 674), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((472, 649), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((472, 595), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((472, 546), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package egovframework.example.API;
import java.time.Duration;
import java.util.List;
import com.theokanning.openai.embedding.Embedding;
import com.theokanning.openai.embedding.EmbeddingRequest;
import com.theokanning.openai.service.OpenAiService;
public class OAISingleton {
//create and manage OpenAiService singleton.
public static OAISingleton instance = new OAISingleton();
private static OpenAiService service;
private OAISingleton() {
try {
service = new OpenAiService(Keys.OPENAPI_KEY,Duration.ofMinutes(9999));
}
catch(Exception e) {
throw new RuntimeException("Error While creating class: OAISingleton\n");
}
}
public static OAISingleton getInstance() {
return instance;
}
private EmbeddingRequest emb = new EmbeddingRequest();
private EmbeddingRequest getEmbeddingModel(String model, List<String> input) {
new EmbeddingRequest();
return EmbeddingRequest.builder()
.input(input)
.model(model)
.build();
}
//build and return data
public List<Embedding> getEmbeddingData(String model, List<String> input){
OpenAiService s = service;
emb = getEmbeddingModel(model,input);
return s.createEmbeddings(emb).getData();
}
public List<Embedding> getEmbeddingData(List<String> input){
OpenAiService s = service;
emb = getEmbeddingModel("text-embedding-ada-002",input);
return s.createEmbeddings(emb).getData();
}
}
| [
"com.theokanning.openai.embedding.EmbeddingRequest.builder"
] | [((884, 959), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((884, 946), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((884, 928), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')] |
package com.datasqrl.ai.spring;
import com.datasqrl.ai.Examples;
import com.datasqrl.ai.api.GraphQLExecutor;
import com.datasqrl.ai.backend.APIChatBackend;
import com.datasqrl.ai.backend.AnnotatedChatMessage;
import com.datasqrl.ai.backend.MessageTruncator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.knuddels.jtokkit.Encodings;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionRequest.ChatCompletionRequestFunctionCall;
import com.theokanning.openai.completion.chat.ChatFunctionCall;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
@SpringBootApplication
public class SimpleServer {
public static final String DEFAULT_GRAPHQL_ENDPOINT = "http://localhost:8888/graphql";
public static void main(String[] args) {
SpringApplication.run(SimpleServer.class, args);
}
@CrossOrigin(origins = "*")
@RestController
public static class MessageController {
private final Examples example;
OpenAiService service;
GraphQLExecutor apiExecutor;
APIChatBackend backend;
ChatMessage systemMessage;
MessageTruncator messageTruncator;
List functions;
String chartFunctionName="";
public MessageController(@Value("${example:nutshop}") String exampleName) throws IOException {
this.example = Examples.valueOf(exampleName.trim().toUpperCase());
String openAIToken = System.getenv("OPENAI_TOKEN");
this.service = new OpenAiService(openAIToken, Duration.ofSeconds(60));
String graphQLEndpoint = DEFAULT_GRAPHQL_ENDPOINT;
this.apiExecutor = new GraphQLExecutor(graphQLEndpoint);
this.backend = APIChatBackend.of(Path.of(example.getConfigFile()), apiExecutor);
this.systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), example.getSystemPrompt());
this.messageTruncator = new MessageTruncator(example.getModel().getMaxInputTokens(), systemMessage,
Encodings.newDefaultEncodingRegistry().getEncodingForModel(example.getModel().getEncodingModel()));
this.functions = new ArrayList<>();
this.functions.addAll(backend.getChatFunctions());
if (example.isSupportCharts()) {
ObjectMapper objectMapper = new ObjectMapper();
URL url = SimpleServer.class.getClassLoader().getResource("plotfunction.json");
if (url != null) {
try {
JsonNode functionJson = objectMapper.readTree(url);
this.chartFunctionName = functionJson.get("name").textValue();
this.functions.add(functionJson);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private Map<String,Object> getContext(String userId) {
return Map.of(example.getUserIdFieldName(), example.getPrepareUserIdFct().apply(
userId));
}
@GetMapping("/messages")
public List<ResponseMessage> getMessages(@RequestParam String userId) {
Map<String,Object> context = getContext(userId);
List<AnnotatedChatMessage> messages = backend.getChatMessages(context, 50);
return messages.stream().filter(msg -> {
ChatMessage m = msg.getMessage();
ChatMessageRole role = ChatMessageRole.valueOf(m.getRole().toUpperCase());
switch (role) {
case USER:
case ASSISTANT:
return true;
}
return false;
}).map(ResponseMessage::of).collect(Collectors.toUnmodifiableList());
}
@PostMapping("/messages")
public ResponseMessage postMessage(@RequestBody InputMessage message) {
Map<String,Object> context = getContext(message.getUserId());
List<ChatMessage> messages = new ArrayList<>(30);
backend.getChatMessages(context, 20).stream().map(AnnotatedChatMessage::getMessage)
.forEach(messages::add);
System.out.printf("Retrieved %d messages\n", messages.size());
ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), message.getContent());
messages.add(chatMessage);
backend.saveChatMessage(chatMessage, context);
while (true) {
System.out.println("Calling OpenAI");
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
.builder()
.model(example.getModel().getOpenAIModel())
.messages(messageTruncator.truncateMessages(messages, backend.getChatFunctions()))
.functions(functions)
.functionCall(ChatCompletionRequestFunctionCall.of("auto"))
.n(1)
.maxTokens(example.getModel().getCompletionLength())
.logitBias(new HashMap<>())
.build();
ChatMessage responseMessage = service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage();
messages.add(responseMessage); // don't forget to update the conversation with the latest response
backend.saveChatMessage(responseMessage, context);
ChatFunctionCall functionCall = responseMessage.getFunctionCall();
if (functionCall != null && !functionCall.getName().equalsIgnoreCase(chartFunctionName)) {
System.out.println("Executing " + functionCall.getName() + " with arguments " + functionCall.getArguments().toPrettyString());
ChatMessage functionResponse = backend.executeAndConvertToMessageHandlingExceptions(
functionCall, context);
//System.out.println("Executed " + fctCall.getName() + ".");
messages.add(functionResponse);
backend.saveChatMessage(functionResponse, context);
} else {
//The text answer
return ResponseMessage.of(responseMessage);
}
}
}
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value"
] | [((2444, 2474), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((2620, 2717), 'com.knuddels.jtokkit.Encodings.newDefaultEncodingRegistry'), ((4611, 4639), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')] |
package org.example.openai;
import static com.theokanning.openai.service.OpenAiService.defaultClient;
import static com.theokanning.openai.service.OpenAiService.defaultObjectMapper;
import static com.theokanning.openai.service.OpenAiService.defaultRetrofit;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.theokanning.openai.OpenAiApi;
import com.theokanning.openai.embedding.EmbeddingRequest;
import com.theokanning.openai.service.OpenAiService;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import okhttp3.OkHttpClient;
import org.example.EmbeddingsGenerator;
import retrofit2.Retrofit;
public class OpenAiConnector implements EmbeddingsGenerator {
private final OpenAiService openAiService;
public OpenAiConnector() {
ObjectMapper objectMapper = defaultObjectMapper();
OkHttpClient client = defaultClient(System.getenv("OPENAI_API_KEY"), Duration.ofSeconds(30));
Retrofit retrofit = defaultRetrofit(client, objectMapper);
OpenAiApi api = retrofit.create(OpenAiApi.class);
openAiService = new OpenAiService(api);
}
public List<Double> getEmbeddings(String sentence) {
var request =
EmbeddingRequest.builder()
.model("text-embedding-ada-002")
.input(Collections.singletonList(sentence))
.build();
var response = openAiService.createEmbeddings(request);
return response.getData().get(0).getEmbedding();
}
}
| [
"com.theokanning.openai.embedding.EmbeddingRequest.builder"
] | [((1179, 1327), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((1179, 1306), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((1179, 1250), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')] |
package io.qifan.chatgpt.assistant;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.theokanning.openai.OpenAiApi;
import com.theokanning.openai.completion.chat.ChatCompletionChunk;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.service.OpenAiService;
import io.qifan.chatgpt.assistant.gpt.session.ChatSession;
import io.qifan.chatgpt.assistant.infrastructure.gpt.GPTProperty;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import retrofit2.Retrofit;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import static com.theokanning.openai.service.OpenAiService.*;
@SpringBootTest
@Slf4j
public class ApplicationTest {
@Autowired
GPTProperty property;
@Autowired
MongoTemplate mongoTemplate;
@Test
void findById() {
List<ChatSession> all = mongoTemplate.findAll(ChatSession.class);
all.forEach(chatSession -> log.info(chatSession.toString()));
}
@SneakyThrows
@Test
void chatTest() {
ObjectMapper mapper = defaultObjectMapper();
Proxy proxy = new Proxy(Proxy.Type.HTTP,
new InetSocketAddress(property.getProxy().getHost(), property.getProxy().getPort()));
OkHttpClient client = defaultClient("",
Duration.ofMinutes(1))
.newBuilder()
.proxy(proxy)
.build();
Retrofit retrofit = defaultRetrofit(client, mapper);
OpenAiApi api = retrofit.create(OpenAiApi.class);
OpenAiService service = new OpenAiService(api);
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
.messages(List.of(new ChatMessage("user",
"你好")))
.model("gpt-3.5-turbo")
// .model(chatConfig.getModel().getName())
// .presencePenalty(chatConfig.getPresencePenalty())
// .temperature(chatConfig.getTemperature())
// .maxTokens(chatConfig.getMaxTokens())
.stream(true)
.build();
CountDownLatch countDownLatch = new CountDownLatch(1);
service.streamChatCompletion(chatCompletionRequest).subscribe(new Subscriber<>() {
private Subscription subscription;
private io.qifan.chatgpt.assistant.gpt.message.ChatMessage responseChatMessage;
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
subscription.request(1);
responseChatMessage = new io.qifan.chatgpt.assistant.gpt.message.ChatMessage().setContent("");
log.info("订阅");
}
@Override
public void onNext(ChatCompletionChunk chatCompletionChunk) {
com.theokanning.openai.completion.chat.ChatMessage chatMessage = chatCompletionChunk.getChoices().get(0)
.getMessage();
if (chatMessage.getContent() != null) {
log.info("收到响应消息:{}", chatMessage);
responseChatMessage.setContent(responseChatMessage.getContent() + chatMessage.getContent());
responseChatMessage.setRole(chatMessage.getRole());
}
subscription.request(1);
}
@Override
public void onError(Throwable throwable) {
throwable.printStackTrace();
}
@Override
public void onComplete() {
log.info("请求结束");
countDownLatch.countDown();
}
});
countDownLatch.await();
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((2165, 3184), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2165, 3100), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2165, 2533), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2165, 2434), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package com.theokanning.openai.service;
import com.theokanning.openai.embedding.Embedding;
import com.theokanning.openai.embedding.EmbeddingRequest;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class EmbeddingTest {
String token = System.getenv("OPENAI_TOKEN");
com.theokanning.openai.service.OpenAiService service = new OpenAiService(token);
@Test
void createEmbeddings() {
EmbeddingRequest embeddingRequest = EmbeddingRequest.builder()
.model("text-similarity-babbage-001")
.input(Collections.singletonList("The food was delicious and the waiter..."))
.build();
List<Embedding> embeddings = service.createEmbeddings(embeddingRequest).getData();
assertFalse(embeddings.isEmpty());
assertFalse(embeddings.get(0).getEmbedding().isEmpty());
}
}
| [
"com.theokanning.openai.embedding.EmbeddingRequest.builder"
] | [((552, 751), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((552, 726), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((552, 632), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')] |
package com.theokanning.openai;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionRequest;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class CompletionTest {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
@Test
void createCompletion() {
CompletionRequest completionRequest = CompletionRequest.builder()
.model("ada")
.prompt("Somebody once told me the world is gonna roll me")
.echo(true)
.user("testing")
.logitBias(new HashMap<>())
.build();
List<CompletionChoice> choices = service.createCompletion(completionRequest).getChoices();
assertFalse(choices.isEmpty());
}
@Test
void createCompletionDeprecated() {
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt("Somebody once told me the world is gonna roll me")
.echo(true)
.user("testing")
.build();
List<CompletionChoice> choices = service.createCompletion("ada", completionRequest).getChoices();
assertFalse(choices.isEmpty());
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((522, 785), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((522, 760), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((522, 716), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((522, 683), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((522, 655), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((522, 579), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1030, 1219), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1030, 1194), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1030, 1161), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1030, 1133), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package com.theokanning.openai.service;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionChunk;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class CompletionTest {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
@Test
void createCompletion() {
CompletionRequest completionRequest = CompletionRequest.builder()
.model("babbage-002")
.prompt("Somebody once told me the world is gonna roll me")
.echo(true)
.n(5)
.maxTokens(50)
.user("testing")
.logitBias(new HashMap<>())
.logprobs(5)
.build();
List<CompletionChoice> choices = service.createCompletion(completionRequest).getChoices();
assertEquals(5, choices.size());
assertNotNull(choices.get(0).getLogprobs());
}
@Test
void streamCompletion() {
CompletionRequest completionRequest = CompletionRequest.builder()
.model("babbage-002")
.prompt("Somebody once told me the world is gonna roll me")
.echo(true)
.n(1)
.maxTokens(25)
.user("testing")
.logitBias(new HashMap<>())
.logprobs(5)
.stream(true)
.build();
List<CompletionChunk> chunks = new ArrayList<>();
service.streamCompletion(completionRequest).blockingForEach(chunks::add);
assertTrue(chunks.size() > 0);
assertNotNull(chunks.get(0).getChoices().get(0));
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((659, 1012), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 987), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 958), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 914), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 881), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 850), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 828), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 800), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 724), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1684), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1659), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1629), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1600), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1556), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1523), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1492), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1470), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1442), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1366), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package br.com.alura.screenmatch.service;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
public class ConsultaChatGPT {
public static String obterTraducao(String texto) {
OpenAiService service = new OpenAiService(System.getenv("OPENAI_APIKEY"));
CompletionRequest requisicao = CompletionRequest.builder()
.model("text-davinci-003")
.prompt("traduza para o português o texto: " + texto)
.maxTokens(1000)
.temperature(0.7)
.build();
var resposta = service.createCompletion(requisicao);
return resposta.getChoices().get(0).getText();
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((367, 600), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 575), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 541), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 508), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 437), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package br.com.alura.screenmatch.service;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
public class ConsultaChatGPT {
public static String obterTraducao(String texto) {
OpenAiService service = new OpenAiService(System.getenv("OPENAI_APIKEY"));
CompletionRequest requisicao = CompletionRequest.builder()
.model("text-davinci-003")
.prompt("traduza para o português o texto: " + texto)
.maxTokens(1000)
.temperature(0.7)
.build();
var resposta = service.createCompletion(requisicao);
return resposta.getChoices().get(0).getText();
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((367, 600), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 575), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 541), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 508), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 437), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package br.com.alura.screenmatch.service;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
public class ConsultaChatGPT {
public static String obterTraducao(String texto) {
OpenAiService service = new OpenAiService(System.getenv("OPENAI_APIKEY"));
CompletionRequest requisicao = CompletionRequest.builder()
.model("text-davinci-003")
.prompt("traduza para o português o texto: " + texto)
.maxTokens(1000)
.temperature(0.7)
.build();
var resposta = service.createCompletion(requisicao);
return resposta.getChoices().get(0).getText();
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((367, 600), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 575), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 541), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 508), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 437), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package com.theokanning.openai.service;
import com.theokanning.openai.embedding.Embedding;
import com.theokanning.openai.embedding.EmbeddingRequest;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class EmbeddingTest {
String token = System.getenv("OPENAI_TOKEN");
com.theokanning.openai.service.OpenAiService service = new OpenAiService(token);
@Test
void createEmbeddings() {
EmbeddingRequest embeddingRequest = EmbeddingRequest.builder()
.model("text-similarity-babbage-001")
.input(Collections.singletonList("The food was delicious and the waiter..."))
.build();
List<Embedding> embeddings = service.createEmbeddings(embeddingRequest).getData();
assertFalse(embeddings.isEmpty());
assertFalse(embeddings.get(0).getEmbedding().isEmpty());
}
}
| [
"com.theokanning.openai.embedding.EmbeddingRequest.builder"
] | [((552, 751), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((552, 726), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((552, 632), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')] |
package com.theokanning.openai.service;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionChunk;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class CompletionTest {
String token = System.getenv("OPENAI_TOKEN");
OpenAiService service = new OpenAiService(token);
@Test
void createCompletion() {
CompletionRequest completionRequest = CompletionRequest.builder()
.model("babbage-002")
.prompt("Somebody once told me the world is gonna roll me")
.echo(true)
.n(5)
.maxTokens(50)
.user("testing")
.logitBias(new HashMap<>())
.logprobs(5)
.build();
List<CompletionChoice> choices = service.createCompletion(completionRequest).getChoices();
assertEquals(5, choices.size());
assertNotNull(choices.get(0).getLogprobs());
}
@Test
void streamCompletion() {
CompletionRequest completionRequest = CompletionRequest.builder()
.model("babbage-002")
.prompt("Somebody once told me the world is gonna roll me")
.echo(true)
.n(1)
.maxTokens(25)
.user("testing")
.logitBias(new HashMap<>())
.logprobs(5)
.stream(true)
.build();
List<CompletionChunk> chunks = new ArrayList<>();
service.streamCompletion(completionRequest).blockingForEach(chunks::add);
assertTrue(chunks.size() > 0);
assertNotNull(chunks.get(0).getChoices().get(0));
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((659, 1012), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 987), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 958), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 914), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 881), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 850), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 828), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 800), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 724), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1684), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1659), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1629), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1600), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1556), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1523), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1492), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1470), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1442), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1366), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2024 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.model.ai.openai;
import com.google.gson.Gson;
import com.theokanning.openai.OpenAiHttpException;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import okhttp3.ResponseBody;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.ai.AIConstants;
import org.jkiss.dbeaver.model.ai.AIEngineSettings;
import org.jkiss.dbeaver.model.ai.AISettings;
import org.jkiss.dbeaver.model.ai.completion.AbstractAICompletionEngine;
import org.jkiss.dbeaver.model.ai.completion.DAICompletionContext;
import org.jkiss.dbeaver.model.ai.completion.DAICompletionMessage;
import org.jkiss.dbeaver.model.ai.format.IAIFormatter;
import org.jkiss.dbeaver.model.ai.metadata.MetadataProcessor;
import org.jkiss.dbeaver.model.ai.openai.service.AdaptedOpenAiService;
import org.jkiss.dbeaver.model.ai.openai.service.GPTCompletionAdapter;
import org.jkiss.dbeaver.model.data.json.JSONUtils;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObjectContainer;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.CommonUtils;
import retrofit2.HttpException;
import retrofit2.Response;
import java.io.IOException;
import java.io.StringReader;
import java.time.Duration;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class OpenAICompletionEngine extends AbstractAICompletionEngine<GPTCompletionAdapter, Object> {
private static final Log log = Log.getLog(OpenAICompletionEngine.class);
//How many retries may be done if code 429 happens
protected static final int MAX_REQUEST_ATTEMPTS = 3;
private static final Map<String, GPTCompletionAdapter> clientInstances = new HashMap<>();
private static final Pattern sizeErrorPattern = Pattern.compile("This model's maximum context length is [0-9]+ tokens. "
+ "\\wowever[, ]+you requested [0-9]+ tokens \\(([0-9]+) in \\w+ \\w+[;,] [0-9]+ \\w+ \\w+ completion\\). "
+ "Please reduce .+");
public OpenAICompletionEngine() {
}
private static CompletionRequest buildLegacyAPIRequest(
@NotNull List<DAICompletionMessage> messages,
int maxTokens,
Double temperature,
String modelId
) {
return CompletionRequest.builder()
.prompt(buildSingleMessage(truncateMessages(messages, maxTokens)))
.temperature(temperature)
.maxTokens(maxTokens)
.frequencyPenalty(0.0)
.n(1)
.presencePenalty(0.0)
.stop(List.of("#", ";"))
.model(modelId)
//.echo(true)
.build();
}
private static ChatCompletionRequest buildChatRequest(
@NotNull List<DAICompletionMessage> messages,
int maxTokens,
Double temperature,
String modelId
) {
return ChatCompletionRequest.builder()
.messages(truncateMessages(messages, maxTokens).stream()
.map(m -> new ChatMessage(m.role().getId(), m.content()))
.toList())
.temperature(temperature)
.maxTokens(maxTokens)
.frequencyPenalty(0.0)
.presencePenalty(0.0)
.n(1)
.model(modelId)
//.echo(true)
.build();
}
/**
* Resets GPT client cache
*/
public static void resetServices() {
clientInstances.clear();
}
@Override
public String getEngineName() {
return "OpenAI GPT";
}
public String getModelName() {
return CommonUtils.toString(getSettings().getProperties().get(AIConstants.GPT_MODEL), GPTModel.GPT_TURBO16.getName());
}
public boolean isValidConfiguration() {
return !CommonUtils.isEmpty(acquireToken());
}
@Override
public Map<String, GPTCompletionAdapter> getServiceMap() {
return clientInstances;
}
/**
* Request completion from GPT API uses parameters from {@link AIConstants} for model settings\
* Adds current schema metadata to starting query
*
* @param monitor execution monitor
* @param context completion context
* @param messages request messages
* @return resulting string
*/
@Nullable
protected String requestCompletion(
@NotNull DBRProgressMonitor monitor,
@NotNull DAICompletionContext context,
@NotNull List<DAICompletionMessage> messages,
@NotNull IAIFormatter formatter,
boolean chatCompletion
) throws DBException {
final DBCExecutionContext executionContext = context.getExecutionContext();
DBSObjectContainer mainObject = getScopeObject(context, executionContext);
final GPTModel model = getModel();
final DAICompletionMessage metadataMessage = MetadataProcessor.INSTANCE.createMetadataMessage(
monitor,
context,
mainObject,
formatter,
model.isChatAPI(),
getMaxTokens() - AIConstants.MAX_RESPONSE_TOKENS,
chatCompletion
);
final List<DAICompletionMessage> mergedMessages = new ArrayList<>();
mergedMessages.add(metadataMessage);
mergedMessages.addAll(messages);
if (monitor.isCanceled()) {
return "";
}
GPTCompletionAdapter service = getServiceInstance(executionContext);
Object completionRequest = createCompletionRequest(mergedMessages);
String completionText = callCompletion(monitor, mergedMessages, service, completionRequest);
return processCompletion(
mergedMessages,
monitor,
executionContext,
mainObject,
completionText,
formatter,
model.isChatAPI()
);
}
protected int getMaxTokens() {
return GPTModel.getByName(getModelName()).getMaxTokens();
}
/**
* Initializes OpenAiService instance using token provided by {@link AIConstants} GTP_TOKEN_PATH
*/
protected GPTCompletionAdapter initGPTApiClientInstance() throws DBException {
String token = acquireToken();
if (CommonUtils.isEmpty(token)) {
throw new DBException("Empty API token value");
}
return new AdaptedOpenAiService(token, Duration.ofSeconds(30));
}
protected String acquireToken() {
AIEngineSettings config = getSettings();
Object token = config.getProperties().get(AIConstants.GPT_API_TOKEN);
if (token != null) {
return token.toString();
}
return DBWorkbench.getPlatform().getPreferenceStore().getString(AIConstants.GPT_API_TOKEN);
}
@NotNull
protected AIEngineSettings getSettings() {
return AISettings.getSettings().getEngineConfiguration(AIConstants.OPENAI_ENGINE);
}
@Nullable
protected String callCompletion(
@NotNull DBRProgressMonitor monitor,
@NotNull List<DAICompletionMessage> messages,
@NotNull GPTCompletionAdapter service,
@NotNull Object completionRequest
) throws DBException {
monitor.subTask("Request GPT completion");
try {
if (CommonUtils.toBoolean(getSettings().getProperties().get(AIConstants.AI_LOG_QUERY))) {
if (completionRequest instanceof ChatCompletionRequest) {
log.debug("Chat GPT request:\n" + ((ChatCompletionRequest) completionRequest).getMessages().stream()
.map(message -> "# " + message.getRole() + "\n" + message.getContent())
.collect(Collectors.joining("\n")));
} else {
log.debug("GPT request:\n" + ((CompletionRequest) completionRequest).getPrompt());
}
}
if (monitor.isCanceled()) {
return null;
}
try {
List<?> choices;
int responseSize = AIConstants.MAX_RESPONSE_TOKENS;
for (int i = 0; ; i++) {
try {
choices = getCompletionChoices(service, completionRequest);
break;
} catch (Exception e) {
if ((e instanceof HttpException && ((HttpException) e).code() == 429)
|| (e instanceof OpenAiHttpException && e.getMessage().contains("This model's maximum"))) {
if (e instanceof HttpException) {
RuntimeUtils.pause(1000);
} else {
// Extracts resulted prompt size from the error message and resizes max response to
// value lower that (maxTokens - prompt size)
Matcher matcher = sizeErrorPattern.matcher(e.getMessage());
int promptSize;
if (matcher.find()) {
String numberStr = matcher.group(1);
promptSize = CommonUtils.toInt(numberStr);
} else {
throw e;
}
responseSize = Math.min(responseSize,
getMaxTokens() - promptSize - 1);
if (responseSize < 0) {
throw e;
}
completionRequest = createCompletionRequest(messages, responseSize);
}
if (i >= MAX_REQUEST_ATTEMPTS - 1) {
throw e;
} else {
if (e instanceof HttpException) {
log.debug("AI service failed. Retry (" + e.getMessage() + ")");
}
continue;
}
}
throw e;
}
}
String completionText;
Object choice = choices.stream().findFirst().orElseThrow();
if (choice instanceof CompletionChoice) {
completionText = ((CompletionChoice) choice).getText();
} else {
completionText = ((ChatCompletionChoice) choice).getMessage().getContent();
}
if (CommonUtils.toBoolean(getSettings().getProperties().get(AIConstants.AI_LOG_QUERY))) {
log.debug("GPT response:\n" + completionText);
}
return completionText;
} catch (Exception exception) {
if (exception instanceof HttpException) {
Response<?> response = ((HttpException) exception).response();
if (response != null) {
try {
try (ResponseBody responseBody = response.errorBody()) {
if (responseBody != null) {
String bodyString = responseBody.string();
if (!CommonUtils.isEmpty(bodyString)) {
try {
Gson gson = new Gson();
Map<String, Object> map = JSONUtils.parseMap(gson, new StringReader(bodyString));
Map<String, Object> error = JSONUtils.deserializeProperties(map, "error");
if (error != null) {
String message = JSONUtils.getString(error, "message");
if (!CommonUtils.isEmpty(message)) {
bodyString = message;
}
}
} catch (Exception e) {
// ignore json errors
}
throw new DBException("AI service error: " + bodyString);
}
}
}
} catch (IOException e) {
log.debug(e);
}
}
} else if (exception instanceof RuntimeException &&
!(exception instanceof OpenAiHttpException) &&
exception.getCause() != null) {
throw new DBException("AI service error: " + exception.getCause().getMessage(), exception.getCause());
}
throw exception;
}
} finally {
monitor.done();
}
}
protected GPTCompletionAdapter getServiceInstance(@NotNull DBCExecutionContext executionContext) throws DBException {
DBPDataSourceContainer container = executionContext.getDataSource().getContainer();
GPTCompletionAdapter service = clientInstances.get(container.getId());
if (service == null) {
service = initGPTApiClientInstance();
clientInstances.put(container.getId(), service);
}
return service;
}
protected Object createCompletionRequest(@NotNull List<DAICompletionMessage> messages) {
return createCompletionRequest(messages, AIConstants.MAX_RESPONSE_TOKENS);
}
protected Object createCompletionRequest(@NotNull List<DAICompletionMessage> messages, int responseSize) {
Double temperature =
CommonUtils.toDouble(getSettings().getProperties().get(AIConstants.AI_TEMPERATURE), 0.0);
final GPTModel model = getModel();
if (model.isChatAPI()) {
return buildChatRequest(messages, responseSize, temperature, model.getName());
} else {
return buildLegacyAPIRequest(messages, responseSize, temperature, model.getName());
}
}
@NotNull
private GPTModel getModel() {
final String modelId = CommonUtils.toString(getSettings().getProperties().get(AIConstants.GPT_MODEL), "");
return CommonUtils.isEmpty(modelId) ? GPTModel.GPT_TURBO16 : GPTModel.getByName(modelId);
}
private List<?> getCompletionChoices(GPTCompletionAdapter service, Object completionRequest) {
if (completionRequest instanceof CompletionRequest) {
return service.createCompletion((CompletionRequest) completionRequest).getChoices();
} else {
return service.createChatCompletion((ChatCompletionRequest) completionRequest).getChoices();
}
}
@NotNull
private static String buildSingleMessage(@NotNull List<DAICompletionMessage> messages) {
final StringJoiner buffer = new StringJoiner("\n");
for (DAICompletionMessage message : messages) {
if (message.role() == DAICompletionMessage.Role.SYSTEM) {
buffer.add("###");
buffer.add(message.content()
.lines()
.map(line -> '#' + line)
.collect(Collectors.joining("\n")));
buffer.add("###");
} else {
buffer.add(message.content());
}
}
buffer.add("SELECT ");
return buffer.toString();
}
@NotNull
private static List<DAICompletionMessage> truncateMessages(@NotNull List<DAICompletionMessage> messages, int maxTokens) {
final Deque<DAICompletionMessage> pending = new LinkedList<>(messages);
final List<DAICompletionMessage> truncated = new ArrayList<>();
int remainingTokens = maxTokens - 20; // Just to be sure
if (pending.getFirst().role() == DAICompletionMessage.Role.SYSTEM) {
// Always append system message
truncated.add(pending.remove());
}
while (!pending.isEmpty()) {
final DAICompletionMessage message = pending.remove();
final int messageTokens = message.content().length();
if (remainingTokens < 0 || messageTokens > remainingTokens) {
// Exclude old messages that don't fit into given number of tokens
break;
}
truncated.add(message);
remainingTokens -= messageTokens;
}
return truncated;
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder",
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((3458, 3835), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3788), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3760), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3723), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3689), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3671), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3636), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3602), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3564), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4054, 4489), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4054, 4442), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4054, 4414), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4054, 4396), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4054, 4362), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4054, 4327), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4054, 4293), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4054, 4255), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5994, 6262), 'org.jkiss.dbeaver.model.ai.metadata.MetadataProcessor.INSTANCE.createMetadataMessage'), ((7784, 7867), 'org.jkiss.dbeaver.runtime.DBWorkbench.getPlatform'), ((7784, 7830), 'org.jkiss.dbeaver.runtime.DBWorkbench.getPlatform'), ((7951, 8025), 'org.jkiss.dbeaver.model.ai.AISettings.getSettings')] |
package cn.com.ogtwelve.utils;
import cn.com.ogtwelve.entity.Billing;
import cn.com.ogtwelve.entity.Subscription;
import cn.com.ogtwelve.enums.ImageSizeEnum;
import cn.com.ogtwelve.enums.ModelEnum;
import cn.com.ogtwelve.enums.RoleEnum;
import cn.com.ogtwelve.service.OpenAIService;
import com.google.common.cache.Cache;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.image.CreateImageRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* @Author OGtwelve
* @Date 2023/7/12 12:03
* @Description: openai工具类
*/
public class OpenAIUtils {
private static final Log LOG = LogFactory.getLog(OpenAIUtils.class);
private static OpenAIService openAIService;
public OpenAIUtils(OpenAIService openAIService) {
OpenAIUtils.openAIService = openAIService;
}
public static void createStreamChatCompletion(String content) {
createStreamChatCompletion(content, "DEFAULT USER", System.out);
}
public static void createStreamChatCompletion(String content, OutputStream os) {
createStreamChatCompletion(content, "DEFAULT USER", os);
}
public static void createStreamChatCompletion(String content, String user, OutputStream os) {
openAIService.createStreamChatCompletion(content, user, os);
}
public static void createStreamChatCompletion(String content, String user, String model, OutputStream os) {
createStreamChatCompletion(RoleEnum.USER.getRoleName(), content, user, model, 1.0, 1.0, os);
}
public static void createStreamChatCompletion(String role, String content, String user, String model, Double temperature, Double topP, OutputStream os) {
createStreamChatCompletion(ChatCompletionRequest.builder().model(model).messages(Collections.singletonList(new ChatMessage(role, content))).user(user).temperature(temperature).topP(topP).stream(true).build(), os);
}
public static void createStreamChatCompletion(ChatCompletionRequest chatCompletionRequest, OutputStream os) {
openAIService.createStreamChatCompletion(chatCompletionRequest, os);
}
public static List<String> createChatCompletion(String content) {
return createChatCompletion(content, "DEFAULT USER");
}
public static List<String> createChatCompletion(String content, String user) {
return openAIService.chatCompletion(content, user);
}
public static List<String> createChatCompletion(String content, String user, String model) {
return createChatCompletion(RoleEnum.USER.getRoleName(), content, user, model, 1.0, 1.0);
}
public static List<String> createChatCompletion(String role, String content, String user, String model, Double temperature, Double topP) {
return createChatCompletion(ChatCompletionRequest.builder().model(model).messages(Collections.singletonList(new ChatMessage(role, content))).user(user).temperature(temperature).topP(topP).build());
}
public static List<String> createChatCompletion(ChatCompletionRequest chatCompletionRequest) {
return openAIService.chatCompletion(chatCompletionRequest);
}
public static List<String> createImage(String prompt) {
return createImage(prompt, "DEFAULT USER");
}
public static List<String> createImage(String prompt, String user) {
return createImage(CreateImageRequest.builder().prompt(prompt).user(user).build());
}
public static List<String> createImage(CreateImageRequest createImageRequest) {
return openAIService.createImages(createImageRequest);
}
public static void downloadImage(String prompt, HttpServletResponse response) {
downloadImage(prompt, ImageSizeEnum.S1024x1024.getSize(), response);
}
public static void downloadImage(String prompt, Integer n, HttpServletResponse response) {
downloadImage(prompt, n, ImageSizeEnum.S1024x1024.getSize(), response);
}
public static void downloadImage(String prompt, String size, HttpServletResponse response) {
downloadImage(prompt, 1, size, response);
}
public static void downloadImage(String prompt, Integer n, String size, HttpServletResponse response) {
downloadImage(CreateImageRequest.builder().prompt(prompt).n(n).size(size).user("DEFAULT USER").build(), response);
}
public static void downloadImage(CreateImageRequest createImageRequest, HttpServletResponse response) {
openAIService.downloadImage(createImageRequest, response);
}
public static String billingUsage(String... startDate) {
return openAIService.billingUsage(startDate);
}
public static String billingUsage(String startDate, String endDate) {
return openAIService.billingUsage(startDate, endDate);
}
public static Billing billing(String... startDate) {
return openAIService.billing(startDate);
}
public static Subscription subscription() {
return openAIService.subscription();
}
public static void forceClearCache(String cacheName) {
openAIService.forceClearCache(cacheName);
}
public static Cache<String, LinkedList<ChatMessage>> retrieveCache() {
return openAIService.retrieveCache();
}
public static LinkedList<ChatMessage> retrieveChatMessage(String key) {
return openAIService.retrieveChatMessage(key);
}
public static void setCache(Cache<String, LinkedList<ChatMessage>> cache) {
openAIService.setCache(cache);
}
public static void addCache(String key, LinkedList<ChatMessage> chatMessages) {
openAIService.addCache(key, chatMessages);
}
}
| [
"com.theokanning.openai.image.CreateImageRequest.builder",
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((1785, 1812), 'cn.com.ogtwelve.enums.RoleEnum.USER.getRoleName'), ((2051, 2231), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2051, 2223), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2051, 2210), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2051, 2199), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2051, 2174), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2051, 2163), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2051, 2095), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2865, 2892), 'cn.com.ogtwelve.enums.RoleEnum.USER.getRoleName'), ((3113, 3280), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3113, 3272), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3113, 3261), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3113, 3236), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3113, 3225), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3113, 3157), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3683, 3745), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3683, 3737), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3683, 3726), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4023, 4057), 'cn.com.ogtwelve.enums.ImageSizeEnum.S1024x1024.getSize'), ((4205, 4239), 'cn.com.ogtwelve.enums.ImageSizeEnum.S1024x1024.getSize'), ((4543, 4631), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4543, 4623), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4543, 4602), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4543, 4591), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4543, 4586), 'com.theokanning.openai.image.CreateImageRequest.builder')] |
package baritone.plus.brain.utils;
import baritone.plus.main.Debug;
import com.theokanning.openai.OpenAiApi;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.service.OpenAiService;
import java.time.Duration;
import java.util.List;
public class ChatGPT {
private final OpenAiApi api;
protected ChatGPT(String apiKey) {
this.api = OpenAiService.buildApi(apiKey, Duration.ofMinutes(1));
}
public static ChatGPT build() {
return new ChatGPT("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");
}
public String generateTaskNaturalLanguage(WorldState worldState) {
// Create user message
ChatMessage userMessage = new ChatMessage(
"user",
String.format("Given my current situation in an anarchy Minecraft server, what should my next goal be? Here's my current state:\n%s", worldState.toString())
);
// Create system message
ChatMessage systemMessage = new ChatMessage(
"system",
"You are an AI playing on an anarchy Minecraft server. Use the information provided to decide the best next task. Max 50 Words."
);
return prompt(List.of(systemMessage, userMessage));
}
public String prompt(List<ChatMessage> messages) {
// Create chat completion request
ChatCompletionRequest completionRequest = ChatCompletionRequest.builder()
.messages(messages)
.model("gpt-3.5-turbo")
.build();
// Get completion from API
return api.createChatCompletion(completionRequest).blockingGet()
.getChoices().get(0).getMessage().getContent();
}
public String generateTask(WorldState worldState) {
// Generate natural language task with ChatGPT as before...
String task = generateTaskNaturalLanguage(worldState);
Debug.logMessage(task);
// Create user message asking to convert task to command
ChatMessage userMessage = new ChatMessage(
"user",
String.format("Given this task: '%s', what would be the appropriate command to accomplish it? Execute consecutve commands by separating them with ; (e.g @get iron_axe;get log 100;goto 0 0;give Player log 100)", task)
);
StringBuilder lines = new StringBuilder();
/*for (PlusCommand c : AltoClef.getCommandExecutor().allCommands()) {
lines.append("@").append(c.getHelpRepresentation()).append(" | ").append(c.getDescription());
lines.append("\n");
}*/
// Create system message
ChatMessage systemMessage = new ChatMessage(
"system",
"You are an AI assistant tasked with understanding and converting user inputs into valid commands for the Alto Clef bot in Minecraft.\n" +
"Ensure to convert inputs into the most specific commands possible and fill out required parameters. Including coordinates/locations\n" +
"If no valid task can be derived from the input, return the @idle command\n" +
"Respond only with the command chain - no explanations - only command\n" +
"Parameters requiring name assume specific item name e.g diamond_chestplate\n" +
"You must fill out all parameters with values. \n" +
"AltoClef Commands that you can use: " + lines
);
// Create chat completion request
ChatCompletionRequest completionRequest = ChatCompletionRequest.builder()
.messages(List.of(systemMessage, userMessage))
.model("gpt-3.5-turbo")
.temperature(0D)
.build();
// Get completion from API and return it as the command
return api.createChatCompletion(completionRequest).blockingGet()
.getChoices().get(0).getMessage().getContent();
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((1491, 1623), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1491, 1598), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1491, 1558), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3679, 3871), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3679, 3846), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3679, 3813), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3679, 3773), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package cloud.cleo.connectgpt;
import cloud.cleo.connectgpt.lang.LangUtil;
import static cloud.cleo.connectgpt.lang.LangUtil.LanguageIds.*;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.LexV2Event;
import com.amazonaws.services.lambda.runtime.events.LexV2Event.DialogAction;
import com.amazonaws.services.lambda.runtime.events.LexV2Event.Intent;
import com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState;
import com.amazonaws.services.lambda.runtime.events.LexV2Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.service.OpenAiService;
import java.net.SocketTimeoutException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.ZoneId;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.extensions.AutoGeneratedTimestampRecordExtension;
/**
*
* @author sjensen
*/
public class ChatGPTLambda implements RequestHandler<LexV2Event, LexV2Response> {
// Initialize the Log4j logger.
Logger log = LogManager.getLogger(ChatGPTLambda.class);
final static ObjectMapper mapper = new ObjectMapper();
final static TableSchema<ChatGPTSessionState> schema = TableSchema.fromBean(ChatGPTSessionState.class);
final static DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.extensions(AutoGeneratedTimestampRecordExtension.create()).build();
final static DynamoDbTable<ChatGPTSessionState> sessionState = enhancedClient.table(System.getenv("SESSION_TABLE_NAME"), schema);
final static OpenAiService open_ai_service = new OpenAiService(System.getenv("OPENAI_API_KEY"), Duration.ofSeconds(20));
final static String OPENAI_MODEL = System.getenv("OPENAI_MODEL");
@Override
public LexV2Response handleRequest(LexV2Event lexRequest, Context cntxt) {
try {
log.debug(mapper.valueToTree(lexRequest).toString());
final var intentName = lexRequest.getSessionState().getIntent().getName();
log.debug("Intent: " + intentName);
return processGPT(lexRequest);
} catch (Exception e) {
log.error(e);
// Unhandled Exception
return buildResponse(lexRequest, new LangUtil(lexRequest.getBot().getLocaleId()).getString(UNHANDLED_EXCEPTION));
}
}
private LexV2Response processGPT(LexV2Event lexRequest) {
final var input = lexRequest.getInputTranscript();
final var localId = lexRequest.getBot().getLocaleId();
final var lang = new LangUtil(localId);
log.debug("Java Locale is " + lang.getLocale());
if (input == null || input.isBlank()) {
log.debug("Got blank input, so just silent or nothing");
final var attrs = lexRequest.getSessionState().getSessionAttributes();
var count = Integer.valueOf(attrs.getOrDefault("blankCounter", "0"));
count++;
if (count > 2) {
log.debug("Two blank responses, sending to Quit Intent");
// Hang up on caller after 2 silience requests
return buildQuitResponse(lexRequest);
} else {
attrs.put("blankCounter", count.toString());
// If we get slience (timeout without speech), then we get empty string on the transcript
return buildResponse(lexRequest, lang.getString(BLANK_RESPONSE));
}
}
// When testing in lex console input will be text, so use session ID, for speech we shoud have a phone via Connect
final var user_id = "Text".equalsIgnoreCase(lexRequest.getInputMode()) ? lexRequest.getSessionId()
: lexRequest.getSessionState().getSessionAttributes().get("CustomerNumber");
// Key to record in Dynamo
final var key = Key.builder().partitionValue(user_id).sortValue(LocalDate.now(ZoneId.of("America/Chicago")).toString()).build();
// load session state if it exists
log.debug("Start Retreiving Session State");
var session = sessionState.getItem(key);
log.debug("End Retreiving Session State");
if (session == null) {
session = new ChatGPTSessionState(user_id);
}
// Since we can call and change language during session, always specifiy how we want responses
session.addSystemMessage(lang.getString(CHATGPT_RESPONSE_LANGUAGE));
// add this request to the session
session.addUserMessage(input);
String botResponse;
try {
ChatCompletionRequest request = ChatCompletionRequest.builder()
.messages(session.getChatMessages())
.model(OPENAI_MODEL)
.maxTokens(500)
.temperature(0.2) // More focused
.n(1) // Only return 1 completion
.build();
log.debug("Start API Call to ChatGPT");
final var completion = open_ai_service.createChatCompletion(request);
log.debug("End API Call to ChatGPT");
log.debug(completion);
botResponse = completion.getChoices().get(0).getMessage().getContent();
// Add response to session
session.addAssistantMessage(botResponse);
// Since we have a valid response, add message asking if there is anything else
if ( ! "Text".equalsIgnoreCase(lexRequest.getInputMode()) ) {
// Only add if not text (added to voice response)
botResponse = botResponse + lang.getString(ANYTHING_ELSE);
}
// Save the session to dynamo
log.debug("Start Saving Session State");
session.incrementCounter();
sessionState.putItem(session);
log.debug("End Saving Session State");
} catch (RuntimeException rte) {
if (rte.getCause() != null && rte.getCause() instanceof SocketTimeoutException) {
log.error("Response timed out", rte);
botResponse = lang.getString(OPERATION_TIMED_OUT);
} else {
throw rte;
}
}
return buildResponse(lexRequest, botResponse);
}
/**
* Response that sends you to the Quit intent so the call can be ended
*
* @param lexRequest
* @param response
* @return
*/
private LexV2Response buildQuitResponse(LexV2Event lexRequest) {
// State to return
final var ss = SessionState.builder()
// Retain the current session attributes
.withSessionAttributes(lexRequest.getSessionState().getSessionAttributes())
// Send back Quit Intent
.withIntent(Intent.builder().withName("Quit").withState("ReadyForFulfillment").build())
// Indicate the state is Delegate
.withDialogAction(DialogAction.builder().withType("Delegate").build())
.build();
final var lexV2Res = LexV2Response.builder()
.withSessionState(ss)
.build();
log.debug("Response is " + mapper.valueToTree(lexV2Res));
return lexV2Res;
}
/**
* General Response used to send back a message and Elicit Intent again at LEX
*
* @param lexRequest
* @param response
* @return
*/
private LexV2Response buildResponse(LexV2Event lexRequest, String response) {
// State to return
final var ss = SessionState.builder()
// Retain the current session attributes
.withSessionAttributes(lexRequest.getSessionState().getSessionAttributes())
// Always ElictIntent, so you're back at the LEX Bot looking for more input
.withDialogAction(DialogAction.builder().withType("ElicitIntent").build())
.build();
final var lexV2Res = LexV2Response.builder()
.withSessionState(ss)
// We are using plain text responses
.withMessages(new LexV2Response.Message[]{new LexV2Response.Message("PlainText", response, null)})
.build();
log.debug("Response is " + mapper.valueToTree(lexV2Res));
return lexV2Res;
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((1974, 2086), 'software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient.builder'), ((1974, 2078), 'software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient.builder'), ((4502, 4613), 'software.amazon.awssdk.enhanced.dynamodb.Key.builder'), ((4502, 4605), 'software.amazon.awssdk.enhanced.dynamodb.Key.builder'), ((4502, 4539), 'software.amazon.awssdk.enhanced.dynamodb.Key.builder'), ((4550, 4604), 'java.time.LocalDate.now'), ((5270, 5572), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5270, 5515), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5270, 5473), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5270, 5435), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5270, 5399), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5270, 5358), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((7201, 7679), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState.builder'), ((7201, 7654), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState.builder'), ((7201, 7517), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState.builder'), ((7201, 7372), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState.builder'), ((7442, 7516), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.Intent.builder'), ((7442, 7508), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.Intent.builder'), ((7442, 7475), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.Intent.builder'), ((7602, 7653), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.DialogAction.builder'), ((7602, 7645), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.DialogAction.builder'), ((7711, 7797), 'com.amazonaws.services.lambda.runtime.events.LexV2Response.builder'), ((7711, 7772), 'com.amazonaws.services.lambda.runtime.events.LexV2Response.builder'), ((8199, 8578), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState.builder'), ((8199, 8553), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState.builder'), ((8199, 8370), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState.builder'), ((8497, 8552), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.DialogAction.builder'), ((8497, 8544), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.DialogAction.builder'), ((8610, 8864), 'com.amazonaws.services.lambda.runtime.events.LexV2Response.builder'), ((8610, 8839), 'com.amazonaws.services.lambda.runtime.events.LexV2Response.builder'), ((8610, 8671), 'com.amazonaws.services.lambda.runtime.events.LexV2Response.builder')] |
package run.halo.live2d.chat;
import static org.springdoc.core.fn.builders.apiresponse.Builder.responseBuilder;
import static org.springdoc.core.fn.builders.content.Builder.contentBuilder;
import static org.springdoc.core.fn.builders.requestbody.Builder.requestBodyBuilder;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springdoc.core.fn.builders.schema.Builder;
import org.springdoc.webflux.core.fn.SpringdocRouteBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import run.halo.app.core.extension.endpoint.CustomEndpoint;
import run.halo.app.extension.GroupVersion;
import run.halo.app.plugin.ReactiveSettingFetcher;
@Slf4j
@Component
@AllArgsConstructor
public class AiChatEndpoint implements CustomEndpoint {
private final ReactiveSettingFetcher reactiveSettingFetcher;
private final AiChatService aiChatService;
@Override
public RouterFunction<ServerResponse> endpoint() {
var tag = groupVersion().toString();
return SpringdocRouteBuilder.route()
.POST("/live2d/ai/chat-process", this::chatProcess,
builder -> builder.operationId("chatCompletion")
.description("Chat completion")
.tag(tag)
.requestBody(requestBodyBuilder()
.required(true)
.content(contentBuilder()
.mediaType(MediaType.TEXT_EVENT_STREAM_VALUE)
.schema(Builder.schemaBuilder()
.implementation(ChatRequest.class)
)
))
.response(responseBuilder()
.implementation(ServerSentEvent.class))
)
.build();
}
private Mono<ServerResponse> chatProcess(ServerRequest request) {
return request.bodyToMono(ChatRequest.class)
.map(this::chatCompletion)
.onErrorResume(throwable -> {
if (throwable instanceof IllegalArgumentException) {
return Mono.just(
Flux.just(
ServerSentEvent.builder(
ChatResult.ok(throwable.getMessage())).build()
)
);
}
return Mono.error(throwable);
})
.flatMap(sse -> ServerResponse.ok()
.contentType(MediaType.TEXT_EVENT_STREAM)
.body(sse, ServerSentEvent.class)
);
}
private Flux<ServerSentEvent<ChatResult>> chatCompletion(ChatRequest body) {
return reactiveSettingFetcher.fetch("aichat", AiChatConfig.class)
.map(aiChatConfig -> ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.flatMapMany(authentication -> {
if (!aiChatConfig.aiChatBaseSetting.isAnonymous && !isAuthenticated(
authentication)) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "请先登录");
}
String systemMessage = aiChatConfig.aiChatBaseSetting.systemMessage;
List<ChatMessage> messages = this.buildChatMessage(systemMessage, body);
return aiChatService.streamChatCompletion(messages);
}))
.flatMapMany(Flux::from);
}
private boolean isAuthenticated(Authentication authentication) {
return !isAnonymousUser(authentication.getName()) &&
authentication.isAuthenticated();
}
private boolean isAnonymousUser(String name) {
return "anonymousUser".equals(name);
}
private List<ChatMessage> buildChatMessage(String systemMessage, ChatRequest body) {
ChatMessage chatMessage =
new ChatMessage(ChatMessageRole.SYSTEM.value(), systemMessage);
final List<ChatMessage> messages = new ArrayList<>();
messages.add(chatMessage);
messages.addAll(body.getMessage());
return messages;
}
record AiChatConfig(String isAiChat, AiChatBaseSetting aiChatBaseSetting) {
}
record AiChatBaseSetting(boolean isAnonymous, String systemMessage) {
AiChatBaseSetting {
if (StringUtils.isBlank(systemMessage)) {
throw new IllegalArgumentException("system message must not be null");
}
}
}
@Override
public GroupVersion groupVersion() {
return GroupVersion.parseAPIVersion("api.live2d.halo.run/v1alpha1");
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value"
] | [((1915, 2704), 'org.springdoc.webflux.core.fn.SpringdocRouteBuilder.route'), ((1915, 2683), 'org.springdoc.webflux.core.fn.SpringdocRouteBuilder.route'), ((2410, 2500), 'org.springdoc.core.fn.builders.schema.Builder.schemaBuilder'), ((3087, 3190), 'org.springframework.http.codec.ServerSentEvent.builder'), ((3347, 3474), 'org.springframework.web.reactive.function.server.ServerResponse.ok'), ((3347, 3424), 'org.springframework.web.reactive.function.server.ServerResponse.ok'), ((3686, 4362), 'org.springframework.security.core.context.ReactiveSecurityContextHolder.getContext'), ((3686, 3785), 'org.springframework.security.core.context.ReactiveSecurityContextHolder.getContext'), ((4846, 4876), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value')] |
package vip.testops.qa_design.toolWindow.ui;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.intellij.lang.Language;
import com.intellij.openapi.editor.EditorSettings;
import com.intellij.openapi.editor.actions.IncrementalFindAction;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.ui.EditorTextField;
import com.intellij.ui.EditorTextFieldProvider;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.panels.VerticalLayout;
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread;
import com.intellij.util.containers.ContainerUtil;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import org.intellij.plugins.markdown.settings.MarkdownSettings;
import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanel;
import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanelProvider;
import org.intellij.plugins.markdown.ui.preview.html.MarkdownUtil;
import org.jetbrains.annotations.NotNull;
import vip.testops.qa_design.QaDesignNotifier;
import vip.testops.qa_design.services.QaDesignChatService;
import vip.testops.qa_design.toolWindow.ui.entities.Message;
import vip.testops.qa_design.toolWindow.ui.entities.Sender;
import vip.testops.qa_design.utils.CycledList;
import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.Objects;
import static com.theokanning.openai.service.OpenAiService.defaultObjectMapper;
public class ChatToolWindow {
private final JPanel contentPanel = new JPanel();
private Project project;
private final EditorColorsScheme scheme = EditorColorsManager.getInstance().getSchemeForCurrentUITheme();
private CycledList<ChatMessage> chatMessages = new CycledList<>(7,3);
public ChatToolWindow(ToolWindow toolWindow, Project project) {
this.project = project;
contentPanel.setLayout(new BorderLayout(0, 20));
contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JBScrollPane chatHistoryPanel = createChatHistoryPanel();
contentPanel.add(chatHistoryPanel, BorderLayout.CENTER);
contentPanel.add(createChatInputPanel(chatHistoryPanel), BorderLayout.SOUTH);
chatHistoryPanel.revalidate();
chatHistoryPanel.repaint();
SwingUtilities.invokeLater(() -> {
JScrollBar verticalScrollBar = chatHistoryPanel.getVerticalScrollBar();
verticalScrollBar.setValue(verticalScrollBar.getMaximum());
});
chatMessages.add(new ChatMessage(
ChatMessageRole.SYSTEM.value(),
"If need to answer about test points, please reply them with order list."
));
chatMessages.add(new ChatMessage(
ChatMessageRole.SYSTEM.value(),
"If need to answer about test cases design, put each test case like below, and replace every bracket \"{}\" with real content in single line:\n" +
"```\n" +
"TestCase: {case name}\n" +
"TestCaseDesc: {case description}\n" +
"TestCaseData: {test case data}\n" +
"TestCaseStep: {steps of this test case}\n" +
"TestCaseExpect: {expected result of this test case}\n" +
"```\n" +
"do not use index number after testcase."
));
chatMessages.add(new ChatMessage(
ChatMessageRole.SYSTEM.value(),
"put all the testcases into Markdown code segment, language is qa_design."
));
}
@NotNull
private JBScrollPane createChatHistoryPanel() {
JPanel panel = new JPanel(new VerticalLayout(5));
JBScrollPane chatHistoryPanel = new JBScrollPane(
panel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
);
return chatHistoryPanel;
}
@NotNull
private JPanel createChatInputPanel(JBScrollPane chatHistoryPanel) {
JPanel chatInputPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
EditorTextField inputField = EditorTextFieldProvider
.getInstance()
.getEditorField(
Objects.requireNonNull(Language.findLanguageByID("Markdown")),
this.project, List.of((editorEx) -> {
EditorSettings editorSettings = editorEx.getSettings();
editorSettings.setLineNumbersShown(false);
editorSettings.setLineMarkerAreaShown(false);
editorSettings.setUseSoftWraps(true);
editorSettings.setAnimatedScrolling(true);
editorEx.setBorder(BorderFactory.createLineBorder(scheme.getColor(EditorColors.TEARLINE_COLOR)));
})
);
Dimension preferredSize = inputField.getPreferredSize();
inputField.setPreferredSize(new Dimension(preferredSize.width, 60));
chatInputPanel.add(inputField, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 0;
gbc.fill = GridBagConstraints.NONE;
JButton sendButton = new JButton("Send");
sendButton.addActionListener(e -> {
String text = inputField.getText();
JPanel history = (JPanel)chatHistoryPanel.getViewport().getView();
history.add(createMessagePane(new Message(text, Sender.ME)));
history.revalidate();
history.repaint();
SwingUtilities.invokeLater(() -> {
JScrollBar verticalScrollBar = chatHistoryPanel.getVerticalScrollBar();
verticalScrollBar.setValue(verticalScrollBar.getMaximum());
});
inputField.setText("");
chatMessages.add(new ChatMessage(ChatMessageRole.USER.value(), text));
String currentHtml = "<html><head></head></html>";
MarkdownSettings settings = MarkdownSettings.getInstance(project);
settings.setAutoScrollEnabled(false);
MarkdownHtmlPanelProvider provider = retrievePanelProvider(settings);
MarkdownHtmlPanel htmlPanel = provider.createHtmlPanel(project, project.getProjectFile());
htmlPanel.setHtml(currentHtml, 0);
history.add(htmlPanel.getComponent());
new Thread(() -> handleChatCompletion(htmlPanel, history)).start();
});
chatInputPanel.add(sendButton, gbc);
return chatInputPanel;
}
private EditorTextField createMessagePane(Message message) {
EditorTextField messagePane = EditorTextFieldProvider.getInstance().getEditorField(Objects.requireNonNull(Language.findLanguageByID("Markdown")), this.project, List.of((editorEx) -> {
EditorSettings editorSettings = editorEx.getSettings();
editorSettings.setLineNumbersShown(false);
editorSettings.setLineMarkerAreaShown(false);
editorSettings.setFoldingOutlineShown(false);
editorSettings.setAutoCodeFoldingEnabled(false);
editorSettings.setShowIntentionBulb(false);
editorSettings.setBlinkCaret(false);
editorSettings.setAnimatedScrolling(false);
editorSettings.setUseSoftWraps(true);
editorEx.setViewer(true);
editorEx.setRendererMode(true);
editorEx.setCaretVisible(false);
editorEx.setCaretEnabled(false);
editorEx.putUserData(IncrementalFindAction.SEARCH_DISABLED, Boolean.TRUE);
Color c = message.getSender() == Sender.ME ?
scheme.getColor(EditorColors.DOCUMENTATION_COLOR) :
scheme.getColor(EditorColors.READONLY_BACKGROUND_COLOR);
editorEx.setBackgroundColor(c == null ? scheme.getDefaultBackground() : c);
editorEx.setColorsScheme(scheme);
}));
messagePane.setText(message.getContent());
return messagePane;
}
private @NotNull MarkdownHtmlPanelProvider retrievePanelProvider(@NotNull MarkdownSettings settings) {
final MarkdownHtmlPanelProvider.ProviderInfo providerInfo = settings.getPreviewPanelProviderInfo();
MarkdownHtmlPanelProvider provider = MarkdownHtmlPanelProvider.createFromInfo(providerInfo);
if (provider.isAvailable() != MarkdownHtmlPanelProvider.AvailabilityInfo.AVAILABLE) {
final MarkdownHtmlPanelProvider defaultProvider = MarkdownHtmlPanelProvider.createFromInfo(MarkdownSettings.getDefaultProviderInfo());
System.out.println("MarkdownHtmlPanelProvider is not available: " + providerInfo.getName());
MarkdownSettings.getInstance(project).setPreviewPanelProviderInfo(defaultProvider.getProviderInfo());
provider = Objects.requireNonNull(
ContainerUtil.find(
MarkdownHtmlPanelProvider.getProviders(),
p -> p.isAvailable() == MarkdownHtmlPanelProvider.AvailabilityInfo.AVAILABLE
)
);
}
return provider;
}
@RequiresBackgroundThread
private void handleChatCompletion(MarkdownHtmlPanel htmlPanel, JPanel historyPanel) {
StringBuilder sb = new StringBuilder();
QaDesignChatService service = QaDesignChatService.getInstance();
service.sendMessage(
chatMessages,
message -> {
ChatCompletionChoice choice = message.getChoices().get(0);
String msg = choice.getMessage().getContent();
if (null == msg) {
return;
}
sb.append(msg);
String html = MarkdownUtil.INSTANCE.generateMarkdownHtml(Objects.requireNonNull(project.getWorkspaceFile()), sb.toString(), project);
htmlPanel.setHtml("<html><head></head>" + html + "</html>", 0);
historyPanel.revalidate();
historyPanel.repaint();
},
e -> QaDesignNotifier.notifyError(this.project, e.getMessage())
);
chatMessages.add(new ChatMessage(ChatMessageRole.ASSISTANT.value(), sb.toString()));
}
public JPanel getContentPanel() {
return contentPanel;
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value"
] | [((1949, 2011), 'com.intellij.openapi.editor.colors.EditorColorsManager.getInstance'), ((2888, 2918), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3080, 3110), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3807, 3837), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((6447, 6475), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((7238, 8514), 'com.intellij.ui.EditorTextFieldProvider.getInstance'), ((9277, 9377), 'org.intellij.plugins.markdown.settings.MarkdownSettings.getInstance'), ((10361, 10479), 'org.intellij.plugins.markdown.ui.preview.html.MarkdownUtil.INSTANCE.generateMarkdownHtml'), ((10809, 10842), 'com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value')] |
package br.com.fiap.apichatgpt.controllers;
import br.com.fiap.apichatgpt.models.ChatGPT;
import br.com.fiap.apichatgpt.models.Medico;
import br.com.fiap.apichatgpt.repositories.ChatGPTRepository;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Valid;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.PagedModel;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;
import org.springframework.data.domain.Pageable;
import org.slf4j.Logger;
@RestController
@RequestMapping("/baymax/chatbot")
public class ChatGPTController {
@Autowired
ChatGPTRepository repo;
@Autowired
PagedResourcesAssembler<ChatGPT> assembler;
Logger log = LoggerFactory.getLogger(ChatGPTController.class);
private static final String API_KEY = "chave da API";
@GetMapping
public PagedModel<EntityModel<ChatGPT>> index(@PageableDefault(size = 5) Pageable pageable) {
return assembler.toModel(repo.findAll(pageable));
}
@GetMapping("/{id}")
public EntityModel<ChatGPT> show(@PathVariable Long id) {
log.info("buscar chat com id: " + id);
ChatGPT chatGPT = repo.findById(id).orElseThrow(() ->
new ResponseStatusException(HttpStatus.NOT_FOUND, "Cliente não encontrado"));
return chatGPT.toModel();
}
@PostMapping("/api")
public ResponseEntity<ChatGPT> create(@RequestBody @Valid ChatGPT input) {
OpenAiService service = new OpenAiService(API_KEY);
CompletionRequest request = CompletionRequest.builder()
.model("text-davinci-003")
.prompt(input.getPergunta())
.maxTokens(100)
.build();
String resposta = service.createCompletion(request).getChoices().get(0).getText();
ChatGPT chatGPT = new ChatGPT(input.getPergunta(), resposta);
log.info("Saída do chatbot: " + chatGPT);
repo.save(chatGPT);
return ResponseEntity.status(HttpStatus.CREATED).body(chatGPT);
}
@DeleteMapping("/{id}")
public ResponseEntity<ChatGPT>destroy(@PathVariable Long id) {
log.info("deletar chat com o id: " + id);
ChatGPT chatgpt = repo.findById(id).orElseThrow(() ->
new ResponseStatusException(HttpStatus.NOT_FOUND, "Chat não encontrado"));;
repo.delete(chatgpt);
return ResponseEntity.noContent().build();
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<String> handleValidationExceptions(ConstraintViolationException ex) {
log.error("Erro de validação: ", ex);
return ResponseEntity.badRequest().body(ex.getMessage());
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAllExceptions(Exception ex) {
log.error("Erro não esperado: ", ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Ocorreu um erro inesperado. Tente novamente mais tarde.");
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((2102, 2278), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2102, 2252), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2102, 2219), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2102, 2173), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2544, 2599), 'org.springframework.http.ResponseEntity.status'), ((2964, 2998), 'org.springframework.http.ResponseEntity.noContent'), ((3275, 3324), 'org.springframework.http.ResponseEntity.badRequest'), ((3565, 3684), 'org.springframework.http.ResponseEntity.status')] |
package com.toryz.biligpt.service.impl;
import com.alibaba.fastjson.JSON;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import com.toryz.biligpt.entity.response.GetGptSummaryResponse;
import com.toryz.biligpt.service.SummaryService;
import com.toryz.biligpt.util.BiliSdkUtil;
import com.toryz.biligpt.util.GptSdkUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: ztr.wuning
* @Date: 2023/7/30 20:29
*/
@Slf4j
@Service
public class SummaryServiceImpl implements SummaryService {
@Value("${openAI.token}")
String token;
@Autowired
GptSdkUtil gptSdkUtil;
@Override
public String getGptSummary(String bvid) {
log.info("bvid: {}",bvid);
GetGptSummaryResponse getGptSummaryResponse = new GetGptSummaryResponse();
List<String> cidList = BiliSdkUtil.getPartCidList(bvid);
for(String s : cidList){
log.info("cidList: {}",s);
}
StringBuilder AllContent = new StringBuilder();
for(String cid: cidList){
List<String> subtitleUrlList = BiliSdkUtil.getSubtitleUrlList(bvid, cid);
for(String subtitleUrl: subtitleUrlList){
log.info("subtitleUrl: {}",subtitleUrl);
}
if(subtitleUrlList.size() == 0){
getGptSummaryResponse.setMessage("暂不支持该视频的总结功能捏,感谢支持,小乌龟正在升级中...");
getGptSummaryResponse.setCode(201);
return JSON.toJSONString(getGptSummaryResponse);
}
for(String subtitleUrl: subtitleUrlList){
List<String> contentList = BiliSdkUtil.parseSubtitle(subtitleUrl);
for(String content: contentList){
log.info("content: {}",content);
}
for(String content: contentList){
AllContent.append(content);
}
}
}
String s = null;
try{
s = gptSdkUtil.chatForSum(AllContent);
}catch (Exception e){
log.info("gpt连接超时...");
getGptSummaryResponse.setMessage("gpt连接超时...");
getGptSummaryResponse.setCode(400);
}
if(s != null){
getGptSummaryResponse.setMessage(s);
getGptSummaryResponse.setCode(200);
}
return JSON.toJSONString(getGptSummaryResponse);
}
@Override
public String getGptModel(){
System.out.println(token);
OpenAiService service = new OpenAiService(token);
System.out.println(service.listModels());
return service.listModels().toString();
}
@Override
public String getGptSummary() {
// String s = GptSdkUtil.chatForSum("给我背一遍《静夜思》");
OpenAiService service = new OpenAiService(token, Duration.ofSeconds(90));
List<ChatMessage> messages = new ArrayList<>();
ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(),"随便背一首李白的诗吧");
messages.add(userMessage);
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
.messages(messages)
.maxTokens(500)
.model("gpt-3.5-turbo-16k-0613")
.build();
//CompletionResult completion = service.createCompletion(completionRequest);
ChatMessage responseMessage = service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage();
GetGptSummaryResponse getGptSummaryResponse = new GetGptSummaryResponse();
getGptSummaryResponse.setMessage(responseMessage.getContent());
getGptSummaryResponse.setCode(200);
return JSON.toJSONString(getGptSummaryResponse);
}
/* 初始化布隆过滤器
@PostConstruct
public void initBloomFilter(){
// 把所有的 BVid 放进布隆过滤器中
List<String> ids = getAllBVIds();
ids.parallelStream().forEach(item->{
// 添加BV号
bloomFilter.add(ConvertCacheKeyUtil.getFormatString(CacheKeyConstant.CACHE_KEY_REVERSE_BY_BV_ID,item));
});
log.info("***********布隆过滤器初始化数据成功 当前BV数量:{} ***********",bloomFilter.count());
}*/
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value",
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((3413, 3441), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((3574, 3747), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3574, 3722), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3574, 3673), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3574, 3641), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package org.example.chatgpt.service;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.theokanning.openai.OpenAiApi;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import javabean.LogForDB;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import retrofit2.Retrofit;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.theokanning.openai.service.OpenAiService.*;
/**
* 会话服务
*
* @author lijiatao
* 时间: 2023/12/6
*/
@Service
public class ChatService {
private static final Logger LOG = LoggerFactory.getLogger(ChatService.class);
//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
// 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
// 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
String token = "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";
String proxyHost = "127.0.0.1";
int proxyPort = 7890;
/**
* 流式对话
* 注:必须使用异步处理(否则发送消息不会及时返回前端)
*
* @param prompt 输入消息
* @param sseEmitter SSE对象
*/
@Async
public void streamChatCompletion(String prompt, SseEmitter sseEmitter) {
LogForDB logForDB = new LogForDB();
LOG.info("发送消息:" + prompt);
final List<ChatMessage> messages = new ArrayList<>();
final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), prompt);
messages.add(systemMessage);
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
.builder()
.model("gpt-3.5-turbo")
.messages(messages)
.n(1)
.maxTokens(2048)
.logitBias(new HashMap<>())
.build();
//流式对话(逐Token返回)
StringBuilder receiveMsgBuilder = new StringBuilder();
OpenAiService service = buildOpenAiService(token, proxyHost, proxyPort);
service.streamChatCompletion(chatCompletionRequest)
//正常结束
// .doOnComplete(() -> {
// LOG.info("连接结束");
//
// //发送连接关闭事件,让客户端主动断开连接避免重连
// sendStopEvent(sseEmitter);
//
// //完成请求处理
// sseEmitter.complete();
// })
//异常结束
.doOnError(throwable -> {
LOG.error("连接异常", throwable);
//发送连接关闭事件,让客户端主动断开连接避免重连
sendStopEvent(sseEmitter);
//完成请求处理携带异常
sseEmitter.completeWithError(throwable);
})
//收到消息后转发到浏览器
.blockingForEach(x -> {
ChatCompletionChoice choice = x.getChoices().get(0);
LOG.debug("收到消息:" + choice);
if (StrUtil.isEmpty(choice.getFinishReason())) {
//未结束时才可以发送消息(结束后,先调用doOnComplete然后还会收到一条结束消息,因连接关闭导致发送消息失败:ResponseBodyEmitter has already completed)
sseEmitter.send(choice.getMessage());
} else {
LOG.info("连接结束");
//发送连接关闭事件,让客户端主动断开连接避免重连
sendStopEvent(sseEmitter);
//完成请求处理
sseEmitter.complete();
}
String content = choice.getMessage().getContent();
content = content == null ? StrUtil.EMPTY : content;
receiveMsgBuilder.append(content);
});
LOG.info("收到的完整消息:" + receiveMsgBuilder);
logForDB.log2DB("Chat", prompt, receiveMsgBuilder.toString());
}
/**
* 发送连接关闭事件,让客户端主动断开连接避免重连
*
*/
static void sendStopEvent(SseEmitter sseEmitter) throws IOException {
sseEmitter.send(SseEmitter.event().name("stop").data(""));
}
/**
* 构建OpenAiService
*
* @param token API_KEY
* @param proxyHost 代理域名
* @param proxyPort 代理端口号
* @return OpenAiService
*/
private OpenAiService buildOpenAiService(String token, String proxyHost, int proxyPort) {
//构建HTTP代理
Proxy proxy = null;
if (StrUtil.isNotBlank(proxyHost)) {
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
}
//构建HTTP客户端
OkHttpClient client = defaultClient(token, Duration.of(60, ChronoUnit.SECONDS))
.newBuilder()
.proxy(proxy)
.build();
ObjectMapper mapper = defaultObjectMapper();
Retrofit retrofit = defaultRetrofit(client, mapper);
OpenAiApi api = retrofit.create(OpenAiApi.class);
return new OpenAiService(api, client.dispatcher().executorService());
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value"
] | [((2144, 2174), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((5081, 5121), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((5081, 5112), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event')] |
package br.com.p3d50.chatgtp.service;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
@Service
public class ChatGPTService {
public ResponseEntity<String> getPrompt(String prompt) {
final String API_KEY = "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";
OpenAiService service = new OpenAiService(API_KEY);
CompletionRequest request = CompletionRequest.builder()
.model("text-davinci-003")
.prompt(prompt)
.maxTokens(375)
.build();
CompletionResult response = service.createCompletion(request);
return ResponseEntity.ok(response.getChoices().get(0).getText());
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((565, 676), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((565, 663), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((565, 643), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((565, 623), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package com.duzy.service.impl;
import cn.hutool.json.JSONUtil;
import com.duzy.service.ChatGPTService;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.model.Model;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author zhiyuandu
* @since 2023/2/4 19:52
* @description
*/
@Service
@Slf4j
public class ChatGPTServiceImpl implements ChatGPTService {
@Value("${chat-token}")
String token;
/**
* 获取模型
* @return
*/
@Override
public List<Model> models() {
return null;
}
@Override
public String qa(String question) {
OpenAiService service = new OpenAiService(token);
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt(question)
.model("ada")
.echo(true)
.build();
List<CompletionChoice> choices = service.createCompletion(completionRequest).getChoices();
log.info("收到:{},回答:{},", question, choices);
return JSONUtil.toJsonStr(choices);
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((955, 1099), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((955, 1074), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((955, 1046), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((955, 1016), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package br.com.alura.ecomart.chatbot.infra.openai;
import br.com.alura.ecomart.chatbot.domain.DadosCalculoFrete;
import br.com.alura.ecomart.chatbot.domain.service.CalculadorDeFrete;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.theokanning.openai.completion.chat.ChatFunction;
import com.theokanning.openai.completion.chat.ChatFunctionCall;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.messages.Message;
import com.theokanning.openai.messages.MessageRequest;
import com.theokanning.openai.runs.Run;
import com.theokanning.openai.runs.RunCreateRequest;
import com.theokanning.openai.runs.SubmitToolOutputRequestItem;
import com.theokanning.openai.runs.SubmitToolOutputsRequest;
import com.theokanning.openai.service.FunctionExecutor;
import com.theokanning.openai.service.OpenAiService;
import com.theokanning.openai.threads.ThreadRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class OpenAIClient {
private final String apiKey;
private final String assistantId;
private String threadId;
private final OpenAiService service;
private final CalculadorDeFrete calculadorDeFrete;
public OpenAIClient(@Value("${app.openai.api.key}") String apiKey, @Value("${app.openai.assistant.id}") String assistantId, CalculadorDeFrete calculadorDeFrete) {
this.apiKey = apiKey;
this.service = new OpenAiService(apiKey, Duration.ofSeconds(60));
this.assistantId = assistantId;
this.calculadorDeFrete = calculadorDeFrete;
}
public String enviarRequisicaoChatCompletion(DadosRequisicaoChatCompletion dados) {
var messageRequest = MessageRequest
.builder()
.role(ChatMessageRole.USER.value())
.content(dados.promptUsuario())
.build();
if (this.threadId == null) {
var threadRequest = ThreadRequest
.builder()
.messages(Arrays.asList(messageRequest))
.build();
var thread = service.createThread(threadRequest);
this.threadId = thread.getId();
} else {
service.createMessage(this.threadId, messageRequest);
}
var runRequest = RunCreateRequest
.builder()
.assistantId(assistantId)
.build();
var run = service.createRun(threadId, runRequest);
var concluido = false;
var precisaChamarFuncao = false;
try {
while (!concluido && !precisaChamarFuncao) {
Thread.sleep(1000 * 10);
run = service.retrieveRun(threadId, run.getId());
concluido = run.getStatus().equalsIgnoreCase("completed");
precisaChamarFuncao = run.getRequiredAction() != null;
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (precisaChamarFuncao) {
var precoDoFrete = chamarFuncao(run);
var submitRequest = SubmitToolOutputsRequest
.builder()
.toolOutputs(Arrays.asList(
new SubmitToolOutputRequestItem(
run
.getRequiredAction()
.getSubmitToolOutputs()
.getToolCalls()
.get(0)
.getId(),
precoDoFrete)
))
.build();
service.submitToolOutputs(threadId, run.getId(), submitRequest);
try {
while (!concluido) {
Thread.sleep(1000 * 10);
run = service.retrieveRun(threadId, run.getId());
concluido = run.getStatus().equalsIgnoreCase("completed");
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
var mensagens = service.listMessages(threadId);
return mensagens
.getData()
.stream()
.sorted(Comparator.comparingInt(Message::getCreatedAt).reversed())
.findFirst().get().getContent().get(0).getText().getValue()
.replaceAll("\\\u3010.*?\\\u3011", "");
}
private String chamarFuncao(Run run) {
try {
var funcao = run.getRequiredAction().getSubmitToolOutputs().getToolCalls().get(0).getFunction();
var funcaoCalcularFrete = ChatFunction.builder()
.name("calcularFrete")
.executor(DadosCalculoFrete.class, d -> calculadorDeFrete.calcular(d))
.build();
var executorDeFuncoes = new FunctionExecutor(Arrays.asList(funcaoCalcularFrete));
var functionCall = new ChatFunctionCall(funcao.getName(), new ObjectMapper().readTree(funcao.getArguments()));
return executorDeFuncoes.execute(functionCall).toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public List<String> carregarHistoricoDeMensagens() {
var mensagens = new ArrayList<String>();
if (this.threadId != null) {
mensagens.addAll(
service
.listMessages(this.threadId)
.getData()
.stream()
.sorted(Comparator.comparingInt(Message::getCreatedAt))
.map(m -> m.getContent().get(0).getText().getValue())
.collect(Collectors.toList())
);
}
return mensagens;
}
public void apagarThread() {
if (this.threadId != null) {
service.deleteThread(this.threadId);
this.threadId = null;
}
}
}
| [
"com.theokanning.openai.completion.chat.ChatFunction.builder",
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value"
] | [((1972, 2000), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((4533, 4590), 'java.util.Comparator.comparingInt'), ((4935, 5120), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((4935, 5091), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((4935, 5000), 'com.theokanning.openai.completion.chat.ChatFunction.builder')] |
package com.miraclekang.chatgpt.assistant.port.adapter.service;
import com.miraclekang.chatgpt.assistant.domain.model.chat.ChatService;
import com.miraclekang.chatgpt.assistant.domain.model.chat.Message;
import com.miraclekang.chatgpt.assistant.domain.model.chat.MessageConfig;
import com.miraclekang.chatgpt.assistant.port.adapter.thirdparty.openai.OpenAIClient;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import java.util.List;
import java.util.Objects;
@Slf4j
@Service
public class OpenAIServiceImpl implements ChatService {
private final OpenAIClient openaiClient;
public OpenAIServiceImpl(@Value("${third-party.openai.token}") String openaiToken,
@Value("${third-party.openai.proxy:none}") String openaiProxy) {
this.openaiClient = new OpenAIClient(openaiToken, openaiProxy);
}
@Override
public Message sendMessages(List<Message> messages, MessageConfig config) {
return prvSendMessages(messages, config, false)
.blockFirst();
}
@Override
public Flux<Message> fluxSendMessages(List<Message> messages, MessageConfig config) {
return prvSendMessages(messages, config, true);
}
private Flux<Message> prvSendMessages(List<Message> messages, MessageConfig config, boolean stream) {
return openaiClient.chatCompletion(ChatCompletionRequest.builder()
.model(config.getModel().getId())
.temperature(config.getTemperature())
.topP(config.getTopP())
.maxTokens(config.getMaxTokens())
.messages(messages.stream().map(Message::toChatMessage).toList())
.n(config.getChoices())
.stream(stream)
.stop(config.getStop() == null || config.getStop().isEmpty()
? null : config.getStop())
.logitBias(config.getLogitBias() == null || config.getLogitBias().isEmpty()
? null : config.getLogitBias())
.user(config.getEndUser())
.build())
.filter(chatMessage -> !stream || Objects.nonNull(chatMessage)
&& (chatMessage.getRole() != null || chatMessage.getContent() != null))
.mapNotNull(Message::of);
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((1545, 2372), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 2339), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 2288), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 2124), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 1980), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 1940), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 1892), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 1802), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 1744), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 1696), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 1634), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package vwvm.gptweb;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
/**
* <h3>store</h3>
* <p>gpt测试</p>
*
* @author : BlackBox
* @date : 2023-05-13 19:37
**/
public class GptTest {
public static void main(String[] args) {
OpenAiService service = new OpenAiService("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");
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt("Somebody once told me the world is gonna roll me")
.model("ada")
.echo(true)
.build();
service.createCompletion(completionRequest).getChoices().forEach(System.out::println);
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((456, 642), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((456, 617), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((456, 589), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((456, 559), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package com.yxy.nova.service.impl;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.service.OpenAiService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class MyOpenAiServiceImpl implements MyOpenAiService {
@Value("${openai.api-keys}")
private String apiKey;
@Override
public List<String> chat(String content) {
// 消息列表
List<ChatMessage> list = new ArrayList<>();
// 定义一个用户身份,content是用户写的内容
ChatMessage userMessage = new ChatMessage();
userMessage.setRole("user");
userMessage.setContent(content);
list.add(userMessage);
OpenAiService service = new OpenAiService(apiKey);
ChatCompletionRequest request = ChatCompletionRequest.builder()
.messages(list)
.model("gpt-3.5-turbo")
.build();
List<ChatCompletionChoice> choices = service.createChatCompletion(request).getChoices();
List<String> response = new ArrayList<>();
choices.forEach(item -> {
response.add(item.getMessage().getContent());
});
return response;
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((1042, 1170), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1042, 1145), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1042, 1105), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package br.com.alura.screenmatch.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.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import java.util.ArrayList;
import java.util.List;
public class ConsultaChatGPT {
public static String obterTraducao(String texto) {
OpenAiService service = new OpenAiService(System.getenv("OPENAI_APIKEY"));
CompletionRequest requisicao = CompletionRequest.builder()
.model("gpt-3.5-turbo-instruct")
.prompt("traduza para o português o texto: " + texto)
.maxTokens(1000)
.temperature(0.7)
.build();
var resposta = service.createCompletion(requisicao);
return resposta.getChoices().get(0).getText();
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((621, 880), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((621, 851), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((621, 813), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((621, 776), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((621, 701), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package com.github.j0rdanit0.chatgptdiscordbot.service;
import com.github.j0rdanit0.chatgptdiscordbot.repository.ConversationRepository;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import discord4j.common.util.Snowflake;
import discord4j.core.GatewayDiscordClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
@RequiredArgsConstructor
public class ConversationService
{
private final OpenAiService openAiService;
private final GatewayDiscordClient gatewayDiscordClient;
private final ConversationRepository conversationRepository;
@Value( "${bot.name}" )
private String botName;
@Value( "${open-ai.chat-model}" )
private String openAiChatModel;
public String startConversation( Snowflake threadId, Snowflake userId, String prompt, String botPersonality )
{
log.debug( "Sending a prompt in thread {} from user {}: {}", threadId, userId, prompt );
ChatCompletionRequest request = getFirstChatCompletionRequest( threadId, prompt, botPersonality );
return requestChatCompletion( request, threadId );
}
public String continueConversation( Snowflake threadId, Snowflake userId, String prompt )
{
log.debug( "Continuing conversation in thread {} from user {}: {}", threadId, userId, prompt );
ChatCompletionRequest request = getSubsequentChatCompletionRequest( threadId, prompt );
return requestChatCompletion( request, threadId );
}
private String requestChatCompletion( ChatCompletionRequest request, Snowflake threadId )
{
ChatMessage responseMessage = openAiService.createChatCompletion( request ).getChoices().getFirst().getMessage();
log.debug( "Got response from Open AI:\n{}", responseMessage.getContent() );
conversationRepository.appendConversationHistory( threadId, responseMessage );
return responseMessage.getContent();
}
public String getNewThreadTitle( Snowflake threadId )
{
log.debug( "Getting new thread title" );
ChatCompletionRequest request = getTitleChatCompletionRequest( threadId );
return openAiService.createChatCompletion( request ).getChoices().getFirst().getMessage().getContent();
}
private ChatCompletionRequest getFirstChatCompletionRequest( Snowflake threadId, String prompt, String botPersonality )
{
List<ChatMessage> conversationHistory = conversationRepository.getConversationHistory( threadId );
if ( conversationHistory.isEmpty() )
{
ChatMessage initialMessage = new ChatMessage(
ChatMessageRole.SYSTEM.value(),
( "You are a Discord bot whose personality is \"%s\". " +
"Users may refer to you like this: <@%s> or this: \"%s\". " +
"Use Discord's emojis or markdown syntax to style your answers. " +
"Use no more than 2000 characters. " +
"Answer at a high school level unless requested otherwise. " +
"Use brief answers unless requested otherwise. "
).formatted( botPersonality, gatewayDiscordClient.getSelfId().asString(), botName ) );
conversationRepository.appendConversationHistory( threadId, initialMessage );
}
return getSubsequentChatCompletionRequest( threadId, prompt );
}
private ChatCompletionRequest getSubsequentChatCompletionRequest( Snowflake threadId, String prompt )
{
ChatMessage promptMessage = new ChatMessage( ChatMessageRole.USER.value(), prompt );
List<ChatMessage> conversationHistory = conversationRepository.appendConversationHistory( threadId, promptMessage );
return ChatCompletionRequest
.builder()
.model( openAiChatModel )
.messages( conversationHistory )
.build();
}
private ChatCompletionRequest getTitleChatCompletionRequest( Snowflake threadId )
{
ChatMessage promptMessage = new ChatMessage(
ChatMessageRole.USER.value(),
"Give a summary of our conversation so far in 6 words or fewer. " +
"Optionally, you may include a Discord-supported emoji unicode at the beginning if one exists that represents the key point of the conversation. " );
List<ChatMessage> conversationHistory = new ArrayList<>( conversationRepository.getConversationHistory( threadId ) );
conversationHistory.add( promptMessage );
return ChatCompletionRequest
.builder()
.model( openAiChatModel )
.messages( conversationHistory )
.build();
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value"
] | [((2964, 2994), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3874, 3902), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((4359, 4387), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')] |
package jp.mochisuke.lmmchat.embedding;
import com.theokanning.openai.embedding.EmbeddingRequest;
import com.theokanning.openai.service.OpenAiService;
import jp.mochisuke.lmmchat.LMMChatConfig;
import java.util.List;
public class OpenAIEmbedder implements IEmbedderBase {
OpenAiService service;
public OpenAIEmbedder(){
service = new OpenAiService(LMMChatConfig.getApiKey());
}
@Override
public List<List<Double>> calculateEmbedding(List<String> text) {
EmbeddingRequest request = EmbeddingRequest.builder()
.model("text-embedding-ada-002")
.input(text)
.build();
var result= service.createEmbeddings(request);
if(result.getData().size() == 0){
return null;
}
var r= result.getData().stream().map(x->x.getEmbedding()).toList();
return r;
}
}
| [
"com.theokanning.openai.embedding.EmbeddingRequest.builder"
] | [((520, 649), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((520, 624), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((520, 595), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')] |
package com.api.chatgpt;
import com.theokanning.openai.edit.EditRequest;
import com.theokanning.openai.service.OpenAiService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ChatGptApplication {
public static void main(String[] args) {
SpringApplication.run(ChatGptApplication.class, args);
var service = new OpenAiService("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");
var request = EditRequest.builder()
.model("text-davinci-edit-001")
.input("i Jack, I like programn in java, how abt you")
.instruction("Fix the grammar and spelling mistakes")
.build();
service.createEdit(request).getChoices().forEach(System.out::println);
}
}
| [
"com.theokanning.openai.edit.EditRequest.builder"
] | [((534, 769), 'com.theokanning.openai.edit.EditRequest.builder'), ((534, 744), 'com.theokanning.openai.edit.EditRequest.builder'), ((534, 674), 'com.theokanning.openai.edit.EditRequest.builder'), ((534, 603), 'com.theokanning.openai.edit.EditRequest.builder')] |
package com.hqy.cloud.chatgpt.config;
import cn.hutool.core.util.StrUtil;
import com.hqy.cloud.chatgpt.config.interceptor.AuthenticationInterceptor;
import com.hqy.cloud.chatgpt.config.interceptor.ProxyAuthenticator;
import com.hqy.cloud.chatgpt.core.UnofficialApi;
import com.hqy.cloud.chatgpt.service.OpenAiChatgptService;
import com.theokanning.openai.OpenAiApi;
import com.theokanning.openai.service.OpenAiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;
import static com.hqy.cloud.chatgpt.common.lang.Constants.DEFAULT_UNOFFICIAL_PROXY_URL;
/**
* OpenAiChatGptAutoConfiguration.
* @author qiyuan.hong
* @version 1.0
* @date 2023/7/27 13:25
*/
@Slf4j
@Configuration
@RequiredArgsConstructor
public class OpenAiChatGptAutoConfiguration {
private final ChatGptConfigurationProperties properties;
@ConditionalOnMissingBean
@Bean(name = "apiOkHttpClient")
public OkHttpClient apiOkHttpClient() {
OkHttpClient.Builder builder = getBuilder();
builder.addInterceptor(new AuthenticationInterceptor(properties.getApiKey()));
//设置代理
settingProxy(builder);
return builder.build();
}
@ConditionalOnMissingBean
@Bean(name = "unofficialProxyOkHttpClient")
public OkHttpClient unofficialProxyOkHttpClient() {
OkHttpClient.Builder builder = getBuilder();
//设置代理
settingProxy(builder);
return builder.build();
}
@Bean
@ConditionalOnMissingBean
public OpenAiService openAiService(OkHttpClient apiOkHttpClient) {
Retrofit retrofit = OpenAiService.defaultRetrofit(apiOkHttpClient, OpenAiService.defaultObjectMapper()).newBuilder()
.baseUrl(properties.getApiBaseUrl()).build();
return new OpenAiService(retrofit.create(OpenAiApi.class), apiOkHttpClient.dispatcher().executorService());
}
/*@Bean
public OpenAiChatgptService openAiChatgptService(OpenAiService openAiService) {
return new OpenAiChatgptServiceImpl(openAiService, properties);
}*/
@Bean
@ConditionalOnMissingBean
public UnofficialApi unofficialApi(OkHttpClient unofficialProxyOkHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(DEFAULT_UNOFFICIAL_PROXY_URL + StrUtil.SLASH)
.client(unofficialProxyOkHttpClient)
.addConverterFactory(JacksonConverterFactory.create(OpenAiService.defaultObjectMapper()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return retrofit.create(UnofficialApi.class);
}
@NotNull
private OkHttpClient.Builder getBuilder() {
ConnectionPool connectionPool = new ConnectionPool(Runtime.getRuntime().availableProcessors(), 1, TimeUnit.MINUTES);
return new OkHttpClient.Builder()
.connectionPool(connectionPool)
.readTimeout(properties.getApiRequestTimeout(), TimeUnit.MILLISECONDS);
}
private void settingProxy(OkHttpClient.Builder builder) {
Proxy proxy = null;
// HTTP代理
ChatGptConfigurationProperties.HttpProxy httpProxy = properties.getHttpProxy();
if (httpProxy != null && httpProxy.isAvailable()) {
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxy.getHost(), httpProxy.getPort()));
}
// SOCKS代理
ChatGptConfigurationProperties.SocksProxy socksProxy = properties.getSocksProxy();
if (socksProxy != null && socksProxy.isAvailable()) {
proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(socksProxy.getHost(), socksProxy.getPort()));
if (!StringUtils.isAllBlank(socksProxy.getPassword(), socksProxy.getUsername())) {
Authenticator.setDefault(new ProxyAuthenticator(socksProxy.getUsername(), socksProxy.getPassword()));
}
}
if (proxy != null) {
builder.proxy(proxy);
log.info("OkHttpClient using proxy: {}.", proxy);
}
}
}
| [
"com.theokanning.openai.service.OpenAiService.defaultRetrofit"
] | [((2226, 2383), 'com.theokanning.openai.service.OpenAiService.defaultRetrofit'), ((2226, 2375), 'com.theokanning.openai.service.OpenAiService.defaultRetrofit'), ((2226, 2322), 'com.theokanning.openai.service.OpenAiService.defaultRetrofit')] |
package com.gltech.myai.service;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.time.Duration;
@Service
public class OpenAiChatService {
private OpenAiService openAiService;
@Value("${openai.api.key}")
private String apiKey;
private String internalContext;
@PostConstruct
public void init() {
this.openAiService = new OpenAiService(apiKey, Duration.ofSeconds(30));
this.internalContext = "";
}
public String sendChatMessage(String prompt) {
internalContext += prompt + "\n";
System.out.println("Context: " + internalContext);
CompletionRequest completionRequest = CompletionRequest.builder()
.model("text-davinci-003")
.prompt(internalContext)
.maxTokens(150)
.build();
String responseText = openAiService.createCompletion(completionRequest).getChoices().get(0).getText();
System.out.println("OpenAI response: " + responseText);
return responseText;
}
public void shutdownOpenAiService() {
openAiService.shutdownExecutor();
}
public void resetInternalContext() {
internalContext = "";
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((867, 1019), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((867, 998), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((867, 970), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((867, 933), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
/**
* Copyright 2021 Rochester Institute of Technology (RIT). Developed with
* government support under contract 70RCSA22C00000008 awarded by the United
* States Department of Homeland Security for Cybersecurity and Infrastructure Security Agency.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the “Software”), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.rit.se.nvip.characterizer.cwe;
import com.theokanning.openai.OpenAiHttpException;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import edu.rit.se.nvip.db.model.CompositeVulnerability;
import edu.rit.se.nvip.reconciler.openai.OpenAIRequestHandler;
import edu.rit.se.nvip.reconciler.openai.RequestorIdentity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class ChatGPTProcessor {
private final Logger logger = LogManager.getLogger(getClass().getSimpleName());
private OpenAIRequestHandler requestHandler;
private static final String MODEL = "gpt-3.5-turbo";
private static final double TEMP = 0.0;
private static final String SYS_MESSAGE = String.format("You will be presented with several CWE IDs and their corresponding names followed by a CVE description." +
" Your job is to provide a list, from the CWE IDs given to you, of CWE IDs that have a direct correlation to the CVE Description, based on the CWE ID's corresponding name" +
" if you believe that none of the CWEs have a direct correlation with the provided CVE description respond with \"NONE\" otherwise send " +
"ONLY a comma separated list of CWE Ids that match. If you ever send a CWE's name you have failed your job.");
private static final String SYS_ROLE = "system";
private static final String USER_ROLE = "user";
private Set<String> processedIds = new HashSet<>();
private Set<CWETree> out = new HashSet<>();
private Set<CWETree> matches = new HashSet<>();
private Set<Integer> matchedIds = new HashSet<>();
private int tokenCount = 0;
public ChatGPTProcessor() {
requestHandler = OpenAIRequestHandler.getInstance();
}
public String callModel(String arg) {
try {
ChatCompletionRequest request = formRequest(arg);
Future<ChatCompletionResult> futureRes = requestHandler.createChatCompletion(request, RequestorIdentity.FILTER);
ChatCompletionResult res = futureRes.get();
return res.getChoices().get(0).getMessage().getContent();// Return the obtained result
} catch (OpenAiHttpException | InterruptedException | ExecutionException ex) {
logger.error(ex);
return null;
}
}
private ChatCompletionRequest formRequest(String description) {
List<ChatMessage> messages = formMessages(description);
return ChatCompletionRequest.builder().model(MODEL).temperature(TEMP).n(1).messages(messages).maxTokens(1000).build();
}
private List<ChatMessage> formMessages(String description) {
List<ChatMessage> messages = new ArrayList<>();
messages.add(new ChatMessage(SYS_ROLE, SYS_MESSAGE));
messages.add(new ChatMessage(USER_ROLE, description));
return messages;
}
private Set<String> askChatGPT(Set<CWETree> candidates, CompositeVulnerability vuln){
StringBuilder cwes = new StringBuilder(); //String that will be sent to chat gpt
int count = 1; //count so we can ensure only 5 vulns get sent at a time (attempts to not overwhelm chatgpt)
Set<String> out = new HashSet<>(); //the output set
for (CWETree tree : candidates) {
cwes.append(tree.getRoot().getId()).append(": ").append(tree.getRoot().getName()).append("\n"); //append this string in the form{ 123: Cwe Name, 456: Cwe Name2, ...}
if (count % 5 == 0) { //when 5 vulns are added to the cwe string
String chatMessage = cwes + " \nCVE Description: \n" + vuln.getDescription(); //create the message to send to chat gpt
logger.info(chatMessage);
String msg = callModel(chatMessage); //call chatgpt
out.addAll(getIdsFromResponse(msg)); //add a set of ids from chat gpt to the output set
cwes = new StringBuilder(); //clear out previous cwes
}
count++;
}
if (cwes.length() > 0){ //case for if there are 4-1 vulns left... AKA cwes.length is only zero if there are no CWEs left
String chatMessage = cwes + " CVE Description: " + vuln.getDescription(); //create message to send to chat gpt
logger.info(chatMessage);
String finalRun = callModel(chatMessage); //send it
out.addAll(getIdsFromResponse(finalRun)); //add the response to the list of outputs
}
return out;
}
private Set<CWETree> parseResponse(Set<CWETree> candidates, Set<String> response){
Set<CWETree> set = new HashSet<>();
if(response.contains("NONE") || response.isEmpty()){
return set;
}
for (String id : response){ //for each id
for(CWETree cweTree : candidates){ //for each candidate id
try {
if(id.equals("NONE") || id.equals("")) continue;
if (cweTree.getRoot().getId() == Integer.parseInt(id)) { //if the root id matches the id present then add the tree to the set of trees
set.add(cweTree);
}
}catch(NumberFormatException e){
logger.error("Wrong format: {}", id); //in case chatgpt sends some weird format
break;
}
}
}
return set;
}
private Set<CWETree> whichMatchHelper(Set<CWETree> candidates, CompositeVulnerability vuln) {
if (candidates.isEmpty()) { //if candidates is empty return a new set
return new HashSet<>();
}
Set<String> response = askChatGPT(candidates, vuln); //ask chatgpt what candidates might be related to the cve
Set<String> filteredResponse = new HashSet<>();
if(!response.isEmpty()) {
for (String id : response) {
if(id.equals("NONE") || id.equals("")){
break;
}
if (!processedIds.contains(id)) { //keeps repeats from being sent
processedIds.add(id);
filteredResponse.add(id);
}
}
}
matches.addAll(parseResponse(candidates, filteredResponse)); //parse chatgpt's response
List<CWETree> treesToProcess = new ArrayList<>(matches);
for (CWETree match : treesToProcess) {
if(!matchedIds.contains(match.getRoot().getId())) {
matchedIds.add(match.getRoot().getId());
out.add(match);
whichMatchHelper(match.getSubtrees(), vuln);
}
}
return out;
}
public Set<CWE> assignCWEs(CompositeVulnerability vuln) {
CWEForest forest = new CWEForest(); // builds the forest
Set<CWETree> trees = whichMatchHelper(forest.getTrees(), vuln); //gets trees related to vuln
logger.info("trees size: " + trees.size());
Set<CWE> out = new HashSet<>();
for (CWETree tree : trees) {
out.add(tree.getRoot());
}
return out;
}
private Set<String> getIdsFromResponse(String response) {
String[] parts = response.split(","); //split the string by commas (the response string will look like{ 123,456,789 }
Set<String> out = new HashSet<>(); //output set
for (String part : parts) { //for each id
String[] finalParts = part.split("CWE-"); //split one more time (occasionally chatgpt will send {CWE-123,CWE-456} instead so this accounts for that)
for (String finalPart : finalParts){ //for finalPart or the final ID
String trimmedPart = finalPart.trim(); //trim it
if (trimmedPart.equals("")) continue;
out.add(trimmedPart); //add the trimmed part to the list
}
}
return out;
}
public static boolean isInt(String input) {
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((4103, 4213), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4103, 4205), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4103, 4189), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4103, 4170), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4103, 4165), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4103, 4147), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package com.example.wpfsboot.controller;
import com.example.wpfsboot.common.Constants;
import com.example.wpfsboot.common.Result;
import com.example.wpfsboot.entity.GPTParams;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.embedding.EmbeddingRequest;
import com.theokanning.openai.finetune.FineTuneRequest;
import com.theokanning.openai.image.CreateImageEditRequest;
import com.theokanning.openai.image.CreateImageVariationRequest;
import com.theokanning.openai.image.ImageResult;
import com.theokanning.openai.moderation.ModerationRequest;
import io.github.asleepyfish.config.ChatGPTProperties;
import io.github.asleepyfish.entity.billing.Billing;
import io.github.asleepyfish.entity.billing.Subscription;
import io.github.asleepyfish.enums.audio.AudioResponseFormatEnum;
import io.github.asleepyfish.enums.edit.EditModelEnum;
import io.github.asleepyfish.enums.embedding.EmbeddingModelEnum;
import io.github.asleepyfish.enums.image.ImageResponseFormatEnum;
import io.github.asleepyfish.enums.image.ImageSizeEnum;
import io.github.asleepyfish.service.OpenAiProxyService;
import io.github.asleepyfish.util.OpenAiUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @Author: 结束乐队
* @Date: 2023/7/18
*/
@RestController
@RequestMapping("/wpfgpt")
public class ChatGPTController {
@Value("${files.upload.path}")
private String fileUploadPath;
@Value("${server.ip}")
private String serverIp;
@Value("${server.port}")
private String serverPort;
@Value(("${server.password}"))
private String serverPassword;
@Value("${chatgpt.proxy-host}")
private String proxyPort;
@Autowired
private OpenAiUtils openAiUtils;
@Value("${cmd.start}")
private String cmdStart;
/**
* @param question
* @return
*/
public static int containsCode(String question) {
String[] keyword01 = {"图"};
String[] keyword02 = {"报表"};
for (String keyword : keyword01) {
if (question.contains(keyword)) {
return 1;
}
}
for (String keyword : keyword02) {
if (question.contains(keyword)) {
return 2;
}
}
return 3;
}
/**
* @param question
* @return
*/
public static boolean containsJudge(String question) {
String[] keywords = {"预处理后"};
for (String keyword : keywords) {
if (question.contains(keyword)) {
return true;
}
}
return false;
}
/**
* @param originalString
* @param startMarker
* @param endMarker
* @return
*/
public static String extractBetweenMarkers(String originalString, String startMarker, String endMarker) {
int startIndex = originalString.indexOf(startMarker);
int endIndex = originalString.lastIndexOf(endMarker);
if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) {
// 使用substring方法提取两个标记之间的部分
return originalString.substring(startIndex + startMarker.length(), endIndex);
} else {
return ""; // 如果没有找到匹配的标记则返回空字符串
}
}
public static void writePythonCodeToFile(String pythonCode, String filePath) throws IOException {
File file = new File(filePath);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write(pythonCode);
} finally {
if (writer != null) {
writer.close();
}
}
}
private String IMAGE_PATH = fileUploadPath + "/gpt_output/img/"; // 图片文件所在路径
@GetMapping("/api/images/{fileName}")
public ResponseEntity<byte[]> getImage(@PathVariable String fileName) {
try {
String imagePath = fileUploadPath + "/gpt_output/img/" + fileName.replace(".csv", ".png");
System.out.println("imagePath: " + imagePath);
byte[] imageData = readImageData(imagePath);
if (imageData != null) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG); // 设置图片类型,可以根据实际情况调整
return new ResponseEntity<>(imageData, headers, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND); // 图片不存在
}
} catch (Exception e) {
// 处理异常
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// 根据图片路径读取图片数据的方法
private byte[] readImageData(String imagePath) {
try {
Path path = Paths.get(imagePath);
return Files.readAllBytes(path);
} catch (IOException e) {
// 处理读取文件异常
e.printStackTrace();
return null;
}
}
private String docxDirectory = fileUploadPath + "/gpt_output/docx"; // 指定存放 .docx 文件的目录
@GetMapping("/docx/{filename}")
public ResponseEntity<Resource> downloadDocx(@PathVariable String filename) throws MalformedURLException {
System.out.println("docxDirectory: " + fileUploadPath + "/gpt_output/docx");
Path filePath = Paths.get(fileUploadPath + "/gpt_output/docx").resolve(filename);
System.out.println("filePath: " + filePath);
Resource resource = new UrlResource(filePath.toUri());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
/**
* 问答
*
* @param gptParams 问题
* @return 答案
*/
@PostMapping("/postChat2")
public ResponseEntity<Result> postChat2(@RequestBody GPTParams gptParams) {
Result result = new Result();
//时间戳
String time = System.currentTimeMillis() + "";
result.setTime(time);
// 问题预处理
String question = gptParams.getQuestion();
question = question.replace("ROUND(A.WS,1)", "AWS").replace("ROUND(A.POWER,0)", "APOWER");
String fileName = gptParams.getFileName();
// 判断问题类型
int tag1 = containsCode(question);
boolean tag2 = containsJudge(question);
String filePath = tag2 ? fileUploadPath + "/outfile/" + fileName : fileUploadPath + "/pred/" + fileName;
if (tag1 == 3) {
result.setImage(false);
System.out.println(question);
result.setMsg(OpenAiUtils.createChatCompletion(question).get(0));
} else if (tag1 == 1) {
// 判断是否要展示图片
result.setImage(true);
if (tag2) {
question = question.replace("预处理后", "");
} else {
question = question.replace("预测后", "");
}
String text = "我有一个csv文件,位置在" + filePath + ",第一行是列名,第二行开始是数据,其中列名有:DATATIME,WINDSPEED,PREPOWER,WINDDIRECTION,TEMPERATURE,HUMIDITY,PRESSURE,AWS,APOWER,YD15,";
question = text + question
+ ", 图片输出至" + fileUploadPath + "/gpt_output/img/,"
+ "图片名为:" + time + ".png,"
+ "请给出完整的Python代码, 默认我已经安装了所有需要的包。plt.show()不需要,且我只需要你返回给我一个可以执行的完整代码段。整个代码段用markdown中的```包围";
// question = text + question
// + ", 图片输出至/home/wpfs/algorithm/submission75254/gpt_output/img/,"
// + "图片名为:" + time + ".png,"
// + "请给出完整的Python代码, 默认我已经安装了所有需要的包。且我只需要你返回给我一个可以执行的完整代码段。并且注释部分用4个#作为前缀";
System.out.println(question);
result.setMsg(OpenAiUtils.createChatCompletion(question).get(0));
System.out.println(result.getMsg());
String pythonCode = extractBetweenMarkers(result.getMsg(), "```python", "```");
// System.out.println(pythonCode);
String pyFileName = fileName.replace(".csv", ".py");
String pyFilePath = fileUploadPath + "/gpt_output/py/" + pyFileName;
try {
writePythonCodeToFile(pythonCode, pyFilePath);
System.out.println("Python file generated successfully at: " + pyFilePath);
} catch (IOException e) {
System.err.println("Error while generating Python file: " + e.getMessage());
}
String host = serverIp; // 远程服务器IP地址
String user = "root"; // 远程服务器用户名
String password = serverPassword; // 远程服务器密码
if (host.equals("localhost")) {
String command = "conda activate py37 && cd " + fileUploadPath + "/gpt_output/py/ && python ./" + pyFileName;
System.out.println(command);
try {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", command);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // 输出结果到控制台
}
int exitCode = process.waitFor(); // 等待命令执行完成
System.out.println("exit-status: " + exitCode); // 输出退出状态
} catch (Exception e) {
e.printStackTrace(); // 输出错误信息
}
} else {
// 要执行的命令
StringBuilder command = new StringBuilder("conda activate py37;cd " + fileUploadPath + "/gpt_output/py/;python ./" + pyFileName + ";");
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22); // 创建一个SSH会话
session.setPassword(password); // 设置会话密码
session.setConfig("StrictHostKeyChecking", "no"); // 设置会话配置,不检查HostKey
session.connect(); // 连接会话
Channel channel = session.openChannel("exec"); // 打开一个exec通道
((ChannelExec) channel).setCommand(command.toString()); // 设置要执行的命令
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err); // 设置错误输出流
InputStream inputStream = channel.getInputStream();
channel.connect(); // 连接通道
byte[] buffer = new byte[1024];
while (true) {
while (inputStream.available() > 0) {
int i = inputStream.read(buffer, 0, 1024);
if (i < 0) {
break;
}
System.out.print(new String(buffer, 0, i)); // 输出结果到控制台
}
if (channel.isClosed()) {
if (inputStream.available() > 0) {
continue;
}
System.out.println("exit-status: " + channel.getExitStatus()); // 输出退出状态
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
} // 等待一秒钟
}
channel.disconnect(); // 断开通道
session.disconnect(); // 断开会话
} catch (Exception e) {
e.printStackTrace(); // 输出错误信息
}
}
} else {
// 判断是否要展示报表
result.setReport(true);
result.setMsg("报表生成完成");
String tag;
if (tag2) {
question = question.replace("预处理后", "");
tag = "outfile";
} else {
question = question.replace("预测后", "");
tag = "pred";
}
// TODO 数据报表造假
String host = serverIp; // 远程服务器IP地址
String user = "root"; // 远程服务器用户名
String password = serverPassword; // 远程服务器密码
String mdFilePath = fileUploadPath + "/gpt_output/markdown/" + fileName.replace(".csv", "_") + time + ".md";
String docxFilePath = fileUploadPath + "/gpt_output/docx/" + fileName.replace(".csv", "_") + time + ".docx";
String pdfFilePath = fileUploadPath + "/gpt_output/pdf/" + fileName.replace(".csv", "_") + time + ".pdf";
if (serverIp.equals("localhost")) {
String command = "conda activate py37 && cd " + fileUploadPath + "/gpt_output/ && python ./report_local.py --file_name " + fileName + " --time_stamp " + time + " --tag " + tag + " && " + "cd markdown && pandoc " + mdFilePath + " -o " + docxFilePath;
try {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", command);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // 输出结果到控制台
}
int exitCode = process.waitFor(); // 等待命令执行完成
System.out.println("exit-status: " + exitCode); // 输出退出状态
} catch (Exception e) {
e.printStackTrace(); // 输出错误信息
}
} else {
// 要执行的命令
StringBuilder command = new StringBuilder("conda activate py37;cd " + fileUploadPath + "/gpt_output/;python ./report.py --file_name " + fileName + " --time_stamp " + time + " --tag " + tag + ";" + "cd markdown;pandoc " + mdFilePath + " -o " + docxFilePath + ";");
System.out.println("command: " + command.toString());
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22); // 创建一个SSH会话
session.setPassword(password); // 设置会话密码
session.setConfig("StrictHostKeyChecking", "no"); // 设置会话配置,不检查HostKey
session.connect(); // 连接会话
Channel channel = session.openChannel("exec"); // 打开一个exec通道
((ChannelExec) channel).setCommand(command.toString()); // 设置要执行的命令
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err); // 设置错误输出流
InputStream inputStream = channel.getInputStream();
channel.connect(); // 连接通道
byte[] buffer = new byte[1024];
while (true) {
while (inputStream.available() > 0) {
int i = inputStream.read(buffer, 0, 1024);
if (i < 0) {
break;
}
System.out.print(new String(buffer, 0, i)); // 输出结果到控制台
}
if (channel.isClosed()) {
if (inputStream.available() > 0) {
continue;
}
System.out.println("exit-status: " + channel.getExitStatus()); // 输出退出状态
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
} // 等待一秒钟
}
channel.disconnect(); // 断开通道
session.disconnect(); // 断开会话
} catch (Exception e) {
e.printStackTrace(); // 输出错误信息
}
}
}
result.setCode(Constants.CODE_200);
return new ResponseEntity<>(result, HttpStatus.OK);
}
/**
* 问答
*
* @param question 问题
* @return 答案
*/
@PostMapping("/postChat")
public ResponseEntity<Result> postChat(@RequestBody String question) {
Result result = new Result();
result.setMsg(OpenAiUtils.createChatCompletion(question).get(0));
result.setCode(Constants.CODE_200);
return new ResponseEntity<>(result, HttpStatus.OK);
}
/**
* 问答
*
* @param content 问题
* @return 答案
*/
@GetMapping("/getChat")
public List<String> getChat(String content) {
return OpenAiUtils.createChatCompletion(content);
}
/**
* 流式问答,返回到控制台
*/
@GetMapping("/streamChat")
public void streamChat(String content) {
// OpenAiUtils.createStreamChatCompletion(content, System.out);
// 下面的默认和上面这句代码一样,是输出结果到控制台
OpenAiUtils.createStreamChatCompletion(content);
}
/**
* 流式问答,输出结果到WEB浏览器端
*/
@GetMapping("/streamChatWithWeb")
public void streamChatWithWeb(String content, HttpServletResponse response) throws IOException, InterruptedException {
// 需要指定response的ContentType为流式输出,且字符编码为UTF-8
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
// 禁用缓存
response.setHeader("Cache-Control", "no-cache");
OpenAiUtils.createStreamChatCompletion(content, response.getOutputStream());
}
/**
* 生成图片
*
* @param prompt 图片描述
*/
@PostMapping("/createImage")
public void createImage(String prompt) {
System.out.println(OpenAiUtils.createImage(prompt));
}
/**
* 下载图片
*/
@GetMapping("/downloadImage")
public void downloadImage(String prompt, HttpServletResponse response) {
OpenAiUtils.downloadImage(prompt, response);
}
@PostMapping("/billing")
public void billing() {
String monthUsage = OpenAiUtils.billingUsage("2023-04-01", "2023-05-01");
System.out.println("四月使用:" + monthUsage + "美元");
String totalUsage = OpenAiUtils.billingUsage();
System.out.println("一共使用:" + totalUsage + "美元");
String stageUsage = OpenAiUtils.billingUsage("2023-01-31");
System.out.println("自从2023/01/31使用:" + stageUsage + "美元");
Subscription subscription = OpenAiUtils.subscription();
System.out.println("订阅信息(包含到期日期,账户总额度等信息):" + subscription);
// dueDate为到期日,total为总额度,usage为使用量,balance为余额
Billing totalBilling = OpenAiUtils.billing();
System.out.println("历史账单信息:" + totalBilling);
// 默认不传参的billing方法的使用量usage从2023-01-01开始,如果用户的账单使用早于该日期,可以传入开始日期startDate
Billing posibleStartBilling = OpenAiUtils.billing("2022-01-01");
System.out.println("可能的历史账单信息:" + posibleStartBilling);
}
/**
* 自定义Token使用(解决单个SpringBoot项目中只能指定唯一的Token[sk-xxxxxxxxxxxxx]的问题,现在可以自定义ChatGPTProperties内容,添加更多的Token实例)
*/
@PostMapping("/customToken")
public void customToken() {
ChatGPTProperties properties = ChatGPTProperties.builder().token("sk-002xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.proxyHost(serverIp)
.proxyHost(proxyPort)
.build();
OpenAiProxyService openAiProxyService = new OpenAiProxyService(properties);
// 直接使用new出来的openAiProxyService来调用方法,每个OpenAiProxyService都拥有自己的Token。
// 这样在一个SpringBoot项目中,就可以有多个Token,可以有更多的免费额度供使用了
openAiProxyService.createStreamChatCompletion("Java的三大特性是什么");
}
@PostMapping("/models")
public void models() {
System.out.println("models列表:" + OpenAiUtils.listModels());
System.out.println("=============================================");
System.out.println("text-davinci-003信息:" + OpenAiUtils.getModel("text-davinci-003"));
}
/**
* 编辑
*/
@PostMapping("/edit")
public void edit() {
String input = "What day of the wek is it?";
String instruction = "Fix the spelling mistakes";
System.out.println("编辑前:" + input);
// 下面这句和OpenAiUtils.edit(input, instruction, EditModelEnum.TEXT_DAVINCI_EDIT_001);是一样的,默认使用模型TEXT_DAVINCI_EDIT_001
System.out.println("编辑后:" + OpenAiUtils.edit(input, instruction));
System.out.println("=============================================");
input = " public static void mian(String[] args) {\n" +
" system.in.println(\"hello world\");\n" +
" }";
instruction = "Fix the code mistakes";
System.out.println("修正代码前:\n" + input);
System.out.println("修正代码后:\n" + OpenAiUtils.edit(input, instruction, EditModelEnum.CODE_DAVINCI_EDIT_001));
}
@PostMapping("/embeddings")
public void embeddings() {
String text = "Once upon a time";
System.out.println("文本:" + text);
System.out.println("文本的嵌入向量:" + OpenAiUtils.embeddings(text));
System.out.println("=============================================");
String[] texts = {"Once upon a time", "There was a princess"};
System.out.println("文本数组:" + Arrays.toString(texts));
EmbeddingRequest embeddingRequest = EmbeddingRequest.builder()
.model(EmbeddingModelEnum.TEXT_EMBEDDING_ADA_002.getModelName()).input(Arrays.asList(texts)).build();
System.out.println("文本数组的嵌入向量:" + OpenAiUtils.embeddings(embeddingRequest));
}
@PostMapping("/transcription")
public void transcription() {
String filePath = "src/main/resources/audio/想象之中-许嵩.mp3";
System.out.println("语音文件转录后的text文本是:" + OpenAiUtils.transcription(filePath, AudioResponseFormatEnum.TEXT));
// File file = new File("src/main/resources/audio/想象之中-许嵩.mp3");
// System.out.println("语音文件转录后的text文本是:" + OpenAiUtils.transcription(file, AudioResponseFormatEnum.TEXT));
}
@PostMapping("/translation")
public void translation() {
String filePath = "src/main/resources/audio/想象之中-许嵩.mp3";
System.out.println("语音文件翻译成英文后的text文本是:" + OpenAiUtils.translation(filePath, AudioResponseFormatEnum.TEXT));
// File file = new File("src/main/resources/audio/想象之中-许嵩.mp3");
// System.out.println("语音文件翻译成英文后的text文本是:" + OpenAiUtils.translation(file, AudioResponseFormatEnum.TEXT));
}
@PostMapping("/createImageEdit")
public void createImageEdit() {
CreateImageEditRequest createImageEditRequest = CreateImageEditRequest.builder().prompt("Background changed to white")
.n(1).size(ImageSizeEnum.S512x512.getSize()).responseFormat(ImageResponseFormatEnum.URL.getResponseFormat()).build();
ImageResult imageEdit = OpenAiUtils.createImageEdit(createImageEditRequest, "src/main/resources/image/img.png", "src/main/resources/image/mask.png");
System.out.println("图片编辑结果:" + imageEdit);
}
@PostMapping("/createImageVariation")
public void createImageVariation() {
CreateImageVariationRequest createImageVariationRequest = CreateImageVariationRequest.builder()
.n(2).size(ImageSizeEnum.S512x512.getSize()).responseFormat(ImageResponseFormatEnum.URL.getResponseFormat()).build();
ImageResult imageVariation = OpenAiUtils.createImageVariation(createImageVariationRequest, "src/main/resources/image/img.png");
System.out.println("图片变体结果:" + imageVariation);
}
/**
* 文件操作(下面文件操作入参,用户可根据实际情况自行补全)
*/
@PostMapping("/files")
public void files() {
// 上传文件
System.out.println("上传文件信息:" + OpenAiUtils.uploadFile("", ""));
// 获取文件列表
System.out.println("文件列表:" + OpenAiUtils.listFiles());
// 获取文件信息
System.out.println("文件信息:" + OpenAiUtils.retrieveFile(""));
// 获取文件内容
System.out.println("文件内容:" + OpenAiUtils.retrieveFileContent(""));
// 删除文件
System.out.println("删除文件信息:" + OpenAiUtils.deleteFile(""));
}
@PostMapping("/fileTune")
public void fileTune() {
// 创建微调
FineTuneRequest fineTuneRequest = FineTuneRequest.builder().trainingFile("").build();
System.out.println("创建微调信息:" + OpenAiUtils.createFineTune(fineTuneRequest));
// 创建微调完成
CompletionRequest completionRequest = CompletionRequest.builder().build();
System.out.println("创建微调完成信息:" + OpenAiUtils.createFineTuneCompletion(completionRequest));
// 获取微调列表
System.out.println("获取微调列表:" + OpenAiUtils.listFineTunes());
// 获取微调信息
System.out.println("获取微调信息:" + OpenAiUtils.retrieveFineTune(""));
// 取消微调
System.out.println("取消微调信息:" + OpenAiUtils.cancelFineTune(""));
// 列出微调事件
System.out.println("列出微调事件:" + OpenAiUtils.listFineTuneEvents(""));
// 删除微调
System.out.println("删除微调信s息:" + OpenAiUtils.deleteFineTune(""));
}
@PostMapping("/moderation")
public void moderation() {
// 创建moderation
ModerationRequest moderationRequest = ModerationRequest.builder().input("I want to kill them.").build();
System.out.println("创建moderation信息:" + OpenAiUtils.createModeration(moderationRequest));
}
}
| [
"com.theokanning.openai.moderation.ModerationRequest.builder",
"com.theokanning.openai.completion.CompletionRequest.builder",
"com.theokanning.openai.image.CreateImageVariationRequest.builder",
"com.theokanning.openai.finetune.FineTuneRequest.builder",
"com.theokanning.openai.embedding.EmbeddingRequest.builder",
"com.theokanning.openai.image.CreateImageEditRequest.builder"
] | [((6691, 6755), 'java.nio.file.Paths.get'), ((6890, 7122), 'org.springframework.http.ResponseEntity.ok'), ((6890, 7090), 'org.springframework.http.ResponseEntity.ok'), ((6890, 7025), 'org.springframework.http.ResponseEntity.ok'), ((8072, 8121), 'io.github.asleepyfish.util.OpenAiUtils.createChatCompletion'), ((9556, 9605), 'io.github.asleepyfish.util.OpenAiUtils.createChatCompletion'), ((19097, 19146), 'io.github.asleepyfish.util.OpenAiUtils.createChatCompletion'), ((22380, 22559), 'io.github.asleepyfish.config.ChatGPTProperties.builder'), ((22380, 22534), 'io.github.asleepyfish.config.ChatGPTProperties.builder'), ((22380, 22496), 'io.github.asleepyfish.config.ChatGPTProperties.builder'), ((22380, 22459), 'io.github.asleepyfish.config.ChatGPTProperties.builder'), ((24754, 24897), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((24754, 24889), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((24754, 24861), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((24804, 24860), 'io.github.asleepyfish.enums.embedding.EmbeddingModelEnum.TEXT_EMBEDDING_ADA_002.getModelName'), ((26186, 26389), 'com.theokanning.openai.image.CreateImageEditRequest.builder'), ((26186, 26381), 'com.theokanning.openai.image.CreateImageEditRequest.builder'), ((26186, 26317), 'com.theokanning.openai.image.CreateImageEditRequest.builder'), ((26186, 26278), 'com.theokanning.openai.image.CreateImageEditRequest.builder'), ((26186, 26256), 'com.theokanning.openai.image.CreateImageEditRequest.builder'), ((26284, 26316), 'io.github.asleepyfish.enums.image.ImageSizeEnum.S512x512.getSize'), ((26333, 26380), 'io.github.asleepyfish.enums.image.ImageResponseFormatEnum.URL.getResponseFormat'), ((26770, 26940), 'com.theokanning.openai.image.CreateImageVariationRequest.builder'), ((26770, 26932), 'com.theokanning.openai.image.CreateImageVariationRequest.builder'), ((26770, 26868), 'com.theokanning.openai.image.CreateImageVariationRequest.builder'), ((26770, 26829), 'com.theokanning.openai.image.CreateImageVariationRequest.builder'), ((26835, 26867), 'io.github.asleepyfish.enums.image.ImageSizeEnum.S512x512.getSize'), ((26884, 26931), 'io.github.asleepyfish.enums.image.ImageResponseFormatEnum.URL.getResponseFormat'), ((27990, 28040), 'com.theokanning.openai.finetune.FineTuneRequest.builder'), ((27990, 28032), 'com.theokanning.openai.finetune.FineTuneRequest.builder'), ((28217, 28252), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((29087, 29152), 'com.theokanning.openai.moderation.ModerationRequest.builder'), ((29087, 29144), 'com.theokanning.openai.moderation.ModerationRequest.builder')] |
package BackendProg.BookAppWeb.util;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
public class OpenAiComms {
private OpenAiService remoteAiService;
public OpenAiComms() {
// System.out.println("Openai key: " + System.getenv("BOOKAPP_OPENAI_KEY"));
// Fix timeouts
remoteAiService = new OpenAiService(System.getenv("BOOKAPP_OPENAI_KEY"), Duration.ZERO);
}
private OpenAiService getService() {
return remoteAiService;
}
public String getBookRecommendationText(String bookName, String bookAuthors) {
List<ChatMessage> messages = new ArrayList<>();
messages.add(new ChatMessage(
ChatMessageRole.SYSTEM.value(),
"You are a bot meant to summarize books in an engaging, entertaining and enticing way."
));
messages.add(new ChatMessage(
ChatMessageRole.USER.value(),
String.format("Please summarize the book %s by the author(s) %s for me. Make the summary interesting and entertaining. Separate the summary into paragraphs using two newlines.", bookName, bookAuthors)
));
// Could probably add something to customize the used model, maybe someone will want to shell out the cash for GPT-4 lol
ChatCompletionRequest req = ChatCompletionRequest
.builder()
.model("gpt-3.5-turbo")
.messages(messages)
.temperature(1.01)
.build();
ChatMessage resp = getService().createChatCompletion(req).getChoices().get(0).getMessage();
return resp.getContent();
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value"
] | [((943, 973), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((1139, 1167), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')] |
package dev.danilobarreto.portalaluno.Controller;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
import dev.danilobarreto.portalaluno.Model.TextGenerate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
@RestController
public class ChatController {
@Value("${openai.token}")
private String TOKEN_OPEN_AI;
@GetMapping("/chat")
public ModelAndView telaInicio(){
ModelAndView mv = new ModelAndView();
mv.setViewName("chat");
return mv;
}
@ModelAttribute("textGenerate")
public TextGenerate textGenerate() {
return new TextGenerate();
}
@PostMapping("/text")
public Object generate(@RequestBody TextGenerate textGenerate, Model model){
try {
OpenAiService service = new OpenAiService(TOKEN_OPEN_AI);
CompletionRequest completionRequest = CompletionRequest.builder()
.model("text-davinci-003")
.prompt(textGenerate.getText())
.maxTokens(4000)
.build();
model.addAttribute("response", service.createCompletion(completionRequest).getChoices());
model.addAttribute("error", null); // Limpar qualquer mensagem de erro existente
return "response";
} catch (Exception e) {
model.addAttribute("response", null); // Limpar qualquer resposta existente
model.addAttribute("error", e.getMessage());
return "index"; // Redirecionar de volta para o formulário com mensagem de erro
}
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((1059, 1251), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1059, 1222), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1059, 1185), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1059, 1133), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
/*
* Copyright 2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cli.merger.ai.service;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.service.OpenAiService;
import org.jetbrains.annotations.NotNull;
import org.springframework.cli.SpringCliException;
import org.springframework.cli.merger.ai.PromptRequest;
import org.springframework.cli.runtime.engine.templating.HandlebarsTemplateEngine;
import org.springframework.cli.util.PropertyFileUtils;
import org.springframework.cli.util.TerminalMessage;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;
public abstract class AbstractOpenAiService implements org.springframework.cli.merger.ai.service.OpenAiService {
private final HandlebarsTemplateEngine handlebarsTemplateEngine = new HandlebarsTemplateEngine();
private com.theokanning.openai.service.OpenAiService openAiService;
private final TerminalMessage terminalMessage;
public AbstractOpenAiService(TerminalMessage terminalMessage) {
this.terminalMessage = terminalMessage;
}
protected ChatCompletionRequest getChatCompletionRequest(PromptRequest promptRequest) {
createOpenAiService();
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
.model("gpt-3.5-turbo")
.temperature(0.3)
.messages(List.of(new ChatMessage("system", promptRequest.getSystemPrompt()),
new ChatMessage("user", promptRequest.getUserPrompt())))
.build();
return chatCompletionRequest;
}
private void createOpenAiService() {
if (this.openAiService == null) {
// get api token in file ~/.openai
Properties properties = PropertyFileUtils.getPropertyFile();
String apiKey = properties.getProperty("OPEN_AI_API_KEY");
this.openAiService = new OpenAiService(apiKey, Duration.of(5, ChronoUnit.MINUTES));
}
}
public OpenAiService getOpenAiService() {
return openAiService;
}
public HandlebarsTemplateEngine getHandlebarsTemplateEngine() {
return handlebarsTemplateEngine;
}
public TerminalMessage getTerminalMessage() {
return terminalMessage;
}
protected Map<String, String> getContext(String description) {
Map<String, String> context = new HashMap<>();
context.put("description", description);
return context;
}
protected String getPrompt(Map<String, String> context, String promptType) {
String resourceFileName = "/org/springframework/cli/merger/ai/openai-" + promptType + "-prompt.txt";
try {
ClassPathResource promptResource = new ClassPathResource(resourceFileName);
String promptRaw = StreamUtils.copyToString(promptResource.getInputStream(), StandardCharsets.UTF_8);
return getHandlebarsTemplateEngine().process(promptRaw, context);
}
catch (FileNotFoundException ex) {
throw new SpringCliException("Resource file note found:" + resourceFileName);
}
catch (IOException ex) {
throw new SpringCliException("Could read file " + resourceFileName, ex);
}
}
protected PromptRequest createPromptRequest(Map<String, String> context, String promptFamilyName) {
String systemPrompt = getPrompt(context, "system-" + promptFamilyName);
String userPrompt = getPrompt(context, "user-" + promptFamilyName);
return new PromptRequest(systemPrompt, userPrompt);
}
@NotNull
protected String getResponse(ChatCompletionRequest chatCompletionRequest) {
StringBuilder builder = new StringBuilder();
getOpenAiService().createChatCompletion(chatCompletionRequest).getChoices().forEach(choice -> {
builder.append(choice.getMessage().getContent());
});
String response = builder.toString();
return response;
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((2172, 2406), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2172, 2394), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2172, 2251), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2172, 2230), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package com.touchbiz.chatgpt.controller;
import com.theokanning.openai.completion.CompletionRequest;
import com.touchbiz.chatgpt.application.ChatApplicationService;
import com.touchbiz.chatgpt.boot.config.OpenAiConfig;
import com.touchbiz.chatgpt.common.aspect.annotation.RequestLimit;
import com.touchbiz.chatgpt.common.dto.Result;
import com.touchbiz.chatgpt.common.proxy.OpenAiEventStreamService;
import com.touchbiz.chatgpt.database.domain.ChatSessionDetail;
import com.touchbiz.chatgpt.dto.Chat;
import com.touchbiz.chatgpt.dto.ChatResult;
import com.touchbiz.chatgpt.dto.request.ChatCompletionRequest;
import com.touchbiz.chatgpt.dto.request.ChatMessageRequest;
import com.touchbiz.chatgpt.dto.request.ValidChatRight;
import com.touchbiz.chatgpt.dto.response.ChatCompontionsResult;
import com.touchbiz.chatgpt.dto.response.ChatSessionDTO;
import com.touchbiz.chatgpt.infrastructure.constants.CommonConstant;
import com.touchbiz.chatgpt.infrastructure.converter.ChatSessionConverter;
import com.touchbiz.chatgpt.service.ChatSessionInfoService;
import com.touchbiz.common.entity.annotation.Auth;
import com.touchbiz.common.entity.result.MonoResult;
import com.touchbiz.common.utils.tools.JsonUtils;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import javax.validation.Valid;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import static com.touchbiz.chatgpt.infrastructure.constants.CacheConstant.*;
@Slf4j
@RequestMapping("/api/chatGpt/chatting")
@RestController
public class ChatController extends AbstractBaseController<ChatSessionDetail, ChatSessionInfoService> {
@Autowired
private OpenAiConfig config;
@Autowired
private OpenAiEventStreamService service;
@Autowired
private ChatApplicationService chatApplicationService;
@PostMapping
@RequestLimit()
public Mono<Result<?>> prompt(@RequestBody @Valid Chat chat) {
String sessionId = chat.getSessionId();
String prompt = chat.getPrompt();
//sessionId校验合法性
chatApplicationService.checkSessionId(sessionId);
var user = getCurrentUser();
log.info("chat:{}", chat);
String redisKey = CHAT_SESSION_CONTEXT_KEY + sessionId;
String question;
//拼接提问
if (getRedisTemplate().hasKey(redisKey)) {
question = JsonUtils.toJson(getRedisTemplate().get(redisKey)).trim().replace("\\", "").replace("\"", "").replace("n", "\\n") + CommonConstant.SPLICER + prompt;
} else {
question = prompt;
}
log.info("question:{}", question);
CompletionRequest completionRequest = generateRequest(prompt);
try {
long start = System.currentTimeMillis();
var result = service.createCompletion(completionRequest);
log.info("调用openAI接口耗时:{}", System.currentTimeMillis() - start + "ms");
String rt = JsonUtils.toJson(result);
ChatResult chatResult = JsonUtils.toObject(rt, ChatResult.class);
log.info("result:{}", chatResult);
if (!ObjectUtils.isEmpty(chatResult) && !CollectionUtils.isEmpty(chatResult.getChoices())) {
String answerContent = chatResult.getChoices().get(0).getText();
String answer = answerContent.replace("\\", "");
redisTemplate.set(CHAT_SESSION_CONTEXT_KEY + sessionId, question + answer, CHAT_SESSION_INFO_EXPIRE_SECONDS);
chatApplicationService.createSessionInfo(chat, answerContent, user);
return Mono.just(Result.ok(answerContent));
}
} catch (Exception ex) {
log.error("error:", ex);
return Mono.just(Result.error("系统超时,请联系管理员"));
}
return Mono.just(Result.error("请求失败,请重试"));
}
@SneakyThrows
@GetMapping(value = "/completion", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<Result<String>>> completion(@RequestParam("sessionId") String sessionId,
@RequestParam("prompt") String prompt) {
log.info("sessionId:{},prompt:{}", sessionId, prompt);
if (sessionId.contains(" ")) {
sessionId = sessionId.replace(" ", "+");
}
//sessionId校验合法性
chatApplicationService.checkSessionId(sessionId);
var user = getCurrentUser();
String redisKey = CHAT_SESSION_CONTEXT_KEY + sessionId;
String question;
//拼接提问
if (getRedisTemplate().hasKey(redisKey)) {
question = JsonUtils.toJson(getRedisTemplate().get(redisKey)).replace("\"", "").replace(CommonConstant.CHARACTER,"\n") + CommonConstant.SPLICER + prompt;
} else {
question = prompt;
}
log.info("question:{}", question);
var eventStream = service.createCompletionFlux(this.generateRequest(question));
eventStream.doOnError(x -> log.error("doOnError SSE:", x));
String finalSessionId = sessionId;
List<ChatResult> list = new ArrayList<>();
AtomicReference<ChatResult> lastChatResult = null;
eventStream.subscribe(content -> {
String data = content.data();
if ("[DONE]".equals(data)) {
return;
}
ChatResult chatResult = JsonUtils.toObject(data, ChatResult.class);
lastChatResult.set(chatResult);
list.add(chatResult);
log.info("Time: {} - event: name[{}], id [{}], content[{}] ",
LocalTime.now(), content.event(), content.id(), data
);
}, error -> log.error("Error receiving SSE:", error),
() -> {
StringBuilder stringBuilder = new StringBuilder();
list.forEach(item -> {
List<ChatResult.Choice> choices = item.getChoices();
if (!CollectionUtils.isEmpty(choices)) {
String text = choices.get(0).getText();
stringBuilder.append(text);
}
});
String answerContent = stringBuilder.toString();
String qn = question.replace("\n", CommonConstant.CHARACTER);
String answer = answerContent.replace("\n", CommonConstant.CHARACTER);
redisTemplate.set(CHAT_SESSION_CONTEXT_KEY + finalSessionId, qn + answer, CHAT_SESSION_INFO_EXPIRE_SECONDS);
chatApplicationService.createSessionInfo(finalSessionId, prompt, answerContent, user);
}
);
return eventStream.map(x -> {
Result<String> result = Result.ok();
result.setResult(x.data());
return ServerSentEvent.builder(result).build();
}).subscribeOn(Schedulers.elastic());
}
@SneakyThrows
@GetMapping(value = "/completions", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<Result<String>>> chatCompletion(@RequestParam("sessionId") String sessionId,
@RequestParam("prompt") String prompt) {
log.info("sessionId:{},prompt:{}", sessionId, prompt);
if (sessionId.contains(" ")) {
sessionId = sessionId.replace(" ", "+");
}
//sessionId校验合法性
chatApplicationService.checkSessionId(sessionId);
var user = getCurrentUser();
final String redisKey = CHAT_SESSION_CONTEXT_KEY + sessionId;
List<ChatMessageRequest> chatList = redisTemplate.getObjectList(redisKey, ChatMessageRequest.class);
if(chatList == null){
chatList = new ArrayList<>();
}
chatList.add(new ChatMessageRequest("user", prompt));
var eventStream = service.createChatCompletionFlux(this.generateChatRequest(chatList));
eventStream.doOnError(x -> log.error("doOnError SSE:", x));
String finalSessionId = sessionId;
List<ChatCompontionsResult> list = new ArrayList<>();
AtomicReference<ChatCompontionsResult> lastChatResult = null;
List<ChatMessageRequest> finalChatList = chatList;
eventStream.subscribe(content -> {
String data = content.data();
if ("[DONE]".equals(data)) {
//判断上一条的结束原因,如果是因为长度不足,则如何继续请求并拼接到目前的数据中去
return;
}
ChatCompontionsResult chatResult = JsonUtils.toObject(data, ChatCompontionsResult.class);
list.add(chatResult);
log.info("Time: {} - event: name[{}], id [{}], content[{}] ",
LocalTime.now(), content.event(), content.id(), data
);
}, error -> log.error("Error receiving SSE:", error),
() -> {
StringBuilder stringBuilder = new StringBuilder();
list.forEach(item -> {
List<ChatCompontionsResult.Choice> choices = item.getChoices();
if (!CollectionUtils.isEmpty(choices)) {
choices.forEach(choice->{
choice.getDelta().forEach(delta->{
stringBuilder.append(delta.getContent());
});
});
}
});
String answerContent = stringBuilder.toString();
ChatMessageRequest request = new ChatMessageRequest("system", answerContent);
finalChatList.add(request);
redisTemplate.setObjectList(CHAT_SESSION_CONTEXT_KEY + finalSessionId, finalChatList, CHAT_SESSION_INFO_EXPIRE_SECONDS);
chatApplicationService.createSessionInfo(finalSessionId, prompt, answerContent, user);
}
);
return eventStream.map(x -> {
Result<String> result = Result.ok();
result.setResult(x.data());
return ServerSentEvent.builder(result).build();
}).subscribeOn(Schedulers.elastic());
}
@SneakyThrows
@GetMapping(value = "/continueCompletion", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<Result<String>>> continueCompletion(@RequestParam("sessionId") String sessionId) {
if (sessionId.contains(" ")) {
sessionId = sessionId.replace(" ", "+");
}
//sessionId校验合法性
chatApplicationService.checkSessionId(sessionId);
var user = getCurrentUser();
String redisKey = CHAT_SESSION_CONTEXT_KEY + sessionId;
String question;
//拼接提问
if (getRedisTemplate().hasKey(redisKey)) {
question = JsonUtils.toJson(getRedisTemplate().get(redisKey)).replace("\"", "").replace(CommonConstant.CHARACTER,"\n") + CommonConstant.SPLICER;
} else {
question = "";
}
log.info("question:{}", question);
var eventStream = service.createCompletionFlux(this.generateRequest(question));
eventStream.doOnError(x -> log.error("doOnError SSE:", x));
String finalSessionId = sessionId;
List<ChatResult> list = new ArrayList<>();
AtomicReference<ChatResult> lastChatResult = null;
eventStream.subscribe(content -> {
String data = content.data();
if ("[DONE]".equals(data)) {
return;
}
ChatResult chatResult = JsonUtils.toObject(data, ChatResult.class);
lastChatResult.set(chatResult);
list.add(chatResult);
log.info("Time: {} - event: name[{}], id [{}], content[{}] ",
LocalTime.now(), content.event(), content.id(), data
);
}, error -> log.error("Error receiving SSE:", error),
() -> {
StringBuilder stringBuilder = new StringBuilder();
list.forEach(item -> {
List<ChatResult.Choice> choices = item.getChoices();
if (!CollectionUtils.isEmpty(choices)) {
String text = choices.get(0).getText();
stringBuilder.append(text);
}
});
String answerContent = stringBuilder.toString();
String qn = question.replace("\n", CommonConstant.CHARACTER);
String answer = answerContent.replace("\n", CommonConstant.CHARACTER);
redisTemplate.set(CHAT_SESSION_CONTEXT_KEY + finalSessionId, qn + answer, CHAT_SESSION_INFO_EXPIRE_SECONDS);
chatApplicationService.createSessionInfo(finalSessionId, "prompt", answerContent, user);
}
);
return eventStream.map(x -> {
Result<String> result = Result.ok();
result.setResult(x.data());
return ServerSentEvent.builder(result).build();
}).subscribeOn(Schedulers.elastic());
}
@Auth
@ApiOperation("获取会话列表")
@GetMapping
public MonoResult<List<ChatSessionDTO>> getPageList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
var user = getCurrentUser();
var result = chatApplicationService.getChatSessionPageList(pageNo, pageSize, user);
var list = result.getRecords().stream().map(ChatSessionConverter.INSTANCE::transformOut)
.toList();
return MonoResult.ok(list);
}
@ApiOperation("新增会话id")
@PostMapping("/session")
public MonoResult<?> createSession() {
var user = getCurrentUser();
var session = chatApplicationService.createSession(user);
//添加缓存
String key = CHAT_SESSION_KEY + session.getSessionId();
getRedisTemplate().setObject(key, session, CHAT_SESSION_EXPIRE_SECONDS);
return MonoResult.OK(ChatSessionConverter.INSTANCE.transformOut(session));
}
/**
* 判断是否允许进行聊天,如果没有相应的次数,则不能进行后续的聊天,并返回相应的提示内容
*
* @return
*/
@PostMapping("/validRight")
public MonoResult<Object> validChatRight(@RequestBody ValidChatRight validChatRight) {
return MonoResult.ok("");
}
@Auth
@ApiOperation(value = "删除会话")
@DeleteMapping("/{id}")
public MonoResult<?> delete(@PathVariable String id) {
var user = getCurrentUser();
chatApplicationService.deleteSession(id, user);
return MonoResult.ok("删除成功!");
}
private CompletionRequest generateRequest(String prompt) {
return CompletionRequest.builder()
.prompt(prompt)
.model(config.getModel())
.stop(Arrays.asList(" Human:", " AI:"))
.maxTokens(1280)
.presencePenalty(0.6d)
.frequencyPenalty(0d)
.temperature(0.9D)
.bestOf(1)
.topP(1d)
.build();
}
private ChatCompletionRequest generateChatRequest(List<ChatMessageRequest> list) {
var request = ChatCompletionRequest.builder().temperature(0d)
.messages(list)
.build();
request.setFrequencyPenalty(0d);
request.setMaxTokens(4096);
return request;
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((2841, 2954), 'com.touchbiz.common.utils.tools.JsonUtils.toJson'), ((2841, 2934), 'com.touchbiz.common.utils.tools.JsonUtils.toJson'), ((2841, 2916), 'com.touchbiz.common.utils.tools.JsonUtils.toJson'), ((2841, 2898), 'com.touchbiz.common.utils.tools.JsonUtils.toJson'), ((5131, 5238), 'com.touchbiz.common.utils.tools.JsonUtils.toJson'), ((5131, 5199), 'com.touchbiz.common.utils.tools.JsonUtils.toJson'), ((7426, 7465), 'org.springframework.http.codec.ServerSentEvent.builder'), ((10847, 10886), 'org.springframework.http.codec.ServerSentEvent.builder'), ((11585, 11692), 'com.touchbiz.common.utils.tools.JsonUtils.toJson'), ((11585, 11653), 'com.touchbiz.common.utils.tools.JsonUtils.toJson'), ((13869, 13908), 'org.springframework.http.codec.ServerSentEvent.builder'), ((14986, 15037), 'com.touchbiz.chatgpt.infrastructure.converter.ChatSessionConverter.INSTANCE.transformOut'), ((15749, 16129), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((15749, 16104), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((15749, 16078), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((15749, 16051), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((15749, 16016), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((15749, 15978), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((15749, 15939), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((15749, 15906), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((15749, 15850), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((15749, 15808), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((16247, 16351), 'com.touchbiz.chatgpt.dto.request.ChatCompletionRequest.builder'), ((16247, 16326), 'com.touchbiz.chatgpt.dto.request.ChatCompletionRequest.builder'), ((16247, 16294), 'com.touchbiz.chatgpt.dto.request.ChatCompletionRequest.builder')] |
package com.notorious;
import com.notorious.models.Data;
import com.notorious.models.User;
import com.notorious.repositorys.DataRepository;
import com.notorious.repositorys.UserRepository;
import com.notorious.request.AssociationRequest;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.image.CreateImageRequest;
import com.theokanning.openai.service.OpenAiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@CrossOrigin(origins = {"http://localhost:3000", "https://notorious-799tu.ondigitalocean.app"})
@RestController("/")
public class OpenAIController {
Object response;
OpenAiService service;
final List<ChatMessage> messages;
ChatMessage systemMessage;
public OpenAIController(@Value("${openai.apikey}") String token) {
this.service = new OpenAiService(token);
this.systemMessage = new ChatMessage();
this.response = "";
messages = new ArrayList<>();
}
@GetMapping("hello")
public String hello() {
return "Hola!";
}
@GetMapping("words")
public Object GenerateWords (String word) {
/*Streaming chat completion...*/
systemMessage = new ChatMessage(ChatMessageRole.USER.value(), "I am memorizing, and I need to create associations between words." + "Give me 5 Spanish words that exist, with a 90% similarity in writing to: " + word +
". Like these similarities: shower/chofer, snake/esnife, get/jet. Give me only words that exist in real life. May your answer only be the words, eliminate numbers and signs from your answer.");
return getObject();
}
@GetMapping("idea")
public Object GenerateWords (String wordOne, String wordTwo) {
/*Streaming chat completion...*/
systemMessage = new ChatMessage(ChatMessageRole.USER.value(), "I am memorizing Give me a single short implausible idea in Spanish with a maximum of 30 words that includes the words: " + wordOne + " and " + wordTwo + ". Let my 5 senses be involved in the implausible idea. that your answer is in spanish");
return getObject();
}
private Object getObject() {
messages.add(systemMessage);
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
.builder()
.model("gpt-3.5-turbo")
.messages(messages)
.n(1)
.logitBias(new HashMap<>())
.build();
Object response = service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage();
service.shutdownExecutor();
return response;
}
@GetMapping("image")
public Object ImageGenerate(String history) {
//Creating Image
CreateImageRequest request = CreateImageRequest.builder()
.prompt(history)
.size("256x256")
.build();
//Image is located at:
response = service.createImage(request).getData().get(0);
service.shutdownExecutor();
return response;
}
/*______________________*/
@Autowired
private UserRepository userRepository;
@Autowired
private DataRepository dataRepository;
//Añadir Usuario
@PostMapping(path = "add")
public @ResponseBody User addNewUser(@RequestParam String username, @RequestParam String password) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
userRepository.save(user);
return user;
}
//Obtener Usuario
@GetMapping(path = "getUser")
public ResponseEntity<Object> getUser(@RequestParam String username) {
User user = userRepository.findByUsername(username);
if(user != null) {
return ResponseEntity.ok(user);
} else {
return ResponseEntity.ok(new HashMap<>());
}
}
//Obtener todos los usuarios
@GetMapping(path = "all")
public @ResponseBody Iterable<User> getAllUsers() {
return userRepository.findAll();
}
//Añadir nueva Asociacion
@PostMapping(path = "addNewAssociation")
public @ResponseBody String addNewAssociation (@RequestBody
AssociationRequest request) {
User user = userRepository.findByUsername(request.getUsernameFK());
if(user != null) {
Data data = new Data();
data.setUser(user);
data.setWordEnglish(request.getWordEnglish());
data.setWordSimilar(request.getWordSimilar());
data.setIdea(request.getIdea());
data.setImage(request.getImage());
dataRepository.save(data);
return "Data added successfully";
} else {
return "User not found";
}
}
@GetMapping(path = "getAssociation")
public @ResponseBody Data getAssociation (@RequestParam String wordEnglish) {
Data data = dataRepository.findByWordEnglish(wordEnglish);
return data;
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value",
"com.theokanning.openai.image.CreateImageRequest.builder"
] | [((1585, 1613), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((2188, 2216), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((3159, 3278), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3159, 3253), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3159, 3220), 'com.theokanning.openai.image.CreateImageRequest.builder')] |
package edu.uniceub.calendar_man.chatworkflowmanager.open_ai.functions;
import com.theokanning.openai.completion.chat.ChatFunction;
import edu.uniceub.calendar_man.chatworkflowmanager.models.Event;
import edu.uniceub.calendar_man.chatworkflowmanager.open_ai.functions.contexts.GetCurrentDateResponse;
import edu.uniceub.calendar_man.chatworkflowmanager.open_ai.functions.contexts.GetEventsRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class FunctionUtils {
final Logger LOGGER = LoggerFactory.getLogger(FunctionUtils.class);
private FunctionUtils() {}
public static final List<String> ASSISTANT_ACTION_FUNCTIONS =
List.of("get_calendar_context", "schedule_event", "get_current_date");
public static ChatFunction getCalendarEventsFunction(
final Function<GetEventsRequest, Object> getEvents) {
return ChatFunction.builder()
.name("get_calendar_context")
.description("Accesses the user's calendar and gets the events for the given date.")
.executor(GetEventsRequest.class, getEvents)
.build();
}
public static ChatFunction scheduleNewEvent(final Function<Event, Object> scheduleEvent) {
return ChatFunction.builder()
.name("schedule_event")
.description("Schedules a new event to the user's calendar.")
.executor(Event.class, scheduleEvent)
.build();
}
public static ChatFunction getCurrentDate() {
return ChatFunction.builder()
.name("get_current_date")
.description("Returns the current date.")
.executor(
Object.class, empty -> GetCurrentDateResponse.fromDate(LocalDateTime.now().toString()))
.build();
}
}
| [
"com.theokanning.openai.completion.chat.ChatFunction.builder"
] | [((954, 1177), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((954, 1160), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((954, 1107), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((954, 1014), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((1289, 1476), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((1289, 1459), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((1289, 1413), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((1289, 1343), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((1542, 1784), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((1542, 1767), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((1542, 1648), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((1542, 1598), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((1735, 1765), 'java.time.LocalDateTime.now')] |
package br.com.alura.screenmatch.service;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
public class ConsultaChatGPT {
public static String obterTraducao(String texto) {
OpenAiService service = new OpenAiService("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");
CompletionRequest requisicao = CompletionRequest.builder()
.model("text-davinci-003")
.prompt("traduza para o português o texto: " + texto)
.maxTokens(1000)
.temperature(0.7)
.build();
var resposta = service.createCompletion(requisicao);
return resposta.getChoices().get(0).getText();
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((390, 623), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((390, 598), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((390, 564), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((390, 531), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((390, 460), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package learn.scraibe.controllers;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import learn.scraibe.models.Note;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/generate-completion")
public class OpenAIController {
@Value("${openai.api.key}")
private String openaiApiKey;
@PostMapping
public ResponseEntity<Object> generateCompletion(@RequestBody Note note) {
if(note.getContent() == null || note.getContent().isBlank()){
return new ResponseEntity<>("Cannot have blank notes", HttpStatus.BAD_REQUEST);
}
//create service that will route to OpenAI endpoint, provide key and timeout value incase openai takes a long time
OpenAiService service = new OpenAiService(openaiApiKey, Duration.ofSeconds(60));
//set up messages and Roles
List<ChatMessage> messages = new ArrayList<>();
ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), "organize with bullet points, only respond with bullet points "+ note.getContent());
ChatMessage systemMessage = new ChatMessage(ChatMessageRole.ASSISTANT.value(), "you are a helpful assistant");
messages.add(userMessage);
messages.add((systemMessage));
// configure chatCompletionRequest object that will be sent over via the api
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
.builder()
.model("gpt-3.5-turbo-0613")
.messages(messages)
.build();
//use service to make the request to OpenAI and then get the specific message to send back to the frontend.
ChatMessage responseMessage = service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage();
note.setContent(responseMessage.getContent());
return new ResponseEntity<>(note, HttpStatus.OK);
//TODO make a conditional statement based on the success of a response message,
//one previous error occurred because the request timed out(openai took too long to send back a request)
// but extending the duration seemed to solved the issue, just wondering what other issues to anticipate.
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value"
] | [((1638, 1666), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((1805, 1838), 'com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value')] |
package Server;
import Protocol.ChatServerInterface;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
public class ChatServer {
private final ServerSocket serverSocket;
private final List<ClientHandler> clients;
private final List<String> chatLog;
private final OpenAiService openapi;
List<ChatMessage> messages = new ArrayList<>();
private int nextUserId = 0;
public ChatServer(int port) throws IOException {
clients = new ArrayList<>();
chatLog = new ArrayList<>();
serverSocket = new ServerSocket(port);
System.out.println("Server is now open on port " + port); // 서버가 열린 포트 번호를 로그로 찍는 코드 추가
Properties prop = new Properties();
String openaiKey = "";
try (InputStream input = new FileInputStream("config.properties")) {
// .properties 파일 로드
prop.load(input);
// 키를 사용하여 값을 검색
openaiKey = prop.getProperty("OPENAI_KEY");
} catch (IOException ex) {
ex.printStackTrace();
}
openapi = new OpenAiService(openaiKey);
ChatMessage customInstruction = new ChatMessage(ChatMessageRole.SYSTEM.value(), "'지피티' is designed for group chat interactions, understanding and responding to individual users based on their names in the chat. It has a rough, friendly speaking style, similar to that of a close friend. The GPT is knowledgeable in computer science, especially Java, AI, and gaming, with a particular interest in League of Legends and the latest computer hardware. Its responses are brief, typically no more than two sentences, and mirror the user's speech style. The GPT seamlessly integrates into group conversations, offering tech and gaming insights in a casual, engaging manner.");
messages.add(customInstruction);
}
public void start() throws IOException {
while (true) {
Socket socket = serverSocket.accept();
ClientHandler clientHandler = new ClientHandler(socket, this, nextUserId++);
clients.add(clientHandler);
clientHandler.start();
}
}
public synchronized void broadcastMessage(String message, int userId) {
chatLog.add(message);
System.out.println(message);
for (ClientHandler client : clients) {
client.sendMessage(message, userId);
}
}
public List<String> getChatLog() {
return chatLog;
}
public static class ClientHandler extends Thread {
private final Socket socket;
private final ChatServer server;
private final int userId;
private final ChatServerInterface chatServerInterface;
private static final Map<Integer, String> nameMap = new HashMap<>();
public ClientHandler(Socket socket, ChatServer server, int userId) throws IOException {
this.socket = socket;
this.server = server;
this.userId = userId;
this.chatServerInterface = new ChatServerInterface(socket.getInputStream(), socket.getOutputStream());
chatServerInterface.setClientHandler(new ChatServerInterface.ClientHandler() {
@Override
public void onNameSet(String name) {
nameMap.put(userId, name);
}
@Override
public void onMessageReceived(String message) {
String userName = nameMap.getOrDefault(userId, "Unknown");
server.broadcastMessage(userName + ": " + message, userId); // 사용자 이름과 메시지를 모든 클라이언트에게 전송
try {
ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), userName + ": " + message);
server.messages.add(userMessage);
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
.builder()
.model("gpt-3.5-turbo-0613")
.messages(server.messages)
// .functionCall(new ChatCompletionRequest.ChatCompletionRequestFunctionCall("auto"))
.maxTokens(256)
.build();
ChatMessage responseMessage = server.openapi.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage();
server.messages.add(responseMessage);
server.broadcastMessage(responseMessage.getContent(), userId);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onMessageEditRequest(int messageId, String newMessage) {
// 메시지 수정 요청 처리
}
@Override
public void onMessageDeleteRequest(int messageId) {
// 메시지 삭제 요청 처리
}
@Override
public void onInvalidRequest(String[] messages) {
// 잘못된 요청 처리
}
});
}
public void run() {
try {
while (!interrupted() && chatServerInterface.readCommand()) ;
} catch (IOException e) {
e.printStackTrace();
} finally {
closeConnection();
}
}
private void closeConnection() {
try {
System.out.println("Client " + userId + " disconnected.");
socket.close();
server.clients.remove(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String message, int userId) {
try {
chatServerInterface.sendMessageToClient(server.getChatLog().size() - 1, userId, message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value",
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value"
] | [((1440, 1470), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3681, 3709), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')] |
package com.odde.doughnut.services.ai.tools;
import com.odde.doughnut.services.ai.*;
import com.theokanning.openai.completion.chat.ChatFunction;
import java.util.List;
public class AiToolFactory {
public static final String COMPLETE_NOTE_DETAILS = "complete_note_details";
public static AiToolList mcqWithAnswerAiTool() {
return new AiToolList(
"""
Please assume the role of a Memory Assistant, which involves helping me review, recall, and reinforce information from my notes. As a Memory Assistant, focus on creating exercises that stimulate memory and comprehension. Please adhere to the following guidelines:
1. Generate a MCQ based on the note in the current context path
2. Only the top-level of the context path is visible to the user.
3. Provide 2 to 4 choices with only 1 correct answer.
4. Vary the lengths of the choice texts so that the correct answer isn't consistently the longest.
5. If there's insufficient information in the note to create a question, leave the 'stem' field empty.
Note: The specific note of focus and its more detailed contexts are not known. Focus on memory reinforcement and recall across various subjects.
""",
List.of(
ChatFunction.builder()
.name("ask_single_answer_multiple_choice_question")
.description("Ask a single-answer multiple-choice question to the user")
.executor(MCQWithAnswer.class, null)
.build()));
}
public static AiToolList questionEvaluationAiTool(MCQWithAnswer question) {
MultipleChoicesQuestion clone = question.getMultipleChoicesQuestion();
String messageBody =
"""
Please assume the role of a learner, who has learned the note of focus as well as many other notes.
Only the top-level of the context path is visible to you.
Without the specific note of focus and its more detailed contexts revealed to you,
please critically check if the following question makes sense and is possible to you:
%s
"""
.formatted(clone.toJsonString());
return new AiToolList(
messageBody,
List.of(
ChatFunction.builder()
.name("evaluate_question")
.description("answer and evaluate the feasibility of the question")
.executor(QuestionEvaluation.class, null)
.build()));
}
}
| [
"com.theokanning.openai.completion.chat.ChatFunction.builder"
] | [((1248, 1505), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((1248, 1480), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((1248, 1427), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((1248, 1338), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((2165, 2397), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((2165, 2372), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((2165, 2314), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((2165, 2230), 'com.theokanning.openai.completion.chat.ChatFunction.builder')] |
package com.github.starrygaze.midjourney.service.translate.impl;
import cn.hutool.core.text.CharSequenceUtil;
import com.github.starrygaze.midjourney.ProxyProperties;
import com.github.starrygaze.midjourney.service.translate.TranslateService;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.service.OpenAiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionValidationException;
import java.util.List;
/**
* 这个类叫做 GPTTranslateServiceImpl,它实现了 TranslateService 接口。根据类名和代码内容,我们可以看出这个类是用来提供基于 OpenAI GPT (Generative Pre-training Transformer) 的翻译服务。
* 这个类提供了一个基于 OpenAI GPT 的翻译服务,可以将中文文本翻译成英语文本。尽管 OpenAI GPT 不是专门的翻译模型,但是由于其强大的语言生成和理解能力,也可以用来做一些简单的翻译任务。
*/
@Slf4j
public class GPTTranslateServiceImpl implements TranslateService {
/**
* 初始化(构造函数):在构造函数中,接收一个类型为 ProxyProperties.OpenaiConfig 的参数 openaiConfig,并从这个参数中获取了 OpenAI GPT 所需要的 API 密钥。
* 如果这个密钥为空,将会抛出一个 BeanDefinitionValidationException 异常。然后,使用这个 API 密钥和超时时间创建一个 OpenAiService 实例。
*/
private final OpenAiService openAiService;
private final ProxyProperties.OpenaiConfig openaiConfig;
public GPTTranslateServiceImpl(ProxyProperties.OpenaiConfig openaiConfig) {
if (CharSequenceUtil.isBlank(openaiConfig.getGptApiKey())) {
throw new BeanDefinitionValidationException("mj-proxy.openai.gpt-api-key未配置");
}
this.openaiConfig = openaiConfig;
this.openAiService = new OpenAiService(openaiConfig.getGptApiKey(), openaiConfig.getTimeout());
}
/**
* translateToEnglish(String prompt):这个方法用来将输入的文本翻译成英语。首先,它会检查输入的文本是否包含中文,如果不包含,直接返回原来的文本,否则会进行翻译。
* 翻译的过程中,它会创建两个 ChatMessage 实例,一个是系统消息,告诉 GPT 需要将中文翻译成英文,另一个是用户消息,包含了需要翻译的中文。然后,使用这两个消息创建一个
* ChatCompletionRequest 实例。接下来,使用 OpenAiService 来执行这个请求,并获取返回的结果。从结果中提取出翻译后的英文并返回。如果在调用过程中出现任何异常,
* 都会被捕获并打印警告信息,然后返回原来的文本。
* @param prompt
* @return
*/
@Override
public String translateToEnglish(String prompt) {
if (!containsChinese(prompt)) {
return prompt;
}
ChatMessage m1 = new ChatMessage("system", "把中文翻译成英文");
ChatMessage m2 = new ChatMessage("user", prompt);
ChatCompletionRequest request = ChatCompletionRequest.builder()
.model(this.openaiConfig.getModel())
.temperature(this.openaiConfig.getTemperature())
.maxTokens(this.openaiConfig.getMaxTokens())
.messages(List.of(m1, m2))
.build();
try {
List<ChatCompletionChoice> choices = this.openAiService.createChatCompletion(request).getChoices();
if (!choices.isEmpty()) {
return choices.get(0).getMessage().getContent();
}
} catch (Exception e) {
log.warn("调用chat-gpt接口翻译中文失败: {}", e.getMessage());
}
return prompt;
}
} | [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((3138, 3356), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3138, 3343), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3138, 3312), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3138, 3263), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3138, 3210), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package alura.jmilhas.api.infra.integration;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
import org.springframework.stereotype.Service;
@Service
public class ChatGptIntegrationService {
private static final String API_KEY = System.getenv("MY_API_KEY");
private final OpenAiService service = new OpenAiService(API_KEY);
public String destinationText(String destination) {
String prompt =
String.format("Aja como um redator para um site de venda de viagens. " +
"Faça um resumo sobre o local %s. Enfatize os pontos positivos da cidade." +
"Utilize uma linguagem informal. " +
"Cite ideias de passeios neste lugar. " +
"Crie 2 parágrafos neste resumo.", destination);
CompletionRequest request = CompletionRequest.builder()
.model("text-davinci-003")
.prompt(prompt)
.maxTokens(2048)
.temperature(0.6)
.build();
return service.createCompletion(request)
.getChoices()
.get(0)
.getText();
}
} | [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((910, 1104), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((910, 1079), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((910, 1045), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((910, 1012), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((910, 980), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package com.jwtly10.aicontentgenerator.service.OpenAI;
import com.jwtly10.aicontentgenerator.model.Gender;
import com.theokanning.openai.OpenAiHttpException;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
@Slf4j
public class OpenAPIService {
private final OpenAiService service;
public OpenAPIService(OpenAiService service) {
this.service = service;
}
/**
* Improve content by correcting grammar mistakes
*
* @param content Content to improve
* @return Improved content
*/
public String improveContent(String content) throws OpenAiHttpException {
log.info("Improving content via OpenAPI");
String instructions = "Given the following reddit post, correct grammar mistakes. Don't alter curse words or swearing. Replace slashes and " +
"dashes with the appropriate word.Remove dashes between words like high-end. Add punctuation as necessary for smooth speech flow. Only respond " +
"with the modified (or unmodified if no changes were made) text. Do not include any other information. ";
ChatMessage responseMessage = getResponseMessage(List.of(instructions, content));
log.debug("Original content: {}", content);
log.debug("Improved content: {}", responseMessage.getContent());
log.info("Content improved successfully");
return responseMessage.getContent();
}
/**
* Determine gender from given content
*
* @param content Content to determine gender
* @return Gender of content
*/
public Gender determineGender(String content) {
log.info("Determining gender");
String instructions = "From the given text, determine the poster's gender. Use the context provided by the text. " +
"If the gender is ambiguous, reply with the most probable gender. Respond with a single letter: 'M' for Male or 'F' for Female. Again. ONLY REPLY WITH M OR F. NOTHING ELSE.";
ChatMessage responseMessage = getResponseMessage(List.of(instructions, content));
log.info("Determined gender: {}", responseMessage.getContent());
if (responseMessage.getContent().equalsIgnoreCase("M")) {
return Gender.MALE;
} else if (responseMessage.getContent().equalsIgnoreCase("F")) {
return Gender.FEMALE;
} else {
log.error("OPEN API responded with something else: '{}'. Defaulting to male", responseMessage.getContent());
return Gender.MALE;
}
}
/**
* Get response message from given messages
*
* @param messages Messages to get response from
* @return Response message
*/
private ChatMessage getResponseMessage(List<String> messages) throws OpenAiHttpException {
List<ChatMessage> chatMessages = new ArrayList<>();
for (String message : messages) {
chatMessages.add(new ChatMessage(ChatMessageRole.USER.value(), message));
}
ChatCompletionRequest completionRequest = ChatCompletionRequest.builder()
.messages(chatMessages)
.model("gpt-3.5-turbo")
.build();
return service.createChatCompletion(completionRequest).getChoices().get(0).getMessage();
}
}
| [
"com.theokanning.openai.completion.chat.ChatMessageRole.USER.value",
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((3261, 3289), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((3363, 3499), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3363, 3474), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3363, 3434), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package br.com.alura.screenmatch.service;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
public class ConsultaChatGPT {
public static String obterTraducao(String texto) {
OpenAiService service = new OpenAiService(System.getenv("OPENAI_APIKEY"));
CompletionRequest requisicao = CompletionRequest.builder()
.model("gpt-3.5-turbo-instruct")
.prompt("traduza para o português o texto: " + texto)
.maxTokens(1000)
.temperature(0.7)
.build();
var resposta = service.createCompletion(requisicao);
return resposta.getChoices().get(0).getText();
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((366, 605), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((366, 580), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((366, 546), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((366, 513), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((366, 442), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package school.sptech.zup.service;
import com.theokanning.openai.OpenAiHttpException;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import school.sptech.zup.domain.ChaveKey;
import school.sptech.zup.domain.Gpt;
import school.sptech.zup.domain.ZupLog;
import school.sptech.zup.dto.response.GptResponse;
import school.sptech.zup.repository.ChaveKeyRepository;
import school.sptech.zup.repository.ZupLogRepository;
import school.sptech.zup.util.DateUtil;
import java.time.LocalDateTime;
@Service
@RequiredArgsConstructor
public class GptService {
private final ZupLogRepository _zupLog;
private final ChaveKeyRepository _chaveKey;
private final DateUtil _dateutil;
public ChaveKey InserirChave(String idChave){
ChaveKey chave = new ChaveKey();
chave.setIdChave(idChave);
_chaveKey.save(chave);
return chave;
}
public GptResponse gptNoticia(Gpt gpt) {
GptResponse gptResponse = new GptResponse();
var buscaChave = _chaveKey.UltimaChaveInserida();
try{
OpenAiService service = new OpenAiService(buscaChave.get(0).getIdChave());
CompletionRequest request = CompletionRequest.builder()
.model("text-davinci-003")
.prompt(gpt.getTitulo() + gpt.getPergunta())
.maxTokens(1000)
.build();
gptResponse.setResposta(service.createCompletion(request).getChoices().get(0).getText());
gptResponse.setId(gpt.getId());
return gptResponse;
}
catch (OpenAiHttpException ex){
if (ex.statusCode == 401){
ZupLog log = new ZupLog();
log.setDescricao("GPT: ERRO 401, Token expirado => " + ex.getMessage());
log.setDt_entrada(
_dateutil.formLocalDate(LocalDateTime.now())
);
_zupLog.save(log);
} else if (ex.statusCode == 404) {
ZupLog log = new ZupLog();
log.setDescricao("GPT: ERRO 404 => " + ex.getMessage());
log.setDt_entrada(
_dateutil.formLocalDate(LocalDateTime.now())
);
_zupLog.save(log);
}
}
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Erro, acesse o Log!");
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((1422, 1627), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1422, 1598), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1422, 1561), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1422, 1496), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package com.challenge.challengeapi.controller;
import com.challenge.challengeapi.entity.Message;
import com.challenge.challengeapi.entity.UserIdRequest;
import com.challenge.challengeapi.service.MessageService;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin(origins = "http://127.0.0.1:5173/", maxAge = 5173)
@RestController
@RequestMapping("/hearmeout/messages")
public class MessageController {
private final MessageService messageService;
@Autowired
public MessageController(MessageService messageService) {
this.messageService = messageService;
}
@PostMapping("/send")
@CrossOrigin
public ResponseEntity<String> sendMessage(@RequestBody Message message) {
try {
messageService.sendMessage(message.getUserId(), message.getText());
OpenAiService service = new OpenAiService("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");
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt(message.getText())
.model("ada")
.build();
String response;
try {
response = service.createCompletion(completionRequest).getChoices().get(0).getText();
} catch (Exception e) {
System.err.println("Erro ao chamar a API do GPT: " + e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Erro ao chamar a API do GPT");
}
System.out.println("Resposta do GPT: " + response);
message.setResponse(response);
messageService.saveMessage(message);
// Retorna a mensagem retornada pelo GPT-3 no corpo da resposta
return ResponseEntity.ok(response);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Erro na mensagem");
}
}
@GetMapping("/history")
@CrossOrigin
public ResponseEntity<List<Message>> getMessageHistory(@RequestBody UserIdRequest request) {
try {
List<Message> history = messageService.getMessageHistory(request.getUserId());
return ResponseEntity.ok(history);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((1255, 1392), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1255, 1363), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1255, 1329), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1689, 1780), 'org.springframework.http.ResponseEntity.status'), ((2130, 2210), 'org.springframework.http.ResponseEntity.status'), ((2574, 2640), 'org.springframework.http.ResponseEntity.status')] |
package alura.api.challenge.service;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class GeraTextoDescritivoService {
@Value("${chatgpt.api.key}")
private String API_KEY;
public String geraTextoDescritivo(String destino){
OpenAiService service = new OpenAiService(API_KEY);
var pergunta = String.format(
"Gere um resumo de até 200 caracteres sobre %s enfatizanfo características do local e argumentando porque é um bom local para viajar."
, destino);
CompletionRequest request = CompletionRequest.builder()
.model("text-davinci-003")
.prompt(pergunta)
.maxTokens(500)
.build();
var response = service.createCompletion(request);
return response.getChoices().get(0).getText().replace("\n", "").trim();
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((744, 905), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((744, 880), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((744, 848), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((744, 814), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package br.com.alura.screenmatch.service;
import br.com.alura.screenmatch.config.OpenAiConfig;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.service.OpenAiService;
public class ConsultaChatGPT {
public static String obterTraducao(String texto) {
String apiKey = OpenAiConfig.getApiKey();
OpenAiService service = new OpenAiService(apiKey);
CompletionRequest requisicao = CompletionRequest.builder()
.model("gpt-3.5-turbo-instruct")
.prompt("traduza para o português o texto: " + texto)
.maxTokens(1000)
.temperature(0.7)
.build();
var resposta = service.createCompletion(requisicao);
return resposta.getChoices().get(0).getText();
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((446, 685), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((446, 660), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((446, 626), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((446, 593), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((446, 522), 'com.theokanning.openai.completion.CompletionRequest.builder')] |
package br.com.fiap.gsjava.controllers;
import br.com.fiap.gsjava.models.ChatGPT;
import br.com.fiap.gsjava.repositories.ChatGPTRepository;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Valid;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.PagedModel;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;
import org.springframework.data.domain.Pageable;
import org.slf4j.Logger;
@RestController
@RequestMapping("/chatbot")
public class ChatGPTController {
@Autowired
ChatGPTRepository repo;
@Autowired
PagedResourcesAssembler<ChatGPT> assembler;
Logger log = LoggerFactory.getLogger(ChatGPTController.class);
private static final String API_KEY = "Sua Chave da API aqui";
@GetMapping
public PagedModel<EntityModel<ChatGPT>> index(@PageableDefault(size = 5) Pageable pageable) {
return assembler.toModel(repo.findAll(pageable));
}
@GetMapping("/busca/{id}")
public EntityModel<ChatGPT> show(@PathVariable Long id) {
log.info("buscar chat com id: " + id);
ChatGPT chatGPT = repo.findById(id).orElseThrow(() ->
new ResponseStatusException(HttpStatus.NOT_FOUND, "Cliente não encontrado"));
return chatGPT.toModel();
}
@PostMapping("/api")
public ResponseEntity<ChatGPT> create(@RequestBody @Valid ChatGPT input) {
OpenAiService service = new OpenAiService(API_KEY);
CompletionRequest request = CompletionRequest.builder()
.model("text-davinci-003")
.prompt(input.getPergunta())
.maxTokens(100)
.build();
String resposta = service.createCompletion(request).getChoices().get(0).getText();
ChatGPT chatGPT = new ChatGPT(input.getPergunta(), resposta);
log.info("Saída do chatbot: " + chatGPT);
repo.save(chatGPT);
return ResponseEntity.status(HttpStatus.CREATED).body(chatGPT);
}
@DeleteMapping("/{id}")
public ResponseEntity<ChatGPT>destroy(@PathVariable Long id) {
log.info("deletar chat com o id: " + id);
ChatGPT chatgpt = repo.findById(id).orElseThrow(() ->
new ResponseStatusException(HttpStatus.NOT_FOUND, "Chat não encontrado"));;
repo.delete(chatgpt);
return ResponseEntity.noContent().build();
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<String> handleValidationExceptions(ConstraintViolationException ex) {
log.error("Erro de validação: ", ex);
return ResponseEntity.badRequest().body(ex.getMessage());
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAllExceptions(Exception ex) {
log.error("Erro não esperado: ", ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Ocorreu um erro inesperado. Tente novamente mais tarde.");
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder"
] | [((2009, 2185), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2009, 2159), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2009, 2126), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2009, 2080), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2451, 2506), 'org.springframework.http.ResponseEntity.status'), ((2871, 2905), 'org.springframework.http.ResponseEntity.noContent'), ((3182, 3231), 'org.springframework.http.ResponseEntity.badRequest'), ((3472, 3591), 'org.springframework.http.ResponseEntity.status')] |
package com.d_d.aifoodideageneratord_d.services;
import com.d_d.aifoodideageneratord_d.model.RecipeType;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.service.OpenAiService;
import java.time.Duration;
import java.util.List;
public class AiRecommendationService {
private static final String MODEL = "gpt-4-turbo-preview";
private static final String OPENAI_API_KEY_ENV = "OPENAI_API_KEY";
private final OpenAiService openAiService;
public AiRecommendationService() {
String apiToken = System.getenv(OPENAI_API_KEY_ENV);
validApiToken(apiToken);
this.openAiService = new OpenAiService(apiToken, Duration.ofSeconds(60));
}
public String getRecommendation(List<String> products, String choice) {
RecipeType recipeType = RecipeType.fromChoice(choice);
if (recipeType == null) {
throw new IllegalArgumentException("Invalid choice");
}
String question = createQuestion(products, recipeType);
ChatCompletionRequest request = buildChatCompletionRequest(question);
return getChatCompletionResult(request);
}
private String createQuestion(List<String> products, RecipeType recipeType) {
String productList = String.join(", ", products);
return String.format("I have the following products in my fridge: %s. " +
"Create a recipe using only the items in this list. " +
"You do not have to use all the products, but make sure that the recipe does not contain anything that is not on the list. " +
"Present the result in a clear, organised way, always starting with 'Recipe Title:', including the name of the recipe, a list of ingredients used including grams, preparation time, calories, step-by-step instructions. " +
"If it is not possible to make something with these products, please let me know and let the answer be in Polish..", productList, recipeType.getDescription());
}
private ChatCompletionRequest buildChatCompletionRequest(String question) {
return ChatCompletionRequest.builder()
.messages(List.of(new ChatMessage("user", question)))
.model(MODEL)
.build();
}
private String getChatCompletionResult(ChatCompletionRequest request) {
ChatCompletionResult result = openAiService.createChatCompletion(request);
return result.getChoices().stream()
.map(ChatCompletionChoice::getMessage)
.map(ChatMessage::getContent)
.findFirst()
.orElse("Failed to get a response");
}
private void validApiToken(String apiToken) {
if (apiToken == null || apiToken.isEmpty()) {
throw new IllegalArgumentException("Please set the OPENAI_API_KEY in environment variable");
}
}
}
| [
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((2320, 2476), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2320, 2451), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2320, 2421), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')] |
package io.github.asleepyfish.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
import com.knuddels.jtokkit.Encodings;
import com.knuddels.jtokkit.api.Encoding;
import com.knuddels.jtokkit.api.EncodingRegistry;
import com.knuddels.jtokkit.api.ModelType;
import com.theokanning.openai.DeleteResult;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionChunk;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.edit.EditRequest;
import com.theokanning.openai.edit.EditResult;
import com.theokanning.openai.embedding.EmbeddingRequest;
import com.theokanning.openai.embedding.EmbeddingResult;
import com.theokanning.openai.finetune.FineTuneEvent;
import com.theokanning.openai.finetune.FineTuneRequest;
import com.theokanning.openai.finetune.FineTuneResult;
import com.theokanning.openai.image.Image;
import com.theokanning.openai.image.*;
import com.theokanning.openai.moderation.ModerationRequest;
import com.theokanning.openai.moderation.ModerationResult;
import io.github.asleepyfish.client.OpenAiApi;
import io.github.asleepyfish.config.ChatGPTProperties;
import io.github.asleepyfish.entity.audio.TranscriptionRequest;
import io.github.asleepyfish.entity.audio.TranslationRequest;
import io.github.asleepyfish.entity.billing.Billing;
import io.github.asleepyfish.entity.billing.Subscription;
import io.github.asleepyfish.enums.audio.AudioModelEnum;
import io.github.asleepyfish.enums.audio.AudioResponseFormatEnum;
import io.github.asleepyfish.enums.chat.FinishReasonEnum;
import io.github.asleepyfish.enums.chat.RoleEnum;
import io.github.asleepyfish.enums.edit.EditModelEnum;
import io.github.asleepyfish.enums.embedding.EmbeddingModelEnum;
import io.github.asleepyfish.enums.exception.ChatGPTErrorEnum;
import io.github.asleepyfish.enums.image.ImageResponseFormatEnum;
import io.github.asleepyfish.enums.image.ImageSizeEnum;
import io.github.asleepyfish.enums.model.ModelEnum;
import io.github.asleepyfish.exception.ChatGPTException;
import io.github.asleepyfish.service.openai.OpenAiService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.util.CollectionUtils;
import retrofit2.Retrofit;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ComponentColorModel;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @Author: asleepyfish
* @Date: 2023/3/3 14:00
* @Description: OpenAiProxyService
*/
@Slf4j
public class OpenAiProxyService extends OpenAiService {
private final Random random = new Random();
private final ChatGPTProperties chatGPTProperties;
private final OkHttpClient client;
private Cache<String, LinkedList<ChatMessage>> cache;
private static final EncodingRegistry REGISTRY = Encodings.newDefaultEncodingRegistry();
public OpenAiProxyService(ChatGPTProperties chatGPTProperties) {
this(chatGPTProperties, Duration.ZERO);
}
public OpenAiProxyService(ChatGPTProperties chatGPTProperties, OkHttpClient okHttpClient) {
this(chatGPTProperties, Duration.ZERO, okHttpClient);
}
public OpenAiProxyService(ChatGPTProperties chatGPTProperties, Duration timeout) {
super(buildApi(chatGPTProperties, timeout, null), defaultClient(chatGPTProperties, timeout).dispatcher().executorService(), chatGPTProperties.getBaseUrl());
this.chatGPTProperties = chatGPTProperties;
this.cache = chatGPTProperties.getSessionExpirationTime() == null ? CacheBuilder.newBuilder().build() :
CacheBuilder.newBuilder().expireAfterAccess(chatGPTProperties.getSessionExpirationTime(), TimeUnit.MINUTES).build();
this.client = OpenAiProxyService.defaultClient(chatGPTProperties, timeout);
}
public OpenAiProxyService(ChatGPTProperties chatGPTProperties, Duration timeout, OkHttpClient client) {
super(buildApi(chatGPTProperties, timeout, client), client.dispatcher().executorService(), chatGPTProperties.getBaseUrl());
this.chatGPTProperties = chatGPTProperties;
this.cache = chatGPTProperties.getSessionExpirationTime() == null ? CacheBuilder.newBuilder().build() :
CacheBuilder.newBuilder().expireAfterAccess(chatGPTProperties.getSessionExpirationTime(), TimeUnit.MINUTES).build();
this.client = client;
}
public static OpenAiApi buildApi(ChatGPTProperties properties, Duration timeout, OkHttpClient okHttpClient) {
ObjectMapper mapper = defaultObjectMapper();
OkHttpClient client = okHttpClient == null ? defaultClient(properties, timeout) : okHttpClient;
Retrofit retrofit = defaultRetrofit(client, mapper, properties.getBaseUrl());
return retrofit.create(OpenAiApi.class);
}
public static OkHttpClient defaultClient(ChatGPTProperties properties, Duration timeout) {
if (Strings.isNullOrEmpty(properties.getProxyHost())) {
return OpenAiService.defaultClient(properties, timeout);
}
// Create proxy object
Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(properties.getProxyHost(), properties.getProxyPort()));
return OpenAiService.defaultClient(properties, timeout).newBuilder()
.proxy(proxy)
.build();
}
/**
* createStreamChatCompletion
*
* @param content content
*/
public void createStreamChatCompletion(String content) {
createStreamChatCompletion(content, "DEFAULT USER", System.out);
}
/**
* createStreamChatCompletion
*
* @param content content
* @param os os
*/
public void createStreamChatCompletion(String content, OutputStream os) {
createStreamChatCompletion(content, "DEFAULT USER", os);
}
/**
* createStreamChatCompletion
*
* @param content content
* @param user user
* @param os os
*/
public void createStreamChatCompletion(String content, String user, OutputStream os) {
createStreamChatCompletion(content, user, chatGPTProperties.getChatModel(), os);
}
/**
* createStreamChatCompletion
*
* @param content content
* @param user user
* @param model model
* @param os os
*/
public void createStreamChatCompletion(String content, String user, String model, OutputStream os) {
createStreamChatCompletion(RoleEnum.USER.getRoleName(), content, user, model, 1.0D, 1.0D, os);
}
/**
* createStreamChatCompletion
*
* @param role role
* @param content content
* @param user user
* @param model model
* @param temperature temperature
* @param topP topP
* @param os os
*/
public void createStreamChatCompletion(String role, String content, String user, String model, Double temperature, Double topP, OutputStream os) {
createStreamChatCompletion(ChatCompletionRequest.builder()
.model(model)
.messages(Collections.singletonList(new ChatMessage(role, content)))
.user(user)
.temperature(temperature)
.topP(topP)
.stream(true)
.build(), os);
}
/**
* createStreamChatCompletion
*
* @param chatCompletionRequest chatCompletionRequest
* @param os os
*/
public void createStreamChatCompletion(ChatCompletionRequest chatCompletionRequest, OutputStream os) {
chatCompletionRequest.setStream(true);
chatCompletionRequest.setN(1);
String user = chatCompletionRequest.getUser();
LinkedList<ChatMessage> contextInfo = new LinkedList<>();
try {
contextInfo = cache.get(user, LinkedList::new);
} catch (ExecutionException e) {
e.printStackTrace();
}
// if the contextInfo is empty, add system prompt
addSystemPrompt(contextInfo);
contextInfo.addAll(chatCompletionRequest.getMessages());
chatCompletionRequest.setMessages(contextInfo);
List<ChatCompletionChunk> chunks = new ArrayList<>();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
// avoid frequently request, random sleep 0.5s~0.7s
if (i > 0) {
randomSleep();
}
super.streamChatCompletion(chatCompletionRequest).doOnError(Throwable::printStackTrace).blockingForEach(chunk -> {
chunk.getChoices().stream().map(choice -> choice.getMessage().getContent())
.filter(Objects::nonNull).findFirst().ifPresent(o -> {
try {
os.write(o.getBytes(Charset.defaultCharset()));
os.flush();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
chunks.add(chunk);
});
os.close();
// if the last line code is correct, we can simply break the circle
break;
} catch (Exception e) {
String message = e.getMessage();
boolean overload = checkTokenUsage(message);
if (overload) {
int size = Objects.requireNonNull(cache.getIfPresent(user)).size();
Iterator<ChatMessage> iterator = Objects.requireNonNull(cache.getIfPresent(user)).iterator();
for (int j = 0; j < size / 2; j++) {
ChatMessage chatMessage = iterator.next();
if (!RoleEnum.SYSTEM.getRoleName().equals(chatMessage.getRole())) {
iterator.remove();
}
}
chatCompletionRequest.setMessages(cache.getIfPresent(user));
}
log.info("answer failed " + (i + 1) + " times, the error message is: " + message);
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
// when the call fails, remove the last item in the list
Objects.requireNonNull(cache.getIfPresent(user)).removeLast();
throw new ChatGPTException(ChatGPTErrorEnum.FAILED_TO_GENERATE_ANSWER, message);
}
}
}
LinkedList<ChatMessage> chatMessages = new LinkedList<>();
try {
chatMessages = cache.get(user, LinkedList::new);
} catch (ExecutionException e) {
e.printStackTrace();
}
chatMessages.add(new ChatMessage(RoleEnum.ASSISTANT.getRoleName(), chunks.stream()
.flatMap(chunk -> chunk.getChoices().stream())
.map(ChatCompletionChoice::getMessage)
.map(ChatMessage::getContent)
.filter(Objects::nonNull)
.collect(Collectors.joining())));
}
/**
* chatCompletion
*
* @param content content
* @return List
*/
public List<String> chatCompletion(String content) {
return chatCompletion(content, "DEFAULT USER");
}
/**
* chatCompletion
*
* @param content content
* @param user user
* @return List
*/
public List<String> chatCompletion(String content, String user) {
return chatCompletion(content, user, chatGPTProperties.getChatModel());
}
/**
* chatCompletion
*
* @param content content
* @param user user
* @param model model
* @return List
*/
public List<String> chatCompletion(String content, String user, String model) {
return chatCompletion(RoleEnum.USER.getRoleName(), content, user, model, 1.0D, 1.0D);
}
/**
* chatCompletion
*
* @param role role
* @param content content
* @param user user
* @param model model
* @param temperature temperature
* @param topP topP
* @return List
*/
public List<String> chatCompletion(String role, String content, String user, String model, Double temperature, Double topP) {
return chatCompletion(ChatCompletionRequest.builder()
.model(model)
.messages(Collections.singletonList(new ChatMessage(role, content)))
.user(user)
.temperature(temperature)
.topP(topP)
.build());
}
/**
* chatCompletion
*
* @param chatCompletionRequest chatCompletionRequest
* @return List
*/
public List<String> chatCompletion(ChatCompletionRequest chatCompletionRequest) {
String user = chatCompletionRequest.getUser();
LinkedList<ChatMessage> contextInfo = new LinkedList<>();
try {
contextInfo = cache.get(user, LinkedList::new);
} catch (ExecutionException e) {
e.printStackTrace();
}
addSystemPrompt(contextInfo);
contextInfo.addAll(chatCompletionRequest.getMessages());
chatCompletionRequest.setMessages(contextInfo);
List<ChatCompletionChoice> choices = new ArrayList<>();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
// avoid frequently request, random sleep 0.5s~0.7s
if (i > 0) {
randomSleep();
}
choices = super.createChatCompletion(chatCompletionRequest).getChoices();
// if the last line code is correct, we can simply break the circle
break;
} catch (Exception e) {
String message = e.getMessage();
boolean overload = checkTokenUsage(message);
if (overload) {
int size = Objects.requireNonNull(cache.getIfPresent(user)).size();
Iterator<ChatMessage> iterator = Objects.requireNonNull(cache.getIfPresent(user)).iterator();
for (int j = 0; j < size / 2; j++) {
ChatMessage chatMessage = iterator.next();
if (!RoleEnum.SYSTEM.getRoleName().equals(chatMessage.getRole())) {
iterator.remove();
}
}
chatCompletionRequest.setMessages(cache.getIfPresent(user));
}
log.info("answer failed " + (i + 1) + " times, the error message is: " + message);
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
// when the call fails, remove the last item in the list
Objects.requireNonNull(cache.getIfPresent(user)).removeLast();
throw new ChatGPTException(ChatGPTErrorEnum.FAILED_TO_GENERATE_ANSWER, message);
}
}
}
List<String> results = new ArrayList<>();
LinkedList<ChatMessage> chatMessages = new LinkedList<>();
try {
chatMessages = cache.get(user, LinkedList::new);
} catch (ExecutionException e) {
e.printStackTrace();
}
for (ChatCompletionChoice choice : choices) {
String text = choice.getMessage().getContent();
results.add(text);
if (FinishReasonEnum.LENGTH.getMessage().equals(choice.getFinishReason())) {
results.add("答案过长,请输入继续~");
}
chatMessages.add(choice.getMessage());
}
return results;
}
/**
* please use ChatCompletion instead
*
* @param prompt prompt
* @return List<String>
*/
@Deprecated
public List<String> completion(String prompt) {
return completion(prompt, "DEFAULT USER");
}
@Deprecated
public List<String> completion(String prompt, String user) {
return completion(prompt, user, chatGPTProperties.getModel());
}
@Deprecated
public List<String> completion(String prompt, String user, String model) {
return completion(prompt, user, model, 0D, 1D);
}
@Deprecated
public List<String> completion(String prompt, String user, String model, Double temperature, Double topP) {
return completion(CompletionRequest.builder()
.model(model)
.prompt(prompt)
.user(user)
.temperature(temperature)
.topP(topP)
.maxTokens(ModelEnum.getMaxTokens(model))
.build());
}
@Deprecated
public List<String> completion(CompletionRequest completionRequest) {
List<CompletionChoice> choices = new ArrayList<>();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
// avoid frequently request, random sleep 0.5s~0.7s
if (i > 0) {
randomSleep();
}
choices = super.createCompletion(completionRequest).getChoices();
// if the last line code is correct, we can simply break the circle
break;
} catch (Exception e) {
log.info("answer failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.FAILED_TO_GENERATE_ANSWER, e.getMessage());
}
}
}
List<String> results = new ArrayList<>();
choices.forEach(choice -> {
String text = choice.getText();
if (FinishReasonEnum.LENGTH.getMessage().equals(choice.getFinish_reason())) {
text = text + System.lineSeparator() + "The answer is too long, Please disassemble the above problems into several minor problems.";
}
results.add(text);
});
return results;
}
/**
* createImages
*
* @param prompt prompt
* @return List
*/
public List<String> createImages(String prompt) {
return createImages(prompt, "DEFAULT USER");
}
/**
* createImages
*
* @param prompt prompt
* @param user user
* @return List
*/
public List<String> createImages(String prompt, String user) {
return createImages(prompt, user, ImageResponseFormatEnum.URL);
}
/**
* createImages
*
* @param prompt prompt
* @param user user
* @param responseFormat responseFormat
* @return List
*/
public List<String> createImages(String prompt, String user, ImageResponseFormatEnum responseFormat) {
ImageResult imageResult = createImages(CreateImageRequest.builder()
.prompt(prompt)
.user(user)
.responseFormat(responseFormat.getResponseFormat())
.build());
String format = responseFormat.getResponseFormat();
return imageResult.getData().stream().map(image -> format == null ||
ImageResponseFormatEnum.URL.getResponseFormat().equals(format) ?
image.getUrl() : image.getB64Json()).collect(Collectors.toList());
}
/**
* createImages
*
* @param prompt prompt
* @param user user
* @param responseFormat responseFormat
* @param imageSizeEnum imageSizeEnum
* @return List
*/
public List<String> createImages(String prompt, String user, ImageResponseFormatEnum responseFormat, ImageSizeEnum imageSizeEnum) {
ImageResult imageResult = createImages(CreateImageRequest.builder()
.prompt(prompt)
.user(user)
.responseFormat(responseFormat.getResponseFormat())
.size(imageSizeEnum.getSize())
.build());
String format = responseFormat.getResponseFormat();
return imageResult.getData().stream().map(image -> format == null ||
ImageResponseFormatEnum.URL.getResponseFormat().equals(format) ?
image.getUrl() : image.getB64Json()).collect(Collectors.toList());
}
/**
* createImages
*
* @param createImageRequest createImageRequest
* @return ImageResult
*/
public ImageResult createImages(CreateImageRequest createImageRequest) {
ImageResult imageResult = new ImageResult();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
imageResult = super.createImage(createImageRequest);
break;
} catch (Exception e) {
log.info("image generate failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.FAILED_TO_GENERATE_IMAGE, e.getMessage());
}
}
}
return imageResult;
}
/**
* downloadImage
*
* @param prompt prompt
* @param os os
*/
public void downloadImage(String prompt, OutputStream os) {
downloadImage(prompt, ImageSizeEnum.S1024x1024.getSize(), os);
}
/**
* downloadImage
*
* @param prompt prompt
* @param n n
* @param os os
*/
public void downloadImage(String prompt, Integer n, OutputStream os) {
downloadImage(prompt, n, ImageSizeEnum.S1024x1024.getSize(), os);
}
/**
* downloadImage
*
* @param prompt prompt
* @param size size
* @param os os
*/
public void downloadImage(String prompt, String size, OutputStream os) {
downloadImage(prompt, 1, size, os);
}
/**
* downloadImage
*
* @param prompt prompt
* @param n size
* @param size size
* @param os os
*/
public void downloadImage(String prompt, Integer n, String size, OutputStream os) {
downloadImage(CreateImageRequest.builder()
.prompt(prompt)
.n(n)
.size(size)
.user("DEFAULT USER").build(), os);
}
/**
* downloadImage
*
* @param createImageRequest createImageRequest
* @param os os
*/
public void downloadImage(CreateImageRequest createImageRequest, OutputStream os) {
createImageRequest.setResponseFormat(ImageResponseFormatEnum.B64_JSON.getResponseFormat());
if (!ImageResponseFormatEnum.B64_JSON.getResponseFormat().equals(createImageRequest.getResponseFormat())) {
throw new ChatGPTException(ChatGPTErrorEnum.ERROR_RESPONSE_FORMAT);
}
List<String> imageList = createImages(createImageRequest).getData().stream()
.map(Image::getB64Json).collect(Collectors.toList());
try {
if (imageList.size() == 1) {
BufferedImage bufferedImage = getImageFromBase64(imageList.get(0));
ImageIO.write(bufferedImage, "png", os);
} else {
try (ZipOutputStream zipOut = new ZipOutputStream(os)) {
for (int i = 0; i < imageList.size(); i++) {
BufferedImage bufferedImage = getImageFromBase64(imageList.get(i));
ZipEntry zipEntry = new ZipEntry("image" + (i + 1) + ".png");
zipOut.putNextEntry(zipEntry);
ImageIO.write(bufferedImage, "png", zipOut);
zipOut.closeEntry();
}
}
}
} catch (Exception e) {
throw new ChatGPTException(ChatGPTErrorEnum.DOWNLOAD_IMAGE_ERROR);
}
}
/**
* Get Bill Since startDate
*
* @param startDate startDate (yyyy-MM-dd)
* @return bill
*/
@Deprecated
public String billingUsage(String... startDate) {
String start = startDate.length == 0 ? "2023-01-01" : startDate[0];
BigDecimal totalUsage = BigDecimal.ZERO;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
try {
LocalDate endDate = LocalDate.now();
// the max query bills scope up to 100 days. The interval for each query is defined as 3 months.
Period threeMonth = Period.ofMonths(3);
LocalDate nextDate = LocalDate.parse(start, formatter);
while (nextDate.isBefore(endDate)) {
String left = nextDate.format(formatter);
nextDate = nextDate.plus(threeMonth);
String right = nextDate.format(formatter);
totalUsage = totalUsage.add(new BigDecimal(billingUsage(left, right)));
}
} catch (Exception e) {
e.printStackTrace();
}
return totalUsage.toPlainString();
}
/**
* You can query bills for up to 100 days at a time.
*
* @param startDate startDate (yyyy-MM-dd)
* @param endDate endDate (yyyy-MM-dd)
* @return Unit: (USD)
*/
@Deprecated
public String billingUsage(@NonNull String startDate, @NonNull String endDate) {
String billingUsage = "0";
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
String cents = execute(api.billingUsage(startDate, endDate)).getTotalUsage();
billingUsage = new BigDecimal(cents).divide(new BigDecimal("100")).toPlainString();
break;
} catch (Exception e) {
log.info("query billingUsage failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.QUERY_BILLINGUSAGE_ERROR, e.getMessage());
}
}
}
return billingUsage;
}
/**
* You can query all the available billing for a given date range.
*
* @param startDate startDate
* @return billing
*/
@Deprecated
public Billing billing(String... startDate) {
String start = startDate.length == 0 ? "2023-01-01" : startDate[0];
Subscription subscription = subscription();
String usage = billingUsage(start);
String dueDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date(subscription.getAccessUntil() * 1000));
String total = subscription.getSystemHardLimitUsd();
Billing billing = new Billing();
billing.setDueDate(dueDate);
billing.setTotal(total);
billing.setUsage(usage);
billing.setBalance(new BigDecimal(total).subtract(new BigDecimal(usage)).toPlainString());
return billing;
}
/**
* Obtain subscription information
*
* @return subscription information
*/
public Subscription subscription() {
Subscription subscription = null;
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
subscription = execute(api.subscription());
break;
} catch (Exception e) {
log.info("query billingUsage failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.QUERY_BILLINGUSAGE_ERROR, e.getMessage());
}
}
}
return subscription;
}
/**
* Edit
*
* @param input input
* @param instruction instruction
* @return {@link String}
*/
public String edit(String input, String instruction) {
return edit(input, instruction, EditModelEnum.TEXT_DAVINCI_EDIT_001);
}
/**
* Edit
*
* @param input input
* @param instruction instruction
* @param editModelEnum editModelEnum
* @return {@link String}
*/
public String edit(String input, String instruction, EditModelEnum editModelEnum) {
return edit(input, instruction, 1D, 1D, editModelEnum);
}
/**
* Edit
*
* @param input input
* @param instruction instruction
* @param temperature temperature
* @param topP topP
* @param editModelEnum editModelEnum
* @return {@link String}
*/
public String edit(String input, String instruction, Double temperature, Double topP, EditModelEnum editModelEnum) {
EditResult editResult = edit(EditRequest.builder()
.model(editModelEnum.getModelName())
.input(input)
.instruction(instruction)
.temperature(temperature)
.topP(topP)
.build());
List<String> results = Lists.newArrayList();
editResult.getChoices().forEach(choice -> results.add(choice.getText()));
return results.get(0);
}
/**
* edit
*
* @param editRequest editRequest
* @return results
*/
public EditResult edit(EditRequest editRequest) {
EditResult editResult = new EditResult();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
editResult = super.createEdit(editRequest);
break;
} catch (Exception e) {
log.info("edit failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.EDIT_ERROR, e.getMessage());
}
}
}
return editResult;
}
/**
* embeddings
*
* @param input input
* @return results
*/
public List<Double> embeddings(String input) {
return embeddings(input, EmbeddingModelEnum.TEXT_EMBEDDING_ADA_002);
}
/**
* embeddings
*
* @param input input
* @param embeddingModelEnum embeddingModelEnum
* @return results
*/
public List<Double> embeddings(String input, EmbeddingModelEnum embeddingModelEnum) {
return embeddings(EmbeddingRequest.builder()
.input(Collections.singletonList(input))
.model(embeddingModelEnum.getModelName())
.build()).getData().get(0).getEmbedding();
}
/**
* edit
*
* @param embeddingRequest embeddingRequest
* @return results
*/
public EmbeddingResult embeddings(EmbeddingRequest embeddingRequest) {
EmbeddingResult embeddingResult = new EmbeddingResult();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
embeddingResult = super.createEmbeddings(embeddingRequest);
} catch (Exception e) {
log.info("embeddings failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.EMBEDDINGS_ERROR, e.getMessage());
}
}
}
return embeddingResult;
}
/**
* Transcribes audio into the input language.
*
* @param filePath filePath
* @param audioResponseFormatEnum audioResponseFormatEnum
* @return text
*/
public String transcription(String filePath, AudioResponseFormatEnum audioResponseFormatEnum) {
File file = new File(filePath);
return transcription(file, audioResponseFormatEnum);
}
/**
* Transcribes audio into the input language.
*
* @param file file
* @param audioResponseFormatEnum audioResponseFormatEnum
* @return text
*/
public String transcription(File file, AudioResponseFormatEnum audioResponseFormatEnum) {
TranscriptionRequest transcriptionRequest = TranscriptionRequest.builder()
.file(file).model(AudioModelEnum.WHISPER_1.getModelName())
.responseFormat(audioResponseFormatEnum.getFormat()).build();
return transcription(transcriptionRequest);
}
/**
* Transcribes audio into the input language.
*
* @param transcriptionRequest transcriptionRequest
* @return text
*/
public String transcription(TranscriptionRequest transcriptionRequest) {
// Create Request Body
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("model", transcriptionRequest.getModel())
.addFormDataPart("file", transcriptionRequest.getFile().getName(),
RequestBody.Companion.create(transcriptionRequest.getFile(), MediaType.parse("application/octet-stream")));
if (transcriptionRequest.getPrompt() != null) {
builder.addFormDataPart("prompt", transcriptionRequest.getPrompt());
}
if (transcriptionRequest.getResponseFormat() != null) {
builder.addFormDataPart("response_format", transcriptionRequest.getResponseFormat());
}
if (transcriptionRequest.getTemperature() != null) {
builder.addFormDataPart("temperature", String.valueOf(transcriptionRequest.getTemperature()));
}
if (transcriptionRequest.getLanguage() != null) {
builder.addFormDataPart("language", transcriptionRequest.getLanguage());
}
RequestBody requestBody = builder.build();
Request request = new Request.Builder()
.post(requestBody)
.url(baseUrl + "v1/audio/transcriptions")
.build();
String text = null;
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try (Response response = client.newCall(request).execute()) {
if (i > 0) {
randomSleep();
}
text = response.body().string();
break;
} catch (Exception e) {
log.info("transcription failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.TRANSCRIPTION_ERROR, e.getMessage());
}
}
}
return text;
}
/**
* Translates audio into English.
*
* @param filePath filePath
* @param audioResponseFormatEnum audioResponseFormatEnum
* @return text
*/
public String translation(String filePath, AudioResponseFormatEnum audioResponseFormatEnum) {
File file = new File(filePath);
return translation(file, audioResponseFormatEnum);
}
/**
* Translates audio into English.
*
* @param file file
* @param audioResponseFormatEnum audioResponseFormatEnum
* @return text
*/
public String translation(File file, AudioResponseFormatEnum audioResponseFormatEnum) {
TranslationRequest translationRequest = TranslationRequest.builder()
.file(file).model(AudioModelEnum.WHISPER_1.getModelName())
.responseFormat(audioResponseFormatEnum.getFormat()).build();
return translation(translationRequest);
}
/**
* Translates audio into English.
*
* @param translationRequest translationRequest
* @return text
*/
public String translation(TranslationRequest translationRequest) {
// Create Request Body
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("model", translationRequest.getModel())
.addFormDataPart("file", translationRequest.getFile().getName(),
RequestBody.Companion.create(translationRequest.getFile(), MediaType.parse("application/octet-stream")));
if (translationRequest.getPrompt() != null) {
builder.addFormDataPart("prompt", translationRequest.getPrompt());
}
if (translationRequest.getResponseFormat() != null) {
builder.addFormDataPart("response_format", translationRequest.getResponseFormat());
}
if (translationRequest.getTemperature() != null) {
builder.addFormDataPart("temperature", String.valueOf(translationRequest.getTemperature()));
}
RequestBody requestBody = builder.build();
Request request = new Request.Builder()
.post(requestBody)
.url(baseUrl + "v1/audio/translations")
.build();
String text = null;
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try (Response response = client.newCall(request).execute()) {
if (i > 0) {
randomSleep();
}
text = response.body().string();
break;
} catch (Exception e) {
log.info("translation failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.TRANSLATION_ERROR, e.getMessage());
}
}
}
return text;
}
/**
* create Image Edit
*
* @param createImageEditRequest createImageEditRequest
* @param imagePath imagePath
* @param maskPath maskPath
* @return imageResult
*/
public ImageResult createImageEdit(CreateImageEditRequest createImageEditRequest, String imagePath, String maskPath) {
File image = new File(imagePath);
File mask = null;
if (maskPath != null) {
mask = new File(maskPath);
}
return createImageEdit(createImageEditRequest, image, mask);
}
/**
* create Image Edit
*
* @param createImageEditRequest createImageEditRequest
* @param image image
* @param mask mask
* @return imageResult
*/
public ImageResult createImageEdit(CreateImageEditRequest createImageEditRequest, File image, File mask) {
try {
convertColorFormats(image);
if (mask != null) {
convertColorFormats(mask);
}
} catch (Exception e) {
log.error(e.getMessage());
}
// Create Request Body
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("prompt", createImageEditRequest.getPrompt())
.addFormDataPart("image", image.getName(),
RequestBody.Companion.create(image, MediaType.parse("application/octet-stream")));
if (mask != null) {
builder.addFormDataPart("mask", mask.getName(),
RequestBody.Companion.create(mask, MediaType.parse("application/octet-stream")));
}
if (createImageEditRequest.getN() != null) {
builder.addFormDataPart("n", String.valueOf(createImageEditRequest.getN()));
}
if (createImageEditRequest.getResponseFormat() != null) {
builder.addFormDataPart("response_format", createImageEditRequest.getResponseFormat());
}
if (createImageEditRequest.getSize() != null) {
builder.addFormDataPart("size", createImageEditRequest.getSize());
}
if (createImageEditRequest.getUser() != null) {
builder.addFormDataPart("user", createImageEditRequest.getUser());
}
ImageResult imageResult = new ImageResult();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
imageResult = execute(api.createImageEdit(builder.build()));
break;
} catch (Exception e) {
log.info("create image edit failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.CREATE_IMAGE_EDIT_ERROR, e.getMessage());
}
}
}
return imageResult;
}
/**
* create Image Edit
*
* @param createImageVariationRequest createImageVariationRequest
* @param imagePath imagePath
* @return imageResult
*/
public ImageResult createImageVariation(CreateImageVariationRequest createImageVariationRequest, String imagePath) {
File image = new File(imagePath);
return createImageVariation(createImageVariationRequest, image);
}
/**
* create Image Variation
*
* @param createImageVariationRequest createImageVariationRequest
* @param image image
* @return imageResult
*/
public ImageResult createImageVariation(CreateImageVariationRequest createImageVariationRequest, File image) {
try {
convertColorFormats(image);
} catch (Exception e) {
log.error(e.getMessage());
}
// Create Request Body
MultipartBody.Builder builder = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image", image.getName(),
RequestBody.Companion.create(image, MediaType.parse("application/octet-stream")));
if (createImageVariationRequest.getN() != null) {
builder.addFormDataPart("n", String.valueOf(createImageVariationRequest.getN()));
}
if (createImageVariationRequest.getResponseFormat() != null) {
builder.addFormDataPart("response_format", createImageVariationRequest.getResponseFormat());
}
if (createImageVariationRequest.getSize() != null) {
builder.addFormDataPart("size", createImageVariationRequest.getSize());
}
if (createImageVariationRequest.getUser() != null) {
builder.addFormDataPart("user", createImageVariationRequest.getUser());
}
ImageResult imageResult = new ImageResult();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
imageResult = execute(api.createImageVariation(builder.build()));
break;
} catch (Exception e) {
log.info("create image variation failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.CREATE_IMAGE_VARIATION_ERROR, e.getMessage());
}
}
}
return imageResult;
}
/**
* list files
*
* @return files
*/
public List<com.theokanning.openai.file.File> listFiles() {
List<com.theokanning.openai.file.File> files = new ArrayList<>();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
files = super.listFiles();
break;
} catch (Exception e) {
log.info("list files failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.LIST_FILES_ERROR, e.getMessage());
}
}
}
return files;
}
/**
* upload file
*
* @param purpose purpose
* @param filepath filepath
* @return file
*/
public com.theokanning.openai.file.File uploadFile(@NonNull String purpose, @NonNull String filepath) {
com.theokanning.openai.file.File file = null;
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
file = super.uploadFile(purpose, filepath);
break;
} catch (Exception e) {
log.info("upload file failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.UPLOAD_FILE_ERROR, e.getMessage());
}
}
}
return file;
}
/**
* delete file
*
* @param fileId fileId
* @return deleteResult
*/
public DeleteResult deleteFile(@NonNull String fileId) {
DeleteResult deleteResult = null;
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
deleteResult = super.deleteFile(fileId);
break;
} catch (Exception e) {
log.info("delete file failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.DELETE_FILE_ERROR, e.getMessage());
}
}
}
return deleteResult;
}
/**
* retrieve file
*
* @param fileId fileId
* @return file
*/
public com.theokanning.openai.file.File retrieveFile(@NonNull String fileId) {
com.theokanning.openai.file.File file = null;
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
file = super.retrieveFile(fileId);
break;
} catch (Exception e) {
log.info("retrieve file failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.RETRIEVE_FILE_ERROR, e.getMessage());
}
}
}
return file;
}
/**
* retrieve file content
*
* @param fileId fileId
* @return file content
*/
public String retrieveFileContent(@NonNull String fileId) {
Request request = new Request.Builder()
.url(baseUrl + "v1/files/{" + fileId + "}/content")
.build();
String fileContent = null;
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try (Response response = client.newCall(request).execute()) {
if (i > 0) {
randomSleep();
}
fileContent = response.body().string();
break;
} catch (Exception e) {
log.info("retrieve file content failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.RETRIEVE_FILE_CONTENT_ERROR, e.getMessage());
}
}
}
return fileContent;
}
/**
* list fine-tunes
*
* @param fineTuneRequest fineTuneRequest
* @return fineTunes
*/
public FineTuneResult createFineTune(FineTuneRequest fineTuneRequest) {
FineTuneResult fineTuneResult = new FineTuneResult();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
fineTuneResult = super.createFineTune(fineTuneRequest);
break;
} catch (Exception e) {
log.info("create fine tune failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.CREATE_FINE_TUNE_ERROR, e.getMessage());
}
}
}
return fineTuneResult;
}
/**
* createFineTuneCompletion
*
* @param completionRequest completionRequest
* @return completionResult
*/
public CompletionResult createFineTuneCompletion(CompletionRequest completionRequest) {
CompletionResult completionResult = new CompletionResult();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
completionResult = super.createFineTuneCompletion(completionRequest);
break;
} catch (Exception e) {
log.info("create fine tune completion failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.CREATE_FINE_TUNE_COMPLETION_ERROR, e.getMessage());
}
}
}
return completionResult;
}
/**
* list fine-tunes
*
* @return fineTunes
*/
public List<FineTuneResult> listFineTunes() {
List<FineTuneResult> fineTunes = new ArrayList<>();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
fineTunes = super.listFineTunes();
break;
} catch (Exception e) {
log.info("list fine tunes failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.LIST_FINE_TUNES_ERROR, e.getMessage());
}
}
}
return fineTunes;
}
/**
* retrieve fine-tune
*
* @param fineTuneId fineTuneId
* @return fineTune
*/
public FineTuneResult retrieveFineTune(String fineTuneId) {
FineTuneResult fineTuneResult = new FineTuneResult();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
fineTuneResult = super.retrieveFineTune(fineTuneId);
break;
} catch (Exception e) {
log.info("retrieve fine tune failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.RETRIEVE_FINE_TUNE_ERROR, e.getMessage());
}
}
}
return fineTuneResult;
}
/**
* cancel fine-tune
*
* @param fineTuneId fineTuneId
* @return fineTune
*/
public FineTuneResult cancelFineTune(String fineTuneId) {
FineTuneResult fineTuneResult = new FineTuneResult();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
fineTuneResult = super.cancelFineTune(fineTuneId);
break;
} catch (Exception e) {
log.info("cancel fine tune failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.CANCEL_FINE_TUNE_ERROR, e.getMessage());
}
}
}
return fineTuneResult;
}
/**
* list fine-tune events
*
* @param fineTuneId fineTuneId
* @return fineTuneEvents
*/
public List<FineTuneEvent> listFineTuneEvents(String fineTuneId) {
List<FineTuneEvent> fineTuneEvents = new ArrayList<>();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
fineTuneEvents = super.listFineTuneEvents(fineTuneId);
break;
} catch (Exception e) {
log.info("list fine tune events failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.LIST_FINE_TUNE_EVENTS_ERROR, e.getMessage());
}
}
}
return fineTuneEvents;
}
/**
* delete fine-tune
*
* @param fineTuneId fineTuneId
* @return deleteResult
*/
public DeleteResult deleteFineTune(String fineTuneId) {
DeleteResult deleteResult = new DeleteResult();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
deleteResult = super.deleteFineTune(fineTuneId);
break;
} catch (Exception e) {
log.info("delete fine tune failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.DELETE_FINE_TUNE_ERROR, e.getMessage());
}
}
}
return deleteResult;
}
/**
* create moderation
*
* @param moderationRequest moderationRequest
* @return moderationResult
*/
public ModerationResult createModeration(ModerationRequest moderationRequest) {
ModerationResult moderationResult = new ModerationResult();
for (int i = 0; i < chatGPTProperties.getRetries(); i++) {
try {
if (i > 0) {
randomSleep();
}
moderationResult = super.createModeration(moderationRequest);
break;
} catch (Exception e) {
log.info("create moderation failed " + (i + 1) + " times, the error message is: " + e.getMessage());
if (i == chatGPTProperties.getRetries() - 1) {
e.printStackTrace();
throw new ChatGPTException(ChatGPTErrorEnum.CREATE_MODERATION_ERROR, e.getMessage());
}
}
}
return moderationResult;
}
/**
* force clear cache
*
* @param cacheName cacheName
*/
public void forceClearCache(String cacheName) {
this.cache.invalidate(cacheName);
}
/**
* retrieveCache
*
* @return cache
*/
public Cache<String, LinkedList<ChatMessage>> retrieveCache() {
return this.cache;
}
/**
* retrieveChatMessage
*
* @param key key
* @return chatMessage
*/
public LinkedList<ChatMessage> retrieveChatMessage(String key) {
return this.cache.getIfPresent(key);
}
/**
* setCache
*
* @param cache cache
*/
public void setCache(Cache<String, LinkedList<ChatMessage>> cache) {
String systemPrompt = getSystemPrompt();
if (Strings.isNullOrEmpty(getSystemPrompt())) {
this.cache = cache;
return;
}
ConcurrentMap<String, LinkedList<ChatMessage>> map = cache.asMap();
for (LinkedList<ChatMessage> chatMessages : map.values()) {
boolean findSystemFlag = false;
for (ChatMessage chatMessage : chatMessages) {
if (chatMessage.getRole().equals(RoleEnum.SYSTEM.getRoleName())) {
chatMessage.setContent(systemPrompt);
findSystemFlag = true;
break;
}
}
if (!findSystemFlag) {
chatMessages.addFirst(new ChatMessage(RoleEnum.SYSTEM.getRoleName(), systemPrompt));
}
}
this.cache = cache;
}
/**
* addCache
*
* @param key key
* @param chatMessages chatMessages
*/
public void addCache(String key, LinkedList<ChatMessage> chatMessages) {
if (Strings.isNullOrEmpty(getSystemPrompt())) {
this.cache.put(key, chatMessages);
return;
}
boolean findSystemFlag = false;
for (ChatMessage chatMessage : chatMessages) {
if (chatMessage.getRole().equals(RoleEnum.SYSTEM.getRoleName())) {
chatMessage.setContent(getSystemPrompt());
findSystemFlag = true;
break;
}
}
if (!findSystemFlag) {
chatMessages.addFirst(new ChatMessage(RoleEnum.SYSTEM.getRoleName(), getSystemPrompt()));
}
this.cache.put(key, chatMessages);
}
/**
* 设置系统提示
*
* @param systemPrompt 系统提示
*/
public void setSystemPrompt(String systemPrompt) {
super.setSystemPrompt(systemPrompt);
ConcurrentMap<String, LinkedList<ChatMessage>> map = cache.asMap();
for (LinkedList<ChatMessage> chatMessages : map.values()) {
for (ChatMessage chatMessage : chatMessages) {
if (chatMessage.getRole().equals(RoleEnum.SYSTEM.getRoleName())) {
chatMessage.setContent(systemPrompt);
break;
}
}
}
}
/**
* 获取系统提示
*
* @return {@link String}
*/
public String getSystemPrompt() {
return super.getSystemPrompt();
}
/**
* 清理系统提示
*/
public void cleanUpSystemPrompt() {
super.setSystemPrompt(null);
ConcurrentMap<String, LinkedList<ChatMessage>> map = cache.asMap();
for (LinkedList<ChatMessage> chatMessages : map.values()) {
Iterator<ChatMessage> iterator = chatMessages.iterator();
while (iterator.hasNext()) {
ChatMessage chatMessage = iterator.next();
if (chatMessage.getRole().equals(RoleEnum.SYSTEM.getRoleName())) {
iterator.remove();
break;
}
}
}
}
/**
* 计数Token
*
* @param text 文本
* @return int
*/
public int countTokens(String text) {
return countTokens(text, ModelType.GPT_3_5_TURBO);
}
/**
* 计数Token
*
* @param text 文本
* @param modelType 型号类型
* @return int
*/
public int countTokens(String text, ModelType modelType) {
return getEncodingForModel(modelType).countTokens(text);
}
/**
* 获取模型编码
*
* @param modelType 型号类型
* @return {@link Encoding}
*/
public Encoding getEncodingForModel(ModelType modelType) {
return REGISTRY.getEncodingForModel(modelType);
}
private void randomSleep() throws InterruptedException {
Thread.sleep(500 + random.nextInt(200));
}
private static boolean checkTokenUsage(String message) {
return message != null && message.contains("This model's maximum context length is");
}
private BufferedImage getImageFromBase64(String base64) throws IOException {
byte[] imageBytes = Base64.getDecoder().decode(base64.getBytes());
try (ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes)) {
return ImageIO.read(bis);
}
}
/**
* convert color formats
*
* @param image image
* @throws IOException IOException
*/
private void convertColorFormats(File image) throws IOException {
BufferedImage inputImage = ImageIO.read(image);
// Get the color model of the image
ComponentColorModel componentColorModel = (ComponentColorModel) inputImage.getColorModel();
// Check the pixel format of the image
int pixelSize = componentColorModel.getPixelSize();
int numComponents = componentColorModel.getNumComponents();
boolean isRGBA = pixelSize == 32 && numComponents == 4;
boolean isL = pixelSize == 8 && numComponents == 1;
boolean isLA = pixelSize == 16 && numComponents == 2;
if (!isRGBA && !isL && !isLA) {
// Create a new RGBA image
BufferedImage outputImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(),
BufferedImage.TYPE_INT_ARGB);
// Draw the original image to the new image
Graphics2D g2d = outputImage.createGraphics();
g2d.drawImage(inputImage, 0, 0, null);
g2d.dispose();
// Save New Image
ImageIO.write(outputImage, "png", image);
}
}
private void addSystemPrompt(LinkedList<ChatMessage> contextInfo) {
if (CollectionUtils.isEmpty(contextInfo) && !Strings.isNullOrEmpty(getSystemPrompt())) {
ChatMessage chatMessage = new ChatMessage();
chatMessage.setRole(RoleEnum.SYSTEM.getRoleName());
chatMessage.setContent(getSystemPrompt());
contextInfo.addFirst(chatMessage);
}
}
}
| [
"com.theokanning.openai.completion.CompletionRequest.builder",
"com.theokanning.openai.edit.EditRequest.builder",
"com.theokanning.openai.embedding.EmbeddingRequest.builder",
"com.theokanning.openai.completion.chat.ChatCompletionRequest.builder"
] | [((4608, 4641), 'com.google.common.cache.CacheBuilder.newBuilder'), ((4660, 4775), 'com.google.common.cache.CacheBuilder.newBuilder'), ((4660, 4767), 'com.google.common.cache.CacheBuilder.newBuilder'), ((5236, 5269), 'com.google.common.cache.CacheBuilder.newBuilder'), ((5288, 5403), 'com.google.common.cache.CacheBuilder.newBuilder'), ((5288, 5395), 'com.google.common.cache.CacheBuilder.newBuilder'), ((6267, 6383), 'io.github.asleepyfish.service.openai.OpenAiService.defaultClient'), ((6267, 6358), 'io.github.asleepyfish.service.openai.OpenAiService.defaultClient'), ((6267, 6328), 'io.github.asleepyfish.service.openai.OpenAiService.defaultClient'), ((7515, 7542), 'io.github.asleepyfish.enums.chat.RoleEnum.USER.getRoleName'), ((8059, 8358), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((8059, 8333), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((8059, 8303), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((8059, 8275), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((8059, 8233), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((8059, 8205), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((8059, 8120), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((10908, 10967), 'io.github.asleepyfish.enums.chat.RoleEnum.SYSTEM.getRoleName'), ((10908, 10937), 'io.github.asleepyfish.enums.chat.RoleEnum.SYSTEM.getRoleName'), ((11938, 11970), 'io.github.asleepyfish.enums.chat.RoleEnum.ASSISTANT.getRoleName'), ((13009, 13036), 'io.github.asleepyfish.enums.chat.RoleEnum.USER.getRoleName'), ((13502, 13771), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((13502, 13746), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((13502, 13718), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((13502, 13676), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((13502, 13648), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((13502, 13563), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((15459, 15518), 'io.github.asleepyfish.enums.chat.RoleEnum.SYSTEM.getRoleName'), ((15459, 15488), 'io.github.asleepyfish.enums.chat.RoleEnum.SYSTEM.getRoleName'), ((16659, 16728), 'io.github.asleepyfish.enums.chat.FinishReasonEnum.LENGTH.getMessage'), ((16659, 16695), 'io.github.asleepyfish.enums.chat.FinishReasonEnum.LENGTH.getMessage'), ((17619, 17889), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((17619, 17864), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((17619, 17806), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((17619, 17778), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((17619, 17736), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((17619, 17708), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((17619, 17676), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((19016, 19086), 'io.github.asleepyfish.enums.chat.FinishReasonEnum.LENGTH.getMessage'), ((19016, 19052), 'io.github.asleepyfish.enums.chat.FinishReasonEnum.LENGTH.getMessage'), ((20463, 20525), 'io.github.asleepyfish.enums.image.ImageResponseFormatEnum.URL.getResponseFormat'), ((20463, 20510), 'io.github.asleepyfish.enums.image.ImageResponseFormatEnum.URL.getResponseFormat'), ((21405, 21467), 'io.github.asleepyfish.enums.image.ImageResponseFormatEnum.URL.getResponseFormat'), ((21405, 21452), 'io.github.asleepyfish.enums.image.ImageResponseFormatEnum.URL.getResponseFormat'), ((22699, 22733), 'io.github.asleepyfish.enums.image.ImageSizeEnum.S1024x1024.getSize'), ((22974, 23008), 'io.github.asleepyfish.enums.image.ImageSizeEnum.S1024x1024.getSize'), ((23965, 24017), 'io.github.asleepyfish.enums.image.ImageResponseFormatEnum.B64_JSON.getResponseFormat'), ((24033, 24132), 'io.github.asleepyfish.enums.image.ImageResponseFormatEnum.B64_JSON.getResponseFormat'), ((24033, 24085), 'io.github.asleepyfish.enums.image.ImageResponseFormatEnum.B64_JSON.getResponseFormat'), ((30314, 30555), 'com.theokanning.openai.edit.EditRequest.builder'), ((30314, 30530), 'com.theokanning.openai.edit.EditRequest.builder'), ((30314, 30502), 'com.theokanning.openai.edit.EditRequest.builder'), ((30314, 30460), 'com.theokanning.openai.edit.EditRequest.builder'), ((30314, 30418), 'com.theokanning.openai.edit.EditRequest.builder'), ((30314, 30388), 'com.theokanning.openai.edit.EditRequest.builder'), ((32090, 32256), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((32090, 32231), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((32090, 32173), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((33971, 34153), 'io.github.asleepyfish.entity.audio.TranscriptionRequest.builder'), ((33971, 34145), 'io.github.asleepyfish.entity.audio.TranscriptionRequest.builder'), ((33971, 34076), 'io.github.asleepyfish.entity.audio.TranscriptionRequest.builder'), ((33971, 34029), 'io.github.asleepyfish.entity.audio.TranscriptionRequest.builder'), ((34036, 34075), 'io.github.asleepyfish.enums.audio.AudioModelEnum.WHISPER_1.getModelName'), ((37211, 37391), 'io.github.asleepyfish.entity.audio.TranslationRequest.builder'), ((37211, 37383), 'io.github.asleepyfish.entity.audio.TranslationRequest.builder'), ((37211, 37314), 'io.github.asleepyfish.entity.audio.TranslationRequest.builder'), ((37211, 37267), 'io.github.asleepyfish.entity.audio.TranslationRequest.builder'), ((37274, 37313), 'io.github.asleepyfish.enums.audio.AudioModelEnum.WHISPER_1.getModelName'), ((58713, 58742), 'io.github.asleepyfish.enums.chat.RoleEnum.SYSTEM.getRoleName'), ((58996, 59025), 'io.github.asleepyfish.enums.chat.RoleEnum.SYSTEM.getRoleName'), ((59562, 59591), 'io.github.asleepyfish.enums.chat.RoleEnum.SYSTEM.getRoleName'), ((59822, 59851), 'io.github.asleepyfish.enums.chat.RoleEnum.SYSTEM.getRoleName'), ((60376, 60405), 'io.github.asleepyfish.enums.chat.RoleEnum.SYSTEM.getRoleName'), ((61190, 61219), 'io.github.asleepyfish.enums.chat.RoleEnum.SYSTEM.getRoleName'), ((64151, 64180), 'io.github.asleepyfish.enums.chat.RoleEnum.SYSTEM.getRoleName')] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.