code
stringlengths
619
138k
apis
sequencelengths
1
8
extract_api
stringlengths
79
7.3k
package example; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.utils.TikTokensUtil; import java.util.ArrayList; import java.util.List; class TikTokensExample { public static void main(String... args) { List<ChatMessage> messages = new ArrayList<>(); messages.add(new ChatMessage(ChatMessageRole.SYSTEM.value(), "Hello OpenAI 1.")); messages.add(new ChatMessage(ChatMessageRole.SYSTEM.value(), "Hello OpenAI 2. ")); int tokens_1 = TikTokensUtil.tokens(TikTokensUtil.ModelEnum.GPT_3_5_TURBO.getName(), messages); int tokens_2 = TikTokensUtil.tokens(TikTokensUtil.ModelEnum.GPT_3_5_TURBO.getName(), "Hello OpenAI 1."); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.utils.TikTokensUtil.ModelEnum.GPT_3_5_TURBO.getName" ]
[((409, 439), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((499, 529), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((600, 647), 'com.theokanning.openai.utils.TikTokensUtil.ModelEnum.GPT_3_5_TURBO.getName'), ((704, 751), 'com.theokanning.openai.utils.TikTokensUtil.ModelEnum.GPT_3_5_TURBO.getName')]
package com.ashin.util; import com.ashin.client.GptClient; import com.ashin.config.GptConfig; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.service.OpenAiService; import lombok.Getter; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.util.*; /** * bot工具类 * * @author ashinnotfound * @date 2023/2/1 */ @Component public class BotUtil { @Resource private GptConfig gptConfig; @Resource private GptClient gptClient; @Resource private Tokenizer tokenizer; private final Map<String, List<ChatMessage>> PROMPT_MAP = new HashMap<>(); private final Map<OpenAiService, Integer> COUNT_FOR_OPEN_AI_SERVICE = new HashMap<>(); @Getter private ChatCompletionRequest.ChatCompletionRequestBuilder completionRequestBuilder; private final List<ChatMessage> BASIC_PROMPT_LIST = new ArrayList<>(); @PostConstruct public void init() { completionRequestBuilder = ChatCompletionRequest.builder().model(gptConfig.getModel()).temperature(gptConfig.getTemperature()).maxTokens(gptConfig.getMaxToken()); for (OpenAiService openAiService : gptClient.getOpenAiServiceList()) { COUNT_FOR_OPEN_AI_SERVICE.put(openAiService, 0); } for (String prompt : gptConfig.getBasicPrompt()){ BASIC_PROMPT_LIST.add(new ChatMessage("system", prompt)); } } public OpenAiService getOpenAiService() { //获取使用次数最小的openAiService 否则获取map中的第一个 Optional<OpenAiService> openAiServiceToUse = COUNT_FOR_OPEN_AI_SERVICE.entrySet().stream() .min(Map.Entry.comparingByValue()) .map(Map.Entry::getKey); if (openAiServiceToUse.isPresent()) { COUNT_FOR_OPEN_AI_SERVICE.put(openAiServiceToUse.get(), COUNT_FOR_OPEN_AI_SERVICE.get(openAiServiceToUse.get()) + 1); return openAiServiceToUse.get(); } else { COUNT_FOR_OPEN_AI_SERVICE.put(COUNT_FOR_OPEN_AI_SERVICE.keySet().iterator().next(), COUNT_FOR_OPEN_AI_SERVICE.get(COUNT_FOR_OPEN_AI_SERVICE.keySet().iterator().next()) + 1); return COUNT_FOR_OPEN_AI_SERVICE.keySet().iterator().next(); } } public List<ChatMessage> buildPrompt(String sessionId, String newPrompt) { if (!PROMPT_MAP.containsKey(sessionId)) { if (!BASIC_PROMPT_LIST.isEmpty()){ List<ChatMessage> promptList = new ArrayList<>(BASIC_PROMPT_LIST); PROMPT_MAP.put(sessionId, promptList); } } List<ChatMessage> promptList = PROMPT_MAP.getOrDefault(sessionId, new ArrayList<>()); promptList.add(new ChatMessage("user", newPrompt)); if (tokenizer.countMessageTokens(gptConfig.getModel(), promptList) > gptConfig.getMaxToken()){ List<ChatMessage> tempChatMessage = deleteFirstPrompt(sessionId); if (tempChatMessage != null){ return buildPrompt(sessionId, newPrompt); } return null; } return promptList; } public boolean isPromptEmpty(String sessionId){ if (!PROMPT_MAP.containsKey(sessionId)){ return true; } return PROMPT_MAP.get(sessionId).size() == BASIC_PROMPT_LIST.size(); } public List<ChatMessage> deleteFirstPrompt(String sessionId) { if (!isPromptEmpty(sessionId)){ int index = BASIC_PROMPT_LIST.size(); List<ChatMessage> promptList = PROMPT_MAP.get(sessionId); //问 promptList.remove(index); //答 if (index < promptList.size()){ promptList.remove(index); return promptList; }else { // 已经是初始聊天记录 return null; } } // 已经是初始聊天记录 return null; } public void resetPrompt(String sessionId) { PROMPT_MAP.remove(sessionId); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1115, 1249), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1115, 1214), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1115, 1174), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package com.odde.doughnut.services.openAiApis; import static com.odde.doughnut.services.openAiApis.ApiExecutor.blockGet; import static java.lang.Thread.sleep; import com.fasterxml.jackson.databind.JsonNode; import com.odde.doughnut.controllers.dto.AiCompletionAnswerClarifyingQuestionParams; import com.odde.doughnut.exceptions.OpenAIServiceErrorException; import com.odde.doughnut.services.ai.OpenAIChatGPTFineTuningExample; import com.theokanning.openai.assistants.Assistant; import com.theokanning.openai.assistants.AssistantRequest; import com.theokanning.openai.client.OpenAiApi; import com.theokanning.openai.completion.chat.*; import com.theokanning.openai.fine_tuning.FineTuningJob; import com.theokanning.openai.fine_tuning.FineTuningJobRequest; import com.theokanning.openai.fine_tuning.Hyperparameters; import com.theokanning.openai.image.CreateImageRequest; import com.theokanning.openai.image.ImageResult; import com.theokanning.openai.messages.Message; import com.theokanning.openai.messages.MessageRequest; import com.theokanning.openai.model.Model; 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.threads.Thread; import com.theokanning.openai.threads.ThreadRequest; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import okhttp3.MediaType; import okhttp3.RequestBody; import org.springframework.http.HttpStatus; public class OpenAiApiHandler { private final OpenAiApi openAiApi; public OpenAiApiHandler(OpenAiApi openAiApi) { this.openAiApi = openAiApi; } public String getOpenAiImage(String prompt) { CreateImageRequest completionRequest = CreateImageRequest.builder().prompt(prompt).responseFormat("b64_json").build(); ImageResult choices = blockGet(openAiApi.createImage(completionRequest)); return choices.getData().get(0).getB64Json(); } public Optional<JsonNode> getFunctionCallArguments(ChatCompletionRequest chatRequest) { return getFunctionCall(chatRequest).map(ChatFunctionCall::getArguments); } public Optional<ChatFunctionCall> getFunctionCall(ChatCompletionRequest chatRequest) { return chatCompletion(chatRequest) // .map(x->{ // System.out.println(chatRequest); // System.out.println(x); // return x; // }) .map(ChatCompletionChoice::getMessage) .map(ChatMessage::getFunctionCall); } public Optional<ChatCompletionChoice> chatCompletion(ChatCompletionRequest request) { return blockGet(openAiApi.createChatCompletion(request)).getChoices().stream().findFirst(); } public List<Model> getModels() { return blockGet(openAiApi.listModels()).data; } public String uploadFineTuningExamples( List<OpenAIChatGPTFineTuningExample> examples, String subFileName) throws IOException { FineTuningFileWrapper uploader = new FineTuningFileWrapper(examples, subFileName); return uploader.withFileToBeUploaded( (file) -> { RequestBody purpose = RequestBody.create("fine-tune", MediaType.parse("text/plain")); try { return blockGet(openAiApi.uploadFile(purpose, file)).getId(); } catch (Exception e) { throw new OpenAIServiceErrorException( "Upload failed.", HttpStatus.INTERNAL_SERVER_ERROR); } }); } public FineTuningJob triggerFineTuning(String fileId) { FineTuningJobRequest fineTuningJobRequest = new FineTuningJobRequest(); fineTuningJobRequest.setTrainingFile(fileId); fineTuningJobRequest.setModel("gpt-3.5-turbo-1106"); fineTuningJobRequest.setHyperparameters( new Hyperparameters(3)); // not sure what should be the nEpochs value FineTuningJob fineTuningJob = blockGet(openAiApi.createFineTuningJob(fineTuningJobRequest)); if (List.of("failed", "cancelled").contains(fineTuningJob.getStatus())) { throw new OpenAIServiceErrorException( "Trigger Fine-Tuning Failed: " + fineTuningJob, HttpStatus.BAD_REQUEST); } return fineTuningJob; } public Assistant createAssistant(AssistantRequest assistantRequest) { return blockGet(openAiApi.createAssistant(assistantRequest)); } public Thread createThread(ThreadRequest threadRequest) { return blockGet(openAiApi.createThread(threadRequest)); } public void createMessage(String threadId, MessageRequest messageRequest) { blockGet(openAiApi.createMessage(threadId, messageRequest)); } private Run retrieveRun(String threadId, String runId) { return blockGet(openAiApi.retrieveRun(threadId, runId)); } public Run createRun(String threadId, String assistantId) { RunCreateRequest runCreateRequest = RunCreateRequest.builder().assistantId(assistantId).build(); return blockGet(openAiApi.createRun(threadId, runCreateRequest)); } public Run retrieveUntilCompletedOrRequiresAction(String threadId, Run currentRun) { Run retrievedRun = currentRun; int count = 0; while (!(retrievedRun.getStatus().equals("completed")) && !(retrievedRun.getStatus().equals("failed")) && !(retrievedRun.getStatus().equals("requires_action"))) { count++; if (count > 15) { break; } wait(count - 1); retrievedRun = retrieveRun(threadId, currentRun.getId()); } if (retrievedRun.getStatus().equals("requires_action") || retrievedRun.getStatus().equals("completed")) { return retrievedRun; } throw new RuntimeException("OpenAI run status: " + retrievedRun.getStatus()); } private static void wait(int hundredMilliSeconds) { try { sleep(hundredMilliSeconds * 200L); } catch (InterruptedException e) { throw new RuntimeException(e); } } public Run submitToolOutputs( AiCompletionAnswerClarifyingQuestionParams answerClarifyingQuestionParams) { SubmitToolOutputRequestItem toolOutputRequestItem = SubmitToolOutputRequestItem.builder() .toolCallId(answerClarifyingQuestionParams.getToolCallId()) .output(answerClarifyingQuestionParams.getAnswer()) .build(); List<SubmitToolOutputRequestItem> toolOutputRequestItems = new ArrayList<>(); toolOutputRequestItems.add(toolOutputRequestItem); SubmitToolOutputsRequest submitToolOutputsRequest = SubmitToolOutputsRequest.builder().toolOutputs(toolOutputRequestItems).build(); return blockGet( openAiApi.submitToolOutputs( answerClarifyingQuestionParams.getThreadId(), answerClarifyingQuestionParams.getRunId(), submitToolOutputsRequest)); } public Message getThreadLastMessage(String threadId) { return blockGet(openAiApi.listMessages(threadId)).getData().getLast(); } }
[ "com.theokanning.openai.runs.SubmitToolOutputsRequest.builder", "com.theokanning.openai.image.CreateImageRequest.builder", "com.theokanning.openai.runs.RunCreateRequest.builder", "com.theokanning.openai.runs.SubmitToolOutputRequestItem.builder" ]
[((1844, 1922), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((1844, 1914), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((1844, 1887), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4032, 4098), 'java.util.List.of'), ((4910, 4969), 'com.theokanning.openai.runs.RunCreateRequest.builder'), ((4910, 4961), 'com.theokanning.openai.runs.RunCreateRequest.builder'), ((6134, 6328), 'com.theokanning.openai.runs.SubmitToolOutputRequestItem.builder'), ((6134, 6307), 'com.theokanning.openai.runs.SubmitToolOutputRequestItem.builder'), ((6134, 6243), 'com.theokanning.openai.runs.SubmitToolOutputRequestItem.builder'), ((6531, 6609), 'com.theokanning.openai.runs.SubmitToolOutputsRequest.builder'), ((6531, 6601), 'com.theokanning.openai.runs.SubmitToolOutputsRequest.builder')]
/* ### * IP: GHIDRA * * 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 ghidrachatgpt; 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 docking.Tool; import ghidra.app.CorePluginPackage; import ghidra.app.ExamplesPluginPackage; import ghidra.app.decompiler.flatapi.FlatDecompilerAPI; import ghidra.app.plugin.PluginCategoryNames; import ghidra.app.plugin.ProgramPlugin; import ghidra.app.services.CodeViewerService; import ghidra.app.services.ConsoleService; import ghidra.framework.plugintool.*; import ghidra.framework.plugintool.util.PluginStatus; import ghidra.program.flatapi.FlatProgramAPI; import ghidra.program.model.address.Address; import ghidra.program.model.listing.Function; import ghidra.program.model.listing.Program; import ghidra.program.model.listing.Variable; import ghidra.program.model.symbol.SourceType; import ghidra.program.util.ProgramLocation; import ghidra.util.HelpLocation; import java.lang.Integer; import java.time.Duration; import java.util.List; import org.json.JSONObject; //@formatter:off @PluginInfo(status = PluginStatus.RELEASED, packageName = CorePluginPackage.NAME, category = PluginCategoryNames.ANALYSIS, shortDescription = "ChatGPT Plugin for Ghidra", description = "Brings the power of ChatGPT to Ghidra!", servicesRequired = {ConsoleService.class, CodeViewerService.class}) //@formatter:on public class GhidraChatGPTPlugin extends ProgramPlugin { ConsoleService cs; CodeViewerService cvs; private GhidraChatGPTComponent uiComponent; private String apiToken; private String openAiModel = "gpt-3.5-turbo"; private int OPENAI_TIMEOUT = 120; private static final String GCG_IDENTIFY_STRING = "Describe the function with as much detail as possible and include a link to an open source version if there is one\n %s"; private static final String GCG_VULNERABILITY_STRING = "Describe all vulnerabilities in this function with as much detail as possible\n %s"; private static final String GCG_BEAUTIFY_STRING = "Analyze the function and suggest function and variable names in a json format where the key is the previous name and the value is the suggested name\n %s"; /** * Plugin constructor. * * @param tool The plugin tool that this plugin is added to. */ public GhidraChatGPTPlugin(PluginTool tool) { super(tool); String pluginName = getName(); uiComponent = new GhidraChatGPTComponent(this, pluginName); String topicName = this.getClass().getPackage().getName(); String anchorName = "HelpAnchor"; uiComponent.setHelpLocation(new HelpLocation(topicName, anchorName)); } @Override public void init() { super.init(); cs = tool.getService(ConsoleService.class); cvs = tool.getService(CodeViewerService.class); apiToken = System.getenv("OPENAI_TOKEN"); if (apiToken != null) ok(String.format("Loaded OpenAI Token: %s", censorToken(apiToken))); ok(String.format("Default model is: %s", openAiModel)); } public Boolean setToken(String token) { if (token == null) return false; apiToken = token; return true; } private static String censorToken(String token) { StringBuilder censoredBuilder = new StringBuilder(token.length()); censoredBuilder.append(token.substring(0, 2)); for (int i = 2; i < token.length(); i++) { censoredBuilder.append('*'); } return censoredBuilder.toString(); } public String getToken() { return apiToken; } public void setModel(String model) { openAiModel = model; } public void identifyFunction() { String result; DecompilerResults decResult = decompileCurrentFunc(); if (decResult == null) return; log(String.format("Identifying the current function: %s", decResult.func.getName())); result = askChatGPT( String.format(GCG_IDENTIFY_STRING, decResult.decompiledFunc)); if (result == null) return; addComment(decResult.prog, decResult.func, result, "[GhidraChatGPT] - Identify Function"); } public void findVulnerabilities() { String result; DecompilerResults decResult = decompileCurrentFunc(); if (decResult == null) return; log(String.format("Finding vulnerabilities in the current function: %s", decResult.func.getName())); result = askChatGPT( String.format(GCG_VULNERABILITY_STRING, decResult.decompiledFunc)); if (result == null) return; addComment(decResult.prog, decResult.func, result, "[GhidraChatGPT] - Find Vulnerabilities"); } public void beautifyFunction() { String result; DecompilerResults decResult = decompileCurrentFunc(); if (decResult == null) return; log(String.format("Beautifying the function: %s", decResult.func.getName())); result = askChatGPT( String.format(GCG_BEAUTIFY_STRING, decResult.decompiledFunc)); if (result == null) return; updateVariables(decResult.prog, decResult, result); ok(String.format("Beautified the function: %s", decResult.func.getName())); } private Boolean checkOpenAIToken() { if (apiToken != null) return true; if (!setToken(uiComponent.askForOpenAIToken())) { error("Failed to update the OpenAI API token"); return false; } return true; } private class DecompilerResults { public Program prog; public Function func; public String decompiledFunc; public DecompilerResults(Program prog, Function func, String decompiledFunc) { this.prog = prog; this.func = func; this.decompiledFunc = decompiledFunc; } } private DecompilerResults decompileCurrentFunc() { String decompiledFunc; ProgramLocation progLoc = cvs.getCurrentLocation(); Program prog = progLoc.getProgram(); FlatProgramAPI programApi = new FlatProgramAPI(prog); FlatDecompilerAPI decompiler = new FlatDecompilerAPI(programApi); Function func = programApi.getFunctionContaining(progLoc.getAddress()); if (func == null) { error("Failed to find the current function"); return null; } try { decompiledFunc = decompiler.decompile(func); } catch (Exception e) { error(String.format( "Failed to decompile the function: %s with the error %s", func.getName(), e)); return null; } return new DecompilerResults(prog, func, decompiledFunc); } private void updateVariables(Program prog, DecompilerResults decResult, String result) { JSONObject jsonObj; try { jsonObj = new JSONObject(result); } catch (Exception e) { error("Failed to parse beautify JSON"); return; } Variable[] vars = decResult.func.getAllVariables(); if (vars == null) { log("Nothing to beautify"); return; } var id = prog.startTransaction("GhidraChatGPT"); for (Variable var : vars) { if (jsonObj.has(var.getName())) { String val = jsonObj.getString(var.getName()); try { var.setName(val, SourceType.USER_DEFINED); ok(String.format("Beautified %s => %s", var.getName(), val)); } catch (Exception e) { error( String.format("Failed to beautify %s => %s", var.getName(), val)); } } }; if (jsonObj.has(decResult.func.getName())) { String val = jsonObj.getString(decResult.func.getName()); try { decResult.func.setName(val, SourceType.USER_DEFINED); ok(String.format("Beautified %s => %s", decResult.func.getName(), val)); } catch (Exception e) { error(String.format("Failed to beautify %s => %s", decResult.func.getName(), val)); } } prog.endTransaction(id, true); } private void addComment(Program prog, Function func, String comment, String commentHeader) { var id = prog.startTransaction("GhidraChatGPT"); String currentComment = func.getComment(); if (currentComment != null) { currentComment = String.format("%s\n%s\n\n%s", commentHeader, comment, currentComment); } else { currentComment = String.format("%s\n%s", commentHeader, comment); } func.setComment(currentComment); prog.endTransaction(id, true); ok(String.format( "Added the ChatGPT response as a comment to the function: %s", func.getName())); } private String askChatGPT(String prompt) { String response = sendOpenAIRequest(prompt); if (response == null) { error("The ChatGPT response was empty, try again!"); return null; } return response; } private String sendOpenAIRequest(String prompt) { StringBuilder response = new StringBuilder(); if (!checkOpenAIToken()) return null; OpenAiService openAIService = new OpenAiService(apiToken, Duration.ofSeconds(OPENAI_TIMEOUT)); if (openAIService == null) { error("Faild to start the OpenAI service, try again!"); return null; } ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .model(openAiModel) .temperature(0.8) .messages(List.of( new ChatMessage( ChatMessageRole.SYSTEM.value(), "You are an assistant helping out with reverse engineering and vulnerability research"), new ChatMessage(ChatMessageRole.USER.value(), prompt))) .build(); try { StringBuilder builder = new StringBuilder(); openAIService.createChatCompletion(chatCompletionRequest) .getChoices() .forEach( choice -> { builder.append(choice.getMessage().getContent()); }); return builder.toString(); } catch (Exception e) { error(String.format("Asking ChatGPT failed with the error %s", e)); return null; } } public void log(String message) { cs.println(String.format("%s [>] %s", getName(), message)); } public void error(String message) { cs.println(String.format("%s [-] %s", getName(), message)); } public void ok(String message) { cs.println(String.format("%s [+] %s", getName(), message)); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value", "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((9946, 10357), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((9946, 10336), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((9946, 10039), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((9946, 10009), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((10124, 10154), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((10297, 10325), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')]
package com.frizzcode.gpt3.services; import com.frizzcode.gpt3.models.Gpt3Request; import com.frizzcode.gpt3.models.Gpt3Response; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.edit.EditRequest; import com.theokanning.openai.model.Model; import com.theokanning.openai.service.OpenAiService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import java.time.Duration; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; @RequiredArgsConstructor @Slf4j @Service public class Gpt3ServiceImpl implements Gpt3Service { @Value("${gpt3.token}") public String API_TOKEN; @Override @Async("asyncExecution") public CompletableFuture<List<Gpt3Response>> getResponses(Gpt3Request request) { OpenAiService service = new OpenAiService(API_TOKEN, Duration.ofMinutes(5)); ModelMapper mapper = new ModelMapper(); String[] promptSplit = request.getPrompt().split("\\."); String instruction = promptSplit[promptSplit.length-1]; StringBuilder input = new StringBuilder(); log.info("Instruction: {}", instruction); for (int i=0; i<promptSplit.length -1; i++){ String message = promptSplit[i] + ". "; input.append(message); } log.info("Input: {}", input); if (request.getModel().contains("gpt")) return CompletableFuture.completedFuture(service.createChatCompletion(ChatCompletionRequest.builder() .model(request.getModel()) .frequencyPenalty(0.5) .topP(1.0) .user(UUID.randomUUID().toString()) .temperature(0.3) .maxTokens(3500) .messages(List.of(new ChatMessage("user", request.getPrompt()))) .build()).getChoices().stream().map( chatCompletionChoice -> mapper.map(chatCompletionChoice, Gpt3Response.class) ).toList()).orTimeout(5, TimeUnit.MINUTES); else if (request.getModel().contains("edit")) return CompletableFuture.completedFuture(service.createEdit(EditRequest.builder() .model(request.getModel()) .temperature(0.7) .input(input.toString()) .instruction(instruction) .build()).getChoices().stream().map( editChoice -> mapper.map(editChoice, Gpt3Response.class) ).toList()).orTimeout(5, TimeUnit.MINUTES); else return CompletableFuture.completedFuture(service.createCompletion(CompletionRequest.builder() .model(request.getModel()) .frequencyPenalty(0.5) .topP(1.0) .user(UUID.randomUUID().toString()) .temperature(0.3) .maxTokens(3500) .prompt(request.getPrompt()) .build()).getChoices().stream().map( completionChoice -> mapper.map(completionChoice, Gpt3Response.class) ).toList()).orTimeout(5, TimeUnit.MINUTES); } @Override public List<Model> getEngineList() { OpenAiService service = new OpenAiService(API_TOKEN, Duration.ofMinutes(5)); return service.listModels(); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder", "com.theokanning.openai.edit.EditRequest.builder", "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1848, 2498), 'java.util.concurrent.CompletableFuture.completedFuture'), ((1911, 2316), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1911, 2286), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1911, 2200), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1911, 2162), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1911, 2123), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1911, 2066), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1911, 2034), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1911, 1990), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2094, 2122), 'java.util.UUID.randomUUID'), ((2575, 3021), 'java.util.concurrent.CompletableFuture.completedFuture'), ((2628, 2859), 'com.theokanning.openai.edit.EditRequest.builder'), ((2628, 2829), 'com.theokanning.openai.edit.EditRequest.builder'), ((2628, 2782), 'com.theokanning.openai.edit.EditRequest.builder'), ((2628, 2736), 'com.theokanning.openai.edit.EditRequest.builder'), ((2628, 2697), 'com.theokanning.openai.edit.EditRequest.builder'), ((3057, 3655), 'java.util.concurrent.CompletableFuture.completedFuture'), ((3116, 3481), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3116, 3451), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3116, 3401), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3116, 3363), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3116, 3324), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3116, 3267), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3116, 3235), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3116, 3191), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3295, 3323), 'java.util.UUID.randomUUID')]
package com.zs.project.service.impl; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; 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 com.zs.project.exception.ErrorCode; import com.zs.project.exception.ServiceException; import com.zs.project.model.dto.gpt.OpenAIRequestBuilder; import com.zs.project.service.GptService; import com.zs.project.service.ResultCallback; import lombok.Synchronized; import lombok.extern.slf4j.Slf4j; import okhttp3.OkHttpClient; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.*; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import retrofit2.Retrofit; import java.net.InetSocketAddress; import java.net.Proxy; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.*; import static com.theokanning.openai.service.OpenAiService.*; /** * @author ShuaiZhang * 需要用流式处理(已支持) */ @Service @Slf4j public class GptServiceImpl implements GptService { /** * openai的token */ @Value("${openai.token}") String token; /** * 代理服务器 */ @Value("${proxy.host}") private String proxyHost; /** * 代理端口 */ @Value("${proxy.port}") private int proxyPort; @Value("${openai.token}") private String OPENAI_KEYS; RestTemplate restTemplate; @Autowired public GptServiceImpl(@Qualifier("restTemplateWithProxy") RestTemplate restTemplate) { this.restTemplate = restTemplate; } /** * 阻塞式调用gpt3.5 * @param query 你的promote * @return 结果 */ @Override public String GptResponse(String query) { //建造者模式创建实体 HttpEntity<Map<String, Object>> entity = new OpenAIRequestBuilder(OPENAI_KEYS).withContent(query).buildRequestEntity(); ResponseEntity<String> response = restTemplate.exchange(OpenAIRequestBuilder.OPENAI_ENDPOINT_URL, HttpMethod.POST, entity, String.class); //我个人倾向这里手动进行解析而不是封装成DTO //封装成DTO要处理的字段很多 ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode; try{ rootNode = objectMapper.readTree(response.getBody()); } catch (JsonProcessingException e){ throw new ServiceException(ErrorCode.SYSTEM_ERROR,"Json解析失败"); } JsonNode choicesNode = rootNode.path("choices"); JsonNode firstChoiceNode = choicesNode.get(0); JsonNode messageNode = firstChoiceNode.path("message"); String gptResponse = messageNode.path("content").asText(); return gptResponse; } /** * 流式传输 * @param prompt 用户问题 * @param sseEmitter 实时推送 */ @Override @Async public void streamChatCompletion(String prompt, SseEmitter sseEmitter) { streamChatCompletion(prompt, sseEmitter, result -> {}); } /** * 关闭链接 * @param sseEmitter */ @Override public void sendStopEvent(SseEmitter sseEmitter) { try { sseEmitter.send(SseEmitter.event().name("stop").data("")); } catch (Exception e){ throw new ServiceException(ErrorCode.SYSTEM_ERROR,"事件停止接口出错"); } } /** * 创建一个OpenAI服务 * @param token API key * @param proxyHost 代理服务器地址 * @param proxyPort 代理端口地址 * @return */ @Override public OpenAiService buildOpenAiService(String token, String proxyHost, int proxyPort) { //构建HTTP代理 Proxy proxy = null; if (StringUtils.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; } /** * 支持回调 * @param prompt 用户问题 * @param sseEmitter SSE对象 * @param resultCallback 回调接口 */ @Override @Async public void streamChatCompletion(String prompt, SseEmitter sseEmitter, ResultCallback resultCallback) { 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.info("收到消息:" + choice); if (StringUtils.isEmpty(choice.getFinishReason())) { //未结束时才可以发送消息(结束后,先调用doOnComplete然后还会收到一条结束消息,因连接关闭导致发送消息失败:ResponseBodyEmitter has already completed) sseEmitter.send(choice.getMessage()); } String content = choice.getMessage().getContent(); content = StringUtils.defaultString(content); receiveMsgBuilder.append(content); }); log.info("收到的完整消息:" + receiveMsgBuilder); try { resultCallback.onCompletion(receiveMsgBuilder.toString()); } catch (IllegalStateException e){ log.info("事件已经回调完毕"); } } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value" ]
[((3905, 3945), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((3905, 3936), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((5531, 5561), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value')]
package oracleai; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import com.oracle.bmc.aivision.AIServiceVisionClient; import com.oracle.bmc.aivision.model.*; import com.oracle.bmc.aivision.requests.AnalyzeImageRequest; import com.oracle.bmc.aivision.responses.AnalyzeImageResponse; import com.oracle.bmc.auth.AuthenticationDetailsProvider; import com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider; import com.oracle.bmc.auth.InstancePrincipalsAuthenticationDetailsProvider; 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 lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; @RestController @RequestMapping("/health") public class ExplainAndAdviseOnHealthTestResults { private static Logger log = LoggerFactory.getLogger(ExplainAndAdviseOnHealthTestResults.class); @GetMapping("/form") public String form(){ return " <html><form method=\"post\" action=\"/health/analyzedoc\" enctype=\"multipart/form-data\">\n" + " Select an image file to conduct object detection upon...\n" + " <input type=\"file\" name=\"file\" accept=\"image/*\">\n" + " <br>\n" + " <br>Hit submit and a raw JSON return of objects detected and other info will be returned...\n" + " <br><input type=\"submit\" value=\"Send Request to Vision AI\">\n" + " </form></html>"; } @PostMapping("/analyzedoc") public String analyzedoc(@RequestParam("file") MultipartFile file) throws Exception { log.info("analyzing image file:" + file); String objectDetectionResults = processImage(file.getBytes(), true); ImageAnalysis imageAnalysis = parseJsonToImageAnalysis(objectDetectionResults); List<Line> lines = imageAnalysis.getImageText().getLines(); String fullText = ""; for (Line line : lines) fullText += line.getText(); log.info("fullText = " + fullText); String explanationOfResults = chat("explain these test results in simple terms " + "and tell me what should I do to get better results: \"" + fullText + "\""); return "<html><br><br>explanationOfResults:" + explanationOfResults + "</html>"; } String chat(String textcontent) throws Exception { OpenAiService service = new OpenAiService(System.getenv("OPENAI_KEY"), Duration.ofSeconds(60)); System.out.println("Streaming chat completion... textcontent:" + textcontent); final List<ChatMessage> messages = new ArrayList<>(); final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), textcontent); messages.add(systemMessage); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest .builder() .model("gpt-3.5-turbo") .messages(messages) .n(1) .maxTokens(300) //was 50 .logitBias(new HashMap<>()) .build(); String replyString = ""; String content; for (ChatCompletionChoice choice : service.createChatCompletion(chatCompletionRequest).getChoices()) { content = choice.getMessage().getContent(); replyString += (content == null?" ": content); } service.shutdownExecutor(); return replyString; } String processImage(byte[] bytes, boolean isConfigFileAuth) throws Exception { AIServiceVisionClient aiServiceVisionClient; AuthenticationDetailsProvider provider; if (isConfigFileAuth) { provider = new ConfigFileAuthenticationDetailsProvider( System.getenv("OCICONFIG_FILE"),System.getenv("OCICONFIG_PROFILE")); aiServiceVisionClient = AIServiceVisionClient.builder().build(provider); } else { aiServiceVisionClient = new AIServiceVisionClient(InstancePrincipalsAuthenticationDetailsProvider.builder().build()); } List<ImageFeature> features = new ArrayList<>(); ImageFeature classifyFeature = ImageClassificationFeature.builder() .maxResults(10) .build(); ImageFeature detectImageFeature = ImageObjectDetectionFeature.builder() .maxResults(10) .build(); ImageFeature textDetectImageFeature = ImageTextDetectionFeature.builder().build(); features.add(classifyFeature); features.add(detectImageFeature); features.add(textDetectImageFeature); InlineImageDetails inlineImageDetails = InlineImageDetails.builder() .data(bytes) .build(); AnalyzeImageDetails analyzeImageDetails = AnalyzeImageDetails.builder() .image(inlineImageDetails) .features(features) .build(); AnalyzeImageRequest request = AnalyzeImageRequest.builder() .analyzeImageDetails(analyzeImageDetails) .build(); AnalyzeImageResponse response = aiServiceVisionClient.analyzeImage(request); ObjectMapper mapper = new ObjectMapper(); mapper.setFilterProvider(new SimpleFilterProvider().setFailOnUnknownId(false)); String json = mapper.writeValueAsString(response.getAnalyzeImageResult()); System.out.println("AnalyzeImage Result"); System.out.println(json); return json; } @Data class ImageObject { private String name; private double confidence; private BoundingPolygon boundingPolygon; } @Data class BoundingPolygon { private List<Point> normalizedVertices; } @Data class Point { private double x; private double y; public Point(double x, double y) { this.x = x; this.y = y; } } @Data class Label { private String name; private double confidence; } @Data class OntologyClass { private String name; private List<String> parentNames; private List<String> synonymNames; } @Data class ImageText { private List<Word> words; private List<Line> lines; } @Data class Word { private String text; private double confidence; private BoundingPolygon boundingPolygon; } @Data class Line { private String text; private double confidence; private BoundingPolygon boundingPolygon; private List<Integer> wordIndexes; } @Data class ImageAnalysis { private List<ImageObject> imageObjects; private List<Label> labels; private List<OntologyClass> ontologyClasses; private ImageText imageText; private String imageClassificationModelVersion; private String objectDetectionModelVersion; private String textDetectionModelVersion; private List<String> errors; } private ImageAnalysis parseJsonToImageAnalysis(String jsonString) { JSONObject json = new JSONObject(jsonString); JSONArray imageObjectsArray = json.getJSONArray("imageObjects"); List<ImageObject> imageObjects = new ArrayList<>(); for (int i = 0; i < imageObjectsArray.length(); i++) { JSONObject imageObjectJson = imageObjectsArray.getJSONObject(i); ImageObject imageObject = new ImageObject(); imageObject.setName(imageObjectJson.getString("name")); imageObject.setConfidence(imageObjectJson.getDouble("confidence")); JSONObject boundingPolygonJson = imageObjectJson.getJSONObject("boundingPolygon"); JSONArray normalizedVerticesArray = boundingPolygonJson.getJSONArray("normalizedVertices"); List<Point> normalizedVertices = new ArrayList<>(); for (int j = 0; j < normalizedVerticesArray.length(); j++) { JSONObject vertexJson = normalizedVerticesArray.getJSONObject(j); Point vertex = new Point(vertexJson.getDouble("x"), vertexJson.getDouble("y")); normalizedVertices.add(vertex); } BoundingPolygon boundingPolygon = new BoundingPolygon(); boundingPolygon.setNormalizedVertices(normalizedVertices); imageObject.setBoundingPolygon(boundingPolygon); imageObjects.add(imageObject); } JSONArray labelsArray = json.getJSONArray("labels"); List<Label> labels = new ArrayList<>(); for (int i = 0; i < labelsArray.length(); i++) { JSONObject labelJson = labelsArray.getJSONObject(i); Label label = new Label(); label.setName(labelJson.getString("name")); label.setConfidence(labelJson.getDouble("confidence")); labels.add(label); } JSONArray ontologyClassesArray = json.getJSONArray("ontologyClasses"); List<OntologyClass> ontologyClasses = new ArrayList<>(); for (int i = 0; i < ontologyClassesArray.length(); i++) { JSONObject ontologyClassJson = ontologyClassesArray.getJSONObject(i); OntologyClass ontologyClass = new OntologyClass(); ontologyClass.setName(ontologyClassJson.getString("name")); JSONArray parentNamesArray = ontologyClassJson.getJSONArray("parentNames"); List<String> parentNames = new ArrayList<>(); for (int j = 0; j < parentNamesArray.length(); j++) { parentNames.add(parentNamesArray.getString(j)); } ontologyClass.setParentNames(parentNames); ontologyClasses.add(ontologyClass); } JSONObject imageTextJson = json.getJSONObject("imageText"); JSONArray wordsArray = imageTextJson.getJSONArray("words"); List<Word> words = new ArrayList<>(); for (int i = 0; i < wordsArray.length(); i++) { JSONObject wordJson = wordsArray.getJSONObject(i); Word word = new Word(); word.setText(wordJson.getString("text")); word.setConfidence(wordJson.getDouble("confidence")); JSONObject boundingPolygonJson = wordJson.getJSONObject("boundingPolygon"); JSONArray normalizedVerticesArray = boundingPolygonJson.getJSONArray("normalizedVertices"); List<Point> normalizedVertices = new ArrayList<>(); for (int j = 0; j < normalizedVerticesArray.length(); j++) { JSONObject vertexJson = normalizedVerticesArray.getJSONObject(j); Point vertex = new Point(vertexJson.getDouble("x"), vertexJson.getDouble("y")); normalizedVertices.add(vertex); } BoundingPolygon boundingPolygon = new BoundingPolygon(); boundingPolygon.setNormalizedVertices(normalizedVertices); word.setBoundingPolygon(boundingPolygon); words.add(word); } JSONArray linesArray = imageTextJson.getJSONArray("lines"); List<Line> lines = new ArrayList<>(); for (int i = 0; i < linesArray.length(); i++) { JSONObject lineJson = linesArray.getJSONObject(i); Line line = new Line(); line.setText(lineJson.getString("text")); line.setConfidence(lineJson.getDouble("confidence")); JSONObject boundingPolygonJson = lineJson.getJSONObject("boundingPolygon"); JSONArray normalizedVerticesArray = boundingPolygonJson.getJSONArray("normalizedVertices"); List<Point> normalizedVertices = new ArrayList<>(); for (int j = 0; j < normalizedVerticesArray.length(); j++) { JSONObject vertexJson = normalizedVerticesArray.getJSONObject(j); Point vertex = new Point(vertexJson.getDouble("x"), vertexJson.getDouble("y")); normalizedVertices.add(vertex); } BoundingPolygon boundingPolygon = new BoundingPolygon(); boundingPolygon.setNormalizedVertices(normalizedVertices); line.setBoundingPolygon(boundingPolygon); JSONArray wordIndexesArray = lineJson.getJSONArray("wordIndexes"); List<Integer> wordIndexes = new ArrayList<>(); for (int j = 0; j < wordIndexesArray.length(); j++) { wordIndexes.add(wordIndexesArray.getInt(j)); } line.setWordIndexes(wordIndexes); lines.add(line); } String imageClassificationModelVersion = json.getString("imageClassificationModelVersion"); String objectDetectionModelVersion = json.getString("objectDetectionModelVersion"); String textDetectionModelVersion = json.getString("textDetectionModelVersion"); List<String> errors = new ArrayList<>(); JSONArray errorsArray = json.getJSONArray("errors"); for (int i = 0; i < errorsArray.length(); i++) { errors.add(errorsArray.getString(i)); } ImageText imageText = new ImageText(); imageText.setWords(words); imageText.setLines(lines); ImageAnalysis imageAnalysis = new ImageAnalysis(); imageAnalysis.setImageObjects(imageObjects); imageAnalysis.setLabels(labels); imageAnalysis.setOntologyClasses(ontologyClasses); imageAnalysis.setImageText(imageText); imageAnalysis.setImageClassificationModelVersion(imageClassificationModelVersion); imageAnalysis.setObjectDetectionModelVersion(objectDetectionModelVersion); imageAnalysis.setTextDetectionModelVersion(textDetectionModelVersion); imageAnalysis.setErrors(errors); return imageAnalysis; } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value" ]
[((3353, 3383), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((4522, 4569), 'com.oracle.bmc.aivision.AIServiceVisionClient.builder'), ((4650, 4715), 'com.oracle.bmc.auth.InstancePrincipalsAuthenticationDetailsProvider.builder'), ((5630, 5742), 'com.oracle.bmc.aivision.requests.AnalyzeImageRequest.builder'), ((5630, 5717), 'com.oracle.bmc.aivision.requests.AnalyzeImageRequest.builder')]
package org.ncgr.chatbot.openai; import java.util.Collections; import java.util.List; import com.theokanning.openai.embedding.Embedding; import com.theokanning.openai.embedding.EmbeddingRequest; import com.theokanning.openai.embedding.EmbeddingResult; import com.theokanning.openai.service.OpenAiService; /** * Class to retrieve embeddings from OpenAI. */ public class EmbeddingTest { // the OpenAI embedding model to use static String EMBED_MODEL = "text-embedding-ada-002"; public static void main(String[] args) { String token = System.getenv("OPENAI_API_KEY"); OpenAiService service = new OpenAiService(token); EmbeddingRequest embeddingRequest = EmbeddingRequest.builder() .model("text-embedding-ada-002") .input(Collections.singletonList("List photosynthesis genes.")) .build(); List<Embedding> embeddings = service.createEmbeddings(embeddingRequest).getData(); for (Embedding embedding : embeddings) { List<Double> vector = embedding.getEmbedding(); System.out.println("object: " + embedding.getObject()); System.out.println("index: " + embedding.getIndex()); System.out.println("vector: " + vector); } } }
[ "com.theokanning.openai.embedding.EmbeddingRequest.builder" ]
[((696, 864), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((696, 843), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((696, 767), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')]
package oracleai.services; import com.theokanning.openai.image.CreateImageRequest; import com.theokanning.openai.service.OpenAiService; import java.time.Duration; public class ImageGeneration { static public String imagegeneration(String imagedescription) throws Exception { OpenAiService service = new OpenAiService(System.getenv("OPENAI_KEY"), Duration.ofSeconds(60)); CreateImageRequest openairequest = CreateImageRequest.builder() .prompt(imagedescription) .build(); String imageLocation = service.createImage(openairequest).getData().get(0).getUrl(); System.out.println("Image is located at:" + imageLocation); service.shutdownExecutor(); return imageLocation; } }
[ "com.theokanning.openai.image.CreateImageRequest.builder" ]
[((446, 541), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((446, 516), 'com.theokanning.openai.image.CreateImageRequest.builder')]
package br.com.alura.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.time.Duration; import java.util.Arrays; import java.util.Scanner; public class CategorizadorDeProdutos { public static void main(String[] args) { var leitor = new Scanner(System.in); System.out.println("Digite as categorias válidas:"); var categorias = leitor.nextLine(); while(true) { System.out.println("\nDigite o nome do produto:"); var user = leitor.nextLine(); var system = """ Você é um categorizador de produtos e deve responder apenas o nome da categoria do produto informado Escolha uma categoria dentra a lista abaixo: %s ###### exemplo de uso: Pergunta: Bola de futebol Resposta: Esportes ###### regras a serem seguidas: Caso o usuario pergunte algo que nao seja de categorizacao de produtos, voce deve responder que nao pode ajudar pois o seu papel é apenas responder a categoria dos produtos """.formatted(categorias); dispararRequisicao(user, system); } } public static void dispararRequisicao(String user, String system) { var chave = System.getenv("OPENAI_API_KEY"); var service = new OpenAiService(chave, Duration.ofSeconds(30)); var completionRequest = ChatCompletionRequest .builder() .model("gpt-4") .messages(Arrays.asList( new ChatMessage(ChatMessageRole.USER.value(), user), new ChatMessage(ChatMessageRole.SYSTEM.value(), system) )) .build(); service .createChatCompletion(completionRequest) .getChoices() .forEach(c -> System.out.println(c.getMessage().getContent())); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((1993, 2021), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((2070, 2100), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value')]
package it.ohalee.minecraftgpt; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.service.OpenAiService; import org.bukkit.configuration.ConfigurationSection; import retrofit2.HttpException; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; public class OpenAI { private static OpenAiService service; public static CompletableFuture<Void> init(String key) { return CompletableFuture.runAsync(() -> service = new OpenAiService(key, Duration.ofSeconds(5))); } public static CompletableFuture<String> getResponse(ConfigurationSection section, List<ChatMessage> chatMessages, String message) { chatMessages.add(new ChatMessage("user", message)); return CompletableFuture.supplyAsync(() -> { String model = section.getString("model", "text-davinci-003"); int maxTokens = section.getInt("max-tokens"); double frequencyPenalty = section.getDouble("frequency-penalty"); double presencePenalty = section.getDouble("presence-penalty"); double topP = section.getDouble("top-p"); double temperature = section.getDouble("temperature"); String reply = service.createChatCompletion(ChatCompletionRequest.builder() .messages(chatMessages) .model(model) .temperature(temperature) .maxTokens(maxTokens) .topP(topP) .frequencyPenalty(frequencyPenalty) .presencePenalty(presencePenalty) .stop(Arrays.asList("Human:", "AI:")) .build()) .getChoices().get(0).getMessage().getContent(); chatMessages.add(new ChatMessage("assistant", reply)); return reply; }).exceptionally(throwable -> { if (throwable.getCause() instanceof HttpException e) { String reason = switch (e.response().code()) { case 401 -> "Invalid API key! Please check your configuration."; case 429 -> "Too many requests! Please wait a few seconds and try again."; case 500 -> "OpenAI service is currently unavailable. Please try again later."; default -> "Unknown error! Please try again later. If this error persists, contact the plugin developer."; }; throw new RuntimeException(reason, throwable); } throw new RuntimeException(throwable); }); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((876, 2775), 'java.util.concurrent.CompletableFuture.supplyAsync'), ((1379, 1877), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1379, 1840), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1379, 1774), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1379, 1712), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1379, 1648), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1379, 1608), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1379, 1558), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1379, 1504), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1379, 1462), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package com.example.gpt3inhebrew; import android.os.Handler; import android.os.Message; import com.theokanning.openai.OpenAiService; import com.theokanning.openai.completion.CompletionRequest; public class GptThread extends Thread { String prompt,temperature, top_p, frequency_penalty, presence_penalty, maximum_length; Handler handler; public GptThread(String prompt, String temperature, String top_p, String frequency_penalty, String presence_penalty, String maximum_length, Handler handler) { this.prompt = prompt; this.temperature = temperature; this.top_p = top_p; this.frequency_penalty = frequency_penalty; this.presence_penalty = presence_penalty; this.maximum_length = maximum_length; this.handler = handler; } @Override public void run() { super.run(); Message message = new Message(); String token = Helper.open_ai_api_key; OpenAiService service = new OpenAiService(token); CompletionRequest completionRequest = CompletionRequest.builder() .prompt(prompt) .temperature(Double.valueOf(temperature)) .topP(Double.valueOf(top_p)) .frequencyPenalty(Double.valueOf(frequency_penalty)) .presencePenalty(Double.valueOf(presence_penalty)) .maxTokens(Integer.valueOf(maximum_length)) .echo(true) .build(); try { message.obj = service.createCompletion("text-davinci-002", completionRequest).getChoices(); message.what = 200; handler.sendMessage(message); } catch (Exception e) { message.obj = e.getMessage(); message.what = 400; handler.sendMessage(message); } } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((1056, 1467), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1056, 1442), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1056, 1414), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1056, 1354), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1056, 1287), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1056, 1218), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1056, 1173), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1056, 1115), 'com.theokanning.openai.completion.CompletionRequest.builder')]
import java.awt.Color; import java.awt.Desktop; import java.awt.Dimension; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.border.EmptyBorder; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultCaret; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import javax.swing.text.StyledDocument; import com.google.gson.Gson; import com.jtattoo.plaf.hifi.HiFiLookAndFeel; import javax.swing.JTextArea; import javax.swing.KeyStroke; //import javax.swing.JTextPane; import javax.swing.UIManager; import javax.swing.JButton; import javax.swing.JFileChooser; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.lang.reflect.Field; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.Properties; import java.util.Random; import java.awt.event.ActionEvent; import javax.swing.JScrollPane; import java.awt.Font; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import javax.swing.ImageIcon; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JEditorPane; 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.commonmark.node.*; import org.commonmark.parser.Parser; import org.commonmark.renderer.html.HtmlRenderer; public class MainFrame extends JFrame { private static MainFrame frame; private JPanel contentPane; private OpenAiService service; private final static ArrayList<ChatMessage> messages = new ArrayList<>(); private static JTextArea ChatArea; private static JButton SubmitButton; private static JScrollPane scrollPane; private static JScrollPane scrollPane_1; private static JButton SaveButton; private static JButton ImportButton; private static JButton ResetButton; private static JEditorPane DisplayArea; private static JEditorPane HTMLArea; private static StyledDocument doc; private JMenuBar menuBar; private static String GPTConvo; private File FGPTConvo; public static Properties prop; public static String version = "1.3.2"; private Boolean first = true; private Boolean chathistory = true; private Boolean autotitle = true; private Boolean enter2submit = true; private Boolean cloaderopen = false; private Boolean aframeopen = false; private static Boolean isHTMLView = false; private static Parser parser; private static HtmlRenderer renderer; public static Boolean isAlpha = true; private Boolean isStreamRunning = false; private static int FormSize = 3; private static int FontSize = 12; public static int seltheme = 0; private ChatLoader cloader; private String chatDir; //Initializing Style objects for RTF text in DisplayArea private static Style YouStyle; private static Style InvisibleStyle; private static Style GPTStyle; private static Style ChatStyle; private static Style ErrorStyle; private static MainFrame INSTANCE = null; //This function is used to load a chat from a file specified by the full file path and filename. //It sets the title of the instance to include the filename and clears the display area. //It also resets the messages and reads them from the file. If the view is set to HTML, it resets the HTML area style and renders the document. //If there is an exception, it displays an error message and prints the stack trace. Finally, it sets the FGPTConvo file and sets the first flag to false. public static void loadchat(String fullfilepath, String filename) throws BadLocationException { INSTANCE.setTitle("JavaGPT - " + filename); try { DisplayArea.setText(""); messages.clear(); readMessagesFromFile(fullfilepath); if(isHTMLView) { resetHTMLAreaStyle(); Node document = parser.parse(DisplayArea.getDocument().getText(0, DisplayArea.getDocument().getLength())); //System.out.println(renderer.render(document)); HTMLArea.setText(renderer.render(document)); } } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } INSTANCE.FGPTConvo = new File(fullfilepath); INSTANCE.first = false; } //Writes chat contents to .json format public void writeMessagesToFile(String filename) throws IOException { try (PrintWriter writer = new PrintWriter(filename)) { Gson gson = new Gson(); for (ChatMessage message : messages) { String json = gson.toJson(message); writer.println(json); } } } //Reads chat contents from provided .json, stores it in the messages ArrayList and outputs contents in DisplayArea public static void readMessagesFromFile(String filename) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { String line; Gson gson = new Gson(); while ((line = reader.readLine()) != null) { ChatMessage message = gson.fromJson(line, ChatMessage.class); if(message.getRole().equals("user")) { try { doc.insertString(doc.getLength(), "You", YouStyle); doc.insertString(doc.getLength(), ":\n", InvisibleStyle); doc.insertString(doc.getLength(), message.getContent() + "\n\n", ChatStyle); } catch (BadLocationException e) { e.printStackTrace(); } }else{ try { doc.insertString(doc.getLength(), "ChatGPT", GPTStyle); doc.insertString(doc.getLength(), ":\n", InvisibleStyle); doc.insertString(doc.getLength(), message.getContent() + "\n\n", ChatStyle); } catch (BadLocationException e) { e.printStackTrace(); } } messages.add(message); } } } //Refreshes DisplayArea contents with current messages ArrayList items public void refreshMessages() { DisplayArea.setText(""); for (ChatMessage message : messages) { if(message.getRole().equals("user")) { try { doc.insertString(doc.getLength(), "You", YouStyle); doc.insertString(doc.getLength(), ":\n", InvisibleStyle); doc.insertString(doc.getLength(), message.getContent() + "\n\n", ChatStyle); } catch (BadLocationException e) { e.printStackTrace(); } }else{ try { doc.insertString(doc.getLength(), "ChatGPT", GPTStyle); doc.insertString(doc.getLength(), ":\n", InvisibleStyle); doc.insertString(doc.getLength(), message.getContent() + "\n\n", ChatStyle); } catch (BadLocationException e) { e.printStackTrace(); } } } } //Used in newFile() to create a new file name (Ex: Chat_x0y, Chat_09k, Chat_rc7) public static String getRandomString() { String letters = "abcdefghijklmnopqrstuvwxyz1234567890"; Random rand = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 3; i++) { int index = rand.nextInt(letters.length()); sb.append(letters.charAt(index)); } return sb.toString(); } //Creates a new chat file by setting FGPTConvo File object to a new file name public void newFile() { String randfilename = getRandomString(); FGPTConvo = new File(chatDir + "\\Chat_" + randfilename + ".json"); while(FGPTConvo.exists()) { randfilename = getRandomString(); FGPTConvo = new File(chatDir + "\\Chat_" + randfilename + ".json"); } setTitle("JavaGPT - Chat_" + randfilename); } //Resets all objects used for chat. Is invoked when "New Chat" is pressed or a chat file is loaded public void Reset() { isStreamRunning = false; messages.clear(); FGPTConvo = null; GPTConvo = ""; DisplayArea.setText(""); HTMLArea.setText(""); resetHTMLAreaStyle(); ChatArea.setText(""); setTitle("JavaGPT"); first = true; } /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { //Sets project to support Unicode try { System.setProperty("file.encoding","UTF-8"); Field charset = Charset.class.getDeclaredField("defaultCharset"); charset.setAccessible(true); charset.set(null,null); }catch(Exception e) {} //------------------------------- //Loads properties------------------------ prop = new Properties(); InputStream input = null; try { input = new FileInputStream("config.properties"); prop.load(input); } catch (FileNotFoundException e1) { int choice = JOptionPane.showConfirmDialog(null, "No config file found. Would you like to create one?", "Create Config File", JOptionPane.YES_NO_OPTION); if(choice == JOptionPane.YES_OPTION) { String apikey = JOptionPane.showInputDialog( null, "Please enter your API key:"); prop.setProperty("apikey", apikey); prop.setProperty("model", "gpt-3.5-turbo"); prop.setProperty("maxTokens", "1024"); prop.setProperty("timeout", "30"); prop.setProperty("proxyip", ""); // WIP Support will be added back prop.setProperty("proxyport", ""); // WIP Support will be added back prop.setProperty("proxytype", ""); prop.setProperty("autotitle", "true"); prop.setProperty("autoscroll", "true"); prop.setProperty("EnterToSubmit", "true"); prop.setProperty("chat_history", "true"); prop.setProperty("chat_location_override", ""); prop.setProperty("WindowSize", "medium"); prop.setProperty("FontSize", "12"); prop.setProperty("Theme", "dark"); try { FileOutputStream out = new FileOutputStream("config.properties"); prop.store(out, "Generated config file"); out.close(); JOptionPane.showMessageDialog(null, "Config file created successfully!"); } catch (IOException ex) { ex.printStackTrace(); } } e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } //---------------------------------------- //Sets proxy settings if(prop.getProperty("proxyip") != null && !prop.getProperty("proxyip").isEmpty() && prop.getProperty("proxyport") != null && !prop.getProperty("proxyport").isEmpty()) { if(prop.getProperty("proxytype").toLowerCase().equals("http")) { System.setProperty("http.proxyHost", prop.getProperty("proxyip")); System.setProperty("http.proxyPort", prop.getProperty("proxyport")); }else if(prop.getProperty("proxytype").toLowerCase().equals("https")){ System.setProperty("https.proxyHost", prop.getProperty("proxyip")); System.setProperty("https.proxyPort", prop.getProperty("proxyport")); }else { System.getProperties().put( "proxySet", "true" ); System.getProperties().put( "socksProxyHost", prop.getProperty("proxyip") ); System.getProperties().put( "socksProxyPort", prop.getProperty("proxyport") ); } } //------------------- //Sets selected JTattoo theme------------- try { if(!prop.getProperty("Theme").isEmpty()) { if(prop.getProperty("Theme").equals("dark")) { Properties p = new Properties(); p.put("windowTitleFont", "Ebrima PLAIN 15"); p.put("backgroundPattern", "off"); p.put("logoString", ""); HiFiLookAndFeel.setCurrentTheme(p); UIManager.setLookAndFeel("com.jtattoo.plaf.hifi.HiFiLookAndFeel"); seltheme = 1; } } } catch (Exception e) { e.printStackTrace(); } //---------------------------------------- frame = new MainFrame(); //Loads main JFrame //Scales JFrame based on "WindowSize" prop switch(prop.getProperty("WindowSize")){ case "small": FormSize=1; break; case "large": FormSize=2; break; default: FormSize=3; break; } setFormSize(); //---------------------------------------- //Sets app icon to JavaGPT logo frame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("logo.png"))); if(prop.getProperty("FontSize") != null && !prop.getProperty("FontSize").isEmpty()) { try { FontSize = Integer.parseInt(prop.getProperty("FontSize")); } catch (NumberFormatException e) { } } //Makes JFrame visible frame.setVisible(true); } }); } /** * Create the frame. * @param GPTStyle * @param ChatStyle */ public MainFrame() { setResizable(false); INSTANCE = this; setTitle("JavaGPT"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Initializes OpenAI's ChatGPT API with provided API key service = new OpenAiService(prop.getProperty("apikey"),(prop.getProperty("timeout") == null && prop.getProperty("timeout").isEmpty()) ? Duration.ZERO : Duration.ofSeconds(Long.parseLong(prop.getProperty("timeout")))); menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu OptionMenu = new JMenu("Options"); menuBar.add(OptionMenu); //Renderer and Parser for HTMLView parser = Parser.builder().build(); renderer = HtmlRenderer.builder().build(); // //Code for HTML Viewer JMenu. If clicked, it will set isHTMLView to its counter value. //If true, it will switch scrollPane to show HTMLArea and display the plain text contents for DisplayArea in it //If false, it will switch scrollPane to show DisplayArea JMenuItem HTMLViewMenuItem = new JMenuItem("HTML View"); HTMLViewMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(isHTMLView) { try { scrollPane.setViewportView(DisplayArea); HTMLViewMenuItem.setText("HTML View"); isHTMLView=false; } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }else { try { scrollPane.setViewportView(HTMLArea); resetHTMLAreaStyle(); Node document = parser.parse(DisplayArea.getDocument().getText(0, DisplayArea.getDocument().getLength())); HTMLArea.setText(renderer.render(document)); HTMLViewMenuItem.setText("Normal View"); isHTMLView=true; } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); OptionMenu.add(HTMLViewMenuItem); //Will scale the JFrame based on preset dimensions for JMenu options Large, Medium, & Small JMenu FormSizeMenu = new JMenu("Form Size"); OptionMenu.add(FormSizeMenu); JMenuItem SmallMenuItem = new JMenuItem("Small"); FormSizeMenu.add(SmallMenuItem); SmallMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(FormSize != 1) { FormSize = 1; setFormSize(); } } }); JMenuItem MediumMenuItem = new JMenuItem("Medium"); FormSizeMenu.add(MediumMenuItem); MediumMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(FormSize != 3) { FormSize = 3; setFormSize(); } } }); JMenuItem LargeMenuItem = new JMenuItem("Large"); FormSizeMenu.add(LargeMenuItem); LargeMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(FormSize != 2) { FormSize = 2; setFormSize(); } } }); JMenu FontSizeMenu = new JMenu("Font Size"); OptionMenu.add(FontSizeMenu); JMenuItem DefaultFSMenuItem = new JMenuItem("Default (12)"); FontSizeMenu.add(DefaultFSMenuItem); DefaultFSMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(FontSize != 12) { FontSize = 12; setFontSize(); refreshMessages(); } } }); JMenuItem LargeFSMenuItem = new JMenuItem("Large (16)"); FontSizeMenu.add(LargeFSMenuItem); LargeFSMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(FontSize != 16) { FontSize = 16; setFontSize(); refreshMessages(); } } }); JMenuItem ExtraLargeFSMenuItem = new JMenuItem("Ex-Large (20)"); FontSizeMenu.add(ExtraLargeFSMenuItem); ExtraLargeFSMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(FontSize != 20) { FontSize = 20; setFontSize(); refreshMessages(); } } }); JMenuItem CustomFSMenuItem = new JMenuItem("Custom"); FontSizeMenu.add(CustomFSMenuItem); CustomFSMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String input = JOptionPane.showInputDialog(null, "Enter font size:", "Font Size", JOptionPane.PLAIN_MESSAGE); try { FontSize = Integer.parseInt(input); setFontSize(); refreshMessages(); } catch (NumberFormatException e1) { JOptionPane.showMessageDialog(null, "Invalid font size", "Error", JOptionPane.ERROR_MESSAGE); } } }); //---------------------------------------------------------------------------------- JMenu RenameMenu = new JMenu("Rename"); OptionMenu.add(RenameMenu); //Rename option which when clicked has ChatGPT generate a title based on current chat context JMenuItem AutoMenuItem = new JMenuItem("Auto"); RenameMenu.add(AutoMenuItem); AutoMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(FGPTConvo != null) { AutoTitle(); }else { JOptionPane.showMessageDialog(null, "No chat file loaded", "Error", JOptionPane.ERROR_MESSAGE); } } }); //This code adds a manual menu item to a rename menu. //When the manual menu item is clicked, it prompts the user to enter a title for the file to be renamed. //If the file already exists with the inputted title, an error message is shown. //Otherwise, the file is renamed and a success message is shown along with the new title in the window title bar. //However, if no file is loaded, an error message is shown. JMenuItem ManualMenuItem = new JMenuItem("Manual"); RenameMenu.add(ManualMenuItem); ManualMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(FGPTConvo != null) { String title = JOptionPane.showInputDialog(null, "Please enter a title:", "Rename", JOptionPane.PLAIN_MESSAGE); if(title != null) { File file = new File(FGPTConvo.getParentFile(), title + ".json"); if(file.exists()) { JOptionPane.showMessageDialog(null, "File already exists", "Error", JOptionPane.ERROR_MESSAGE); }else { FGPTConvo.renameTo(file); FGPTConvo = file; JOptionPane.showMessageDialog(null, "File renamed successfully", "Success", JOptionPane.INFORMATION_MESSAGE); INSTANCE.setTitle("JavaGPT - " + title); } } }else { JOptionPane.showMessageDialog(null, "No chat file loaded", "Error", JOptionPane.ERROR_MESSAGE); } } }); //Deletes chat file if it exists JMenuItem DeleteMenuItem = new JMenuItem("Delete"); DeleteMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(FGPTConvo != null && FGPTConvo.exists()) { //checks if the file exists FGPTConvo.delete(); //deletes the file Reset(); } else { JOptionPane.showMessageDialog(null, "File not found", "Error", JOptionPane.ERROR_MESSAGE); } } }); //Reverts chat contents to previous state by removing the last prompt & response from messages ArrayList and reloads the DisplayArea JMenuItem RevertMenuItem = new JMenuItem("Revert"); RevertMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(messages.size() >= 4) { //checks if the file exists messages.remove(messages.size() - 1); messages.remove(messages.size() - 1); refreshMessages(); } else { if(messages.isEmpty()) { JOptionPane.showMessageDialog(null, "No chat loaded", "Error", JOptionPane.ERROR_MESSAGE); }else { JOptionPane.showMessageDialog(null, "Can't revert first prompt", "Error", JOptionPane.ERROR_MESSAGE); } } } }); OptionMenu.add(RevertMenuItem); OptionMenu.add(DeleteMenuItem); //Opens "About" JFrame JMenuItem AboutMenuItem = new JMenuItem("About"); AboutMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(aframeopen != true) { AboutFrame aframe = new AboutFrame(); aframe.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("logo.png"))); aframe.setVisible(true); aframeopen = true; aframe.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { aframeopen = false; } }); } } }); OptionMenu.add(AboutMenuItem); //Opens "ChatLoader" (Chat History) JFrame JMenu LoadChatButton = new JMenu("Load Chat"); LoadChatButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(cloaderopen != true) { cloader = new ChatLoader(chatDir); cloader.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("logo.png"))); cloader.setVisible(true); cloaderopen = true; cloader.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { cloaderopen = false; } }); } } }); menuBar.add(LoadChatButton); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); scrollPane = new JScrollPane(); contentPane.add(scrollPane); DisplayArea = new JEditorPane(); scrollPane.setViewportView(DisplayArea); DisplayArea.setEditable(false); DisplayArea.setContentType("text/rtf"); HTMLArea = new JEditorPane(); HTMLArea.setEditable(false); HTMLArea.setBackground(Color.white); HTMLArea.setContentType("text/html"); //Sets properties for Style objects StyleContext sc = StyleContext.getDefaultStyleContext(); YouStyle = sc.addStyle("bold", null); StyleConstants.setFontFamily(YouStyle, "Tahoma"); StyleConstants.setFontSize(YouStyle, FontSize); StyleConstants.setBold(YouStyle, true); GPTStyle = sc.addStyle("bold", null); StyleConstants.setFontFamily(GPTStyle, "Tahoma"); StyleConstants.setFontSize(GPTStyle, FontSize); StyleConstants.setBold(GPTStyle, true); StyleConstants.setForeground(GPTStyle, Color.RED); //getHSBColor(0, 0.8f, 0.8f) InvisibleStyle = sc.addStyle("bold", null); StyleConstants.setForeground(InvisibleStyle, DisplayArea.getBackground()); ChatStyle = sc.addStyle("black", null); StyleConstants.setFontFamily(ChatStyle, "Tahoma"); StyleConstants.setFontSize(ChatStyle, FontSize); ErrorStyle = sc.addStyle("ErrorStyle", null); StyleConstants.setItalic(ErrorStyle, true); StyleConstants.setFontFamily(ErrorStyle, "Tahoma"); StyleConstants.setFontSize(ErrorStyle, FontSize); if(seltheme == 1) { StyleConstants.setForeground(YouStyle, Color.ORANGE); //getHSBColor(30f/360, 0.8f, 1f) StyleConstants.setForeground(ChatStyle, Color.WHITE); //Color.getHSBColor(0f, 0f, 0.8f) StyleConstants.setForeground(ErrorStyle, Color.WHITE); //Color.getHSBColor(0f, 0f, 0.8f) }else { StyleConstants.setForeground(YouStyle, Color.BLUE); StyleConstants.setForeground(ChatStyle, Color.BLACK); StyleConstants.setForeground(ErrorStyle, Color.BLACK); } //------------------------------------ doc = (StyledDocument) DisplayArea.getDocument(); //"Submit" button SubmitButton = new JButton("Submit"); SubmitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { submit(); } }); contentPane.add(SubmitButton); //"New Chat" button ResetButton = new JButton("New Chat"); ResetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Reset(); } }); contentPane.add(ResetButton); scrollPane_1 = new JScrollPane(); contentPane.add(scrollPane_1); ChatArea = new JTextArea(); ChatArea.setWrapStyleWord(true); scrollPane_1.setViewportView(ChatArea); ChatArea.setLineWrap(true); //Makes hotkeys for ChatArea ChatArea.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if(enter2submit) { if (e.getKeyCode() == KeyEvent.VK_ENTER && e.isShiftDown()) { int caret = ChatArea.getCaretPosition(); ChatArea.insert("\n", caret); ChatArea.setCaretPosition(caret + 1); }else if(e.getKeyCode() == KeyEvent.VK_ENTER) { submit(); } }else { if (e.getKeyCode() == KeyEvent.VK_ENTER && e.isControlDown()) { submit(); } } } }); //Save Button code: takes contents of DisplayArea and saves it in plain text in user selected location with user provided filename SaveButton = new JButton(""); try { SaveButton.setIcon(new ImageIcon(MainFrame.class.getResource("FloppyDrive.gif"))); }catch(Exception e4) { JOptionPane.showMessageDialog(null, e4.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } SaveButton.setFont(new Font("Arial Black", Font.BOLD, 6)); SaveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File defaultDir = new File("."); JFileChooser fileChooser = new JFileChooser(defaultDir); fileChooser.setDialogTitle("Save chat"); int result = fileChooser.showSaveDialog(null); if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); try { FileWriter writer = new FileWriter(selectedFile); String plaintext = DisplayArea.getDocument().getText(0, DisplayArea.getDocument().getLength()); writer.write(plaintext); writer.close(); JOptionPane.showMessageDialog(null, "File saved successfully."); } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(null, e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } catch (BadLocationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); contentPane.add(SaveButton); //Imports user selected file and sets contents to ChatArea ImportButton = new JButton(""); ImportButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Import prompt"); int returnVal = fileChooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { String filename = fileChooser.getSelectedFile().getAbsolutePath(); try { ChatArea.setText(new String(Files.readAllBytes(Paths.get(filename)))); } catch (IOException e1) { // TODO Auto-generated catch block JOptionPane.showMessageDialog(null, e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } }); ImportButton.setIcon(new ImageIcon(MainFrame.class.getResource("upFolder.gif"))); contentPane.add(ImportButton); //Right-click menu MouseListners for various chat elements DisplayArea.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { showDisplayMenu(e.getX(), e.getY()); } } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { showDisplayMenu(e.getX(), e.getY()); } } }); HTMLArea.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { showHTMLMenu(e.getX(), e.getY()); } } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { showHTMLMenu(e.getX(), e.getY()); } } }); ChatArea.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { showChatMenu(e.getX(), e.getY()); } } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { showChatMenu(e.getX(), e.getY()); } } }); //-------------------------------------------------------------------- //Allows for HTMLArea to have HyperLinks HTMLArea.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { try { Desktop.getDesktop().browse(e.getURL().toURI()); } catch (IOException | URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); //Default /*setBounds(100, 100, 702, 707); //Uncomment this when editing design SubmitButton.setBounds(10, 554, 89, 23); ResetButton.setBounds(10, 616, 89, 23); scrollPane.setBounds(10, 11, 667, 532); scrollPane_1.setBounds(109, 554, 568, 85); SaveButton.setBounds(10, 585, 43, 23); ImportButton.setBounds(56, 585, 43, 23);*/ //Bulk property setting------------------- try { if(prop.getProperty("autoscroll") != null && !prop.getProperty("autoscroll").isEmpty()) { if(prop.getProperty("autoscroll").equals("true")) { DefaultCaret caret = (DefaultCaret)DisplayArea.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); } } if(prop.getProperty("chat_history") != null && !prop.getProperty("chat_history").isEmpty()) { if(prop.getProperty("chat_history").equals("true")){ chathistory = true; }else{ chathistory = false; } } if(prop.getProperty("autotitle") != null && !prop.getProperty("autotitle").isEmpty()) { if(prop.getProperty("autotitle").equals("true")){ autotitle = true; }else{ autotitle = false; } } if(prop.getProperty("EnterToSubmit") != null && !prop.getProperty("EnterToSubmit").isEmpty()) { if(prop.getProperty("EnterToSubmit").equals("true")){ ChatArea.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "none"); }else{ enter2submit = false; } } if(prop.getProperty("chat_location_override") != null && !prop.getProperty("chat_location_override").isEmpty()){ chatDir = prop.getProperty("chat_location_override"); }else { try { chatDir = new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParent(); chatDir = chatDir + "\\chat_history"; File directory = new File(chatDir); if (!directory.exists()) { directory.mkdirs(); } } catch (URISyntaxException e1) { JOptionPane.showMessageDialog(null, e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } //---------------------------------------- } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } //Processes ChatArea contents submitted by user to ChatGPT API and displays response private void submit() { if(isStreamRunning) { isStreamRunning = false; SubmitButton.setText("Submit"); return; } Thread myThread = new Thread(new Runnable() { public void run() { SubmitButton.setText("Cancel Req"); //Boolean success = false; try { doc.insertString(doc.getLength(), "You", YouStyle); doc.insertString(doc.getLength(), ":\n", InvisibleStyle); doc.insertString(doc.getLength(), ChatArea.getText() + "\n\n", ChatStyle); doc.insertString(doc.getLength(), "ChatGPT", GPTStyle); doc.insertString(doc.getLength(), ":\n", InvisibleStyle); } catch (BadLocationException e2) { e2.printStackTrace(); } try { StringBuilder GPTConvoBuilder = new StringBuilder(); final ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), ChatArea.getText()); messages.add(userMessage); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest .builder() .model(prop.getProperty("model")) .messages(messages) .n(1) .maxTokens(Integer.parseInt(prop.getProperty("maxTokens"))) .logitBias(new HashMap<>()) .build(); isStreamRunning = true; service.streamChatCompletion(chatCompletionRequest) .doOnError(Throwable::printStackTrace) .takeWhile(resultsBatch -> isStreamRunning) .blockingForEach(chunk -> { for (ChatCompletionChoice choice : chunk.getChoices()) { if(choice.getMessage().getContent() != null) { GPTConvoBuilder.append(choice.getMessage().getContent()); } try { //String messageContent = new String(choice.getMessage().getContent().getBytes("UTF-8"), "UTF-8"); //doc.putProperty("console.encoding", "UTF-8"); doc.insertString(doc.getLength(), choice.getMessage().getContent(), ChatStyle); } catch (BadLocationException e2) { e2.printStackTrace(); } } }); //service.shutdownExecutor(); if(isStreamRunning) { try { doc.insertString(doc.getLength(), "\n\n", ChatStyle); if(isHTMLView) { resetHTMLAreaStyle(); Node document = parser.parse(DisplayArea.getDocument().getText(0, DisplayArea.getDocument().getLength())); HTMLArea.setText(renderer.render(document)); } } catch (BadLocationException e2) { e2.printStackTrace(); } GPTConvo = GPTConvoBuilder.toString(); final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), GPTConvo); messages.add(systemMessage); if(chathistory) { if(first) { newFile(); } try { writeMessagesToFile(FGPTConvo.getPath()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(first && autotitle){ AutoTitle(); first = false; } } ChatArea.setText(""); }else { if(messages.size() != 0) { messages.remove(messages.size() - 1); doc.insertString(doc.getLength(), "\n\n" + "Note: The previous prompt and response did not save as it was canceled" + "\n\n", ErrorStyle); } } }catch(Exception e) { //JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); try { doc.insertString(doc.getLength(), "Error: " + e.getMessage() + "\n\n", ErrorStyle); } catch (BadLocationException e2) { e2.printStackTrace(); } } isStreamRunning = false; SubmitButton.setText("Submit"); } }); myThread.start(); // Start the thread } //Right-click functions for various JFrame objects private void showDisplayMenu(int x, int y) { JPopupMenu popupMenu = new JPopupMenu(); JMenuItem copyMenuItem = new JMenuItem("Copy"); copyMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String selectedText = DisplayArea.getSelectedText(); if (selectedText != null) { StringSelection selection = new StringSelection(selectedText); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, null); } } }); popupMenu.add(copyMenuItem); popupMenu.show(DisplayArea, x, y); } private void showHTMLMenu(int x, int y) { JPopupMenu popupMenu = new JPopupMenu(); JMenuItem copyMenuItem = new JMenuItem("Copy"); copyMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String selectedText = HTMLArea.getSelectedText(); if (selectedText != null) { StringSelection selection = new StringSelection(selectedText); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, null); } } }); popupMenu.add(copyMenuItem); popupMenu.show(HTMLArea, x, y); } private void showChatMenu(int x, int y) { JPopupMenu popupMenu = new JPopupMenu(); JMenuItem copyMenuItem = new JMenuItem("Copy"); copyMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String selectedText = ChatArea.getSelectedText(); if (selectedText != null) { StringSelection selection = new StringSelection(selectedText); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, null); } } }); popupMenu.add(copyMenuItem); JMenuItem pasteMenuItem = new JMenuItem("Paste"); pasteMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String selectedText = ChatArea.getSelectedText(); if (selectedText != null && !selectedText.isEmpty()) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable contents = clipboard.getContents(null); if (contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { String clipboardText = (String) contents.getTransferData(DataFlavor.stringFlavor); ChatArea.replaceSelection(clipboardText); } catch (UnsupportedFlavorException | IOException ex) { ex.printStackTrace(); } } } else { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable contents = clipboard.getContents(null); if (contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { String clipboardText = (String) contents.getTransferData(DataFlavor.stringFlavor); int caretPos = ChatArea.getCaretPosition(); ChatArea.insert(clipboardText, caretPos); } catch (UnsupportedFlavorException | IOException ex) { ex.printStackTrace(); } } } } }); popupMenu.add(pasteMenuItem); JMenuItem clearMenuItem = new JMenuItem("Clear"); clearMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ChatArea.setText(""); } }); popupMenu.add(clearMenuItem); popupMenu.show(ChatArea, x, y); } //-------------------------------------------------- //Function that auto generates title for current chat based off its context public void AutoTitle() { Thread myThread = new Thread(new Runnable() { public void run() { setTitle("JavaGPT *** ChatGPT is generating a title. Please wait..."); SubmitButton.setText("Loading..."); StringBuilder TitleBuilder = new StringBuilder(); try { final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "Create a short title that summarizes this conversation. Provide title only."); messages.add(systemMessage); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest .builder() .model(prop.getProperty("model")) .messages(messages) .n(1) .maxTokens(25) .logitBias(new HashMap<>()) .build(); service.streamChatCompletion(chatCompletionRequest) .doOnError(Throwable::printStackTrace) .blockingForEach(chunk -> { for (ChatCompletionChoice choice : chunk.getChoices()) { if(choice.getMessage().getContent() != null) { TitleBuilder.append(choice.getMessage().getContent()); } } }); messages.remove(messages.size() - 1); String title = TitleBuilder.toString(); title = title.replaceAll("[\\\\/:*?\"<>|]", ""); if(title.substring(title.length() - 1).equals(".")) { title = title.substring(0, title.length() - 1); } SubmitButton.setText("Submit"); if(title != null) { File file = new File(FGPTConvo.getParentFile(), title + ".json"); if(file.exists()) { JOptionPane.showMessageDialog(null, "File already exists", "Error", JOptionPane.ERROR_MESSAGE); setTitle("JavaGPT - " + FGPTConvo.getName().substring(0, FGPTConvo.getName().length()-5)); }else { FGPTConvo.renameTo(file); FGPTConvo = file; INSTANCE.setTitle("JavaGPT - " + title); } } }catch(Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); SubmitButton.setText("Submit"); setTitle("JavaGPT - " + FGPTConvo.getName().substring(0, FGPTConvo.getName().length()-5)); } } }); myThread.start(); } //Resets HTMLArea to properly display new HTML content public static void resetHTMLAreaStyle() { HTMLArea.setContentType("text/plain"); HTMLArea.setContentType("text/html"); } //sets FormSize to presets defined public static void setFormSize(){ switch(FormSize){ case 1: frame.getContentPane().setPreferredSize(new Dimension(475, 532)); frame.pack(); scrollPane_1.setBounds(103, 454, 363, 69); scrollPane.setBounds(10, 11, 456, 432); SubmitButton.setBounds(10, 454, 89, 23); SaveButton.setBounds(10, 477, 43, 23); ImportButton.setBounds(56, 477, 43, 23); ResetButton.setBounds(10, 500, 89, 23); break; case 2: frame.getContentPane().setPreferredSize(new Dimension(1370, 960)); frame.pack(); SubmitButton.setBounds(13, 831, 148, 36); ResetButton.setBounds(13, 914, 148, 36); scrollPane.setBounds(13, 15, 1344, 802); scrollPane_1.setBounds(171, 831, 1186, 118); SaveButton.setBounds(13, 873, 73, 36); ImportButton.setBounds(88, 873, 73, 36); break; default: frame.getContentPane().setPreferredSize(new Dimension(686, 647)); frame.pack(); SubmitButton.setBounds(10, 554, 89, 23); ResetButton.setBounds(10, 616, 89, 23); scrollPane.setBounds(10, 11, 667, 532); scrollPane_1.setBounds(109, 554, 568, 85); SaveButton.setBounds(10, 585, 43, 23); ImportButton.setBounds(56, 585, 43, 23); break; } } public void setFontSize() { StyleConstants.setFontSize(YouStyle, FontSize); StyleConstants.setFontSize(GPTStyle, FontSize); StyleConstants.setFontSize(ChatStyle, FontSize); StyleConstants.setFontSize(ErrorStyle, FontSize); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((9623, 9671), 'java.nio.charset.Charset.class.getDeclaredField'), ((14539, 14611), 'java.awt.Toolkit.getDefaultToolkit'), ((15633, 15657), 'org.commonmark.parser.Parser.builder'), ((15672, 15702), 'org.commonmark.renderer.html.HtmlRenderer.builder'), ((23570, 23642), 'java.awt.Toolkit.getDefaultToolkit'), ((24311, 24383), 'java.awt.Toolkit.getDefaultToolkit'), ((32327, 32374), 'java.awt.Desktop.getDesktop'), ((36175, 36203), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((38513, 38543), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((40381, 40429), 'java.awt.Toolkit.getDefaultToolkit'), ((41081, 41129), 'java.awt.Toolkit.getDefaultToolkit'), ((41783, 41831), 'java.awt.Toolkit.getDefaultToolkit'), ((42314, 42362), 'java.awt.Toolkit.getDefaultToolkit'), ((42963, 43011), 'java.awt.Toolkit.getDefaultToolkit'), ((44481, 44511), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value')]
package br.com.danilo.ecommerce; 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.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.time.Duration; import java.util.Arrays; // --> Identificador de Perfil de Compra de Clientes public class ProfileIdentifier { public static void main(String[] args) { var promptSystem = """ Identifique o perfil de compra de cada cliente. A resposta deve ser: Cliente - descreva o perfil do cliente em três palavras """; var client = loadCustomersFromFile(); // --> Carrega os clientes do arquivo String modelOpenAI = "gpt-3.5-turbo"; // --> Modelo do OpenAI a ser utilizado var tokens = countTokens(promptSystem); // --> Contador de Tokens var expectedResponseSize = 2048; // --> Tamanho esperado da resposta //? ------------------------------------ TESTE MODEL OPENAI -------------------------------------------------- System.out.println("Quantidade de Tokens: | Number of Tokens:" + tokens); System.out.println("Modelo OpenAI: | Model OpenAI: " + modelOpenAI + "\n"); System.out.println("||- ---------------------------------------------------------------- -||" + "\n" + "\n"); if (tokens > 4096) { // verificador de quantidade de tokens para escolha do melhor modelo do OpenAI modelOpenAI = "gpt-3.5-turbo-16k"; } //? ------------------------------------------------------------------------------------------------------------ var request = ChatCompletionRequest .builder() .model(modelOpenAI) // --> Modelo do OpenAI a ser utilizado .maxTokens(expectedResponseSize) // --> Tamanho esperado da resposta .messages(Arrays.asList( new ChatMessage( ChatMessageRole.SYSTEM.value(), promptSystem), new ChatMessage( ChatMessageRole.SYSTEM.value(), client))) .build(); var keyToken = System.getenv("OPENAI_API_KEY"); var serviceOpenAI = new OpenAiService(keyToken, Duration.ofSeconds(30)); System.out.println( serviceOpenAI .createChatCompletion(request) .getChoices().get(0).getMessage().getContent()); } // --> Carrega os clientes do arquivo private static String loadCustomersFromFile() { try { var path = Path.of(ClassLoader .getSystemResource("src/main/resources/shoppingList/lista_de_compras_10_clientes.csv") .toURI()); return Files.readAllLines(path).toString(); } catch (Exception errorLoadFile) { throw new RuntimeException("Erro ao carregar o arquivo! | Error loading file!", errorLoadFile); } } // --> Contador de Tokens private static int countTokens(String prompt) { EncodingRegistry registry = Encodings.newDefaultEncodingRegistry(); // Registro de codificação Encoding enc = registry.getEncodingForModel(ModelType.GPT_3_5_TURBO); // Modelo utilizado para o cálculo return enc.countTokens(prompt); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value" ]
[((2571, 2601), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((2723, 2753), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3463, 3498), 'java.nio.file.Files.readAllLines')]
/* * Copyright (c) 2023-2024 Jean Schmitz. * * 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 com.talkforgeai.backend.assistant.service; import com.talkforgeai.backend.assistant.domain.AssistantEntity; import com.talkforgeai.backend.assistant.domain.AssistantPropertyValue; import com.talkforgeai.backend.assistant.domain.MessageEntity; import com.talkforgeai.backend.assistant.domain.ThreadEntity; import com.talkforgeai.backend.assistant.dto.AssistantDto; import com.talkforgeai.backend.assistant.dto.GenerateImageResponse; import com.talkforgeai.backend.assistant.dto.MessageListParsedDto; import com.talkforgeai.backend.assistant.dto.ParsedMessageDto; import com.talkforgeai.backend.assistant.dto.ProfileImageUploadResponse; import com.talkforgeai.backend.assistant.dto.ThreadDto; import com.talkforgeai.backend.assistant.dto.ThreadTitleDto; import com.talkforgeai.backend.assistant.dto.ThreadTitleGenerationRequestDto; import com.talkforgeai.backend.assistant.dto.ThreadTitleUpdateRequestDto; import com.talkforgeai.backend.assistant.exception.AssistentException; import com.talkforgeai.backend.assistant.repository.AssistantRepository; import com.talkforgeai.backend.assistant.repository.MessageRepository; import com.talkforgeai.backend.assistant.repository.ThreadRepository; import com.talkforgeai.backend.storage.FileStorageService; import com.talkforgeai.backend.transformers.MessageProcessor; import com.theokanning.openai.ListSearchParameters; import com.theokanning.openai.OpenAiResponse; import com.theokanning.openai.assistants.Assistant; import com.theokanning.openai.assistants.AssistantRequest; import com.theokanning.openai.assistants.ModifyAssistantRequest; 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.image.ImageResult; import com.theokanning.openai.messages.Message; import com.theokanning.openai.messages.MessageRequest; import com.theokanning.openai.model.Model; import com.theokanning.openai.runs.Run; import com.theokanning.openai.runs.RunCreateRequest; import com.theokanning.openai.service.OpenAiService; import com.theokanning.openai.threads.Thread; import com.theokanning.openai.threads.ThreadRequest; import jakarta.transaction.Transactional; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import javax.imageio.ImageIO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.util.StreamUtils; import org.springframework.web.multipart.MultipartFile; @Service public class AssistantService { public static final Logger LOGGER = LoggerFactory.getLogger(AssistantService.class); private final OpenAiService openAiService; private final AssistantRepository assistantRepository; private final MessageRepository messageRepository; private final ThreadRepository threadRepository; private final FileStorageService fileStorageService; private final MessageProcessor messageProcessor; private final AssistantMapper assistantMapper; public AssistantService(OpenAiService openAiService, AssistantRepository assistantRepository, MessageRepository messageRepository, ThreadRepository threadRepository, FileStorageService fileStorageService, MessageProcessor messageProcessor, AssistantMapper assistantMapper) { this.openAiService = openAiService; this.assistantRepository = assistantRepository; this.messageRepository = messageRepository; this.threadRepository = threadRepository; this.fileStorageService = fileStorageService; this.messageProcessor = messageProcessor; this.assistantMapper = assistantMapper; } public AssistantDto retrieveAssistant(String assistantId) { Assistant assistant = this.openAiService.retrieveAssistant(assistantId); if (assistant != null) { Optional<AssistantEntity> assistantEntity = assistantRepository.findById(assistant.getId()); if (assistantEntity.isPresent()) { return assistantMapper.mapAssistantDto(assistant, assistantEntity.get()); } } return null; } public List<AssistantDto> listAssistants(ListSearchParameters listAssistantsRequest) { OpenAiResponse<Assistant> assistantOpenAiResponse = this.openAiService.listAssistants( listAssistantsRequest); List<AssistantDto> assistantDtoList = new ArrayList<>(); assistantOpenAiResponse.data.forEach(assistant -> { Optional<AssistantEntity> assistantEntity = assistantRepository.findById(assistant.getId()); assistantEntity.ifPresent(entity -> { AssistantDto assistantDto = assistantMapper.mapAssistantDto( assistant, entity ); assistantDtoList.add(assistantDto); }); }); return assistantDtoList; } @Transactional public void syncAssistants() { ListSearchParameters searchParameters = new ListSearchParameters(); OpenAiResponse<Assistant> assistantList = this.openAiService.listAssistants( searchParameters); List<AssistantEntity> assistantEntities = assistantRepository.findAll(); // Create assistantList.data.forEach(assistant -> { LOGGER.info("Syncing assistant: {}", assistant.getId()); Optional<AssistantEntity> assistantEntity = assistantEntities.stream() .filter(entity -> entity.getId().equals(assistant.getId())) .findFirst(); if (assistantEntity.isEmpty()) { LOGGER.info("New assistant detected. Creating entity: {}", assistant.getId()); AssistantEntity entity = new AssistantEntity(); entity.setId(assistant.getId()); // Map persona.properties() to Map<String, PersonaPropertyValue> Arrays.stream(AssistantProperties.values()).forEach(p -> { AssistantPropertyValue propertyValue = new AssistantPropertyValue(); String value = p.getDefaultValue(); propertyValue.setPropertyValue(value); entity.getProperties().put(p.getKey(), propertyValue); }); assistantRepository.save(entity); } }); // Delete assistantEntities.forEach(entity -> { Optional<Assistant> assistant = assistantList.data.stream() .filter(a -> a.getId().equals(entity.getId())) .findFirst(); if (assistant.isEmpty()) { LOGGER.info("Assistant not found. Deleting entity: {}", entity.getId()); assistantRepository.delete(entity); } }); } @Transactional public ThreadDto createThread() { ThreadRequest threadRequest = new ThreadRequest(); Thread thread = this.openAiService.createThread(threadRequest); ThreadEntity threadEntity = new ThreadEntity(); threadEntity.setId(thread.getId()); threadEntity.setTitle("<no title>"); threadEntity.setCreatedAt(new Date(thread.getCreatedAt())); threadRepository.save(threadEntity); return mapToDto(threadEntity); } public List<ThreadDto> retrieveThreads() { return this.threadRepository.findAll(Sort.by(Sort.Direction.DESC, "createdAt")).stream() .map(this::mapToDto) .toList(); } public Message postMessage(String threadId, MessageRequest messageRequest) { return this.openAiService.createMessage(threadId, messageRequest); } public Run runConversation(String threadId, RunCreateRequest runCreateRequest) { return this.openAiService.createRun(threadId, runCreateRequest); } public MessageListParsedDto listMessages(String threadId, ListSearchParameters listSearchParameters) { OpenAiResponse<Message> messageList = this.openAiService.listMessages(threadId, listSearchParameters); Map<String, String> parsedMessages = new HashMap<>(); messageList.data.forEach(message -> { Optional<MessageEntity> messageEntity = messageRepository.findById(message.getId()); messageEntity.ifPresent( entity -> parsedMessages.put(message.getId(), entity.getParsedContent())); }); return new MessageListParsedDto(messageList, parsedMessages); } public Run retrieveRun(String threadId, String runId) { return this.openAiService.retrieveRun(threadId, runId); } public Run cancelRun(String threadId, String runId) { return openAiService.cancelRun(threadId, runId); } private ThreadDto mapToDto(ThreadEntity threadEntity) { return new ThreadDto(threadEntity.getId(), threadEntity.getTitle(), threadEntity.getCreatedAt()); } @Transactional public ParsedMessageDto postProcessMessage(String threadId, String messageId) { LOGGER.info("Post processing message: {}", messageId); Message message = this.openAiService.retrieveMessage(threadId, messageId); Optional<MessageEntity> messageEntity = messageRepository.findById(messageId); MessageEntity newMessageEntity = null; if (messageEntity.isPresent()) { newMessageEntity = messageEntity.get(); } else { newMessageEntity = new MessageEntity(); newMessageEntity.setId(message.getId()); newMessageEntity.setParsedContent(""); } String transformed = messageProcessor.transform( message.getContent().get(0).getText().getValue(), threadId, messageId); newMessageEntity.setParsedContent(transformed); messageRepository.save(newMessageEntity); ParsedMessageDto parsedMessageDto = new ParsedMessageDto(); parsedMessageDto.setMessage(message); parsedMessageDto.setParsedContent(transformed); return parsedMessageDto; } public byte[] getImage(String threadId, String filename) throws IOException { Path imgFilePath = fileStorageService.getThreadDirectory().resolve(threadId).resolve(filename); Resource resource = new FileSystemResource(imgFilePath); return StreamUtils.copyToByteArray(resource.getInputStream()); } @Transactional public ThreadTitleDto generateThreadTitle(String threadId, ThreadTitleGenerationRequestDto request) { ThreadEntity threadEntity = threadRepository.findById(threadId) .orElseThrow(() -> new AssistentException("Thread not found")); String content = """ Generate a title in less than 6 words for the following message: %s """.formatted(request.userMessageContent()); ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), content); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest .builder() .model("gpt-3.5-turbo") .messages(List.of(chatMessage)) .maxTokens(256) .build(); ChatMessage responseMessage = openAiService.createChatCompletion(chatCompletionRequest) .getChoices().get(0).getMessage(); String generatedTitle = responseMessage.getContent(); String parsedTitle = generatedTitle.replaceAll("\"", ""); threadEntity.setTitle(parsedTitle); threadRepository.save(threadEntity); return new ThreadTitleDto(generatedTitle); } public ThreadDto retrieveThread(String threadId) { return threadRepository.findById(threadId) .map(this::mapToDto) .orElseThrow(() -> new AssistentException("Thread not found")); } @Transactional public void modifyAssistant(String assistantId, AssistantDto modifiedAssistant) { Assistant assistant = openAiService.retrieveAssistant(assistantId); if (assistant == null) { throw new AssistentException("Assistant not found"); } AssistantEntity assistantEntity = assistantRepository.findById(assistantId) .orElseThrow(() -> new AssistentException("Assistant entity not found")); assistantEntity.setImagePath(modifiedAssistant.imagePath()); assistantEntity.setProperties(assistantMapper.mapProperties(modifiedAssistant.properties())); assistantRepository.save(assistantEntity); ModifyAssistantRequest modifyAssistantRequest = new ModifyAssistantRequest(); modifyAssistantRequest.setName(modifiedAssistant.name()); modifyAssistantRequest.setDescription(modifiedAssistant.description()); modifyAssistantRequest.setModel(modifiedAssistant.model()); modifyAssistantRequest.setInstructions(modifiedAssistant.instructions()); modifyAssistantRequest.setTools(modifiedAssistant.tools()); modifyAssistantRequest.setFileIds(modifiedAssistant.fileIds()); modifyAssistantRequest.setMetadata(modifiedAssistant.metadata()); openAiService.modifyAssistant(assistantId, modifyAssistantRequest); } public GenerateImageResponse generateImage(String prompt) throws IOException { CreateImageRequest request = new CreateImageRequest(); request.setPrompt(prompt); request.setN(1); request.setSize("1024x1024"); request.setModel("dall-e-3"); request.setStyle("natural"); ImageResult image = openAiService.createImage(request); return new GenerateImageResponse(downloadImage(image.getData().get(0).getUrl())); } private String downloadImage(String imageUrl) throws IOException { String fileName = UUID.randomUUID() + "_image.png"; Path subDirectoryPath = fileStorageService.getAssistantsDirectory(); Path localFilePath = subDirectoryPath.resolve(fileName); // Ensure the directory exists and is writable if (!Files.exists(subDirectoryPath)) { Files.createDirectories(subDirectoryPath); } if (!Files.isWritable(subDirectoryPath)) { throw new IOException("Directory is not writable: " + subDirectoryPath); } LOGGER.info("Downloading image {}...", imageUrl); try { URI uri = URI.create(imageUrl); try (InputStream in = uri.toURL().openStream()) { Files.copy(in, localFilePath, StandardCopyOption.REPLACE_EXISTING); } } catch (Exception ex) { LOGGER.error("Failed to download image: {}", imageUrl); throw ex; } return fileName; } public ProfileImageUploadResponse uploadImage(MultipartFile file) { if (file.isEmpty()) { throw new IllegalArgumentException("File is empty"); } try { byte[] bytes = file.getBytes(); String fileEnding = file.getOriginalFilename() .substring(file.getOriginalFilename().lastIndexOf(".")); String filename = UUID.randomUUID() + fileEnding; Path path = fileStorageService.getAssistantsDirectory().resolve(filename); Files.write(path, bytes); if (!isImageFile(path)) { Files.delete(path); throw new AssistentException("File is not an image."); } return new ProfileImageUploadResponse(filename); } catch (IOException e) { throw new AssistentException("Failed to upload file", e); } } private boolean isImageFile(Path filePath) { try { BufferedImage image = ImageIO.read(filePath.toFile()); return image != null; } catch (IOException e) { return false; } } @Transactional public AssistantDto createAssistant(AssistantDto modifiedAssistant) { AssistantRequest assistantRequest = new AssistantRequest(); assistantRequest.setName(modifiedAssistant.name()); assistantRequest.setDescription(modifiedAssistant.description()); assistantRequest.setModel(modifiedAssistant.model()); assistantRequest.setInstructions(modifiedAssistant.instructions()); assistantRequest.setTools(modifiedAssistant.tools()); assistantRequest.setFileIds(modifiedAssistant.fileIds()); assistantRequest.setMetadata(modifiedAssistant.metadata()); Assistant newAssistant = openAiService.createAssistant(assistantRequest); AssistantEntity assistantEntity = new AssistantEntity(); assistantEntity.setId(newAssistant.getId()); assistantEntity.setImagePath(modifiedAssistant.imagePath()); assistantEntity.setProperties(assistantMapper.mapProperties(modifiedAssistant.properties())); assistantRepository.save(assistantEntity); return assistantMapper.mapAssistantDto(newAssistant, assistantEntity); } public List<String> retrieveModels() { return openAiService.listModels().stream() .map(Model::getId) .filter(id -> id.startsWith("gpt") && !id.contains("instruct")) .toList(); } @Transactional public void deleteAssistant(String assistantId) { openAiService.deleteAssistant(assistantId); assistantRepository.deleteById(assistantId); } @Transactional public void deleteThread(String threadId) { threadRepository.deleteById(threadId); } @Transactional public ThreadTitleDto updateThreadTitle(String threadId, ThreadTitleUpdateRequestDto request) { ThreadEntity threadEntity = threadRepository.findById(threadId) .orElseThrow(() -> new AssistentException("Thread not found")); threadEntity.setTitle(request.title()); threadRepository.save(threadEntity); return new ThreadTitleDto(request.title()); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((6874, 7182), 'java.util.Arrays.stream'), ((11433, 11461), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')]
package com.example.idear.src.chatGPT; import com.example.idear.common.BaseResponseStatus; import com.example.idear.common.Constant; import com.example.idear.exception.BaseException; import com.example.idear.src.content.ContentProvider; import com.example.idear.src.content.dto.response.GetContentRes; import com.example.idear.src.profile.ProfileRepository; import com.example.idear.src.profile.models.Profile; import com.example.idear.src.query.dto.request.QueryReq; import com.example.idear.src.query.dto.request.RequeryReq; import com.example.idear.src.query.model.MyQuery; import com.theokanning.openai.OpenAiService; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.time.Duration; import java.util.ArrayList; import java.util.List; @Service @RequiredArgsConstructor public class ChatGPTService { private OpenAiService openAiService = new OpenAiService(Constant.OPEN_API_KEY, Duration.ofSeconds(60)); private final ProfileRepository profileRepository; private final ContentProvider contentProvider; public ChatCompletionChoice query(String content){ List<ChatMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatMessage("system", "You are the author. please apply the options below to compose your mail.")); chatMessages.add(new ChatMessage("user", content)); // content = "안녕 나의 사랑,\n" + // "이번 주는 어떤 하루를 보내고 있니? 이렇게 일어나서 바로 너에게 참 좋은 아침인 것 같아. 그래도 조금 더 너와 함께 기상할 수 있다면 정말 행복할 거야.\n" + // "오늘도 반가운 하루가 되길 바래. 매 순간, 내 마음은 당신만을 바라보며 달려요. 언제든지 연락해줘, 나는 항상 당신 곁에서 지켜볼게.\n" + // "너무 사랑스러운 하루 보내길!\n" + // "사랑해 ♥"; // // chatMessages.add(new ChatMessage("assistant", content)); // // content = "더 귀엽게 써줘"; // // chatMessages.add(new ChatMessage("user", content)); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .model("gpt-3.5-turbo") .messages(chatMessages) .temperature(0.8) .frequencyPenalty(0.8) .presencePenalty(0.8) .build(); ChatCompletionChoice chatCompletionChoice = openAiService.createChatCompletion(chatCompletionRequest).getChoices().get(0); return chatCompletionChoice; } public ChatCompletionChoice requery(MyQuery query, RequeryReq requeryReq){ // query id로 content list 가져오기 List<GetContentRes> getContentResList = contentProvider.getContentResList(query.getId()); List<ChatMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatMessage("system", "You are the author. please apply the options below to compose your mail.")); for(int i=0; i<getContentResList.size(); i++){ if(getContentResList.size() == 1){ System.out.println(1); chatMessages.add(new ChatMessage("user", query.getQuestion())); chatMessages.add(new ChatMessage("system", getContentResList.get(i).getContent())); chatMessages.add(new ChatMessage("user", requeryReq.getFeedback())); break; } if(i == 0){ System.out.println(2); chatMessages.add(new ChatMessage("user", query.getQuestion())); } else if (i == getContentResList.size()-1) { System.out.println(3); chatMessages.add(new ChatMessage("system", getContentResList.get(i).getContent())); chatMessages.add(new ChatMessage("user", requeryReq.getFeedback())); } else { System.out.println(4); chatMessages.add(new ChatMessage("system", getContentResList.get(i).getContent())); chatMessages.add(new ChatMessage("user", getContentResList.get(i).getFeedback())); } } chatMessages.forEach(System.out::println); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .model("gpt-3.5-turbo") .messages(chatMessages) .temperature(0.8) .frequencyPenalty(0.8) .presencePenalty(0.8) .build(); ChatCompletionChoice chatCompletionChoice = openAiService.createChatCompletion(chatCompletionRequest).getChoices().get(0); return chatCompletionChoice; } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((2389, 2636), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2389, 2611), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2389, 2573), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2389, 2534), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2389, 2500), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2389, 2460), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4513, 4760), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4513, 4735), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4513, 4697), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4513, 4658), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4513, 4624), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4513, 4584), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package com.example.recipegenie; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.service.OpenAiService; import java.util.Arrays; public class ChatGptTask extends AsyncTask<String, Void, String> { private final TextView responseTextView; private final String apiKey; private final ProgressBar progressBar; private String breakfast = null; private String lunch = null; private String dinner = null; private final Button continueButton; public ChatGptTask(TextView responseTextView, String apiKey, ProgressBar progressBar, Button continueButton) { this.responseTextView = responseTextView; this.apiKey = apiKey; this.progressBar = progressBar; this.continueButton = continueButton; // Initialize button reference } @Override protected String doInBackground(String... strings) { // Initializse the OpenAI service with the API key OpenAiService service = new OpenAiService(apiKey); String modifiedPrompt = "You are a friendly and intelligent nutritional wellness coach communicating with a human. " + "Try to respond in a way that a health advisor would, using understandable language. " + "Generate three healthy meal ideas for the day, including breakfast, lunch, and dinner. Keep all the answers very short\n\n" + "User: " + strings[0]; //Take into consideration the user's dietary preferences, allergies, and nutritional needs: " + userInput + ". // Create a chat completion request with the appropriate model ChatCompletionRequest request = ChatCompletionRequest.builder() .messages(Arrays.asList(new ChatMessage("user", modifiedPrompt))) .model("gpt-3.5-turbo") // This model is optimized for conversations .build(); try { // Execute the request and get the response String response = service.createChatCompletion(request).getChoices().get(0).getMessage().getContent(); // Process the response to extract the generated meal plan String mealPlan = processResponse(response); return mealPlan; } catch (Exception e) { e.printStackTrace(); return "Error: " + e.getMessage(); // Return error message } } private String processResponse(String response) { //extract and format the meal plan from the response // Split the response into lines String[] lines = response.split("\n"); // Iterate through each line and categorize the meal for (String line : lines) { if (line.toLowerCase().contains("breakfast")) { breakfast = line.trim(); } else if (line.toLowerCase().contains("lunch")) { lunch = line.trim(); } else if (line.toLowerCase().contains("dinner")) { dinner = line.trim(); } } // Format the result StringBuilder result = new StringBuilder(); if (breakfast != null) { result.append(breakfast).append("\n").append("\n"); } if (lunch != null) { result.append(lunch).append("\n").append("\n"); } if (dinner != null) { result.append(dinner).append("\n").append("\n"); } return "Generated Meal Plan:\n" + "\n" + result.toString(); } @Override protected void onPostExecute(String result) { // Update UI with the result on the main thread if (result != null && !result.isEmpty()) { responseTextView.setText(result); progressBar.setVisibility(View.GONE); saveMealPlanToPrefs(result); // Enable the ContinueToWeeklyMenu button continueButton.setEnabled(true); continueButton.setAlpha(1f); } else { responseTextView.setText("Error retrieving response, please try again."); progressBar.setVisibility(View.GONE); } } private void saveMealPlanToPrefs(String mealPlan) { // Use SharedPreferences to save the meal plan SharedPreferences preferences = responseTextView.getContext().getSharedPreferences("MealPlanPrefs", Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("mealPlan", mealPlan); editor.apply(); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1991, 2214), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1991, 2144), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1991, 2104), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package net.jubbery.symai; import com.theokanning.openai.audio.CreateTranscriptionRequest; import com.theokanning.openai.audio.TranscriptionResult; 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 lombok.Getter; import net.minecraft.client.Minecraft; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.npc.Villager; import net.minecraft.world.entity.player.Player; import net.minecraft.world.phys.EntityHitResult; import net.minecraft.world.phys.HitResult; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import okhttp3.*; import net.minecraftforge.client.event.InputEvent; import org.lwjgl.glfw.GLFW; import javax.sound.sampled.*; import java.io.*; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; // The value here should match an entry in the META-INF/mods.toml file @Mod(SYMAI_Mod.MODID) public class SYMAI_Mod { @Getter private final AtomicBoolean isRecording = new AtomicBoolean(false); // Define mod id in a common place for everything to reference public static final String MODID = "symai"; public static final Logger LOGGER = LoggerFactory.getLogger(MODID); private final OpenAiService openAiService; private final OkHttpClient httpClient = new OkHttpClient(); public SYMAI_Mod() { LOGGER.info("Starting SYMAI"); MinecraftForge.EVENT_BUS.register(this); MinecraftForge.EVENT_BUS.register(new KeyInputHandler(this)); // Initialize OpenAiService with your OpenAI API key openAiService = new OpenAiService(""); // replace YOUR_OPENAI_API_KEY with your actual key } @Mod.EventBusSubscriber(modid = SYMAI_Mod.MODID, value = Dist.CLIENT) public static class KeyInputHandler { private final SYMAI_Mod modInstance; public KeyInputHandler(SYMAI_Mod mod) { this.modInstance = mod; } @SubscribeEvent public void onKeyInput(InputEvent.Key event) { Minecraft minecraft = Minecraft.getInstance(); Player player = minecraft.player; if (player == null) { return; } // Check for the Villager in crosshairs HitResult hitResult = minecraft.hitResult; assert hitResult != null; if (hitResult.getType() == HitResult.Type.ENTITY) { EntityHitResult entityHitResult = (EntityHitResult) hitResult; Entity entity = entityHitResult.getEntity(); // LOGGER.info(String.valueOf(event.getKey())); // LOGGER.info(String.valueOf(event.getAction())); if (entity instanceof Villager && player.distanceTo(entity) <= 5.0D) { // LOGGER.info("Detected Villager"); // LOGGER.info("Distance is valid"); if (event.getKey() == GLFW.GLFW_KEY_TAB && event.getAction() == GLFW.GLFW_REPEAT) { // LOGGER.info("TAB key detected"); // LOGGER.info("Repeat action detected"); boolean isCurrentlyRecording = modInstance.getIsRecording().get(); if (!isCurrentlyRecording) { LOGGER.info("Recording TRUE"); modInstance.getIsRecording().set(true); CompletableFuture<Void> recordingTask = CompletableFuture.runAsync(modInstance::captureAudioFromMicrophone); } } else if (event.getAction() == GLFW.GLFW_RELEASE) { LOGGER.info("Recording FALSE"); modInstance.getIsRecording().set(false); } } } } } @SubscribeEvent public static void onPlayerTick(TickEvent.PlayerTickEvent event) { if (event.phase != TickEvent.Phase.END) { return; } Player player = event.player; // Using the getEntitiesOfClass method to fetch nearby villagers List<LivingEntity> nearbyVillagers = player.level().getEntitiesOfClass( LivingEntity.class, player.getBoundingBox().inflate(5.0D), (entity) -> entity instanceof Villager ); if (nearbyVillagers.isEmpty()) { return; } // Here, you can consider adding additional logic to prevent // the code from running every tick a villager is nearby to avoid spamming. // The rest of your logic: // Step 3: Capture Voice, Step 4: Chat with GPT, etc. } public static void startService() { } private final ExecutorService executorService = Executors.newSingleThreadExecutor(); private void captureAudioFromMicrophone() { AudioFormat format = new AudioFormat(44100.0f, 16, 2, true, true); TargetDataLine microphone; ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] data = new byte[4096]; LOGGER.info("Starting recording"); try { microphone = AudioSystem.getTargetDataLine(format); microphone.open(format); microphone.start(); while (this.getIsRecording().get()) { int numBytesRead = microphone.read(data, 0, data.length); out.write(data, 0, numBytesRead); } microphone.close(); } catch (LineUnavailableException e) { e.printStackTrace(); } try { String translatedSpeech = capturePlayerVoice(data); LOGGER.info(translatedSpeech); } catch (IOException e) { LOGGER.error("Error while capturing or processing audio", e); } } private String capturePlayerVoice(byte[] audioData) throws IOException { // Construct the CreateTranscriptionRequest CreateTranscriptionRequest transcriptionRequest = CreateTranscriptionRequest.builder() .model("whisper-1") .language("en") .responseFormat("json") .prompt("You are a minecraft villager") .build(); LOGGER.info("Requesting Transcript..."); TranscriptionResult transcriptionResult = openAiService.createTranscription(transcriptionRequest, saveToWav(audioData)); try (FileInputStream fis = new FileInputStream("somefile.txt")) { if (!transcriptionResult.getText().isEmpty()) { String transcribedText = transcriptionResult.getText(); LOGGER.info(transcribedText); return transcribedText; } } catch (IOException e) { LOGGER.error("Error while transcribing voice using Whisper ASR", e); } return "Error capturing voice"; } public static File saveToWav(byte[] audioData) throws IOException { // Define the audio format parameters AudioFormat format = new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, // Encoding 44100.0f, // Sample rate (44.1KHz) 16, // Bits per sample (16 bits) 2, // Channels (2 for stereo) 4, // Frame size 44100.0f, // Frame rate false // Little endian ); // Create an audio input stream from the byte array ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(audioData); AudioInputStream audioInputStream = new AudioInputStream(byteArrayInputStream, format, audioData.length / format.getFrameSize()); // Use the AudioSystem to write to a temporary file File tempFile = File.createTempFile("recordedAudio", ".wav"); AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, tempFile); return tempFile; } private String chatWithGPT(String input) { // Use the Chat GPT API to get a response for the given input ChatCompletionRequest request = new ChatCompletionRequest(); request.getMessages().add(new ChatMessage("user", input)); ChatCompletionResult result = openAiService.createChatCompletion(request); return result.getObject(); // Get the model's response; } private byte[] convertTextToSpeech(String text) { // Use a Text-to-Speech library to convert the text to audio data // Return the audio data return new byte[0]; } private void playAudioToPlayer(Player player, byte[] audioData) { // Play the audio data to the specified player // This would likely involve creating a custom sound event or using another method } }
[ "com.theokanning.openai.audio.CreateTranscriptionRequest.builder" ]
[((1979, 2018), 'net.minecraftforge.common.MinecraftForge.EVENT_BUS.register'), ((2028, 2088), 'net.minecraftforge.common.MinecraftForge.EVENT_BUS.register'), ((6568, 6793), 'com.theokanning.openai.audio.CreateTranscriptionRequest.builder'), ((6568, 6768), 'com.theokanning.openai.audio.CreateTranscriptionRequest.builder'), ((6568, 6712), 'com.theokanning.openai.audio.CreateTranscriptionRequest.builder'), ((6568, 6672), 'com.theokanning.openai.audio.CreateTranscriptionRequest.builder'), ((6568, 6640), 'com.theokanning.openai.audio.CreateTranscriptionRequest.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" ]
[((365, 598), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((365, 573), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((365, 539), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((365, 506), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((365, 435), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package com.vaadin.flow.ai.formfiller.services; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; 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 com.vaadin.flow.ai.formfiller.utils.KeysUtils; import com.vaadin.flow.component.Component; public class ChatGPTChatCompletionService extends OpenAiService implements LLMService { /** * ID of the model to use. */ private String MODEL = "gpt-3.5-turbo-16k-0613"; /** * The maximum number of tokens to generate in the completion. */ private Integer MAX_TOKENS = 12000; /** * What sampling temperature to use, between 0 and 2. * Higher values like 0.8 will make the output more random, * while lower values like 0.2 will make it more focused and deterministic. */ private Double TEMPERATURE = 0d; /** * If true the input prompt is included in the response */ private Boolean ECHO = false; /** * Timeout for AI module response in seconds */ private static Integer TIMEOUT = 60; public ChatGPTChatCompletionService() { super(KeysUtils.getOpenAiKey(), Duration.ofSeconds(TIMEOUT)); } @Override public String getPromptTemplate(String input, Map<String, Object> objectMap, Map<String, String> typesMap, Map<Component, String> componentInstructions, List<String> contextInstructions) { String gptRequest = String.format( "Based on the user input: \n \"%s\", " + "generate a JSON object according to these instructions: " + "Never include duplicate keys, in case of duplicate keys just keep the first occurrence in the response. " + "Fill out \"N/A\" in the JSON value if the user did not specify a value. " + "Return the result as a JSON object in this format: '%s'." , input, objectMap); if (!componentInstructions.isEmpty() || !typesMap.isEmpty()) { gptRequest += "\nAdditional instructions about some of the JSON fields to be filled: "; for (Map.Entry<String, String> entry : typesMap.entrySet()) { gptRequest += "\n" + entry.getKey() + ": Format this JSON field as " + entry.getValue() + "."; } for (Map.Entry<Component, String> entry : componentInstructions.entrySet()) { if (entry.getKey().getId().isPresent()) gptRequest += "\n" + entry.getKey().getId().get() + ": " + entry.getValue() + "."; } if (!contextInstructions.isEmpty()) { gptRequest += "\nAdditional instructions about the context and desired JSON output response: "; for (String contextInstruction : contextInstructions) { gptRequest += " " + contextInstruction + "."; } } } return gptRequest; } @Override public String getGeneratedResponse(String prompt) { ArrayList<ChatMessage> messages = new ArrayList<>(); messages.add(new ChatMessage("user",prompt)); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .messages(messages) .model(MODEL).maxTokens(MAX_TOKENS).temperature(TEMPERATURE) .build(); ChatCompletionResult completionResult = createChatCompletion(chatCompletionRequest); String aiResponse = completionResult.getChoices().get(0).getMessage().getContent(); return aiResponse; } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((3403, 3572), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3403, 3547), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3403, 3522), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3403, 3500), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3403, 3470), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package chatGPT; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; public class ExampleGPT__ { public static void main(String[] a) { String apiKey = "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"; String url = "https://api.openai.com/v1/chat/completions"; String model = "gpt-3.5-turbo"; OpenAiService service = new OpenAiService(apiKey); System.out.println(service); CompletionRequest completionRequest = CompletionRequest.builder() .prompt("hello, how are you? Can you tell me what's a Fibonacci Number?") .model("GPT base") .echo(true) .build(); service.createCompletion(completionRequest).getChoices().forEach(System.out::println); } } /** // Curl Requset curl --location 'https://api.openai.com/v1/embeddings' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer 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' \ --data '{ "input": "list the indian dog breads", "model": "text-embedding-ada-002" }' Response: { "error": { "message": "You exceeded your current quota, please check your plan and billing details.", "type": "insufficient_quota", "param": null, "code": "insufficient_quota" } } I tried several modules yet always getting response of insufficient_quota. */
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((507, 692), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((507, 672), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((507, 649), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((507, 619), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package util; import com.theokanning.openai.OpenAiService; import com.theokanning.openai.completion.CompletionRequest; import retrofit2.HttpException; public class OpenAiApiImpl { public static String createCompletion(String msg) { // String token = System.getenv("OPENAI_TOKEN"); OpenAiService service = new OpenAiService("*****************************"); System.out.println("\nCreating completion..."); CompletionRequest completionRequest = CompletionRequest.builder() .model("davinci") .prompt(msg) .echo(true) .temperature(0.1) .user("testing") .build(); // service.createCompletion(completionRequest).getChoices().forEach(System.out::println); try { return service.createCompletion(completionRequest).getChoices().get(0).getText(); } catch (HttpException e) { System.err.println("createCompletion exception: " + e.getMessage()); return null; } } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((484, 694), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((484, 669), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((484, 636), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((484, 602), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((484, 574), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((484, 545), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package br.com.jornadamilhas.api.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("api_key"); private final OpenAiService service = new OpenAiService(API_KEY); public String geraTextoDestino(String destino) { 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.", destino); 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" ]
[((900, 1094), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((900, 1069), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((900, 1035), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((900, 1002), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((900, 970), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package service; import java.util.ArrayList; import java.util.List; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatFunction; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.FunctionExecutor; import com.theokanning.openai.service.OpenAiService; public class InvestorProfileFinder { String GPTKey = "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"; OpenAiService Service = new OpenAiService(GPTKey); public String Find(String aboutMe) { return GetResponse(GetMessages(GetQuestion(aboutMe))); } String GetResponse(List<ChatMessage> messages) { ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest .builder() .model("gpt-3.5-turbo-1106") .messages(messages) .maxTokens(256) .build(); ChatMessage responseMessage = Service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage(); return responseMessage.getContent(); } List<ChatMessage> GetMessages(String question){ List<ChatMessage> messages = new ArrayList<>(); ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), question); messages.add(userMessage); return messages; } String GetQuestion(String aboutMe) { var question = new StringBuilder(); question.append("Dentre as opções abaixo, qual perfil de investimento eu me encaixo, sendo que:"); question.append(aboutMe+"?"); AddConditions(question); question.append("Só me diga a opção"); return question.toString(); } StringBuilder AddConditions(StringBuilder stringBuilder) { stringBuilder.append("Conservador"); stringBuilder.append("Moderado"); stringBuilder.append("Alto Risco"); return stringBuilder; } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((1319, 1347), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')]
package telegrambotopenai03; 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.theokanning.openai.completion.chat.ChatCompletionChoice; import java.util.ArrayList; import java.util.HashMap; import java.util.List; class OpenAiApiCompletion { private static final String TOKEN = "<YOUR OpenAI Token>"; private static final String MODEL = "gpt-3.5-turbo"; public static String main(String prompt) { OpenAiService service = new OpenAiService(TOKEN); List<ChatMessage> messages = new ArrayList<>(); ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), prompt); messages.add(systemMessage); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest .builder() .model(MODEL) .messages(messages) .n(1) //.maxTokens(1) .logitBias(new HashMap<>()) .build(); StringBuilder response = new StringBuilder(); service.streamChatCompletion(chatCompletionRequest) .blockingSubscribe( data -> { List<ChatCompletionChoice> choices = data.getChoices(); if (!choices.isEmpty()) { String content = choices.get(0).getMessage().getContent(); if (content != null) { response.append(content); } } }, error -> { response.append("Error: ").append(error.getMessage()); error.printStackTrace(); } ); return response.toString(); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value" ]
[((784, 814), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value')]
package org.sia.service; import com.fasterxml.jackson.databind.ObjectMapper; import com.theokanning.openai.client.OpenAiApi; import com.theokanning.openai.service.OpenAiService; import lombok.extern.slf4j.Slf4j; import okhttp3.OkHttpClient; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Service; import retrofit2.Retrofit; import java.net.InetSocketAddress; import java.net.Proxy; import java.time.Duration; /** * @Description: * @Author: 高灶顺 * @CreateDate: 2023/11/8 18:36 */ @Slf4j @Service public class ChatGPTService implements InitializingBean { private final static String Key = "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"; private final static String hostProxy = "127.0.0.1"; private final static Integer portProxy = 7890; private OpenAiService service; public OpenAiService getService() { return service; } @Override public void afterPropertiesSet() throws Exception { ObjectMapper mapper = OpenAiService.defaultObjectMapper(); OkHttpClient client = OpenAiService.defaultClient(Key, Duration.ofSeconds(10L)) .newBuilder() .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(hostProxy, portProxy))) .build(); Retrofit retrofit = OpenAiService.defaultRetrofit(client, mapper); this.service = new OpenAiService(retrofit.create(OpenAiApi.class)); } public static void main(String[] args) { OpenAiService service = new OpenAiService(Key, Duration.ofSeconds(30)); // 计费 // BillingUsage billingUsage = service.(LocalDate.parse("2023-11-08"), LocalDate.now()); // BigDecimal totalUsage = billingUsage.getTotalUsage(); } // public static void main(String[] args) { // String token = Key; // OpenAiService service = new OpenAiService(token, Duration.ofSeconds(30)); // // System.out.println("\nCreating completion..."); // CompletionRequest completionRequest = CompletionRequest.builder() // .model("ada") // .prompt("Somebody once told me the world is gonna roll me") // .echo(true) // .user("testing") // .n(3) // .build(); // service.createCompletion(completionRequest).getChoices().forEach(System.out::println); // // System.out.println("\nCreating Image..."); // CreateImageRequest request = CreateImageRequest.builder() // .prompt("A cow breakdancing with a turtle") // .build(); // // System.out.println("\nImage is located at:"); // System.out.println(service.createImage(request).getData().get(0).getUrl()); // // System.out.println("Streaming chat completion..."); // final List<ChatMessage> messages = new ArrayList<>(); // final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "You are a dog and will speak as such."); // messages.add(systemMessage); // ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest // .builder() // .model("gpt-3.5-turbo") // .messages(messages) // .n(1) // .maxTokens(50) // .logitBias(new HashMap<>()) // .build(); // // service.streamChatCompletion(chatCompletionRequest) // .doOnError(Throwable::printStackTrace) // .blockingForEach(System.out::println); // // service.shutdownExecutor(); // } }
[ "com.theokanning.openai.service.OpenAiService.defaultClient" ]
[((1091, 1299), 'com.theokanning.openai.service.OpenAiService.defaultClient'), ((1091, 1274), 'com.theokanning.openai.service.OpenAiService.defaultClient'), ((1091, 1178), 'com.theokanning.openai.service.OpenAiService.defaultClient')]
package de.throughput.ircbot.handler; import java.util.List; import java.util.Set; 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.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import de.throughput.ircbot.api.Command; import de.throughput.ircbot.api.CommandEvent; import de.throughput.ircbot.api.CommandHandler; import com.theokanning.openai.completion.CompletionRequest; /** * Lagerfeld AI command handler. * <p> * !ailagerfeld <text> - responds with an AI-generated Lagerfeld quote. */ @Component @RequiredArgsConstructor public class LagerfeldAiCommandHandler implements CommandHandler { private static final Logger LOG = LoggerFactory.getLogger(LagerfeldAiCommandHandler.class); private static final String MODEL_GPT_3_5_TURBO = "gpt-3.5-turbo"; private static final int MAX_TOKENS = 100; private static final Command CMD_AILAGERFELD = new Command("lagerfeld", "lagerfeld <text> - responds with an AI-generated Lagerfeld quote."); public static final String PROMPT_TEMPLATE = """ Erzeuge ein Lagerfeld-Zitat aus dem folgenden Wort oder der folgenden Phrase. Ein Lagerfeld-Zitat funktioniert so: 'Wer ..., hat die Kontrolle über sein Leben verloren.' Verwende das Wort oder die Phrase, um einen grammatikalisch korrekten Satz als Lagerfeld-Zitat zu bilden, zum Beispiel, indem du ein passendes Verb ergänzt. Beispiel: Wort = Ohrenschützer; Du antwortest: Wer Ohrenschützer trägt, hat die Kontrolle über sein Leben verloren. Füge der Antwort keine weiteren Kommentare hinzu. Also los. Das Wort oder die Phrase lautet: "%s" """; private final OpenAiService openAiService; @Override public Set<Command> getCommands() { return Set.of(CMD_AILAGERFELD); } @Override public boolean onCommand(CommandEvent command) { command.getArgLine() .ifPresentOrElse( text -> respondWithQuote(command, text), () -> command.respond(CMD_AILAGERFELD.getUsage())); return true; } private void respondWithQuote(CommandEvent command, String text) { try { String prompt = PROMPT_TEMPLATE.replace("\n", " ").formatted(text); var message = new ChatMessage(ChatMessageRole.USER.value(), prompt, command.getEvent().getUser().getNick()); var request = ChatCompletionRequest.builder() .model(MODEL_GPT_3_5_TURBO) .maxTokens(MAX_TOKENS) .messages(List.of(message)) .build(); ChatCompletionResult completionResult = openAiService.createChatCompletion(request); ChatMessage responseMessage = completionResult.getChoices().get(0).getMessage(); command.getEvent() .getChannel() .send() .message("\"" + responseMessage.getContent() + "\" -- Karl Lagerfeld."); } catch (Exception e) { command.respond(e.getMessage()); LOG.error(e.getMessage(), e); } } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value", "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((2771, 2799), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((2877, 3076), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2877, 3047), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2877, 2999), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2877, 2956), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
49
Edit dataset card