code
stringlengths
619
138k
apis
listlengths
1
8
extract_api
stringlengths
79
7.3k
/* * #%L * Script Editor and Interpreter for SciJava script languages. * %% * Copyright (C) 2009 - 2024 SciJava developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package org.scijava.ui.swing.script; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import java.awt.dnd.DragSourceDragEvent; import java.awt.dnd.DragSourceDropEvent; import java.awt.dnd.DragSourceEvent; import java.awt.dnd.DragSourceListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ItemEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.CharArrayWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.Reader; import java.io.StringReader; import java.io.Writer; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.Vector; import java.util.concurrent.ExecutionException; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.zip.ZipException; import javax.script.ScriptEngine; import javax.script.ScriptException; import javax.swing.*; import javax.swing.border.BevelBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter; import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter; import javax.swing.text.Position; import javax.swing.tree.TreePath; 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.fife.ui.rsyntaxtextarea.AbstractTokenMakerFactory; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.Theme; import org.fife.ui.rsyntaxtextarea.TokenMakerFactory; import org.fife.ui.rtextarea.ClipboardHistory; import org.fife.ui.rtextarea.Macro; import org.fife.ui.rtextarea.RTextArea; import org.fife.ui.rtextarea.RTextAreaEditorKit; import org.fife.ui.rtextarea.RTextAreaEditorKit.SetReadOnlyAction; import org.fife.ui.rtextarea.RTextAreaEditorKit.SetWritableAction; import org.scijava.Context; import org.scijava.app.AppService; import org.scijava.batch.BatchService; import org.scijava.command.CommandService; import org.scijava.event.ContextDisposingEvent; import org.scijava.event.EventHandler; import org.scijava.io.IOService; import org.scijava.log.LogService; import org.scijava.module.ModuleException; import org.scijava.module.ModuleService; import org.scijava.options.OptionsService; import org.scijava.platform.PlatformService; import org.scijava.plugin.Parameter; import org.scijava.plugin.PluginInfo; import org.scijava.plugin.PluginService; import org.scijava.plugins.scripting.java.JavaEngine; import org.scijava.prefs.PrefService; import org.scijava.script.ScriptHeaderService; import org.scijava.script.ScriptInfo; import org.scijava.script.ScriptLanguage; import org.scijava.script.ScriptModule; import org.scijava.script.ScriptService; import org.scijava.thread.ThreadService; import org.scijava.ui.CloseConfirmable; import org.scijava.ui.UIService; import org.scijava.ui.swing.script.autocompletion.ClassUtil; import org.scijava.ui.swing.script.commands.ChooseFontSize; import org.scijava.ui.swing.script.commands.ChooseTabSize; import org.scijava.ui.swing.script.commands.GitGrep; import org.scijava.ui.swing.script.commands.KillScript; import org.scijava.util.FileUtils; import org.scijava.util.MiscUtils; import org.scijava.util.POM; import org.scijava.util.PlatformUtils; import org.scijava.util.Types; import org.scijava.widget.FileWidget; import com.formdev.flatlaf.FlatLaf; /** * A versatile script editor for SciJava applications. * <p> * Based on the powerful SciJava scripting framework and the * <a href="http://fifesoft.com/rsyntaxtextarea/">RSyntaxTextArea</a> library, * this text editor lets users script their way to success. Thanks to the * <a href="https://github.com/scijava/scripting-java">Java backend for SciJava * scripting</a>, it is even possible to develop Java plugins in the editor. * </p> * * @author Johannes Schindelin * @author Jonathan Hale * @author Albert Cardona * @author Tiago Ferreira */ public class TextEditor extends JFrame implements ActionListener, ChangeListener, CloseConfirmable, DocumentListener { private static final Set<String> TEMPLATE_PATHS = new HashSet<>(); // private static final int BORDER_SIZE = 4; public static final String AUTO_IMPORT_PREFS = "script.editor.AutoImport"; public static final String WINDOW_HEIGHT = "script.editor.height"; public static final String WINDOW_WIDTH = "script.editor.width"; public static final int DEFAULT_WINDOW_WIDTH = 800; public static final int DEFAULT_WINDOW_HEIGHT = 600; public static final String MAIN_DIV_LOCATION = "script.editor.main.divLocation"; public static final String TAB_DIV_LOCATION = "script.editor.tab.divLocation"; public static final String TAB_DIV_ORIENTATION = "script.editor.tab.divOrientation"; public static final String REPL_DIV_LOCATION = "script.editor.repl.divLocation"; public static final String LAST_LANGUAGE = "script.editor.lastLanguage"; static { // Add known script template paths. addTemplatePath("script_templates"); // This path interferes with javadoc generation but is preserved for // backwards compatibility addTemplatePath("script-templates"); } private static AbstractTokenMakerFactory tokenMakerFactory = null; private JTabbedPane tabbed; private JMenuItem newFile, open, save, saveas, compileAndRun, compile, close, undo, redo, cut, copy, paste, find, selectAll, kill, gotoLine, makeJar, makeJarWithSource, removeUnusedImports, sortImports, removeTrailingWhitespace, findNext, findPrevious, openHelp, addImport, nextError, previousError, openHelpWithoutFrames, nextTab, previousTab, runSelection, extractSourceJar, askChatGPTtoGenerateCode, openSourceForClass, //openSourceForMenuItem, // this never had an actionListener!?? openMacroFunctions, decreaseFontSize, increaseFontSize, chooseFontSize, chooseTabSize, gitGrep, replaceTabsWithSpaces, replaceSpacesWithTabs, zapGremlins,openClassOrPackageHelp; private RecentFilesMenuItem openRecent; private JMenu editMenu, gitMenu, tabsMenu, fontSizeMenu, tabSizeMenu, toolsMenu, runMenu; private int tabsMenuTabsStart; private Set<JMenuItem> tabsMenuItems; private FindAndReplaceDialog findDialog; private JCheckBoxMenuItem autoSave, wrapLines, tabsEmulated, autoImport, autocompletion, fallbackAutocompletion, keylessAutocompletion, markOccurences, paintTabs, whiteSpace, marginLine, lockPane; private ButtonGroup themeRadioGroup; private JTextArea errorScreen = new JTextArea(); private final FileSystemTree tree; private final JSplitPane body; private int compileStartOffset; private Position compileStartPosition; private ErrorHandler errorHandler; private boolean respectAutoImports; private String activeTheme; private int[] panePositions; @Parameter private Context context; @Parameter private LogService log; @Parameter private ModuleService moduleService; @Parameter private PlatformService platformService; @Parameter private IOService ioService; @Parameter private CommandService commandService; @Parameter private ScriptService scriptService; @Parameter private PluginService pluginService; @Parameter private ScriptHeaderService scriptHeaderService; @Parameter private UIService uiService; @Parameter private PrefService prefService; @Parameter private ThreadService threadService; @Parameter private AppService appService; @Parameter private BatchService batchService; @Parameter(required = false) private OptionsService optionsService; private Map<ScriptLanguage, JRadioButtonMenuItem> languageMenuItems; private JRadioButtonMenuItem noneLanguageItem; private EditableScriptInfo scriptInfo; private ScriptModule module; private boolean incremental = false; private DragSource dragSource; private boolean layoutLoading = true; private OutlineTreePanel sourceTreePanel; protected final CommandPalette cmdPalette; public static final ArrayList<TextEditor> instances = new ArrayList<>(); public static final ArrayList<Context> contexts = new ArrayList<>(); public TextEditor(final Context context) { super("Script Editor"); instances.add(this); contexts.add(context); context.inject(this); initializeTokenMakers(); // NB: All panes must be initialized before menus are assembled! tabbed = GuiUtils.getJTabbedPane(); tree = new FileSystemTree(log); final JTabbedPane sideTabs = GuiUtils.getJTabbedPane(); sideTabs.addTab("File Explorer", new FileSystemTreePanel(tree, context)); sideTabs.addTab("Outline", sourceTreePanel = new OutlineTreePanel()); body = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sideTabs, tabbed); // These items are dynamic and need to be initialized before EditorPane creation initializeDynamicMenuComponents(); // -- BEGIN MENUS -- // Initialize menu final int ctrl = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); final int shift = ActionEvent.SHIFT_MASK; final JMenuBar mbar = new JMenuBar(); setJMenuBar(mbar); // -- File menu -- final JMenu file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); newFile = addToMenu(file, "New", KeyEvent.VK_N, ctrl); newFile.setMnemonic(KeyEvent.VK_N); open = addToMenu(file, "Open...", KeyEvent.VK_O, ctrl); open.setMnemonic(KeyEvent.VK_O); openRecent = new RecentFilesMenuItem(prefService, this); openRecent.setMnemonic(KeyEvent.VK_R); file.add(openRecent); file.addSeparator(); save = addToMenu(file, "Save", KeyEvent.VK_S, ctrl); save.setMnemonic(KeyEvent.VK_S); saveas = addToMenu(file, "Save As...", KeyEvent.VK_S, ctrl + shift); saveas.setMnemonic(KeyEvent.VK_A); file.addSeparator(); makeJar = addToMenu(file, "Export as JAR...", 0, 0); makeJar.setMnemonic(KeyEvent.VK_E); makeJarWithSource = addToMenu(file, "Export as JAR (With Source)...", 0, 0); makeJarWithSource.setMnemonic(KeyEvent.VK_X); file.addSeparator(); lockPane = new JCheckBoxMenuItem("Lock (Make Read Only)"); lockPane.setToolTipText("Protects file from accidental editing"); file.add(lockPane); lockPane.addActionListener(e -> { if (lockPane.isSelected()) { new SetReadOnlyAction().actionPerformedImpl(e, getEditorPane()); } else { new SetWritableAction().actionPerformedImpl(e, getEditorPane()); } }); JMenuItem jmi = new JMenuItem("Revert..."); jmi.addActionListener(e -> { if (getEditorPane().isLocked()) { error("File is currently locked."); return; } final File f = getEditorPane().getFile(); if (f == null || !f.exists()) { error(getEditorPane().getFileName() + "\nhas not been saved or its file is not available."); } else { reloadRevert("Revert to Saved File? Any unsaved changes will be lost.", "Revert"); } }); file.add(jmi); file.addSeparator(); jmi = new JMenuItem("Show in System Explorer"); jmi.addActionListener(e -> { final File f = getEditorPane().getFile(); if (f == null || !f.exists()) { error(getEditorPane().getFileName() + "\nhas not been saved or its file is not available."); } else { try { Desktop.getDesktop().open(f.getParentFile()); } catch (final Exception | Error ignored) { error(getEditorPane().getFileName() + "\ndoes not seem to be accessible."); } } }); file.add(jmi); file.addSeparator(); close = addToMenu(file, "Close", KeyEvent.VK_W, ctrl); mbar.add(file); // -- Edit menu -- editMenu = new JMenu("Edit"); // cannot be populated here. see #assembleEditMenu() editMenu.setMnemonic(KeyEvent.VK_E); mbar.add(editMenu); // -- Language menu -- languageMenuItems = new LinkedHashMap<>(); final Set<Integer> usedShortcuts = new HashSet<>(); final JMenu languages = new JMenu("Language"); languages.setMnemonic(KeyEvent.VK_L); final ButtonGroup group = new ButtonGroup(); // get list of languages, and sort them by name final ArrayList<ScriptLanguage> list = new ArrayList<>(scriptService.getLanguages()); Collections.sort(list, (l1, l2) -> { final String name1 = l1.getLanguageName(); final String name2 = l2.getLanguageName(); return MiscUtils.compare(name1, name2); }); list.add(null); final Map<String, ScriptLanguage> languageMap = new HashMap<>(); for (final ScriptLanguage language : list) { final String name = language == null ? "None" : language.getLanguageName(); languageMap.put(name, language); final JRadioButtonMenuItem item = new JRadioButtonMenuItem(name); if (language == null) { noneLanguageItem = item; } else { languageMenuItems.put(language, item); } int shortcut = -1; for (final char ch : name.toCharArray()) { final int keyCode = KeyStroke.getKeyStroke(ch, 0).getKeyCode(); if (usedShortcuts.contains(keyCode)) continue; shortcut = keyCode; usedShortcuts.add(shortcut); break; } if (shortcut > 0) item.setMnemonic(shortcut); item.addActionListener(e -> setLanguage(language, true)); group.add(item); languages.add(item); } noneLanguageItem.setSelected(true); mbar.add(languages); // -- Templates menu -- final JMenu templates = new JMenu("Templates"); templates.setMnemonic(KeyEvent.VK_T); addTemplates(templates); mbar.add(templates); // -- Run menu -- runMenu = new JMenu("Run"); runMenu.setMnemonic(KeyEvent.VK_R); compileAndRun = addToMenu(runMenu, "Compile and Run", KeyEvent.VK_R, ctrl); compileAndRun.setMnemonic(KeyEvent.VK_R); runSelection = addToMenu(runMenu, "Run Selected Code", KeyEvent.VK_R, ctrl | shift); runSelection.setMnemonic(KeyEvent.VK_S); compile = addToMenu(runMenu, "Compile", KeyEvent.VK_C, ctrl | shift); compile.setMnemonic(KeyEvent.VK_C); autoSave = new JCheckBoxMenuItem("Auto-save Before Compiling"); runMenu.add(autoSave); runMenu.addSeparator(); nextError = addToMenu(runMenu, "Next Error", KeyEvent.VK_F4, 0); nextError.setMnemonic(KeyEvent.VK_N); previousError = addToMenu(runMenu, "Previous Error", KeyEvent.VK_F4, shift); previousError.setMnemonic(KeyEvent.VK_P); final JMenuItem clearHighlights = new JMenuItem("Clear Marked Errors"); clearHighlights.addActionListener(e -> getEditorPane().getErrorHighlighter().reset()); runMenu.add(clearHighlights); runMenu.addSeparator(); kill = addToMenu(runMenu, "Kill Running Script...", 0, 0); kill.setMnemonic(KeyEvent.VK_K); kill.setEnabled(false); mbar.add(runMenu); // -- Tools menu -- toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic(KeyEvent.VK_O); cmdPalette = new CommandPalette(this); cmdPalette.install(toolsMenu); GuiUtils.addMenubarSeparator(toolsMenu, "Imports:"); addImport = addToMenu(toolsMenu, "Add Import...", 0, 0); addImport.setMnemonic(KeyEvent.VK_I); respectAutoImports = prefService.getBoolean(getClass(), AUTO_IMPORT_PREFS, false); autoImport = new JCheckBoxMenuItem("Auto-import (Deprecated)", respectAutoImports); autoImport.setToolTipText("Automatically imports common classes before running code"); autoImport.addItemListener(e -> { respectAutoImports = e.getStateChange() == ItemEvent.SELECTED; prefService.put(getClass(), AUTO_IMPORT_PREFS, respectAutoImports); if (respectAutoImports) write("Auto-imports on. Lines associated with execution errors cannot be marked"); else write("Auto-imports off. Lines associated with execution errors can be marked"); }); toolsMenu.add(autoImport); removeUnusedImports = addToMenu(toolsMenu, "Remove Unused Imports", 0, 0); removeUnusedImports.setMnemonic(KeyEvent.VK_U); sortImports = addToMenu(toolsMenu, "Sort Imports", 0, 0); sortImports.setMnemonic(KeyEvent.VK_S); GuiUtils.addMenubarSeparator(toolsMenu, "Source & APIs:"); extractSourceJar = addToMenu(toolsMenu, "Extract Source Jar...", 0, 0); extractSourceJar.setMnemonic(KeyEvent.VK_E); openSourceForClass = addToMenu(toolsMenu, "Open Java File for Class...", 0, 0); openSourceForClass.setMnemonic(KeyEvent.VK_J); //openSourceForMenuItem = addToMenu(toolsMenu, "Open Java File for Menu Item...", 0, 0); //openSourceForMenuItem.setMnemonic(KeyEvent.VK_M); GuiUtils.addMenubarSeparator(toolsMenu, "chatGPT"); askChatGPTtoGenerateCode = addToMenu(toolsMenu, "Ask chatGPT...", 0, 0); addScritpEditorMacroCommands(toolsMenu); mbar.add(toolsMenu); // -- Git menu -- gitMenu = new JMenu("Git"); gitMenu.setMnemonic(KeyEvent.VK_G); /* showDiff = addToMenu(gitMenu, "Show diff...", 0, 0); showDiff.setMnemonic(KeyEvent.VK_D); commit = addToMenu(gitMenu, "Commit...", 0, 0); commit.setMnemonic(KeyEvent.VK_C); */ gitGrep = addToMenu(gitMenu, "Grep...", 0, 0); gitGrep.setMnemonic(KeyEvent.VK_G); mbar.add(gitMenu); // -- Window Menu (previously labeled as Tabs menu -- tabsMenu = new JMenu("Window"); tabsMenu.setMnemonic(KeyEvent.VK_W); GuiUtils.addMenubarSeparator(tabsMenu, "Panes:"); // Assume initial status from prefs or panel visibility final JCheckBoxMenuItem jcmi1 = new JCheckBoxMenuItem("Side Pane", prefService.getInt(getClass(), MAIN_DIV_LOCATION, body.getDividerLocation()) > 0 || isLeftPaneExpanded(body)); jcmi1.addItemListener(e -> collapseSplitPane(0, !jcmi1.isSelected())); tabsMenu.add(jcmi1); // Console not initialized. Assume it is displayed if no prefs read final JCheckBoxMenuItem jcmi2 = new JCheckBoxMenuItem("Console", prefService.getInt(getClass(), TAB_DIV_LOCATION, 1) > 0); jcmi2.addItemListener(e -> collapseSplitPane(1, !jcmi2.isSelected())); tabsMenu.add(jcmi2); final JMenuItem mi = new JMenuItem("Reset Layout..."); mi.addActionListener(e -> { if (confirm("Reset Location of Console and File Explorer?", "Reset Layout?", "Reset")) { resetLayout(); jcmi1.setSelected(true); jcmi2.setSelected(true); } }); tabsMenu.add(mi); GuiUtils.addMenubarSeparator(tabsMenu, "Tabs:"); nextTab = addToMenu(tabsMenu, "Next Tab", KeyEvent.VK_PAGE_DOWN, ctrl); nextTab.setMnemonic(KeyEvent.VK_N); previousTab = addToMenu(tabsMenu, "Previous Tab", KeyEvent.VK_PAGE_UP, ctrl); previousTab.setMnemonic(KeyEvent.VK_P); tabsMenu.addSeparator(); tabsMenuTabsStart = tabsMenu.getItemCount(); tabsMenuItems = new HashSet<>(); mbar.add(tabsMenu); // -- Options menu -- final JMenu options = new JMenu("Options"); options.setMnemonic(KeyEvent.VK_O); // Font adjustments GuiUtils.addMenubarSeparator(options, "Font:"); decreaseFontSize = addToMenu(options, "Decrease Font Size", KeyEvent.VK_MINUS, ctrl); decreaseFontSize.setMnemonic(KeyEvent.VK_D); increaseFontSize = addToMenu(options, "Increase Font Size", KeyEvent.VK_PLUS, ctrl); increaseFontSize.setMnemonic(KeyEvent.VK_C); fontSizeMenu = new JMenu("Font Size"); fontSizeMenu.setMnemonic(KeyEvent.VK_Z); final boolean[] fontSizeShortcutUsed = new boolean[10]; final ButtonGroup buttonGroup = new ButtonGroup(); for (final int size : new int[] { 8, 10, 12, 16, 20, 28, 42 }) { final JRadioButtonMenuItem item = new JRadioButtonMenuItem("" + size + " pt"); item.addActionListener(event -> setFontSize(size)); for (final char c : ("" + size).toCharArray()) { final int digit = c - '0'; if (!fontSizeShortcutUsed[digit]) { item.setMnemonic(KeyEvent.VK_0 + digit); fontSizeShortcutUsed[digit] = true; break; } } buttonGroup.add(item); fontSizeMenu.add(item); } chooseFontSize = new JRadioButtonMenuItem("Other...", false); chooseFontSize.setMnemonic(KeyEvent.VK_O); chooseFontSize.addActionListener(this); buttonGroup.add(chooseFontSize); fontSizeMenu.add(chooseFontSize); options.add(fontSizeMenu); GuiUtils.addMenubarSeparator(options, "Indentation:"); tabsEmulated = new JCheckBoxMenuItem("Indent Using Spaces"); tabsEmulated.setMnemonic(KeyEvent.VK_S); tabsEmulated.addItemListener(e -> setTabsEmulated(tabsEmulated.getState())); options.add(tabsEmulated); tabSizeMenu = new JMenu("Tab Width"); tabSizeMenu.setMnemonic(KeyEvent.VK_T); final ButtonGroup bg = new ButtonGroup(); for (final int size : new int[] { 2, 4, 8 }) { final JRadioButtonMenuItem item = new JRadioButtonMenuItem("" + size); item.addActionListener(event -> { getEditorPane().setTabSize(size); updateTabAndFontSize(false); }); item.setMnemonic(KeyEvent.VK_0 + (size % 10)); bg.add(item); tabSizeMenu.add(item); } chooseTabSize = new JRadioButtonMenuItem("Other...", false); chooseTabSize.setMnemonic(KeyEvent.VK_O); chooseTabSize.addActionListener(this); bg.add(chooseTabSize); tabSizeMenu.add(chooseTabSize); options.add(tabSizeMenu); replaceSpacesWithTabs = addToMenu(options, "Replace Spaces With Tabs", 0, 0); replaceTabsWithSpaces = addToMenu(options, "Replace Tabs With Spaces", 0, 0); GuiUtils.addMenubarSeparator(options, "View:"); options.add(markOccurences); options.add(paintTabs); options.add(marginLine); options.add(whiteSpace); options.add(wrapLines); options.add(applyThemeMenu()); GuiUtils.addMenubarSeparator(options, "Code Completions:"); options.add(autocompletion); options.add(keylessAutocompletion); options.add(fallbackAutocompletion); options.addSeparator(); appendPreferences(options); mbar.add(options); mbar.add(helpMenu()); // -- END MENUS -- // add tab-related listeners tabbed.addChangeListener(this); sideTabs.addChangeListener(e -> { if (sideTabs.getSelectedIndex() == 1) sourceTreePanel.rebuildSourceTree(getTab(tabbed.getSelectedIndex()).editorPane); }); // Add the editor and output area new FileDrop(tabbed, files -> { final ArrayList<File> filteredFiles = new ArrayList<>(); assembleFlatFileCollection(filteredFiles, files); if (filteredFiles.isEmpty()) { warn("None of the dropped file(s) seems parseable."); return; } if (filteredFiles.size() < 10 || confirm("Confirm loading of " + filteredFiles.size() + " items?", "Confirm?", "Load")) { filteredFiles.forEach(f -> open(f)); } }); open(null); // make sure the editor pane is added getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); // Tweaks for JSplitPane body.setOneTouchExpandable(true); body.addPropertyChangeListener(evt -> { if ("dividerLocation".equals(evt.getPropertyName())) saveWindowSizeToPrefs(); }); // Tweaks for FileSystemTree tree.addTopLevelFoldersFrom(getEditorPane().loadFolders()); // Restore top-level directories dragSource = new DragSource(); dragSource.createDefaultDragGestureRecognizer(tree, DnDConstants.ACTION_COPY, new DragAndDrop()); tree.ignoreExtension("class"); tree.setMinimumSize(new Dimension(200, 600)); tree.addLeafListener(f -> { final String name = f.getName(); final int idot = name.lastIndexOf('.'); if (idot > -1) { final String ext = name.substring(idot + 1); final ScriptLanguage lang = scriptService.getLanguageByExtension(ext); if (null != lang) { open(f); return; } } if (isBinary(f)) { log.debug("isBinary: " + true); try { final Object o = ioService.open(f.getAbsolutePath()); // Open in whatever way possible if (null != o) uiService.show(o); else error("Could not open the file at\n" + f.getAbsolutePath()); return; } catch (final Exception e) { log.error(e); error("Could not open file at\n" + f); } } // Ask: if (confirm("Really try to open file " + name + " in a tab?", "Confirm", "Open")) { open(f); } }); getContentPane().add(body); // for Eclipse and MS Visual Studio lovers addAccelerator(compileAndRun, KeyEvent.VK_F11, 0, true); addAccelerator(compileAndRun, KeyEvent.VK_F5, 0, true); compileAndRun.setToolTipText("Also triggered by F5 or F11"); addAccelerator(nextTab, KeyEvent.VK_PAGE_DOWN, ctrl, true); addAccelerator(previousTab, KeyEvent.VK_PAGE_UP, ctrl, true); addAccelerator(increaseFontSize, KeyEvent.VK_EQUALS, ctrl | shift, true); // make sure that the window is not closed by accident addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { if (!confirmClose()) return; tree.destroy(); // Necessary to prevent memory leaks for (final DragSourceListener l : dragSource.getDragSourceListeners()) { dragSource.removeDragSourceListener(l); } dragSource = null; getTab().destroy(); cmdPalette.dispose(); dispose(); } }); addWindowFocusListener(new WindowAdapter() { @Override public void windowGainedFocus(final WindowEvent e) { checkForOutsideChanges(); } }); // Tweaks for Console errorScreen.setFont(getEditorPane().getFont()); errorScreen.setEditable(false); errorScreen.setLineWrap(false); applyConsolePopupMenu(errorScreen); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); try { threadService.invoke(() -> { pack(); body.setDividerLocation(0.2); // Important!: will be read as prefs. default getTab().setREPLVisible(false); loadWindowSizePreferences(); pack(); }); } catch (final Exception ie) { /* ignore */ log.debug(ie); } findDialog = new FindAndReplaceDialog(this); // Save the layout when window is resized. addComponentListener(new ComponentAdapter() { @Override public void componentResized(final ComponentEvent e) { saveWindowSizeToPrefs(); } }); setLocationRelativeTo(null); // center on screen // HACK: Avoid weird macOS bug where window becomes tiny // in bottom left corner if centered while maximized. int y = getLocation().y - 11; if (y < 0) y = 0; setLocation(getLocation().x, y); open(null); final EditorPane editorPane = getEditorPane(); // If dark L&F and using the default theme, assume 'dark' theme applyTheme((GuiUtils.isDarkLaF() && "default".equals(editorPane.themeName())) ? "dark" : editorPane.themeName(), true); // Ensure font sizes are consistent across all panels setFontSize(getEditorPane().getFontSize()); // Ensure menu commands are up-to-date updateUI(true); // Store locations of splitpanes panePositions = new int[]{body.getDividerLocation(), getTab().getDividerLocation()}; editorPane.requestFocus(); } private void resetLayout() { body.setDividerLocation(.2d); getTab().setOrientation(JSplitPane.VERTICAL_SPLIT); getTab().setDividerLocation((incremental) ? .7d : .75d); if (incremental) getTab().getScreenAndPromptSplit().setDividerLocation(.5d); getTab().setREPLVisible(incremental); pack(); } private void assembleEditMenu() { // requires an existing instance of an EditorPane final int ctrl = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); final int shift = ActionEvent.SHIFT_MASK; undo = addToMenu(editMenu, "Undo", KeyEvent.VK_Z, ctrl); redo = addToMenu(editMenu, "Redo", KeyEvent.VK_Y, ctrl); editMenu.addSeparator(); selectAll = addToMenu(editMenu, "Select All", KeyEvent.VK_A, ctrl); cut = addToMenu(editMenu, "Cut", KeyEvent.VK_X, ctrl); copy = addToMenu(editMenu, "Copy", KeyEvent.VK_C, ctrl); addMappedActionToMenu(editMenu, "Copy as Styled Text", EditorPaneActions.rstaCopyAsStyledTextAction, false); paste = addToMenu(editMenu, "Paste", KeyEvent.VK_V, ctrl); addMappedActionToMenu(editMenu, "Paste History...", EditorPaneActions.clipboardHistoryAction, true); GuiUtils.addMenubarSeparator(editMenu, "Find:"); find = addToMenu(editMenu, "Find/Replace...", KeyEvent.VK_F, ctrl); find.setMnemonic(KeyEvent.VK_F); findNext = addToMenu(editMenu, "Find Next", KeyEvent.VK_F3, 0); findNext.setMnemonic(KeyEvent.VK_N); findPrevious = addToMenu(editMenu, "Find Previous", KeyEvent.VK_F3, shift); findPrevious.setMnemonic(KeyEvent.VK_P); GuiUtils.addMenubarSeparator(editMenu, "Go To:"); gotoLine = addToMenu(editMenu, "Go to Line...", KeyEvent.VK_G, ctrl); gotoLine.setMnemonic(KeyEvent.VK_G); addMappedActionToMenu(editMenu, "Go to Matching Bracket", EditorPaneActions.rstaGoToMatchingBracketAction, false); final JMenuItem gotoType = new JMenuItem("Go to Type..."); // we could retrieve the accelerator from paneactions but this may not work, if e.g., an // unsupported syntax (such IJM) has been opened at startup, so we'll just specify it manually //gotoType.setAccelerator(getEditorPane().getPaneActions().getAccelerator("GoToType")); gotoType.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ctrl + shift)); gotoType.addActionListener(e -> { try { getTextArea().getActionMap().get("GoToType").actionPerformed(e); } catch (final Exception | Error ignored) { error("\"Goto Type\" not availabe for current scripting language."); } }); editMenu.add(gotoType); GuiUtils.addMenubarSeparator(editMenu, "Bookmarks:"); addMappedActionToMenu(editMenu, "Next Bookmark", EditorPaneActions.rtaNextBookmarkAction, false); addMappedActionToMenu(editMenu, "Previous Bookmark", EditorPaneActions.rtaPrevBookmarkAction, false); final JMenuItem toggB = addMappedActionToMenu(editMenu, "Toggle Bookmark", EditorPaneActions.rtaToggleBookmarkAction, false); toggB.setToolTipText("Alternatively, click on left bookmark gutter near the line number"); final JMenuItem listBookmarks = addToMenu(editMenu, "List Bookmarks...", 0, 0); listBookmarks.setMnemonic(KeyEvent.VK_L); listBookmarks.addActionListener(e -> listBookmarks()); final JMenuItem clearBookmarks = addToMenu(editMenu, "Clear Bookmarks...", 0, 0); clearBookmarks.addActionListener(e -> clearAllBookmarks()); GuiUtils.addMenubarSeparator(editMenu, "Utilities:"); final JMenuItem commentJMI = addMappedActionToMenu(editMenu, "Toggle Comment", EditorPaneActions.rstaToggleCommentAction, true); commentJMI.setToolTipText("Alternative shortcut: " + getEditorPane().getPaneActions().getAcceleratorLabel(EditorPaneActions.epaToggleCommentAltAction)); addMappedActionToMenu(editMenu, "Insert Time Stamp", EditorPaneActions.rtaTimeDateAction, true); removeTrailingWhitespace = addToMenu(editMenu, "Remove Trailing Whitespace", 0, 0); zapGremlins = addToMenu(editMenu, "Zap Gremlins", 0, 0); zapGremlins.setToolTipText("Removes invalid (non-printable) ASCII characters"); } private void addScritpEditorMacroCommands(final JMenu menu) { GuiUtils.addMenubarSeparator(menu, "Script Editor Macros:"); final JMenuItem startMacro = new JMenuItem("Start/Resume Macro Recording"); startMacro.addActionListener(e -> { if (getEditorPane().isLocked()) { error("File is currently locked."); return; } final String state = (RTextArea.getCurrentMacro() == null) ? "on" : "resumed"; write("Script Editor: Macro recording " + state); RTextArea.beginRecordingMacro(); }); menu.add(startMacro); final JMenuItem pauseMacro = new JMenuItem("Pause Macro Recording..."); pauseMacro.addActionListener(e -> { if (!RTextArea.isRecordingMacro() || RTextArea.getCurrentMacro() == null) { warn("No Script Editor Macro recording exists."); } else { RTextArea.endRecordingMacro(); final int nSteps = RTextArea.getCurrentMacro().getMacroRecords().size(); write("Script Editor: Macro recording off: " + nSteps + " event(s)/action(s) recorded."); if (nSteps == 0) { RTextArea.loadMacro(null); } } }); menu.add(pauseMacro); final JMenuItem endMacro = new JMenuItem("Stop/Save Recording..."); endMacro.addActionListener(e -> { pauseMacro.doClick(); if (RTextArea.getCurrentMacro() != null) { final File fileToSave = getMacroFile(false); if (fileToSave != null) { try { RTextArea.getCurrentMacro().saveToFile(fileToSave); } catch (final IOException e1) { error(e1.getMessage()); e1.printStackTrace(); } } } }); menu.add(endMacro); final JMenuItem clearMacro = new JMenuItem("Clear Recorded Macro..."); clearMacro.addActionListener(e -> { if (RTextArea.getCurrentMacro() == null) { warn("Nothing to clear: No macro has been recorded."); return; } if (confirm("Clear Recorded Macro(s)?", "Clear Recording(s)?", "Clear")) { RTextArea.loadMacro(null); write("Script Editor: Recorded macro(s) cleared."); } }); menu.add(clearMacro); final JMenuItem playMacro = new JMenuItem("Run Recorded Macro"); playMacro.setToolTipText("Runs current recordings. Prompts for\nrecordings file if no recordings exist"); playMacro.addActionListener(e -> { if (getEditorPane().isLocked()) { error("File is currently locked."); return; } if (null == RTextArea.getCurrentMacro()) { final File fileToOpen = getMacroFile(true); if (fileToOpen != null) { try { RTextArea.loadMacro(new Macro(fileToOpen)); } catch (final IOException e1) { error(e1.getMessage()); e1.printStackTrace(); } } } if (RTextArea.isRecordingMacro()) { if (confirm("Recording must be paused before execution. Pause recording now?", "Pause and Run?", "Pause and Run")) { RTextArea.endRecordingMacro(); write("Script Editor: Recording paused"); } else { return; } } if (RTextArea.getCurrentMacro() != null) { final int actions = RTextArea.getCurrentMacro().getMacroRecords().size(); write("Script Editor: Running recorded macro [" + actions + " event(s)/action(s)]"); try { getTextArea().playbackLastMacro(); } catch (final Exception | Error ex) { error("An Exception occured while running macro. See Console for details"); ex.printStackTrace(); } } }); menu.add(playMacro); } private File getMacroFile(final boolean openOtherwiseSave) { final String msg = (openOtherwiseSave) ? "No macros have been recorded. Load macro from file?" : "Recording Stopped. Save recorded macro to local file?"; final String title = (openOtherwiseSave) ? "Load from File?" : "Save to File?"; final String yesLabel = (openOtherwiseSave) ? "Load" : "Save"; if (confirm(msg, title, yesLabel)) { File dir = appService.getApp().getBaseDirectory(); final String filename = "RecordedScriptEditorMacro.xml"; if (getEditorPane().getFile() != null) { dir = getEditorPane().getFile().getParentFile(); } return uiService.chooseFile(new File(dir, filename), (openOtherwiseSave) ? FileWidget.OPEN_STYLE : FileWidget.SAVE_STYLE); } return null; } private void displayRecordableMap() { displayMap(cmdPalette.getRecordableActions(), "Script Editor Recordable Actions/Events"); } private void displayKeyMap() { displayMap(cmdPalette.getShortcuts(), "Script Editor Shortcuts"); } private void displayMap(final Map<String, String> map, final String windowTitle) { final ArrayList<String> lines = new ArrayList<>(); map.forEach( (cmd, key) -> { lines.add("<tr><td>" + cmd + "</td><td>" + key + "</td></tr>"); }); final String prefix = "<HTML><center><table>" // + "<tbody>" // + "<tr>" // + "<td style=\"width: 60%; text-align: center;\"><b>Action</b></td>" // + "<td style=\"width: 40%; text-align: center;\"><b>Shortcut</b></td>" // + "</tr>"; // final String suffix = "</tbody></table></center>"; showHTMLDialog(windowTitle, prefix + String.join("", lines) + suffix); } private class DragAndDrop implements DragSourceListener, DragGestureListener { @Override public void dragDropEnd(final DragSourceDropEvent dsde) {} @Override public void dragEnter(final DragSourceDragEvent dsde) { dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop); } @Override public void dragGestureRecognized(final DragGestureEvent dge) { final TreePath path = tree.getSelectionPath(); if (path == null) // nothing is currently selected return; final String filepath = (String)((FileSystemTree.Node) path.getLastPathComponent()).getUserObject(); dragSource.startDrag(dge, DragSource.DefaultCopyDrop, new Transferable() { @Override public boolean isDataFlavorSupported(final DataFlavor flavor) { return DataFlavor.javaFileListFlavor == flavor; } @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[]{ DataFlavor.javaFileListFlavor }; } @Override public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (isDataFlavorSupported(flavor)) return Arrays.asList(new String[]{filepath}); return null; } }, this); } @Override public void dragExit(final DragSourceEvent dse) { dse.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop); } @Override public void dragOver(final DragSourceDragEvent dsde) { if (tree == dsde.getSource()) { dsde.getDragSourceContext().setCursor(DragSource.DefaultCopyNoDrop); } else if (dsde.getDropAction() == DnDConstants.ACTION_COPY) { dsde.getDragSourceContext().setCursor(DragSource.DefaultCopyDrop); } else { dsde.getDragSourceContext().setCursor(DragSource.DefaultCopyNoDrop); } } @Override public void dropActionChanged(final DragSourceDragEvent dsde) {} } public LogService log() { return log; } public PlatformService getPlatformService() { return platformService; } public JTextArea getErrorScreen() { return errorScreen; } public void setErrorScreen(final JTextArea errorScreen) { this.errorScreen = errorScreen; } public ErrorHandler getErrorHandler() { return errorHandler; } public void setErrorHandler(final ErrorHandler errorHandler) { this.errorHandler = errorHandler; } private synchronized void initializeTokenMakers() { if (tokenMakerFactory != null) return; tokenMakerFactory = (AbstractTokenMakerFactory) TokenMakerFactory.getDefaultInstance(); for (final PluginInfo<SyntaxHighlighter> info : pluginService .getPluginsOfType(SyntaxHighlighter.class)) try { tokenMakerFactory.putMapping("text/" + info.getName().toLowerCase().replace(' ', '-'), info .getClassName()); } catch (final Throwable t) { log.warn("Could not register " + info.getName(), t); } } private void initializeDynamicMenuComponents() { // Options menu. These will be updated once EditorPane is created wrapLines = new JCheckBoxMenuItem("Wrap Lines", false); wrapLines.setMnemonic(KeyEvent.VK_W); marginLine = new JCheckBoxMenuItem("Show Margin Line", false); marginLine.setToolTipText("Displays right margin at column 80"); marginLine.addItemListener(e -> setMarginLineEnabled(marginLine.getState())); wrapLines.addItemListener(e -> setWrapLines(wrapLines.getState())); markOccurences = new JCheckBoxMenuItem("Mark Occurences", false); markOccurences.setToolTipText("Allows for all occurrences of a double-clicked string to be" + " highlighted.\nLines with hits are marked on the Editor's notification strip"); markOccurences.addItemListener(e -> setMarkOccurrences(markOccurences.getState())); whiteSpace = new JCheckBoxMenuItem("Show Whitespace", false); whiteSpace.addItemListener(e -> setWhiteSpaceVisible(whiteSpace.isSelected())); paintTabs = new JCheckBoxMenuItem("Show Indent Guides"); paintTabs.setToolTipText("Displays 'tab lines' for leading whitespace"); paintTabs.addItemListener(e -> setPaintTabLines(paintTabs.getState())); autocompletion = new JCheckBoxMenuItem("Enable Autocompletion", true); autocompletion.setToolTipText("Whether code completion should be used.\nNB: Not all languages support this feature"); autocompletion.addItemListener(e -> setAutoCompletionEnabled(autocompletion.getState())); keylessAutocompletion = new JCheckBoxMenuItem("Show Completions Without Ctrl+Space", false); keylessAutocompletion.setToolTipText("If selected, the completion pop-up automatically appears while typing"); keylessAutocompletion.addItemListener(e -> setKeylessAutoCompletion(keylessAutocompletion.getState())); fallbackAutocompletion = new JCheckBoxMenuItem("Use Java Completions as Fallback", false); fallbackAutocompletion.setToolTipText("<HTML>If selected, Java completions will be used when scripting<br>" + "a language for which auto-completions are not available"); fallbackAutocompletion.addItemListener(e -> setFallbackAutoCompletion(fallbackAutocompletion.getState())); themeRadioGroup = new ButtonGroup(); // Help menu. These are 'dynamic' items openMacroFunctions = new JMenuItem("Open Help on Macro Function(s)..."); openMacroFunctions.setMnemonic(KeyEvent.VK_H); openMacroFunctions.addActionListener(e -> { try { new MacroFunctions(this).openHelp(getTextArea().getSelectedText()); } catch (final IOException ex) { handleException(ex); } }); openHelp = new JMenuItem("Open Help for Class (With Frames)..."); openHelp.setMnemonic(KeyEvent.VK_H); openHelp.addActionListener( e-> openHelp(null)); openHelpWithoutFrames = new JMenuItem("Open Help for Class..."); openHelpWithoutFrames.addActionListener(e -> openHelp(null, false)); } /** * Check whether the file was edited outside of this {@link EditorPane} and * ask the user whether to reload. */ public void checkForOutsideChanges() { final EditorPane editorPane = getEditorPane(); if (editorPane.wasChangedOutside()) { reload(editorPane.getFile().getName() + "\nwas changed outside of the editor."); } } /** * Adds a script template path that will be scanned by future TextEditor * instances. * * @param path Resource path to scan for scripts. */ public static void addTemplatePath(final String path) { TEMPLATE_PATHS.add(path); } @EventHandler private void onEvent( @SuppressWarnings("unused") final ContextDisposingEvent e) { if (isDisplayable()) dispose(); } /** * Loads the Script Editor layout from persisted storage. * @see #saveWindowSizeToPrefs() */ public void loadWindowSizePreferences() { layoutLoading = true; final Dimension dim = getSize(); // If a dimension is 0 then use the default dimension size if (0 == dim.width) dim.width = DEFAULT_WINDOW_WIDTH; if (0 == dim.height) dim.height = DEFAULT_WINDOW_HEIGHT; final int windowWidth = prefService.getInt(getClass(), WINDOW_WIDTH, dim.width); final int windowHeight = prefService.getInt(getClass(), WINDOW_HEIGHT, dim.height); // Avoid creating a window larger than the desktop final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); if (windowWidth > screen.getWidth() || windowHeight > screen.getHeight()) setPreferredSize(new Dimension(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT)); else setPreferredSize(new Dimension(windowWidth, windowHeight)); final int mainDivLocation = prefService.getInt(getClass(), MAIN_DIV_LOCATION, body.getDividerLocation()); body.setDividerLocation(mainDivLocation); final TextEditorTab tab = getTab(); final int tabDivLocation = prefService.getInt(getClass(), TAB_DIV_LOCATION, tab.getDividerLocation()); final int tabDivOrientation = prefService.getInt(getClass(), TAB_DIV_ORIENTATION, tab.getOrientation()); final int replDividerLocation = prefService.getInt(getClass(), REPL_DIV_LOCATION, tab.getScreenAndPromptSplit().getDividerLocation()); tab.setDividerLocation(tabDivLocation); tab.setOrientation(tabDivOrientation); tab.getScreenAndPromptSplit().setDividerLocation(replDividerLocation); layoutLoading = false; } /** * Saves the Script Editor layout to persisted storage. * <p> * Separated from savePreferences because we always want to save the window * size when it's resized, however, we don't want to automatically save the * font, tab size, etc. without the user pressing "Save Preferences" * </p> * @see #loadWindowSizePreferences() */ public void saveWindowSizeToPrefs() { if (layoutLoading) return; final Dimension dim = getSize(); prefService.put(getClass(), WINDOW_HEIGHT, dim.height); prefService.put(getClass(), WINDOW_WIDTH, dim.width); prefService.put(getClass(), MAIN_DIV_LOCATION, body.getDividerLocation()); final TextEditorTab tab = getTab(); prefService.put(getClass(), TAB_DIV_LOCATION, tab.getDividerLocation()); prefService.put(getClass(), TAB_DIV_ORIENTATION, tab.getOrientation()); prefService.put(getClass(), REPL_DIV_LOCATION, tab.getScreenAndPromptSplit().getDividerLocation()); } final public RSyntaxTextArea getTextArea() { return getEditorPane(); } /** * Get the currently selected tab. * * @return The currently selected tab. Never null. */ public TextEditorTab getTab() { int index = tabbed.getSelectedIndex(); if (index < 0) { // should not happen, but safety first. if (tabbed.getTabCount() == 0) { // should not happen either, but, again, safety first. createNewDocument(); } // Ensure the new document is returned - otherwise we would pass // the negative index to the getComponentAt call below. tabbed.setSelectedIndex(0); index = 0; } return (TextEditorTab) tabbed.getComponentAt(index); } /** * Get tab at provided index. * * @param index the index of the tab. * @return the {@link TextEditorTab} at given index or <code>null</code>. */ public TextEditorTab getTab(final int index) { return (TextEditorTab) tabbed.getComponentAt(index); } /** * Return the {@link EditorPane} of the currently selected * {@link TextEditorTab}. * * @return the current {@link EditorPane}. Never <code>null</code>. */ public EditorPane getEditorPane() { return getTab().editorPane; } /** * @return {@link ScriptLanguage} used in the current {@link EditorPane}. */ public ScriptLanguage getCurrentLanguage() { return getEditorPane().getCurrentLanguage(); } public JMenuItem addToMenu(final JMenu menu, final String menuEntry, final int key, final int modifiers) { final JMenuItem item = new JMenuItem(menuEntry); menu.add(item); if (key != 0) item.setAccelerator(KeyStroke.getKeyStroke(key, modifiers)); item.addActionListener(this); return item; } private JMenuItem addMappedActionToMenu(final JMenu menu, String label, String actionID, final boolean editingAction) { final JMenuItem jmi = new JMenuItem(label); jmi.addActionListener(e -> { try { if (editingAction && getEditorPane().isLocked()) { warn("File is currently locked."); return; } if (RTextAreaEditorKit.clipboardHistoryAction.equals(actionID) && ClipboardHistory.get().getHistory().isEmpty()) { warn("The internal clipboard manager is empty."); return; } getTextArea().requestFocusInWindow(); getTextArea().getActionMap().get(actionID).actionPerformed(e); } catch (final Exception | Error ignored) { error("\"" + label + "\" not availabe for current scripting language."); } }); jmi.setAccelerator(getEditorPane().getPaneActions().getAccelerator(actionID)); menu.add(jmi); return jmi; } protected static class AcceleratorTriplet { JMenuItem component; int key, modifiers; } protected List<AcceleratorTriplet> defaultAccelerators = new ArrayList<>(); public void addAccelerator(final JMenuItem component, final int key, final int modifiers) { addAccelerator(component, key, modifiers, false); } public void addAccelerator(final JMenuItem component, final int key, final int modifiers, final boolean record) { if (record) { final AcceleratorTriplet triplet = new AcceleratorTriplet(); triplet.component = component; triplet.key = key; triplet.modifiers = modifiers; defaultAccelerators.add(triplet); } final RSyntaxTextArea textArea = getTextArea(); if (textArea != null) addAccelerator(textArea, component, key, modifiers); } public void addAccelerator(final RSyntaxTextArea textArea, final JMenuItem component, final int key, final int modifiers) { textArea.getInputMap().put(KeyStroke.getKeyStroke(key, modifiers), component); textArea.getActionMap().put(component, new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { if (!component.isEnabled()) return; final ActionEvent event = new ActionEvent(component, 0, "Accelerator"); TextEditor.this.actionPerformed(event); } }); } public void addDefaultAccelerators(final RSyntaxTextArea textArea) { for (final AcceleratorTriplet triplet : defaultAccelerators) addAccelerator(textArea, triplet.component, triplet.key, triplet.modifiers); } private JMenu getMenu(final JMenu root, final String menuItemPath, final boolean createIfNecessary) { final int slash = menuItemPath.indexOf('/'); if (slash < 0) return root; final String menuLabel = menuItemPath.substring(0, slash); final String rest = menuItemPath.substring(slash + 1); for (int i = 0; i < root.getItemCount(); i++) { final JMenuItem item = root.getItem(i); if (item instanceof JMenu && menuLabel.equals(item.getText())) { return getMenu((JMenu) item, rest, createIfNecessary); } } if (!createIfNecessary) return null; final JMenu subMenu = new JMenu(menuLabel); root.add(subMenu); return getMenu(subMenu, rest, createIfNecessary); } /** * Initializes the Templates menu. * <p> * Other components can add templates simply by providing scripts in their * resources, identified by a path of the form * {@code /script_templates/<menu path>/<menu label>}. * </p> * * @param templatesMenu the top-level menu to populate */ private void addTemplates(final JMenu templatesMenu) { final File baseDir = appService.getApp().getBaseDirectory(); for (final String templatePath : TEMPLATE_PATHS) { for (final Map.Entry<String, URL> entry : new TreeMap<>( FileUtils.findResources(null, templatePath, baseDir)).entrySet()) { final String key = entry.getKey(); final String ext = FileUtils.getExtension(key); // try to determine the scripting language final ScriptLanguage lang = ext.isEmpty() ? null : scriptService.getLanguageByExtension(ext); final String langName = lang == null ? null : lang.getLanguageName(); final String langSuffix = lang == null ? null : " (" + langName + ")"; final String path = adjustPath(key, langName); // create a human-readable label final int labelIndex = path.lastIndexOf('/') + 1; final String label = ext.isEmpty() ? path.substring(labelIndex) : path.substring(labelIndex, path.length() - ext.length() - 1); final ActionListener menuListener = e -> loadTemplate(entry.getValue()); // add script to the secondary language-sorted menu structure if (langName != null) { final String langPath = "[by language]/" + langName + "/" + path; final JMenu langMenu = getMenu(templatesMenu, langPath, true); final JMenuItem langItem = new JMenuItem(label); langMenu.add(langItem); langItem.addActionListener(menuListener); } // add script to the primary Templates menu structure final JMenu menu = getMenu(templatesMenu, path, true); final JMenuItem item = new JMenuItem(label + langSuffix); menu.add(item); item.addActionListener(menuListener); } } } /** * Loads a template file from the given resource * * @param url The resource to load. */ public void loadTemplate(final String url) { try { loadTemplate(new URL(url)); } catch (final Exception e) { log.error(e); error("The template '" + url + "' was not found."); } } public void loadTemplate(final URL url) { final String path = url.getPath(); final String ext = FileUtils.getExtension(path); final ScriptLanguage language = ext.isEmpty() ? null : scriptService.getLanguageByExtension(ext); loadTemplate(url, language); } public void loadTemplate(final URL url, final ScriptLanguage language) { createNewDocument(); try { // Load the template final InputStream in = url.openStream(); getTextArea().read(new BufferedReader(new InputStreamReader(in)), null); if (language != null) { setLanguage(language); } final String path = url.getPath(); setEditorPaneFileName(path.substring(path.lastIndexOf('/') + 1)); } catch (final Exception e) { log.error(e); error("The template '" + url + "' was not found."); } } public void createNewDocument() { open(null); } public void createNewDocument(final String title, final String text) { open(null); final EditorPane editorPane = getEditorPane(); editorPane.setText(text); setEditorPaneFileName(title); editorPane.setLanguageByFileName(title); updateLanguageMenu(editorPane.getCurrentLanguage()); } /** * Open a new editor to edit the given file, with a templateFile if the file * does not exist yet */ public void createNewFromTemplate(final File file, final File templateFile) { open(file.exists() ? file : templateFile); if (!file.exists()) { final EditorPane editorPane = getEditorPane(); try { editorPane.open(file); } catch (final IOException e) { handleException(e); } editorPane.setLanguageByFileName(file.getName()); updateLanguageMenu(editorPane.getCurrentLanguage()); } } public boolean fileChanged() { return getEditorPane().fileChanged(); } public boolean handleUnsavedChanges() { return handleUnsavedChanges(false); } public boolean handleUnsavedChanges(final boolean beforeCompiling) { if (!fileChanged()) return true; if (beforeCompiling && autoSave.getState()) { save(); return true; } if (GuiUtils.confirm(this, "Do you want to save changes?", "Save Changes?", "Save")) { return save(); } else { // Compiled languages should not progress if their source is unsaved return !beforeCompiling; } } private boolean isJava(final ScriptLanguage language) { return language != null && language.getLanguageName().equals("Java"); } @Override public void actionPerformed(final ActionEvent ae) { final Object source = ae.getSource(); if (source == newFile) createNewDocument(); else if (source == open) { final EditorPane editorPane = getEditorPane(); final File defaultDir = editorPane.getFile() != null ? editorPane.getFile().getParentFile() : appService.getApp().getBaseDirectory(); final File file = openWithDialog(defaultDir); if (file != null) new Thread(() -> open(file)).start(); return; } else if (source == save) save(); else if (source == saveas) saveAs(); else if (source == makeJar) makeJar(false); else if (source == makeJarWithSource) makeJar(true); else if (source == compileAndRun) runText(); else if (source == compile) compile(); else if (source == runSelection) runText(true); else if (source == nextError) { if (isJava(getEditorPane().getCurrentLanguage())) new Thread(() -> nextError(true)).start(); else getEditorPane().getErrorHighlighter().gotoNextError(); } else if (source == previousError) { if (isJava(getEditorPane().getCurrentLanguage())) new Thread(() -> nextError(false)).start(); else getEditorPane().getErrorHighlighter().gotoPreviousError(); } else if (source == kill) chooseTaskToKill(); else if (source == close) if (tabbed.getTabCount() < 2) processWindowEvent(new WindowEvent( this, WindowEvent.WINDOW_CLOSING)); else { if (!handleUnsavedChanges()) return; int index = tabbed.getSelectedIndex(); removeTab(index); if (index > 0) index--; switchTo(index); } else if (source == copy) getTextArea().copy(); else if (source == find) findOrReplace(true); else if (source == findNext) { findDialog.setRestrictToConsole(false); findDialog.searchOrReplace(false); } else if (source == findPrevious) { findDialog.setRestrictToConsole(false); findDialog.searchOrReplace(false, false); } else if (source == gotoLine) gotoLine(); else if (source == selectAll) { getTextArea().setCaretPosition(0); getTextArea().moveCaretPosition(getTextArea().getDocument().getLength()); } else if (source == chooseFontSize) { commandService.run(ChooseFontSize.class, true, "editor", this); } else if (source == chooseTabSize) { commandService.run(ChooseTabSize.class, true, "editor", this); } else if (source == openClassOrPackageHelp) openClassOrPackageHelp(null); else if (source == extractSourceJar) extractSourceJar(); else if (source == askChatGPTtoGenerateCode) askChatGPTtoGenerateCode(); else if (source == openSourceForClass) { final String className = getSelectedClassNameOrAsk("Class (fully qualified name):", "Which Class?"); if (className != null) { try { final String url = new FileFunctions(this).getSourceURL(className); platformService.open(new URL(url)); } catch (final Throwable e) { handleException(e); } } } /* TODO else if (source == showDiff) { new Thread(() -> { EditorPane pane = getEditorPane(); new FileFunctions(TextEditor.this).showDiff(pane.file, pane.getGitDirectory()); }).start(); } else if (source == commit) { new Thread(() -> { EditorPane pane = getEditorPane(); new FileFunctions(TextEditor.this).commit(pane.file, pane.getGitDirectory()); }).start(); } */ else if (source == gitGrep) { final String searchTerm = getTextArea().getSelectedText(); File searchRoot = getEditorPane().getFile(); if (searchRoot == null) { error("File was not yet saved; no location known!"); return; } searchRoot = searchRoot.getParentFile(); commandService.run(GitGrep.class, true, "editor", this, "searchTerm", searchTerm, "searchRoot", searchRoot); } else if (source == increaseFontSize || source == decreaseFontSize) { getEditorPane().increaseFontSize( (float) (source == increaseFontSize ? 1.2 : 1 / 1.2)); setFontSize(getEditorPane().getFontSize()); } else if (source == nextTab) switchTabRelative(1); else if (source == previousTab) switchTabRelative(-1); else if (handleTabsMenu(source)) return; else { // commands that should not run when files are locked! if (getEditorPane().isLocked()) { error("File is currently locked."); return; } if (source == cut) getTextArea().cut(); else if (source == paste) getTextArea().paste(); else if (source == undo) getTextArea().undoLastAction(); else if (source == redo) getTextArea().redoLastAction(); else if (source == addImport) { addImport(getSelectedClassNameOrAsk("Add import (complete qualified name of class/package)", "Which Class to Import?")); } else if (source == removeUnusedImports) new TokenFunctions(getTextArea()).removeUnusedImports(); else if (source == sortImports) new TokenFunctions(getTextArea()).sortImports(); else if (source == removeTrailingWhitespace) new TokenFunctions(getTextArea()).removeTrailingWhitespace(); else if (source == replaceTabsWithSpaces) getTextArea().convertTabsToSpaces(); else if (source == replaceSpacesWithTabs) getTextArea().convertSpacesToTabs(); else if (source == zapGremlins) zapGremlins(); } } private void setAutoCompletionEnabled(final boolean enabled) { for (int i = 0; i < tabbed.getTabCount(); i++) getEditorPane(i).setAutoCompletion(enabled); keylessAutocompletion.setEnabled(enabled); fallbackAutocompletion.setEnabled(enabled); } private void setTabsEmulated(final boolean emulated) { for (int i = 0; i < tabbed.getTabCount(); i++) getEditorPane(i).setTabsEmulated(emulated); getEditorPane().requestFocusInWindow(); } private void setPaintTabLines(final boolean paint) { for (int i = 0; i < tabbed.getTabCount(); i++) getEditorPane(i).setPaintTabLines(paint); getEditorPane().requestFocusInWindow(); } private void setKeylessAutoCompletion(final boolean noKeyRequired) { for (int i = 0; i < tabbed.getTabCount(); i++) getEditorPane(i).setKeylessAutoCompletion(noKeyRequired); getEditorPane().requestFocusInWindow(); } private void setFallbackAutoCompletion(final boolean fallback) { for (int i = 0; i < tabbed.getTabCount(); i++) getEditorPane(i).setFallbackAutoCompletion(fallback); getEditorPane().requestFocusInWindow(); } private void setMarkOccurrences(final boolean markOccurrences) { for (int i = 0; i < tabbed.getTabCount(); i++) getEditorPane(i).setMarkOccurrences(markOccurrences); getEditorPane().requestFocusInWindow(); } private void setWhiteSpaceVisible(final boolean visible) { for (int i = 0; i < tabbed.getTabCount(); i++) getEditorPane(i).setWhitespaceVisible(visible); getEditorPane().requestFocusInWindow(); } private void setWrapLines(final boolean wrap) { for (int i = 0; i < tabbed.getTabCount(); i++) getEditorPane(i).setLineWrap(wrap); getEditorPane().requestFocusInWindow(); } private void setMarginLineEnabled(final boolean enabled) { for (int i = 0; i < tabbed.getTabCount(); i++) getEditorPane(i).setMarginLineEnabled(enabled); getEditorPane().requestFocusInWindow(); } private JMenu applyThemeMenu() { final LinkedHashMap<String, String> map = new LinkedHashMap<>(); map.put("Default", "default"); map.put("-", "-"); map.put("Dark", "dark"); map.put("Druid", "druid"); map.put("Monokai", "monokai"); map.put("Eclipse (Light)", "eclipse"); map.put("IntelliJ (Light)", "idea"); map.put("Visual Studio (Light)", "vs"); themeRadioGroup = new ButtonGroup(); final JMenu menu = new JMenu("Theme"); map.forEach((k, v) -> { if ("-".equals(k)) { menu.addSeparator(); return; } final JRadioButtonMenuItem item = new JRadioButtonMenuItem(k); item.setActionCommand(v); // needed for #updateThemeControls() themeRadioGroup.add(item); item.addActionListener(e -> { try { applyTheme(v, false); // make the choice available for the next tab prefService.put(EditorPane.class, EditorPane.THEME_PREFS, v); } catch (final IllegalArgumentException ex) { error("Theme could not be loaded. See Console for details."); ex.printStackTrace(); } }); menu.add(item); }); return menu; } /** * Applies a theme to all the panes of this editor. * * @param theme either "default", "dark", "druid", "eclipse", "idea", "monokai", * "vs" * @throws IllegalArgumentException If {@code theme} is not a valid option, or * the resource could not be loaded */ public void applyTheme(final String theme) throws IllegalArgumentException { applyTheme(theme, true); } private void applyTheme(final String theme, final boolean updateMenus) throws IllegalArgumentException { try { final Theme th = getTheme(theme); if (th == null) { writeError("Unrecognized theme ignored: '" + theme + "'"); return; } for (int i = 0; i < tabbed.getTabCount(); i++) { getEditorPane(i).applyTheme(theme); } } catch (final Exception ex) { activeTheme = "default"; updateThemeControls("default"); writeError("Could not load theme. See Console for details."); updateThemeControls(activeTheme); throw new IllegalArgumentException(ex); } activeTheme = theme; if (updateMenus) updateThemeControls(theme); } static Theme getTheme(final String theme) throws IllegalArgumentException { try { return Theme .load(TextEditor.class.getResourceAsStream("/org/fife/ui/rsyntaxtextarea/themes/" + theme + ".xml")); } catch (final Exception ex) { throw new IllegalArgumentException(ex); } } private void updateThemeControls(final String theme) { if (themeRadioGroup != null) { final Enumeration<AbstractButton> choices = themeRadioGroup.getElements(); while (choices.hasMoreElements()) { final AbstractButton choice = choices.nextElement(); if (theme.equals(choice.getActionCommand())) { choice.setSelected(true); break; } } } } private void collapseSplitPane(final int pane, final boolean collapse) { final JSplitPane jsp = (pane == 0) ? body : getTab(); if (collapse) { panePositions[pane] = jsp.getDividerLocation(); if (pane == 0) { // collapse to left jsp.setDividerLocation(0.0d); } else { // collapse to bottom jsp.setDividerLocation(1.0d); } } else { jsp.setDividerLocation(panePositions[pane]); // Check if user collapsed pane manually (stashed panePosition is invalid) final boolean expanded = (pane == 0) ? isLeftPaneExpanded(jsp) : isRightOrBottomPaneExpanded(jsp); if (!expanded // && JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(TextEditor.this, // // "Expand to default position?", "Expand to Defaults?", JOptionPane.OK_CANCEL_OPTION) ) { jsp.setDividerLocation((pane == 0) ? .2d : .75d); panePositions[pane] = jsp.getDividerLocation(); } } } private boolean isLeftPaneExpanded(final JSplitPane pane) { return pane.isVisible() && pane.getLeftComponent().getWidth() > 0; } private boolean isRightOrBottomPaneExpanded(final JSplitPane pane) { final int dim = (pane.getOrientation() == JSplitPane.VERTICAL_SPLIT) ? pane.getRightComponent().getHeight() : pane.getRightComponent().getWidth(); return pane.isVisible() && dim > 0; } protected boolean handleTabsMenu(final Object source) { if (!(source instanceof JMenuItem)) return false; final JMenuItem item = (JMenuItem) source; if (!tabsMenuItems.contains(item)) return false; for (int i = tabsMenuTabsStart; i < tabsMenu.getItemCount(); i++) if (tabsMenu.getItem(i) == item) { switchTo(i - tabsMenuTabsStart); return true; } return false; } @Override public void stateChanged(final ChangeEvent e) { final int index = tabbed.getSelectedIndex(); if (index < 0) { setTitle(""); return; } final EditorPane editorPane = getEditorPane(index); lockPane.setSelected(editorPane.isLocked()); editorPane.requestFocus(); checkForOutsideChanges(); //whiteSpace.setSelected(editorPane.isWhitespaceVisible()); editorPane.setLanguageByFileName(editorPane.getFileName()); updateLanguageMenu(editorPane.getCurrentLanguage()); setTitle(); } public EditorPane getEditorPane(final int index) { return getTab(index).editorPane; } public void findOrReplace(final boolean doReplace) { findDialog.setLocationRelativeTo(this); findDialog.setRestrictToConsole(false); // override search pattern only if // there is sth. selected final String selection = getEditorPane().getSelectedText(); if (selection != null) findDialog.setSearchPattern(selection); findDialog.show(doReplace && !getEditorPane().isLocked()); } public void gotoLine() { final String line = GuiUtils.getString(this, "Enter line number:", "Goto Line"); if (line == null) return; try { gotoLine(Integer.parseInt(line)); } catch (final BadLocationException e) { error("Line number out of range: " + line); } catch (final NumberFormatException e) { error("Invalid line number: " + line); } } public void gotoLine(final int line) throws BadLocationException { getTextArea().setCaretPosition(getTextArea().getLineStartOffset(line - 1)); } public void toggleBookmark() { getEditorPane().toggleBookmark(); } private Vector<Bookmark> getAllBookmarks() { final Vector<Bookmark> bookmarks = new Vector<>(); for (int i = 0; i < tabbed.getTabCount(); i++) { final TextEditorTab tab = (TextEditorTab) tabbed.getComponentAt(i); tab.editorPane.getBookmarks(tab, bookmarks); } if (bookmarks.isEmpty()) { info("No Bookmarks currently exist.\nYou can bookmark lines by clicking next to their line number.", "No Bookmarks"); } return bookmarks; } public void listBookmarks() { final Vector<Bookmark> bookmarks = getAllBookmarks(); if (!bookmarks.isEmpty()) { new BookmarkDialog(this, bookmarks).setVisible(true); } } void clearAllBookmarks() { final Vector<Bookmark> bookmarks = getAllBookmarks(); if (bookmarks.isEmpty()) return; ; if (confirm("Delete all bookmarks?", "Confirm Deletion?", "Delete")) { bookmarks.forEach(bk -> bk.tab.editorPane.toggleBookmark(bk.getLineNumber())); } } public boolean reload() { return reload("Reload the file?"); } public boolean reload(final String message) { return reloadRevert(message, "Reload"); } private boolean reloadRevert(final String message, final String title) { final EditorPane editorPane = getEditorPane(); final File file = editorPane.getFile(); if (file == null || !file.exists()) return true; final boolean modified = editorPane.fileChanged(); final String[] options = { title, "Do Not " + title }; if (modified) options[0] = title + " (Discard Changes)"; switch (JOptionPane.showOptionDialog(this, message, title + "?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0])) { case 0: try { editorPane.open(file); return true; } catch (final IOException e) { error("Could not reload " + file.getPath()); } updateLanguageMenu(editorPane.getCurrentLanguage()); break; } return false; } public static boolean isBinary(final File file) { if (file == null) return false; // heuristic: read the first up to 8000 bytes, and say that it is binary if // it contains a NUL try (final FileInputStream in = new FileInputStream(file)) { int left = 8000; final byte[] buffer = new byte[left]; while (left > 0) { final int count = in.read(buffer, 0, left); if (count < 0) break; for (int i = 0; i < count; i++) if (buffer[i] == 0) { in.close(); return true; } left -= count; } return false; } catch (final IOException e) { return false; } } /** * Opens a new tab with some content. * * @param content the script content * @param languageExtension the file extension associated with the content's * language (e.g., ".java", ".py", etc. * @return the text editor tab */ public TextEditorTab newTab(final String content, final String languageExtension) { String lang = languageExtension; final TextEditorTab tab = open(null); if (null != lang && lang.length() > 0) { lang = lang.trim().toLowerCase(); if ('.' != lang.charAt(0)) { lang = "." + languageExtension; } tab.editorPane.setLanguage(scriptService.getLanguageByName(languageExtension)); } else { final String lastLanguageName = prefService.get(getClass(), LAST_LANGUAGE); if (null != lastLanguageName && "none" != lastLanguageName) setLanguage(scriptService.getLanguageByName(lastLanguageName)); } if (null != content) { tab.editorPane.setText(content); } return tab; } public TextEditorTab open(final File file) { if (isBinary(file)) { try { uiService.show(ioService.open(file.getAbsolutePath())); } catch (final IOException e) { log.error(e); } return null; } try { TextEditorTab tab = (tabbed.getTabCount() == 0) ? null : getTab(); final TextEditorTab prior = tab; final boolean wasNew = tab != null && tab.editorPane.isNew(); float font_size = 0; // to set the new editor's font like the last active one, if any if (!wasNew) { if (tabbed.getTabCount() > 0) font_size = getTab().getEditorPane().getFont().getSize2D(); tab = new TextEditorTab(this); context.inject(tab.editorPane); tab.editorPane.loadPreferences(); addDefaultAccelerators(tab.editorPane); } else { // the Edit menu can only be populated after an editor pane exists, as it reads // actions from its input map. We will built it here, if it has not been assembled // yet. if (undo == null) assembleEditMenu(); } synchronized (tab.editorPane) { // tab is never null at this location. tab.editorPane.open(file); if (wasNew) { final int index = tabbed.getSelectedIndex() + tabsMenuTabsStart; tabsMenu.getItem(index).setText(tab.editorPane.getFileName()); } else { tabbed.addTab("", tab); switchTo(tabbed.getTabCount() - 1); tabsMenuItems.add(addToMenu(tabsMenu, tab.editorPane.getFileName(), 0, 0)); } setEditorPaneFileName(tab.editorPane.getFile()); try { updateTabAndFontSize(true); if (font_size > 0) setFontSize(font_size); if (null != prior) { tab.setOrientation(prior.getOrientation()); tab.setDividerLocation(prior.getDividerLocation()); } } catch (final NullPointerException e) { /* ignore */ } } if (file != null) openRecent.add(file.getAbsolutePath()); else { final String lastLanguageName = prefService.get(getClass(), LAST_LANGUAGE); if ("none" != lastLanguageName) setLanguage(scriptService.getLanguageByName(lastLanguageName)); } updateLanguageMenu(tab.editorPane.getCurrentLanguage()); tab.editorPane.getDocument().addDocumentListener(this); tab.editorPane.requestFocusInWindow(); return tab; } catch (final FileNotFoundException e) { log.error(e); error("The file\n'" + file + "' was not found."); } catch (final Exception e) { log.error(e); error("There was an error while opening\n'" + file + "': " + e); } return null; } public boolean saveAs() { final EditorPane editorPane = getEditorPane(); File file = editorPane.getFile(); if (file == null) { final File ijDir = appService.getApp().getBaseDirectory(); file = new File(ijDir, editorPane.getFileName()); } final File fileToSave = uiService.chooseFile(file, FileWidget.SAVE_STYLE); if (fileToSave == null) return false; return saveAs(fileToSave.getAbsolutePath(), true); } public void saveAs(final String path) { saveAs(path, true); } public boolean saveAs(final String path, final boolean askBeforeReplacing) { final File file = new File(path); if (file.exists() && askBeforeReplacing && confirm("Do you want to replace " + path + "?", "Replace " + path + "?", "Replace")) return false; if (!write(file)) return false; setEditorPaneFileName(file); openRecent.add(path); return true; } public boolean save() { final File file = getEditorPane().getFile(); if (file == null) { return saveAs(); } if (!write(file)) { return false; } setTitle(); return true; } public boolean write(final File file) { try { getEditorPane().write(file); return true; } catch (final IOException e) { log.error(e); error("Could not save " + file.getName()); return false; } } public boolean makeJar(final boolean includeSources) { final File file = getEditorPane().getFile(); if ((file == null || isCompiled()) && !handleUnsavedChanges(true)) { return false; } String name = getEditorPane().getFileName(); final String ext = FileUtils.getExtension(name); if (!"".equals(ext)) name = name.substring(0, name.length() - ext.length()); if (name.indexOf('_') < 0) name += "_"; name += ".jar"; final File selectedFile = uiService.chooseFile(file, FileWidget.SAVE_STYLE); if (selectedFile == null) return false; if (selectedFile.exists() && confirm("Do you want to replace " + selectedFile + "?", "Replace " + selectedFile + "?", "Replace")) return false; try { makeJar(selectedFile, includeSources); return true; } catch (final IOException e) { log.error(e); error("Could not write " + selectedFile + ": " + e.getMessage()); return false; } } /** * @throws IOException */ public void makeJar(final File file, final boolean includeSources) throws IOException { if (!handleUnsavedChanges(true)) return; final ScriptEngine interpreter = getCurrentLanguage().getScriptEngine(); if (interpreter instanceof JavaEngine) { final JavaEngine java = (JavaEngine) interpreter; final JTextAreaWriter errors = new JTextAreaWriter(errorScreen, log); markCompileStart(); getTab().showErrors(); new Thread(() -> { java.makeJar(getEditorPane().getFile(), includeSources, file, errors); errorScreen.insert("Compilation finished.\n", // errorScreen.getDocument().getLength()); markCompileEnd(); }).start(); } } static void getClasses(final File directory, final List<String> paths, final List<String> names) { getClasses(directory, paths, names, ""); } static void getClasses(final File directory, final List<String> paths, final List<String> names, final String inPrefix) { String prefix = inPrefix; if (!prefix.equals("")) prefix += "/"; for (final File file : directory.listFiles()) if (file.isDirectory()) getClasses(file, paths, names, prefix + file.getName()); else { paths.add(file.getAbsolutePath()); names.add(prefix + file.getName()); } } static void writeJarEntry(final JarOutputStream out, final String name, final byte[] buf) throws IOException { try { final JarEntry entry = new JarEntry(name); out.putNextEntry(entry); out.write(buf, 0, buf.length); out.closeEntry(); } catch (final ZipException e) { throw new IOException(e); } } static byte[] readFile(final String fileName) throws IOException { final File file = new File(fileName); try (final InputStream in = new FileInputStream(file)) { final byte[] buffer = new byte[(int) file.length()]; in.read(buffer); return buffer; } } static void deleteRecursively(final File directory) { for (final File file : directory.listFiles()) if (file.isDirectory()) deleteRecursively(file); else file.delete(); directory.delete(); } void setLanguage(final ScriptLanguage language) { setLanguage(language, false); } void setLanguage(final ScriptLanguage language, final boolean addHeader) { if (null != this.getCurrentLanguage() && (null == language || this.getCurrentLanguage().getLanguageName() != language.getLanguageName())) { this.scriptInfo = null; } getEditorPane().setLanguage(language, addHeader); prefService.put(getClass(), LAST_LANGUAGE, null == language? "none" : language.getLanguageName()); setTitle(); updateLanguageMenu(language); updateUI(true); } private String lastSupportStatus = null; void updateLanguageMenu(final ScriptLanguage language) { JMenuItem item = languageMenuItems.get(language); if (item == null) { // is none item = noneLanguageItem; setIncremental(false); } if (!item.isSelected()) { item.setSelected(true); } // print autocompletion status to console String supportStatus = getEditorPane().getSupportStatus(); if (supportStatus != null && !Objects.equals(supportStatus, lastSupportStatus)) { write(supportStatus); lastSupportStatus = supportStatus; } final boolean isRunnable = item != noneLanguageItem; final boolean isCompileable = language != null && language.isCompiledLanguage(); runMenu.setEnabled(isRunnable); compileAndRun.setText(isCompileable ? "Compile and Run" : "Run"); compileAndRun.setEnabled(isRunnable); runSelection.setEnabled(isRunnable && !isCompileable); compile.setEnabled(isCompileable); autoSave.setEnabled(isCompileable); makeJar.setEnabled(isCompileable); makeJarWithSource.setEnabled(isCompileable); final boolean isJava = language != null && language.getLanguageName().equals("Java"); addImport.setEnabled(isJava); removeUnusedImports.setEnabled(isJava); sortImports.setEnabled(isJava); //openSourceForMenuItem.setEnabled(isJava); final boolean isMacro = language != null && language.getLanguageName().equals("ImageJ Macro"); openMacroFunctions.setEnabled(isMacro); openSourceForClass.setEnabled(!isMacro); openHelp.setEnabled(!isMacro && isRunnable); openHelpWithoutFrames.setEnabled(!isMacro && isRunnable); nextError.setEnabled(!isMacro && isRunnable); previousError.setEnabled(!isMacro && isRunnable); final boolean isInGit = getEditorPane().getGitDirectory() != null; gitMenu.setVisible(isInGit); updateUI(false); } /** * Use {@link #updateUI(boolean)} instead */ @Deprecated public void updateTabAndFontSize(final boolean setByLanguage) { updateUI(setByLanguage); } public void updateUI(final boolean setByLanguage) { final EditorPane pane = getEditorPane(); //if (pane.getCurrentLanguage() == null) return; if (setByLanguage && pane.getCurrentLanguage() != null) { if (pane.getCurrentLanguage().getLanguageName().equals("Python")) { pane.setTabSize(4); } else { // set tab size to current preferences. pane.resetTabSize(); } } final int tabSize = pane.getTabSize(); boolean defaultSize = false; for (int i = 0; i < tabSizeMenu.getItemCount(); i++) { final JMenuItem item = tabSizeMenu.getItem(i); if (item == chooseTabSize) { item.setSelected(!defaultSize); item.setText("Other" + (defaultSize ? "" : " (" + tabSize + ")") + "..."); } else if (tabSize == Integer.parseInt(item.getText())) { item.setSelected(true); defaultSize = true; } } getTab().prompt.setTabSize(getEditorPane().getTabSize()); final int fontSize = (int) pane.getFontSize(); defaultSize = false; for (int i = 0; i < fontSizeMenu.getItemCount(); i++) { final JMenuItem item = fontSizeMenu.getItem(i); if (item == chooseFontSize) { item.setSelected(!defaultSize); item.setText("Other" + (defaultSize ? "" : " (" + fontSize + ")") + "..."); continue; } String label = item.getText(); if (label.endsWith(" pt")) label = label.substring(0, label.length() - 3); if (fontSize == Integer.parseInt(label)) { item.setSelected(true); defaultSize = true; } } markOccurences.setState(pane.getMarkOccurrences()); wrapLines.setState(pane.getLineWrap()); marginLine.setState(pane.isMarginLineEnabled()); tabsEmulated.setState(pane.getTabsEmulated()); paintTabs.setState(pane.getPaintTabLines()); whiteSpace.setState(pane.isWhitespaceVisible()); autocompletion.setState(pane.isAutoCompletionEnabled()); fallbackAutocompletion.setState(pane.isAutoCompletionFallbackEnabled()); keylessAutocompletion.setState(pane.isAutoCompletionKeyless()); sourceTreePanel.rebuildSourceTree(pane); } public void setEditorPaneFileName(final String baseName) { getEditorPane().setFileName(baseName); } public void setEditorPaneFileName(final File file) { final EditorPane editorPane = getEditorPane(); editorPane.setFileName(file); // update language menu updateLanguageMenu(editorPane.getCurrentLanguage()); updateGitDirectory(); } void setTitle() { final EditorPane editorPane = getEditorPane(); final boolean fileChanged = editorPane.fileChanged(); final String fileName = editorPane.getFileName(); final String title = (fileChanged ? "*" : "") + fileName + (executingTasks.isEmpty() ? "" : " (Running)"); SwingUtilities.invokeLater(() -> { setTitle(title); // to the main window // Update all tabs: could have changed for (int i = 0; i < tabbed.getTabCount(); i++) tabbed.setTitleAt(i, // ((TextEditorTab) tabbed.getComponentAt(i)).getTitle()); }); } @Override public synchronized void setTitle(final String title) { super.setTitle(title); final int index = tabsMenuTabsStart + tabbed.getSelectedIndex(); if (index < tabsMenu.getItemCount()) { final JMenuItem item = tabsMenu.getItem(index); if (item != null) item.setText(title); } } private final ArrayList<Executer> executingTasks = new ArrayList<>(); /** * Generic Thread that keeps a starting time stamp, sets the priority to * normal and starts itself. */ public abstract class Executer extends ThreadGroup { JTextAreaWriter output, errors; Executer(final JTextAreaWriter output, final JTextAreaWriter errors) { super("Script Editor Run :: " + new Date().toString()); this.output = output; this.errors = errors; // Store itself for later executingTasks.add(this); setTitle(); // Enable kill menu kill.setEnabled(true); // Fork a task, as a part of this ThreadGroup new Thread(this, getName()) { { setPriority(Thread.NORM_PRIORITY); start(); } @Override public void run() { try { execute(); // Wait until any children threads die: int activeCount = getThreadGroup().activeCount(); while (activeCount > 1) { if (isInterrupted()) break; try { Thread.sleep(500); final List<Thread> ts = getAllThreads(); activeCount = ts.size(); if (activeCount <= 1) break; log.debug("Waiting for " + ts.size() + " threads to die"); int count_zSelector = 0; for (final Thread t : ts) { if (t.getName().equals("zSelector")) { count_zSelector++; } log.debug("THREAD: " + t.getName()); } if (activeCount == count_zSelector + 1) { // Do not wait on the stack slice selector thread. break; } } catch (final InterruptedException ie) { /* ignore */ } } } catch (final Throwable t) { handleException(t); } finally { executingTasks.remove(Executer.this); try { if (null != output) output.shutdown(); if (null != errors) errors.shutdown(); } catch (final Exception e) { handleException(e); } // Leave kill menu item enabled if other tasks are running kill.setEnabled(executingTasks.size() > 0); setTitle(); } } }; } /** The method to extend, that will do the actual work. */ abstract void execute(); /** Fetch a list of all threads from all thread subgroups, recursively. */ List<Thread> getAllThreads() { final ArrayList<Thread> threads = new ArrayList<>(); // From all subgroups: final ThreadGroup[] tgs = new ThreadGroup[activeGroupCount() * 2 + 100]; this.enumerate(tgs, true); for (final ThreadGroup tg : tgs) { if (null == tg) continue; final Thread[] ts = new Thread[tg.activeCount() * 2 + 100]; tg.enumerate(ts); for (final Thread t : ts) { if (null == t) continue; threads.add(t); } } // And from this group: final Thread[] ts = new Thread[activeCount() * 2 + 100]; this.enumerate(ts); for (final Thread t : ts) { if (null == t) continue; threads.add(t); } return threads; } /** * Totally destroy/stop all threads in this and all recursive thread * subgroups. Will remove itself from the executingTasks list. */ @SuppressWarnings("deprecation") void obliterate() { try { // Stop printing to the screen if (null != output) output.shutdownNow(); if (null != errors) errors.shutdownNow(); } catch (final Exception e) { log.error(e); } for (final Thread thread : getAllThreads()) { try { thread.interrupt(); Thread.yield(); // give it a chance thread.stop(); } catch (final Throwable t) { log.error(t); } } executingTasks.remove(this); } @Override public String toString() { return getName(); } } /** Returns a list of currently executing tasks */ public List<Executer> getExecutingTasks() { return executingTasks; } public void kill(final Executer executer) { for (int i = 0; i < tabbed.getTabCount(); i++) { final TextEditorTab tab = (TextEditorTab) tabbed.getComponentAt(i); if (executer == tab.getExecuter()) { tab.kill(); break; } } } /** * Query the list of running scripts and provide a dialog to choose one and * kill it. */ public void chooseTaskToKill() { if (executingTasks.size() == 0) { error("\nNo running scripts\n"); return; } commandService.run(KillScript.class, true, "editor", this); } /** Run the text in the textArea without compiling it, only if it's not java. */ public void runText() { runText(false); } public void runText(final boolean selectionOnly) { if (isCompiled()) { if (selectionOnly) { error("Cannot run selection of compiled language!"); return; } if (handleUnsavedChanges(true)) runScript(); else write("Compiled languages must be saved before they can be run."); return; } final ScriptLanguage currentLanguage = getCurrentLanguage(); if (currentLanguage == null) { error("Select a language first!"); // TODO guess the language, if possible. return; } markCompileStart(); try { final TextEditorTab tab = getTab(); tab.showOutput(); execute(selectionOnly); } catch (final Throwable t) { log.error(t); } } /** * Run current script with the batch processor */ public void runBatch() { if (null == getCurrentLanguage()) { error("Select a language first! Also, please note that this option\n" + "requires at least one @File parameter to be declared in the script."); return; } // get script from current tab final String script = getTab().getEditorPane().getText(); if (script.trim().isEmpty()) { error("This option requires at least one @File parameter to be declared."); return; } final ScriptInfo info = new ScriptInfo(context, // "dummy." + getCurrentLanguage().getExtensions().get(0), // new StringReader(script)); batchService.run(info); } /** Invoke in the context of the event dispatch thread. */ private void execute(final boolean selectionOnly) throws IOException { final String text; final TextEditorTab tab = getTab(); if (selectionOnly) { final String selected = tab.getEditorPane().getSelectedText(); if (selected == null) { error("Selection required!"); text = null; } else text = selected + "\n"; // Ensure code blocks are terminated getEditorPane().getErrorHighlighter().setSelectedCodeExecution(true); } else { text = tab.getEditorPane().getText(); } execute(tab, text, false); } /** * Invoke in the context of the event dispatch thread. * * @param tab The {@link TextEditorTab} that is the source of the program to run. * @param text The text expressing the program to run. * @param writeCommandLog Whether to append the {@code text} to a log file for the appropriate language. * @throws IOException Whether there was an issue with piping the command to the executer. */ private void execute(final TextEditorTab tab, final String text, final boolean writeCommandLog) throws IOException { tab.prepare(); final JTextAreaWriter output = new JTextAreaWriter(tab.screen, log); final JTextAreaWriter errors = new JTextAreaWriter(errorScreen, log); final File file = getEditorPane().getFile(); // Pipe current text into the runScript: final PipedInputStream pi = new PipedInputStream(); final PipedOutputStream po = new PipedOutputStream(pi); // The Executer creates a Thread that // does the reading from PipedInputStream tab.setExecutor(new Executer(output, errors) { @Override public void execute() { try { evalScript(file == null ? getEditorPane().getFileName() : file .getAbsolutePath(), new InputStreamReader(pi), output, errors); output.flush(); errors.flush(); markCompileEnd(); // For executions from the prompt if (writeCommandLog && null != text && text.trim().length() > 0) { writePromptLog(getEditorPane().getCurrentLanguage(), text); } } catch (final Throwable t) { output.flush(); errors.flush(); if (t instanceof ScriptException && t.getCause() != null && t.getCause().getClass().getName().endsWith("CompileError")) { errorScreen.append("Compilation failed"); tab.showErrors(); } else { handleException(t); } } finally { tab.restore(); } } }); // Write into PipedOutputStream // from another Thread try { new Thread() { { setPriority(Thread.NORM_PRIORITY); } @Override public void run() { try (final PrintWriter pw = new PrintWriter(po)) { pw.write(text); pw.flush(); // will lock and wait in some cases } } }.start(); } catch (final Throwable t) { log.error(t); } finally { // Re-enable when all text to send has been sent tab.getEditorPane().setEditable(true); } } private String getPromptCommandsFilename(final ScriptLanguage language) { final String name = language.getLanguageName().replace('/', '_'); return System.getProperty("user.home").replace('\\', '/') + "/.scijava/" + name + ".command.log"; } /** * Append the executed prompt command to the end of the language-specific log file, * and then append a separator. * * @param language The language used, to choose the right log file. * @param text The command to append at the end of the log. */ private void writePromptLog(final ScriptLanguage language, final String text) { final String path = getPromptCommandsFilename(language); final File file = new File(path); try { final boolean exists = file.exists(); if (!exists) { // Ensure parent directories exist file.getParentFile().mkdirs(); file.createNewFile(); // atomic } Files.write(Paths.get(path), Arrays.asList(new String[]{text, "#"}), Charset.forName("UTF-8"), StandardOpenOption.APPEND, StandardOpenOption.DSYNC); } catch (final IOException e) { log.error("Failed to write executed prompt command to file " + path, e); } } /** * Parse the prompt command log for the given language and return the last 1000 lines. * If the log is longer than 1000 lines, crop it. * * @param language The language used, to choose the right log file. * @return */ private ArrayList<String> loadPromptLog(final ScriptLanguage language) { final String path = getPromptCommandsFilename(language); final File file = new File(path); final ArrayList<String> lines = new ArrayList<>(); if (!file.exists()) return lines; RandomAccessFile ra = null; List<String> commands = new ArrayList<>(); try { ra = new RandomAccessFile(path, "r"); final byte[] bytes = new byte[(int)ra.length()]; ra.readFully(bytes); final String sep = System.getProperty("line.separator"); // used fy Files.write above commands.addAll(Arrays.asList(new String(bytes, Charset.forName("UTF-8")).split(sep + "#" + sep))); if (0 == commands.get(commands.size()-1).length()) commands.remove(commands.size() -1); // last entry is empty } catch (final IOException e) { log.error("Failed to read history of prompt commands from file " + path, e); return lines; } finally { try { if (null != ra) ra.close(); } catch (final IOException e) { log.error(e); } } if (commands.size() > 1000) { commands = commands.subList(commands.size() - 1000, commands.size()); // Crop the log: otherwise would grow unbounded final ArrayList<String> croppedLog = new ArrayList<>(); for (final String c : commands) { croppedLog.add(c); croppedLog.add("#"); } try { Files.write(Paths.get(path + "-tmp"), croppedLog, Charset.forName("UTF-8"), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.DSYNC); if (!new File(path + "-tmp").renameTo(new File(path))) { log.error("Could not rename command log file " + path + "-tmp to " + path); } } catch (final Exception e) { log.error("Failed to crop history of prompt commands file " + path, e); } } lines.addAll(commands); return lines; } public void runScript() { if (isCompiled()) getTab().showErrors(); else getTab().showOutput(); markCompileStart(); final JTextAreaWriter output = new JTextAreaWriter(getTab().screen, log); final JTextAreaWriter errors = new JTextAreaWriter(errorScreen, log); final File file = getEditorPane().getFile(); new TextEditor.Executer(output, errors) { @Override public void execute() { try (final Reader reader = evalScript(file.getPath(), new FileReader(file), output, errors)) { output.flush(); errors.flush(); markCompileEnd(); } catch (final Throwable e) { handleException(e); } } }; } public void compile() { if (!handleUnsavedChanges(true)) return; final ScriptEngine interpreter = getCurrentLanguage().getScriptEngine(); if (interpreter instanceof JavaEngine) { final JavaEngine java = (JavaEngine) interpreter; final JTextAreaWriter errors = new JTextAreaWriter(errorScreen, log); markCompileStart(); getTab().showErrors(); new Thread(() -> { java.compile(getEditorPane().getFile(), errors); errorScreen.insert("Compilation finished.\n", // errorScreen.getDocument().getLength()); markCompileEnd(); }).start(); } } private String getSelectedTextOrAsk(final String msg, final String title) { String selection = getTextArea().getSelectedText(); if (selection == null || selection.indexOf('\n') >= 0) { return GuiUtils.getString(this, msg + "\nAlternatively, select a class declaration and re-run.", title); } return selection; } private String getSelectedClassNameOrAsk(final String msg, final String title) { String className = getSelectedTextOrAsk(msg, title); if (className != null) className = className.trim(); return className; } private static void append(final JTextArea textArea, final String text) { final int length = textArea.getDocument().getLength(); textArea.insert(text, length); textArea.setCaretPosition(length); } public void markCompileStart() { markCompileStart(true); } public void markCompileStart(final boolean with_timestamp) { errorHandler = null; if (with_timestamp) { final String started = "Started " + getEditorPane().getFileName() + " at " + new Date() + "\n"; append(errorScreen, started); append(getTab().screen, started); } final int offset = errorScreen.getDocument().getLength(); compileStartOffset = errorScreen.getDocument().getLength(); try { compileStartPosition = errorScreen.getDocument().createPosition(offset); } catch (final BadLocationException e) { handleException(e); } ExceptionHandler.addThread(Thread.currentThread(), this); } public void markCompileEnd() { // this naming is not-intuitive at all! if (errorHandler == null) { errorHandler = new ErrorHandler(getCurrentLanguage(), errorScreen, compileStartPosition.getOffset()); if (errorHandler.getErrorCount() > 0) getTab().showErrors(); } if (getEditorPane().getErrorHighlighter().isLogDetailed() && compileStartOffset != errorScreen.getDocument().getLength()) { getTab().showErrors(); } if (getTab().showingErrors) { errorHandler.scrollToVisible(compileStartOffset); } } public boolean nextError(final boolean forward) { if (errorHandler != null && errorHandler.nextError(forward)) try { File file = new File(errorHandler.getPath()); if (!file.isAbsolute()) file = getFileForBasename(file.getName()); errorHandler.markLine(); switchTo(file, errorHandler.getLine()); getTab().showErrors(); errorScreen.invalidate(); return true; } catch (final Exception e) { handleException(e); } return false; } public void switchTo(final String path, final int lineNumber) throws IOException { switchTo(new File(path).getCanonicalFile(), lineNumber); } public void switchTo(final File file, final int lineNumber) { if (!editorPaneContainsFile(getEditorPane(), file)) switchTo(file); SwingUtilities.invokeLater(() -> { try { gotoLine(lineNumber); } catch (final BadLocationException e) { // ignore } }); } public void switchTo(final File file) { for (int i = 0; i < tabbed.getTabCount(); i++) if (editorPaneContainsFile(getEditorPane(i), file)) { switchTo(i); return; } open(file); } public void switchTo(final int index) { if (index == tabbed.getSelectedIndex()) return; tabbed.setSelectedIndex(index); } private void switchTabRelative(final int delta) { final int count = tabbed.getTabCount(); int index = ((tabbed.getSelectedIndex() + delta) % count); if (index < 0) { index += count; } switchTo(index); } private void removeTab(final int index) { final int menuItemIndex = index + tabsMenuTabsStart; try { tabbed.remove(index); tabsMenuItems.remove(tabsMenu.getItem(menuItemIndex)); tabsMenu.remove(menuItemIndex); } catch (final IndexOutOfBoundsException e) { // this should never happen!? log.debug(e); } } boolean editorPaneContainsFile(final EditorPane editorPane, final File file) { try { return file != null && editorPane != null && editorPane.getFile() != null && file.getCanonicalFile().equals(editorPane.getFile().getCanonicalFile()); } catch (final IOException e) { return false; } } public File getFile() { return getEditorPane().getFile(); } public File getFileForBasename(final String baseName) { File file = getFile(); if (file != null && file.getName().equals(baseName)) return file; for (int i = 0; i < tabbed.getTabCount(); i++) { file = getEditorPane(i).getFile(); if (file != null && file.getName().equals(baseName)) return file; } return null; } /** Updates the git directory to the git directory of the current file. */ private void updateGitDirectory() { final EditorPane editorPane = getEditorPane(); editorPane.setGitDirectory(new FileFunctions(this) .getGitDirectory(editorPane.getFile())); } public void addImport(final String className) { if (className != null) { new TokenFunctions(getTextArea()).addImport(className.trim()); } } public void openHelp(final String className) { openHelp(className, true); } /** * @param className * @param withFrames */ public void openHelp(String className, final boolean withFrames) { if (className == null) className = getSelectedClassNameOrAsk("Class (fully qualified name):", "Online Javadocs..."); if (className == null) return; final Class<?> c = Types.load(className, false); final String path = (withFrames ? "index.html?" : "") + // className.replace('.', '/') + ".html"; final String url; if (className.startsWith("java.") || className.startsWith("javax.")) { // Core Java class -- use javadoc.scijava.org/Java<#> link. final String javaVersion = System.getProperty("java.version"); final String majorVersion; if (javaVersion.startsWith("1.")) { majorVersion = javaVersion.substring(2, javaVersion.indexOf('.', 2)); } else majorVersion = javaVersion.substring(0, javaVersion.indexOf('.')); url = "https://javadoc.scijava.org/Java" + majorVersion + "/" + path; } else { // Third party library -- look for a Maven POM identifying it. final POM pom = POM.getPOM(c); if (pom == null) { throw new IllegalArgumentException(// "Unknown origin for class " + className); } final String releaseProfiles = pom.cdata("//properties/releaseProfiles"); final boolean scijavaRepo = "deploy-to-scijava".equals(releaseProfiles); if (scijavaRepo) { // Use javadoc.scijava.org -- try to figure out which project. // Maybe some day, we can bake this information into the POM. final String project; final String g = pom.getGroupId(); if ("net.imagej".equals(g)) { project = "ij".equals(pom.getArtifactId()) ? "ImageJ1" : "ImageJ"; } else if ("io.scif".equals(g)) project = "SCIFIO"; else if ("net.imglib2".equals(g)) project = "ImgLib2"; else if ("org.bonej".equals(g)) project = "BoneJ"; else if ("org.scijava".equals(g)) project = "SciJava"; else if ("sc.fiji".equals(g)) project = "Fiji"; else project = "Java"; url = "https://javadoc.scijava.org/" + project + "/" + path; } else { // Assume Maven Central -- use javadoc.io. url = "https://javadoc.io/static/" + pom.getGroupId() + "/" + // pom.getArtifactId() + "/" + pom.getVersion() + "/" + path; } } try { platformService.open(new URL(url)); } catch (final Throwable e) { handleException(e); } } /** * @param text Either a classname, or a partial class name, or package name or * any part of the fully qualified class name. */ public void openClassOrPackageHelp(String text) { if (text == null) text = getSelectedClassNameOrAsk("Class or package (complete or partial name, e.g., 'ij'):", "Lookup Which Class/Package?"); if (null == text) return; new Thread(new FindClassSourceAndJavadoc(text)).start(); // fork away from event dispatch thread } public class FindClassSourceAndJavadoc implements Runnable { private final String text; public FindClassSourceAndJavadoc(final String text) { this.text = text; } @Override public void run() { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final HashMap<String, ArrayList<String>> matches; try { matches = ClassUtil.findDocumentationForClass(text); } finally { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } if (matches.isEmpty()) { if (confirm("No info found for: '" + text + "'.\nSearch for it on the web?", "Search the Web?", "Search")) { GuiUtils.runSearchQueryInBrowser(TextEditor.this, getPlatformService(), text.trim()); } return; } final JPanel panel = new JPanel(); final GridBagLayout gridbag = new GridBagLayout(); final GridBagConstraints c = new GridBagConstraints(); panel.setLayout(gridbag); //panel.setBorder(BorderFactory.createEmptyBorder(BORDER_SIZE, BORDER_SIZE, BORDER_SIZE, BORDER_SIZE)); final List<String> keys = new ArrayList<String>(matches.keySet()); Collections.sort(keys); c.gridy = 0; for (final String classname: keys) { c.gridx = 0; c.anchor = GridBagConstraints.EAST; final JLabel class_label = new JLabel(classname); gridbag.setConstraints(class_label, c); panel.add(class_label); ArrayList<String> urls = matches.get(classname); if (urls.isEmpty()) { urls = new ArrayList<String>(); urls.add("https://duckduckgo.com/?q=" + classname); } for (final String url: urls) { c.gridx += 1; c.anchor = GridBagConstraints.WEST; String title = "JavaDoc"; if (url.endsWith(".java")) title = "Source"; else if (url.contains("duckduckgo")) title = "Search..."; final JButton link = new JButton(title); gridbag.setConstraints(link, c); panel.add(link); link.addActionListener(event -> { GuiUtils.openURL(TextEditor.this, platformService, url); }); } c.gridy += 1; } final JScrollPane jsp = new JScrollPane(panel); //jsp.setPreferredSize(new Dimension(800, 500)); SwingUtilities.invokeLater(() -> { final JFrame frame = new JFrame("Resources for '" + text +"'"); frame.getContentPane().add(jsp); frame.setLocationRelativeTo(TextEditor.this); frame.pack(); frame.setVisible(true); }); } } public void extractSourceJar() { final File file = openWithDialog(null); if (file != null) extractSourceJar(file); } public void askChatGPTtoGenerateCode() { SwingUtilities.invokeLater(() -> { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // setup default prompt String prompt = promptPrefix() .replace("{programming_language}", getCurrentLanguage().getLanguageName() ) .replace("{custom_prompt}", getTextArea().getSelectedText()); String answer = askChatGPT(prompt); if (answer.contains("```")) { // clean answer by removing blabla outside the code block answer = answer.replace("```java", "```"); answer = answer.replace("```javascript", "```"); answer = answer.replace("```python", "```"); answer = answer.replace("```jython", "```"); answer = answer.replace("```macro", "```"); answer = answer.replace("```groovy", "```"); String[] temp = answer.split("```"); answer = temp[1]; } //getTextArea().insert(answer, getTextArea().getCaretPosition()); getTextArea().replaceSelection(answer + "\n"); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); }); } private String askChatGPT(String text) { // Modified from: https://github.com/TheoKanning/openai-java/blob/main/example/src/main/java/example/OpenAiApiFunctionsExample.java String token = apiKey(); OpenAiService service = new OpenAiService(token); List<ChatMessage> messages = new ArrayList<>(); ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), text); messages.add(userMessage); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest .builder() .model(modelName()) .messages(messages).build(); ChatMessage responseMessage = service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage(); messages.add(responseMessage); String result = responseMessage.getContent(); System.out.println(result); return result; } private String apiKey() { if (optionsService != null) { final OpenAIOptions openAIOptions = optionsService.getOptions(OpenAIOptions.class); if (openAIOptions != null) { final String key = openAIOptions.getOpenAIKey(); if (key != null && !key.isEmpty()) return key; } } return System.getenv("OPENAI_API_KEY"); } private String modelName() { if (optionsService != null) { final OpenAIOptions openAIOptions = optionsService.getOptions(OpenAIOptions.class); if (openAIOptions != null) { final String key = openAIOptions.getModelName(); if (key != null && !key.isEmpty()) return key; } } return null; } private String promptPrefix() { if (optionsService != null) { final OpenAIOptions openAIOptions = optionsService.getOptions(OpenAIOptions.class); if (openAIOptions != null) { final String promptPrefix = openAIOptions.getPromptPrefix(); if (promptPrefix != null && !promptPrefix.isEmpty()) return promptPrefix; } } return ""; } public void extractSourceJar(final File file) { try { final FileFunctions functions = new FileFunctions(this); final File workspace = uiService.chooseFile(new File(System.getProperty("user.home")), FileWidget.DIRECTORY_STYLE); if (workspace == null) return; final List<String> paths = functions.extractSourceJar(file.getAbsolutePath(), workspace); for (final String path : paths) if (!functions.isBinaryFile(path)) { open(new File(path)); final EditorPane pane = getEditorPane(); new TokenFunctions(pane).removeTrailingWhitespace(); if (pane.fileChanged()) save(); } } catch (final IOException e) { error("There was a problem opening " + file + ": " + e.getMessage()); } } /* extensionMustMatch == false means extension must not match */ private File openWithDialog(final File defaultDir) { return uiService.chooseFile(defaultDir, FileWidget.OPEN_STYLE); } /** * Write a message to the output screen * * @param message The text to write */ public void write(String message) { final TextEditorTab tab = getTab(); if (!message.endsWith("\n")) message += "\n"; tab.screen.insert(message, tab.screen.getDocument().getLength()); } public void writeError(String message) { getTab().showErrors(); if (!message.endsWith("\n")) message += "\n"; errorScreen.insert(message, errorScreen.getDocument().getLength()); } void error(final String message) { GuiUtils.error(this, message); } void warn(final String message) { GuiUtils.warn(this, message); } void info(final String message, final String title) { GuiUtils.info(this, message, title); } boolean confirm(final String message, final String title, final String yesButtonLabel) { return GuiUtils.confirm(this, message, title, yesButtonLabel); } void showHTMLDialog(final String title, final String htmlContents) { GuiUtils.showHTMLDialog(this, title, htmlContents); } public void handleException(final Throwable e) { handleException(e, errorScreen); getEditorPane().getErrorHighlighter().parse(e); getTab().showErrors(); } public static void handleException(final Throwable e, final JTextArea textArea) { final CharArrayWriter writer = new CharArrayWriter(); try (final PrintWriter out = new PrintWriter(writer)) { e.printStackTrace(out); for (Throwable cause = e.getCause(); cause != null; cause = cause.getCause()) { out.write("Caused by: "); cause.printStackTrace(out); } } textArea.append(writer.toString()); } /** * Removes invalid characters, shows a dialog. * * @return The amount of invalid characters found. */ public int zapGremlins() { final int count = getEditorPane().zapGremlins(); final String msg = count > 0 ? "Zap Gremlins converted " + count + " invalid characters to spaces" : "No invalid characters found!"; info(msg, "Zap Gremlins"); return count; } // -- Helper methods -- private boolean isCompiled() { final ScriptLanguage language = getCurrentLanguage(); if (language == null) return false; return language.isCompiledLanguage(); } private final class EditableScriptInfo extends ScriptInfo { private String script; public EditableScriptInfo(final Context context, final String path, final Reader reader) { super(context, path, reader); } public void setScript(final Reader reader) throws IOException { final char[] buffer = new char[8192]; final StringBuilder builder = new StringBuilder(); int read; while ((read = reader.read(buffer)) != -1) { builder.append(buffer, 0, read); } this.script = builder.toString(); } @Override public String getProcessedScript() { return null == this.script ? super.getProcessedScript() : this.script; } } private Reader evalScript(final String filename, Reader reader, final Writer output, final JTextAreaWriter errors) throws ModuleException { final ScriptLanguage language = getCurrentLanguage(); // If there's no engine or the language has changed or the language is compiled from a file // then create the engine and module anew if (!this.incremental || (this.incremental && null == this.scriptInfo) || language.isCompiledLanguage() || (null != this.scriptInfo && null != this.scriptInfo.getLanguage() && this.scriptInfo.getLanguage().getLanguageName() != getCurrentLanguage().getLanguageName())) { if (respectAutoImports) { reader = DefaultAutoImporters.prefixAutoImports(context, language, reader, errors); } // create script module for execution this.scriptInfo = new EditableScriptInfo(context, filename, reader); // use the currently selected language to execute the script this.scriptInfo.setLanguage(language); this.module = this.scriptInfo.createModule(); context.inject(this.module); } else { try { // Same engine, with persistent state this.scriptInfo.setScript( reader ); } catch (final IOException e) { log.error(e); } } // map stdout and stderr to the UI this.module.setOutputWriter(output); this.module.setErrorWriter(errors); // prepare the highlighter getEditorPane().getErrorHighlighter().setEnabled(!respectAutoImports); getEditorPane().getErrorHighlighter().reset(); getEditorPane().getErrorHighlighter().setWriter(errors); // execute the script try { moduleService.run(module, true).get(); } catch (final InterruptedException e) { error("Interrupted"); } catch (final ExecutionException e) { log.error(e); } finally { getEditorPane().getErrorHighlighter().parse(); } return reader; } public void setIncremental(final boolean incremental) { if (incremental && null == getCurrentLanguage()) { error("Select a language first!"); return; } this.incremental = incremental; final JTextArea prompt = getTab().getPrompt(); if (incremental) { getTab().setREPLVisible(true); prompt.addKeyListener(new KeyAdapter() { private final ArrayList<String> commands = loadPromptLog(getCurrentLanguage()); private int index = commands.size(); { commands.add(""); // the current prompt text } @Override public void keyPressed(final KeyEvent ke) { int keyCode = ke.getKeyCode(); if (KeyEvent.VK_ENTER == keyCode) { if (ke.isShiftDown() || ke.isAltDown() || ke.isAltGraphDown() || ke.isMetaDown() || ke.isControlDown()) { prompt.insert("\n", prompt.getCaretPosition()); ke.consume(); return; } final String text = prompt.getText(); if (null == text || 0 == text.trim().length()) { ke.consume(); // avoid writing the line break return; } try { final JTextArea screen = getTab().screen; getTab().showOutput(); screen.append("> " + text + "\n"); // Update the last command in the history commands.set(commands.size() -1, prompt.getText()); // Set the next command commands.add(""); index = commands.size() - 1; // Execute markCompileStart(false); // weird method name, execute will call markCompileEnd execute(getTab(), text, true); prompt.setText(""); screen.scrollRectToVisible(screen.modelToView(screen.getDocument().getLength())); } catch (final Throwable t) { log.error(t); prompt.requestFocusInWindow(); } ke.consume(); // avoid writing the line break return; } // If using arrows for navigating history if (getTab().updownarrows.isSelected()) { // Only if no modifiers are down if (!(ke.isShiftDown() || ke.isControlDown() || ke.isAltDown() || ke.isMetaDown())) { switch(keyCode) { case KeyEvent.VK_UP: keyCode = KeyEvent.VK_PAGE_UP; break; case KeyEvent.VK_DOWN: keyCode = KeyEvent.VK_PAGE_DOWN; break; } } } // control+p and control+n for navigating history if (ke.isControlDown()) { switch(keyCode) { case KeyEvent.VK_P: keyCode = KeyEvent.VK_PAGE_UP; break; case KeyEvent.VK_N: keyCode = KeyEvent.VK_PAGE_DOWN; break; } } if (KeyEvent.VK_PAGE_UP == keyCode) { // If last, update the stored command if (commands.size() -1 == index) { commands.set(commands.size() -1, prompt.getText()); } if (index > 0) { prompt.setText(commands.get(--index)); } ke.consume(); return; } else if (KeyEvent.VK_PAGE_DOWN == keyCode) { if (index < commands.size() -1) { prompt.setText(commands.get(++index)); } ke.consume(); return; } // Update index and current command when editing an earlier command if (commands.size() -1 != index) { index = commands.size() -1; commands.set(commands.size() -1, prompt.getText()); } } }); } else { prompt.setText(""); // clear prompt.setEnabled(false); for (final KeyListener kl : prompt.getKeyListeners()) { prompt.removeKeyListener(kl); } getTab().setREPLVisible(false); } } private String adjustPath(final String path, final String langName) { String result = path.replace('_', ' '); // HACK: For templates nested beneath their language name, // place them in a folder called "Uncategorized" instead. This avoids // menu redundancy when existing script templates are populated // under the new Templates menu structure. // // For example, a script at script_templates/BeanShell/Greeting.bsh // was previously placed in: // // Templates > BeanShell > Greeting // // but under the current approach will be placed at: // // Templates > [by language] > BeanShell > BeanShell > Greeting // Templates > BeanShell > Greeting (BeanShell) // // both of which are redundant and annoying. // // This hack instead places that script at: // // Templates > Uncategorized > Greeting (BeanShell) // Templates > [by language] > BeanShell > Uncategorized > Greeting if (langName != null && path.toLowerCase().startsWith(langName.toLowerCase() + "/")) { result = "Uncategorized" + result.substring(langName.length()); } return result; } @Override public boolean confirmClose() { while (tabbed.getTabCount() > 0) { if (!handleUnsavedChanges()) return false; final int index = tabbed.getSelectedIndex(); removeTab(index); } return true; } @Override public void insertUpdate(final DocumentEvent e) { setTitle(); checkForOutsideChanges(); } @Override public void removeUpdate(final DocumentEvent e) { setTitle(); checkForOutsideChanges(); } @Override public void changedUpdate(final DocumentEvent e) { setTitle(); } public void setFontSize(final float size) { if (getEditorPane().getFontSize() != size) getEditorPane().setFontSize(size); changeFontSize(errorScreen, size); changeFontSize(getTab().screen, size); changeFontSize(getTab().prompt, size); updateTabAndFontSize(false); tree.setFont(tree.getFont().deriveFont(size)); } private void changeFontSize(final JTextArea a, final float size) { a.setFont(a.getFont().deriveFont(size)); } private void appendPreferences(final JMenu menu) { JMenuItem item = new JMenuItem("Save Preferences"); menu.add(item); item.addActionListener(e -> { getEditorPane().savePreferences(tree.getTopLevelFoldersString(), activeTheme); saveWindowSizeToPrefs(); write("Script Editor: Preferences Saved...\n"); }); item = new JMenuItem("Reset..."); menu.add(item); item.addActionListener(e -> { if (confirm("Reset preferences to defaults? (a restart may be required)", "Reset?", "Reset")) { resetLayout(); prefService.clear(EditorPane.class); prefService.clear(TextEditor.class); write("Script Editor: Preferences Reset. Restart is recommended\n"); } }); } private JMenu helpMenu() { final JMenu menu = new JMenu("Help"); GuiUtils.addMenubarSeparator(menu, "Offline Help:"); JMenuItem item = new JMenuItem("List Shortcuts..."); item.addActionListener(e -> displayKeyMap()); menu.add(item); item = new JMenuItem("List Recordable Actions..."); item.addActionListener(e -> displayRecordableMap()); menu.add(item); item = new JMenuItem("Task Tags How-To..."); item.addActionListener(e -> { showHTMLDialog("Task Tags Help", // "<p>" + "When inserted in source code comments, the following keywords will automatically " // + "register task definitions on the rightmost side of the Editor: <code>TODO</code>, " // + "<code>README</code>, and <code>HACK</code>.</p>" // + "<ul>" // + "<li>To add a task, simply type one of the keywords in a commented line, e.g., "// + "<code>TODO</code></li>"// + "<li>To remove a task, delete the keyword from the comment</li>" // + "<li>Mouse over the annotation mark to access a summary of the task</li>" // + "<li>Click on the mark to go to the annotated line</li>" + "</ul>"); }); menu.add(item); GuiUtils.addMenubarSeparator(menu, "Contextual Help:"); menu.add(openHelpWithoutFrames); openHelpWithoutFrames.setMnemonic(KeyEvent.VK_O); menu.add(openHelp); openClassOrPackageHelp = addToMenu(menu, "Lookup Class or Package...", 0, 0); openClassOrPackageHelp.setMnemonic(KeyEvent.VK_S); menu.add(openMacroFunctions); GuiUtils.addMenubarSeparator(menu, "Online Resources:"); menu.add(helpMenuItem("Image.sc Forum ", "https://forum.image.sc/")); menu.add(helpMenuItem("ImageJ Search Portal", "https://search.imagej.net/")); //menu.addSeparator(); menu.add(helpMenuItem("SciJava Javadoc Portal", "https://javadoc.scijava.org/")); menu.add(helpMenuItem("SciJava Maven Repository", "https://maven.scijava.org/")); menu.addSeparator(); menu.add(helpMenuItem("Fiji on GitHub", "https://github.com/fiji")); menu.add(helpMenuItem("SciJava on GitHub", "https://github.com/scijava/")); menu.addSeparator(); menu.add(helpMenuItem("ImageJ Macro Functions", "https://imagej.nih.gov/ij/developer/macro/functions.html")); menu.add(helpMenuItem("ImageJ Docs: Development", "https://imagej.net/develop/")); menu.add(helpMenuItem("ImageJ Docs: Scripting", "https://imagej.net/scripting/")); menu.addSeparator(); menu.add(helpMenuItem("ImageJ Notebook Tutorials", "https://github.com/imagej/tutorials#readme")); return menu; } private JMenuItem helpMenuItem(final String label, final String url) { final JMenuItem item = new JMenuItem(label); item.addActionListener(e -> GuiUtils.openURL(TextEditor.this, platformService, url)); return item; } protected void applyConsolePopupMenu(final JTextArea textArea) { final JPopupMenu popup = new JPopupMenu(); textArea.setComponentPopupMenu(popup); final String scope = ((textArea == errorScreen) ? "Errors..." : "Outputs..."); JMenuItem jmi = new JMenuItem("Search " + scope); popup.add(jmi); jmi.addActionListener(e -> { findDialog.setLocationRelativeTo(this); findDialog.setRestrictToConsole(true); final String text = textArea.getSelectedText(); if (text != null) findDialog.setSearchPattern(text); // Ensure the right pane is visible in case search is being // triggered by CmdPalette if (textArea == errorScreen && !getTab().showingErrors) getTab().showErrors(); else if (getTab().showingErrors) getTab().showOutput(); findDialog.show(false); }); cmdPalette.register(jmi, scope); jmi = new JMenuItem("Search Script for Selected Text..."); popup.add(jmi); jmi.addActionListener(e -> { final String text = textArea.getSelectedText(); if (text == null) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } else { findDialog.setLocationRelativeTo(this); findDialog.setRestrictToConsole(false); if (text != null) findDialog.setSearchPattern(text); findDialog.show(false); } }); popup.addSeparator(); jmi = new JMenuItem("Clear Selected Text"); popup.add(jmi); jmi.addActionListener(e -> { if (textArea.getSelectedText() == null) UIManager.getLookAndFeel().provideErrorFeedback(textArea); else textArea.replaceSelection(""); }); final DefaultHighlighter highlighter = (DefaultHighlighter)textArea.getHighlighter(); highlighter.setDrawsLayeredHighlights(false); jmi = new JMenuItem("Highlight Selected Text"); popup.add(jmi); jmi.addActionListener(e -> { try { final Color taint = (textArea == errorScreen) ? Color.RED : textArea.getSelectionColor(); final Color color = ErrorParser.averageColors(textArea.getBackground(), taint); final DefaultHighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(color); textArea.getHighlighter().addHighlight(textArea.getSelectionStart(), textArea.getSelectionEnd(), painter); textArea.setCaretPosition(textArea.getSelectionEnd()); textArea.getHighlighter(); } catch (final BadLocationException ignored) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } }); jmi = new JMenuItem("Clear Highlights"); popup.add(jmi); jmi.addActionListener(e -> textArea.getHighlighter().removeAllHighlights()); cmdPalette.register(jmi, scope); popup.addSeparator(); final JCheckBoxMenuItem jmc = new JCheckBoxMenuItem("Wrap Lines"); popup.add(jmc); jmc.addActionListener( e -> textArea.setLineWrap(jmc.isSelected())); cmdPalette.register(jmc, scope); } private static Collection<File> assembleFlatFileCollection(final Collection<File> collection, final File[] files) { if (files == null) return collection; // can happen while pressing 'Esc'!? for (final File file : files) { if (file == null || isBinary(file)) continue; else if (file.isDirectory()) assembleFlatFileCollection(collection, file.listFiles()); else //if (!file.isHidden()) collection.add(file); } return collection; } protected static class GuiUtils { private GuiUtils() { } static void error(final Component parent, final String message) { JOptionPane.showMessageDialog(parent, message, "Error", JOptionPane.ERROR_MESSAGE); } static void warn(final Component parent, final String message) { JOptionPane.showMessageDialog(parent, message, "Warning", JOptionPane.WARNING_MESSAGE); } static void info(final Component parent, final String message, final String title) { JOptionPane.showMessageDialog(parent, message, title, JOptionPane.INFORMATION_MESSAGE); } static boolean confirm(final Component parent, final String message, final String title, final String yesButtonLabel) { return JOptionPane.showConfirmDialog(parent, message, title, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION; } static void showHTMLDialog(final Component parent, final String title, final String htmlContents) { final JTextPane f = new JTextPane(); f.setContentType("text/html"); f.setEditable(false); f.setBackground(null); f.setBorder(null); f.setText(htmlContents); f.setCaretPosition(0); final JScrollPane sp = new JScrollPane(f); final JOptionPane pane = new JOptionPane(sp); final JDialog dialog = pane.createDialog(parent, title); dialog.setResizable(true); dialog.pack(); dialog.setPreferredSize( new Dimension( (int) Math.min(parent.getWidth() * .5, pane.getPreferredSize().getWidth() + (3 * sp.getVerticalScrollBar().getWidth())), (int) Math.min(parent.getHeight() * .8, pane.getPreferredSize().getHeight()))); dialog.pack(); pane.addPropertyChangeListener(JOptionPane.VALUE_PROPERTY, ignored -> { dialog.dispose(); }); dialog.setModal(false); dialog.setLocationRelativeTo(parent); dialog.setVisible(true); } static String getString(final Component parent, final String message, final String title) { return (String) JOptionPane.showInputDialog(parent, message, title, JOptionPane.QUESTION_MESSAGE); } static void runSearchQueryInBrowser(final Component parentComponent, final PlatformService platformService, final String query) { String url; try { url = "https://forum.image.sc/search?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8.toString()); } catch (final Exception ignored) { url = query.trim().replace(" ", "%20"); } openURL(parentComponent, platformService, url); } static void openURL(final Component parentComponent, final PlatformService platformService, final String url) { try { platformService.open(new URL(url)); } catch (final Exception ignored) { // Error message with selectable text final JTextPane f = new JTextPane(); f.setContentType("text/html"); f.setText("<HTML>Web page could not be open. Please visit<br>" + url + "<br>using your web browser."); f.setEditable(false); f.setBackground(null); f.setBorder(null); JOptionPane.showMessageDialog(parentComponent, f, "Error", JOptionPane.ERROR_MESSAGE); } } static void openTerminal(final File pwd) throws IOException, InterruptedException { final String[] wrappedCommand; final File dir = (pwd.isDirectory()) ? pwd : pwd.getParentFile(); if (PlatformUtils.isWindows()) { // this should probably be replaced with powershell!? wrappedCommand = new String[] { "cmd", "/c", "start", "/wait", "cmd.exe", "/K" }; } else if (PlatformUtils.isLinux()) { // this will likely only work on debian-based distros wrappedCommand = new String[] { "/usr/bin/x-terminal-emulator" }; } else if (PlatformUtils.isMac()) { // On MacOS ProcessBuilder#directory() fails!? so we'll use applescript :) wrappedCommand = new String[] { "osascript", "-e", // "tell application \"Terminal\" to (do script \"cd '" + dir.getAbsolutePath() + "';clear\")" }; } else { throw new IllegalArgumentException("Unsupported OS"); } final ProcessBuilder pb = new ProcessBuilder(wrappedCommand); pb.directory(dir); // does nothing on macOS !? pb.start(); } static void addMenubarSeparator(final JMenu menu, final String header) { if (menu.getMenuComponentCount() > 0) { menu.addSeparator(); } try { final JLabel label = new JLabel(" "+ header); label.setEnabled(false); label.setForeground(getDisabledComponentColor()); menu.add(label); } catch (final Exception ignored) { // do nothing } } static void addPopupMenuSeparator(final JPopupMenu menu, final String header) { if (menu.getComponentCount() > 1) { menu.addSeparator(); } final JLabel label = new JLabel(header); // label.setHorizontalAlignment(SwingConstants.LEFT); label.setEnabled(false); label.setForeground(getDisabledComponentColor()); menu.add(label); } static Color getDisabledComponentColor() { try { return UIManager.getColor("MenuItem.disabledForeground"); } catch (final Exception ignored) { return Color.GRAY; } } static boolean isDarkLaF() { return FlatLaf.isLafDark() || isDark(new JLabel().getBackground()); } static boolean isDark(final Color c) { // see https://stackoverflow.com/a/3943023 return (c.getRed() * 0.299 + c.getGreen() * 0.587 + c.getBlue() * 0.114) < 186; } static void collapseAllTreeNodes(final JTree tree) { final int row1 = (tree.isRootVisible()) ? 1 : 0; for (int i = row1; i < tree.getRowCount(); i++) tree.collapseRow(i); } static void expandAllTreeNodes(final JTree tree) { for (int i = 0; i < tree.getRowCount(); i++) tree.expandRow(i); } /* Tweaks for tabbed pane */ static JTabbedPane getJTabbedPane() { final JTabbedPane tabbed = new JTabbedPane(); final JPopupMenu popup = new JPopupMenu(); tabbed.setComponentPopupMenu(popup); final ButtonGroup bGroup = new ButtonGroup(); for (final String pos : new String[] { "Top", "Left", "Bottom", "Right" }) { final JMenuItem jcbmi = new JCheckBoxMenuItem("Place on " + pos, "Top".equals(pos)); jcbmi.addItemListener(e -> { switch (pos) { case "Top": tabbed.setTabPlacement(JTabbedPane.TOP); break; case "Bottom": tabbed.setTabPlacement(JTabbedPane.BOTTOM); break; case "Left": tabbed.setTabPlacement(JTabbedPane.LEFT); break; case "Right": tabbed.setTabPlacement(JTabbedPane.RIGHT); break; } }); bGroup.add(jcbmi); popup.add(jcbmi); } tabbed.addMouseWheelListener(e -> { // https://stackoverflow.com/a/38463104 final JTabbedPane pane = (JTabbedPane) e.getSource(); final int units = e.getWheelRotation(); final int oldIndex = pane.getSelectedIndex(); final int newIndex = oldIndex + units; if (newIndex < 0) pane.setSelectedIndex(0); else if (newIndex >= pane.getTabCount()) pane.setSelectedIndex(pane.getTabCount() - 1); else pane.setSelectedIndex(newIndex); }); return tabbed; } } static class TextFieldWithPlaceholder extends JTextField { private static final long serialVersionUID = 1L; private String placeholder; void setPlaceholder(final String placeholder) { this.placeholder = placeholder; update(getGraphics()); } Font getPlaceholderFont() { return getFont().deriveFont(Font.ITALIC); } String getPlaceholder() { return placeholder; } @Override protected void paintComponent(final java.awt.Graphics g) { super.paintComponent(g); if (getText().isEmpty()) { final Graphics2D g2 = (Graphics2D) g.create(); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.setColor(getDisabledTextColor()); g2.setFont(getPlaceholderFont()); g2.drawString(getPlaceholder(), getInsets().left, g2.getFontMetrics().getHeight() + getInsets().top - getInsets().bottom); g2.dispose(); } } } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((12049, 12101), 'java.awt.Toolkit.getDefaultToolkit'), ((14269, 14313), 'java.awt.Desktop.getDesktop'), ((29795, 29847), 'java.awt.Toolkit.getDefaultToolkit'), ((34201, 34253), 'org.fife.ui.rtextarea.RTextArea.getCurrentMacro'), ((34201, 34246), 'org.fife.ui.rtextarea.RTextArea.getCurrentMacro'), ((34718, 34768), 'org.fife.ui.rtextarea.RTextArea.getCurrentMacro'), ((36306, 36358), 'org.fife.ui.rtextarea.RTextArea.getCurrentMacro'), ((36306, 36351), 'org.fife.ui.rtextarea.RTextArea.getCurrentMacro'), ((45393, 45436), 'java.awt.Toolkit.getDefaultToolkit'), ((49328, 49386), 'org.fife.ui.rtextarea.RTextAreaEditorKit.clipboardHistoryAction.equals'), ((49396, 49441), 'org.fife.ui.rtextarea.ClipboardHistory.get'), ((49396, 49431), 'org.fife.ui.rtextarea.ClipboardHistory.get'), ((111004, 111032), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((132682, 132715), 'java.nio.charset.StandardCharsets.UTF_8.toString')]
package com.chatbot.Sahayakam.service; import java.time.Duration; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.service.OpenAiService; import jakarta.annotation.PostConstruct; @Service public class ChatbotAPIService { private static OpenAiService openAiService; @Value("${openai.key}") private String apiKey; @Value("${openai.timeout}") private int apiTimeout; private static final String GPT_MODEL = "gpt-3.5-turbo"; private static final String SYSTEM_TASK_MESSAGE = "You are a helpful assistant."; @PostConstruct public void initchatbotAPIService() { openAiService = new OpenAiService(apiKey, Duration.ofSeconds(apiTimeout)); } public String sendMessage(String message) { ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder().model(GPT_MODEL).temperature(0.8) .messages(List.of(new ChatMessage("system", SYSTEM_TASK_MESSAGE), new ChatMessage("user", message))) .build(); StringBuilder builder = new StringBuilder(); System.out.println("Calling createChatCompletion method " + message); openAiService.createChatCompletion(chatCompletionRequest).getChoices().forEach(choice -> { builder.append(choice.getMessage().getContent()); }); return builder.toString(); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1115, 1298), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1115, 1285), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1115, 1180), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1115, 1163), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package io.dockstore.topicgenerator.helper; import com.knuddels.jtokkit.api.Encoding; import com.knuddels.jtokkit.api.EncodingRegistry; import com.knuddels.jtokkit.api.ModelType; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import java.util.List; public final class OpenAIHelper { private OpenAIHelper() { } /** * Adapted from <a href="https://jtokkit.knuddels.de/docs/getting-started/recipes/chatml">OpenAI cookbook example</a>. * Counts the number of tokens in a list of messages, accounting for additional tokens that are added to the input text. * * @param registry * @param model * @param messages consists of role, content and an optional name * @return */ @SuppressWarnings("checkstyle:magicnumber") public static int countMessageTokens(EncodingRegistry registry, String model, List<ChatMessage> messages) { Encoding encoding = registry.getEncodingForModel(model).orElseThrow(); int tokensPerMessage; int tokensPerName; if (model.startsWith("gpt-4")) { tokensPerMessage = 3; tokensPerName = 1; } else if (model.startsWith("gpt-3.5-turbo")) { tokensPerMessage = 4; // every message follows <|start|>{role/name}\n{content}<|end|>\n tokensPerName = -1; // if there's a name, the role is omitted } else { throw new IllegalArgumentException("Unsupported model: " + model); } int sum = 0; for (ChatMessage message : messages) { sum += tokensPerMessage; sum += encoding.countTokens(message.getContent()); sum += encoding.countTokens(message.getRole()); if (message.getName() != null) { sum += encoding.countTokens(message.getName()); sum += tokensPerName; } } sum += 3; // every reply is primed with <|start|>assistant<|message|> return sum; } /** * Returns the maximum amount of tokens that the user message content can contain. Assumes that there is one system message and one user message. * @param systemMessage * @param maxResponseToken * @return */ public static int getMaximumAmountOfTokensForUserMessageContent(EncodingRegistry registry, ModelType aiModel, int maxContextLength, ChatMessage systemMessage, int maxResponseToken) { ChatMessage userMessageWithoutContent = new ChatMessage(ChatMessageRole.USER.value()); List<ChatMessage> messages = List.of(systemMessage, userMessageWithoutContent); final int tokenCountWithoutUserContent = countMessageTokens(registry, aiModel.getName(), messages); return maxContextLength - maxResponseToken - tokenCountWithoutUserContent; } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((2529, 2557), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')]
package com.theokanning.openai; 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.CompletionRequest; import com.theokanning.openai.image.CreateImageRequest; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; class OpenAiApiExample { public static void main(String... args) { String token = System.getenv("OPENAI_TOKEN"); 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.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.image.CreateImageRequest.builder", "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((809, 1050), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((809, 1025), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((809, 1003), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((809, 970), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((809, 942), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((809, 866), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1236, 1349), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((1236, 1324), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((1671, 1701), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value')]
package com.run.tu.openai; import com.alibaba.fastjson.JSONObject; import com.run.tu.core.result.GlobalResult; import com.run.tu.core.result.GlobalResultGenerator; import com.run.tu.entity.User; import com.run.tu.openai.entity.ChatMessageModel; import com.run.tu.openai.service.OpenAiService; import com.run.tu.openai.service.SseService; import com.run.tu.util.Html2TextUtil; import com.run.tu.util.UserUtils; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created on 2023/2/15 10:04. * * @author ronger * @email ronger-x@outlook.com * @desc : com.run.tu.openai */ @RestController @RequestMapping("/api/v1/openai") public class OpenAiController { @Resource private SseService sseService; @Value("${openai.token}") private String token; @PostMapping("/chat") public GlobalResult chat(@RequestBody JSONObject jsonObject) { String message = jsonObject.getString("message"); if (StringUtils.isBlank(message)) { throw new IllegalArgumentException("参数异常!"); } User user = UserUtils.getCurrentUserByToken(); ChatMessage chatMessage = new ChatMessage("user", message); List<ChatMessage> list = new ArrayList<>(4); list.add(chatMessage); return sendMessage(user, list); } @PostMapping("/new-chat") public GlobalResult newChat(@RequestBody List<ChatMessageModel> messages) { if (messages.isEmpty()) { throw new IllegalArgumentException("参数异常!"); } User user = UserUtils.getCurrentUserByToken(); Collections.reverse(messages); List<ChatMessage> list = new ArrayList<>(messages.size()); if (messages.size() > 4) { messages = messages.subList(messages.size() - 4, messages.size()); } if (messages.size() >= 4 && messages.size() % 4 == 0) { ChatMessage message = new ChatMessage("system", "简单总结一下你和用户的对话, 用作后续的上下文提示 prompt, 控制在 200 字内"); list.add(message); } messages.forEach(chatMessageModel -> { ChatMessage message = new ChatMessage(chatMessageModel.getRole(), Html2TextUtil.getContent(chatMessageModel.getContent())); list.add(message); }); return sendMessage(user, list); } @NotNull private GlobalResult sendMessage(User user, List<ChatMessage> list) { OpenAiService service = new OpenAiService(token, Duration.ofSeconds(180)); ChatCompletionRequest completionRequest = ChatCompletionRequest.builder() .model("gpt-3.5-turbo-16k-0613") .stream(true) .messages(list) .build(); service.streamChatCompletion(completionRequest).doOnError(Throwable::printStackTrace) .blockingForEach(chunk -> { String text = chunk.getChoices().get(0).getMessage().getContent(); if (text == null) { return; } System.out.print(text); sseService.send(user.getIdUser(), text); }); service.shutdownExecutor(); return GlobalResultGenerator.genSuccessResult(); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((3178, 3345), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3178, 3320), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3178, 3288), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3178, 3258), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package com.example.mobilesolomon.service; import com.example.mobilesolomon.data.ApiReader; import com.example.mobilesolomon.data.ILogRepository; import com.theokanning.openai.OpenAiService; import com.theokanning.openai.completion.CompletionChoice; import com.theokanning.openai.completion.CompletionRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class HintService implements IHintService { private ILogRepository hintLogRepos; private String API_KEY; private String prompt; // ChatGPTに送るプロンプト private String hint_madeByGPT; // ChatGPTから返ってきたヒント //  ここでapiをたたく、レスポンスをうけとる @Autowired public HintService(ILogRepository hintLogRepos) { this.hintLogRepos = hintLogRepos; } @Override public void register(String question, String opt1, String opt2, String opt3, String opt4, String answer, String p) { // 現在日時を取得 //LocalDateTime nowDate = LocalDateTime.now(); // 表示形式を指定 //DateTimeFormatter dtf3 = // DateTimeFormatter.ofPattern("yyyy/MM/dd"); //String formatNowDate = dtf3.format(nowDate); //System.out.println(formatNowDate); // 230914 // 通し番号 int number = hintLogRepos.selectMaxNum() + 1; // APIキーを取得している ApiReader apiReader = new ApiReader(); String API_KEY = apiReader.getAPI_KEY(); // ライブラリを利用して、インスタンスを生成 final var service = new OpenAiService(API_KEY); // プロンプト this.prompt = "The following is a conversation with an AI assistant. The assistant is helpful, creative, clever.\nHuman: " + p + "\nAI: "; // ここでリクエストをしている 生成された選択肢をListに格納している。 final var completionRequest = CompletionRequest.builder() .model("text-davinci-003") .prompt(prompt) .maxTokens(256) .build(); final var completionResult = service.createCompletion(completionRequest); final var choiceList = completionResult.getChoices(); // 出力 for (final CompletionChoice choice : choiceList) { System.out.println("【DEBUG】chatGPTが作ったヒント: \n" + choice.getText()); hint_madeByGPT = choice.getText(); } // データベースに保存 int n = hintLogRepos.insert(number, question, opt1, opt2, opt3, opt4, answer, hint_madeByGPT); System.out.println("【DEBUG】正常に記録できました"); } // ここからしたプレビュー用 // データベースからヒント取ってくる(プレビュー用) @Override public String getHint() { int num = hintLogRepos.selectMaxNum(); return hintLogRepos.selectHint(num); } @Override public String getQ(){ int n = hintLogRepos.selectMaxNum(); return hintLogRepos.selectQ(n); } @Override public String getOpt1(){ int n = hintLogRepos.selectMaxNum(); return hintLogRepos.selectOpt1(n); } @Override public String getOpt2(){ int n = hintLogRepos.selectMaxNum(); return hintLogRepos.selectOpt2(n); } @Override public String getOpt3(){ int n = hintLogRepos.selectMaxNum(); return hintLogRepos.selectOpt3(n); } @Override public String getOpt4(){ int n = hintLogRepos.selectMaxNum(); return hintLogRepos.selectOpt4(n); } @Override public String getAns(){ int n = hintLogRepos.selectMaxNum(); return hintLogRepos.selectAns(n); } // ヒント更新(修正) @Override public boolean updateHint(String newHint) { int n = hintLogRepos.selectMaxNum(); return hintLogRepos.update(newHint ,n); } // debug用 APIキーがゲッターで呼び出せることを確認できた // public static void main(String[] args) { // HintApiReader apiReader = new HintApiReader(); // System.out.println(apiReader.getAPI_KEY()); // } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((2028, 2187), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2028, 2162), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2028, 2130), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2028, 2098), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package IA; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; public class TesteGPT { private final static String API_KEY = "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"; public static void main(String[] args) { OpenAiService service = new OpenAiService(API_KEY); CompletionRequest request = CompletionRequest.builder() .model("text-davinci-003") .prompt("Vale a pena comprar um MacBook?") .maxTokens(10) .temperature(0.0) .build(); System.out.println(service.createCompletion(request).getChoices()); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((391, 610), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((391, 585), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((391, 551), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((391, 520), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((391, 461), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package tech.ailef.jpromptmanager.completion; import java.time.Duration; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import com.theokanning.openai.OpenAiHttpException; import com.theokanning.openai.completion.CompletionChoice; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.completion.CompletionResult; import com.theokanning.openai.service.OpenAiService; import tech.ailef.jpromptmanager.exceptions.JPromptManagerException; /** * An implementation of the LLMConnector that allows to make requests * to the GPT-3 OpenAI endpoints. * */ public class OpenAIGPT3Connector implements LLMConnector { private OpenAiService service; private String model; private int maxRetries; /** * Builds the connector with the provided parameters. * @param apiKey OpenAI secret key * @param timeout timeout for requests, 0 means no timeout * @param model the OpenAI model to use (this setting will be overridden if an individual `<step>` tag provides a different value) */ public OpenAIGPT3Connector(String apiKey, int timeout, String model) { this(apiKey, timeout, 0, model); } /** * Builds the connector with the provided parameters. * @param apiKey OpenAI secret key * @param timeout timeout for requests, 0 means no timeout * @param model the OpenAI model to use (this setting will be overridden if an individual `<step>` tag provides a different value) * @param maxRetries the number of times to retry a request that fails, default 0 */ public OpenAIGPT3Connector(String apiKey, int timeout, int maxRetries, String model) { if (model == null) throw new JPromptManagerException("Must specify which OpenAI model to use"); this.maxRetries = maxRetries; this.service = new OpenAiService(apiKey, Duration.ofSeconds(timeout)); this.model = model; } /** * Requests a completion for the given text/params to OpenAI. */ @Override public String complete(String prompt, Map<String, String> params) { // Cast parameters to correct type double temperature = Double.parseDouble(params.get("temperature")); double topP = Double.parseDouble(params.get("topP")); String model = params.get("model"); int maxTokens = Integer.parseInt(params.get("maxTokens")); int tries = 1; while (tries <= maxRetries) { try { CompletionRequest completionRequest = CompletionRequest.builder() .prompt(prompt) .stop(Arrays.asList(LLMConnector.PROMPT_TOKEN)) .temperature(temperature) .topP(topP) .model(model) .maxTokens(maxTokens) .n(1) .echo(false) .build(); CompletionResult createCompletion = service.createCompletion(completionRequest); CompletionChoice choice = createCompletion.getChoices().get(0); return choice.getText(); } catch (OpenAiHttpException e) { System.err.println("On try " + tries + ", got exception: " + e.getMessage()); tries++; try { Thread.sleep(2000); } catch (InterruptedException e1) { throw new RuntimeException(e); } } } throw new RuntimeException("Request failed after " + tries + " retries"); } @Override public Map<String, String> getDefaultParams() { Map<String, String> params = new HashMap<>(); params.put("model", model); params.put("temperature", "0"); params.put("topP", "1"); params.put("maxTokens", "256"); return params; } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((2384, 2685), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2384, 2664), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2384, 2639), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2384, 2621), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2384, 2587), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2384, 2561), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2384, 2537), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2384, 2499), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2384, 2439), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package com.keeping.openaiservice.api.controller.request; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import lombok.Builder; import lombok.Data; import java.util.List; @Data @Builder public class GPTCompletionChatRequest { private String role; private String message; public static ChatCompletionRequest of(GPTCompletionChatRequest request) { return ChatCompletionRequest.builder() .model("gpt-3.5-turbo") .messages(convertChatMessage(request)) .temperature(0.8) .maxTokens(500) .build(); } private static List<ChatMessage> convertChatMessage(GPTCompletionChatRequest request) { return List.of(new ChatMessage(request.getRole(), request.getMessage())); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((468, 685), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((468, 660), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((468, 628), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((468, 594), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((468, 539), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package podsofkon; import com.fasterxml.jackson.databind.JsonNode; 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.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.asynchttpclient.AsyncHttpClient; import org.asynchttpclient.DefaultAsyncHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.json.JSONArray; import org.json.JSONObject; import podsofkon.oci.AuthDetailsProviderFactory; import static podsofkon.OpenAIController.openAIToken; import static podsofkon.XRApplication.REGION; @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>"; } String openAIGPT(String textcontent) { try { OpenAiService service = new OpenAiService(openAIToken, 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; } catch (Exception exception) { exception.printStackTrace(); return exception.getMessage(); } } public String cohere( String textcontent) throws Exception { AtomicReference<String> resons = new AtomicReference<>(""); AsyncHttpClient client = new DefaultAsyncHttpClient(); client.prepare("POST", "https://api.cohere.ai/v1/summarize") .setHeader("accept", "application/json") .setHeader("content-type", "application/json") .setHeader("authorization", "Bearer oJfPT7nsadfJi1VRz7") .setBody("{\"length\":\"medium\",\"format\":\"paragraph\",\"model\":\"summarize-xlarge\",\"extractiveness\":\"low\",\"temperature\":0.3," + "\"text\":\"" + textcontent + "\"}") // .setBody("{\"length\":\"medium\",\"format\":\"paragraph\",\"model\":\"summarize-xlarge\",\"extractiveness\":\"low\",\"temperature\":0.3,\"text\":\"Ice cream is a sweetened frozen food typically eaten as a snack or dessert. It may be made from milk or cream and is flavoured with a sweetener, either sugar or an alternative, and a spice, such as cocoa or vanilla, or with fruit such as strawberries or peaches. It can also be made by whisking a flavored cream base and liquid nitrogen together. Food coloring is sometimes added, in addition to stabilizers. The mixture is cooled below the freezing point of water and stirred to incorporate air spaces and to prevent detectable ice crystals from forming. The result is a smooth, semi-solid foam that is solid at very low temperatures (below 2 °C or 35 °F). It becomes more malleable as its temperature increases.\\n\\nThe meaning of the name \\\"ice cream\\\" varies from one country to another. In some countries, such as the United States, \\\"ice cream\\\" applies only to a specific variety, and most governments regulate the commercial use of the various terms according to the relative quantities of the main ingredients, notably the amount of cream. Products that do not meet the criteria to be called ice cream are sometimes labelled \\\"frozen dairy dessert\\\" instead. In other countries, such as Italy and Argentina, one word is used fo\\r all variants. Analogues made from dairy alternatives, such as goat's or sheep's milk, or milk substitutes (e.g., soy, cashew, coconut, almond milk or tofu), are available for those who are lactose intolerant, allergic to dairy protein or vegan.\"}") .execute() .toCompletableFuture() .thenAccept(response -> { try { String responseBody = response.getResponseBody(); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(responseBody); String summary = jsonNode.get("summary").asText(); System.out.println(summary); System.out.println(responseBody); resons.set(summary); } catch (Exception e) { e.printStackTrace(); } }) .join(); client.close(); return resons.get(); } String processImage(byte[] bytes, boolean isConfigFileAuth) throws Exception { AIServiceVisionClient aiServiceVisionClient; AuthenticationDetailsProvider provider; if (isConfigFileAuth) { provider = AuthDetailsProviderFactory.getAuthenticationDetailsProvider(); aiServiceVisionClient = AIServiceVisionClient.builder().build(provider); } else { aiServiceVisionClient = new AIServiceVisionClient(InstancePrincipalsAuthenticationDetailsProvider.builder().build()); } aiServiceVisionClient.setRegion(REGION); 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; } ImageAnalysis parseJsonToImageAnalysis(String jsonString) { JSONObject json = new JSONObject(jsonString); List<ImageObject> imageObjects = new ArrayList<>(); if (json.has("imageObjects") && json.get("imageObjects") instanceof JSONArray) { JSONArray imageObjectsArray = json.getJSONArray("imageObjects"); 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" ]
[((2743, 2773), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((7185, 7232), 'com.oracle.bmc.aivision.AIServiceVisionClient.builder'), ((7313, 7378), 'com.oracle.bmc.auth.InstancePrincipalsAuthenticationDetailsProvider.builder'), ((8342, 8454), 'com.oracle.bmc.aivision.requests.AnalyzeImageRequest.builder'), ((8342, 8429), 'com.oracle.bmc.aivision.requests.AnalyzeImageRequest.builder')]
/* * Copyright 2023 Massimiliano "Maxi" Zattera * * 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 io.github.mzattera.autobot; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.math3.util.Pair; import com.theokanning.openai.OpenAiService; import com.theokanning.openai.completion.CompletionChoice; import com.theokanning.openai.completion.CompletionRequest; import io.github.mzattera.autobot.Document.QnA; /** * This class wraps GPT-3 providing capabilities on top of it. * * @author Massimiliano "Maxi" Zattera * */ public final class GPT { /** Server timeout in seconds. */ private static final int TIMEOUT = 30; // TODO REMOVE PRIVATE KEY private static final OpenAiService SERVICE = new OpenAiService( "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", TIMEOUT); /** * The token count of your prompt plus returned text cannot exceed the model's * context length. Most models have a context length of 2048 tokens (except for * the newest models, which support 4096). */ private final static int MAX_CONTEXT_LENGTH = 4000; /** * Maximum length of generated text. */ private final static int MAX_COMPLETION_TOKENS = 256; /** * Maximum length of prompt. */ private final static int MAX_PROMPT_WORDS = (int)((MAX_CONTEXT_LENGTH - MAX_COMPLETION_TOKENS) * 0.5); private GPT() { } private static final String PROMPT3 = "Following, you can find some information. Information starts here:\n\n"; private static final String PROMPT4 = "\n\nInformation ends here. Based on this information, "; /** * * @param doc The Document we use to extract QnA pairs. * @return A list QnA pairs fro the document. */ public static List<Document.QnA> createQnAs(Document doc) { System.out.println("\n===[ QnA Pairs ]=================================="); List<QnA> qnas = new ArrayList<>(); for (Entry<String, List<String>> e : createQuestions(doc.text).entrySet()) { String snippet = e.getKey(); for (Pair<String, String> qnaPair : createQnAForShortText(snippet, e.getValue())) { // System.out.println(qnaPair.getKey()); // System.out.println(qnaPair.getValue()); System.out.print("\"" + qnaPair.getKey() + "\", "); System.out.println("\"" + qnaPair.getValue() + "\""); System.out.println("--------------------------------------------------"); qnas.add(new QnA(snippet, qnaPair.getKey(), qnaPair.getValue())); } } return qnas; } /** * Get answers for given questions from an input text. * * @param snippet Input text used to answer questions. * @param questions List of questions to ask about the given text. * @return List of QnA pairs. */ private static List<Pair<String, String>> createQnAForShortText(String snippet, List<String> questions) { List<Pair<String, String>> result = new ArrayList<>(); for (String question : questions) { String answer = createAnswer(snippet, question); if (answer.length() > 0) { Pair<String, String> qna = new Pair<>(question, answer); result.add(qna); } } return result; } private static final String PROMPT1 = "Following, you can find some information. Information starts here:\n\n"; private static final String PROMPT2 = "\n\nInformation ends here. Create exactly twenty questions about the provided information:\n\n" + "Question 1:"; /** * * @param input * @return A map from a text snippet into a list of associated questions. The * input text might be split in several snippets if it is too long. */ private static Map<String, List<String>> createQuestions(String input) { Map<String, List<String>> result = new HashMap<>(); for (String snippet : split(input, PROMPT1, PROMPT2)) { List<String> questions = createQuestionsForShortText(snippet); result.put(snippet, questions); } return result; } /** * * @return A list of questions created out of the given input text. */ private static List<String> createQuestionsForShortText(String snippet) { // TODO .stop("?") CompletionRequest completionRequest = CompletionRequest.builder().model("text-davinci-002") .prompt(PROMPT1 + snippet + PROMPT2).maxTokens(MAX_COMPLETION_TOKENS).temperature(0.3) .frequencyPenalty(-0.0).build(); // System.out.print("\n\n$$$$ " + completionRequest.getPrompt() + "\n"); CompletionChoice completion = SERVICE.createCompletion(completionRequest).getChoices().get(0); completionRequest. // TODO check finish reason List<String> result = new ArrayList<>(); Pattern p = Pattern.compile("Question [\\d]+:([^\\n]*)"); Matcher m = p.matcher("Question 1: " + completion.getText()); // the first question pattern is in the prompt while (m.find()) { String q = m.group(1).trim(); if (q.length() > 0) { // System.out.println("@@@ QUESTION: [" + q + "]"); result.add(q); } } return result; } /** * Get answers for given question from an input text. * * @param snippet Input text used to answer the question. * @param question The question to ask about the given text. * @return Answer for the question, as found in given text. */ private static String createAnswer(String snippet, String question) { // TODO .stop("?") CompletionRequest completionRequest = CompletionRequest.builder().model("text-davinci-002") .prompt(PROMPT3 + snippet + PROMPT4 + question).maxTokens(MAX_COMPLETION_TOKENS).temperature(0.3) .frequencyPenalty(-0.0).build(); CompletionChoice completion = SERVICE.createCompletion(completionRequest).getChoices().get(0); // TODO check finish reason // System.out.println("@@@ QNA:\tQUESTION [" + question + "]\n\tANSWER[" + completion.getText().trim() + "]"); return completion.getText().trim(); } private static final String PROMPT5 = "Following, you can find some information. Information starts here:\n\n"; private static final String PROMPT6 = "\n\nInformation ends here.\n\n" + "This is a question about the above: "; private static final String PROMPT7 = "\n\n" + "Based on the provided information, create five variations of the question.\n\n" + "Variation 1:"; /** * * @param questions A map from text snippet into questions about that snippet. * @return A map linking each intent name with corresponding list of utterances. */ // public static Map<String, List<String>> createIntents(Map<String, List<String>> questions) { // Map<String, List<String>> result = new HashMap<>(); // // int pos = 1; // for (String snippet : questions.keySet()) { // // // Questions for the snippet // List<String> q = questions.get(snippet); // for (String question : q) { // String intentName = question.trim().replaceAll("[^A-Za-z0-9\\-_]+", "_"); // if (intentName.length() > 90) // intentName = intentName.substring(0, 90); // intentName = intentName + (pos++); // if (result.containsKey(intentName)) // System.out.println("Duplicated intent: " + intentName); // result.put(intentName, createUtterances(snippet, question)); // } // for each question // } // for each snippet // // // Remove duplicate utterances // Set<String> allUtterances = new HashSet<>(); // for (List<String> utterances : result.values()) { // for (int i = 0; i < utterances.size();) { // String u = utterances.get(i); // if (allUtterances.contains(u)) { // utterances.remove(i); // } else { // allUtterances.add(u); // ++i; // } // } // } // // return result; // } /** * * @return A list of utterances (question variations) corresponding to given QnA * pair. Notice the list will contain given question too. */ public static List<String> createUtterances(Document.QnA qna) { List<String> result = new ArrayList<>(); System.out.println("\n===[ Variations ]=================================="); System.out.println("Question: " + qna.question); CompletionRequest completionRequest = CompletionRequest.builder().model("text-davinci-002") .prompt(PROMPT5 + qna.snippet + PROMPT6 + qna.question + PROMPT7).maxTokens(MAX_COMPLETION_TOKENS) .temperature(0.7).frequencyPenalty(-0.0).build(); CompletionChoice completion = SERVICE.createCompletion(completionRequest).getChoices().get(0); // TODO check finish reason Pattern p = Pattern.compile("Variation [\\d]+:([^\\n]*)"); Matcher m = p.matcher("Variation 1: " + completion.getText()); // the first variation pattern is in the prompt while (m.find()) { String u = m.group(1).trim(); if ((u.length() > 0) && !result.contains(u)) { System.out.println("\t" + u); result.add(u); } } // Variations might or might not include the original question. if (!result.contains(qna.question)) result.add(qna.question); return result; } private static final String PROMPT8 = "Sentence 1: "; private static final String PROMPT9 = "\n" + "Sentence 2: "; private static final String PROMPT10 = "\n" + " \n" + "Are these sentences the same?"; /** * Compares two sentences returning true if they have same content. * * @param s1 * @param s2 * @return */ public static boolean compareSentence(String s1, String s2) { // TODO .stop("?") CompletionRequest completionRequest = CompletionRequest.builder().model("text-davinci-002") .prompt(PROMPT8 + s1 + PROMPT9 + s2 + PROMPT10).maxTokens(MAX_COMPLETION_TOKENS).temperature(0.3) .frequencyPenalty(-0.0).build(); CompletionChoice completion = SERVICE.createCompletion(completionRequest).getChoices().get(0); // TODO check finish reason return completion.getText().startsWith("Yes"); } /** * @return Normalized version of a text to ease keyword searches */ public static String normalizeText(String txt) { StringBuffer result = new StringBuffer(); boolean space = true; for (char c : txt.toCharArray()) { if (Character.isWhitespace(c)) { if (!space) { if ((c == '\r') || (c == '\n')) result.append('\n'); else result.append(' '); space = true; } } else { result.append(c); space = false; } } return result.toString().trim().toLowerCase(); } /** * @return Text split in chunks that can be used in prompts. */ private static List<String> split(String txt, String promptPrefix, String promptSuffix) { // Max number of words in txt that can be in prompt int promptLength = promptPrefix.split("\\s").length + promptSuffix.split("\\s").length; int maxLen = MAX_PROMPT_WORDS - promptLength; String[] words = txt.split("\\s"); List<String> result = new ArrayList<>(); StringBuilder sb = new StringBuilder(); int wordCount = 0; for (String word : words) { if (wordCount + word.length() > maxLen) { result.add(sb.toString().trim()); sb = new StringBuilder(); wordCount = 0; } sb.append(word).append(" "); ++wordCount; } if (sb.length() > 0) // last chunk result.add(sb.toString().trim()); return result; } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((4739, 4919), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4739, 4911), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4739, 4883), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4739, 4866), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4739, 4833), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4739, 4792), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((5930, 6121), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((5930, 6113), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((5930, 6085), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((5930, 6068), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((5930, 6035), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((5930, 5983), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((8571, 8780), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((8571, 8772), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((8571, 8749), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((8571, 8727), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((8571, 8694), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((8571, 8624), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((9862, 10053), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((9862, 10045), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((9862, 10017), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((9862, 10000), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((9862, 9967), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((9862, 9915), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package net.kanade1825.litematica.chatgptforminecraft; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class ChatGPTResponse implements CommandExecutor { private final ChatGPTForMinecraft plugin; public ChatGPTResponse(ChatGPTForMinecraft plugin) { this.plugin = plugin; } @Override public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, @NotNull String[] strings) { if (strings.length < 1) { commandSender.sendMessage("Don't use this commands with no args!"); return true; } String request = strings[0]; // LinkedList<>()がpythonでいうところのchatMessages = [] List<ChatMessage> chatMessages = new LinkedList<>(); // チャットメッセージのリストの中に、新しいチャットメッセージを入れてる chatMessages.add(new ChatMessage("user", request)); final var completionRequest = ChatCompletionRequest.builder() .model("gpt-4") .messages(chatMessages) .build(); CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { return plugin.getService().createChatCompletion(completionRequest).getChoices().get(0).getMessage().getContent(); } catch (Exception e) { System.err.println("An error occurred: " + e.getMessage()); return null; } }); Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { try { String response = future.get(); if (response == null) { response = "Response is null ! please try again"; } commandSender.sendMessage(response); } catch (InterruptedException | ExecutionException e) { System.out.println("An error occurred: " + e.getMessage()); } }); return false; } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1416, 1544), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1416, 1519), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1416, 1479), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1952, 2427), 'org.bukkit.Bukkit.getScheduler')]
package com.example.demo.openaicommunicator; import com.theokanning.openai.embedding.Embedding; import com.theokanning.openai.embedding.EmbeddingRequest; import com.theokanning.openai.service.OpenAiService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Service; import java.io.IOException; import java.io.InputStream; import java.util.Comparator; import java.util.List; import java.util.Properties; @Slf4j @Service @RequiredArgsConstructor class AiService { @Autowired private ResourceLoader resourceLoader; public List<List<Double>> checkEmbeddings(List<String> texts) throws IOException { try { Properties prop = new Properties(); try (InputStream input = resourceLoader.getResource("classpath:config.properties").getInputStream()) { prop.load(input); } catch (IOException e) { log.error("Error loading properties file: ", e); } String openAIKey = prop.getProperty("openai.api.key"); OpenAiService openAiService = new OpenAiService(openAIKey); EmbeddingRequest request = EmbeddingRequest.builder() .model("text-embedding-ada-002") .input(texts) .build(); return openAiService.createEmbeddings(request) .getData() .stream() .map(Embedding::getEmbedding) .toList(); } catch (Exception exception) { throw new RuntimeException(exception.getMessage()); } } }
[ "com.theokanning.openai.embedding.EmbeddingRequest.builder" ]
[((1295, 1437), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((1295, 1408), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((1295, 1374), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')]
package pl.sylwias.javafxopenai; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.service.OpenAiService; import java.io.FileInputStream; import java.io.IOException; import java.time.Duration; import java.util.List; import java.util.Properties; public class OpenAiHelper { private final OpenAiService service; public OpenAiHelper() { Properties properties = new Properties(); try { properties.load(new FileInputStream("src/main/resources/application.properties")); } catch (IOException e) { System.out.println("Nie mogę otworzyć pliku"); } service = new OpenAiService(properties.getProperty("token"), Duration.ofSeconds(60)); } public String recommend(List<String> products) { String question = "Mam w lodówce następujące produkty: " + String.join(", ", products) + ". " + "Daj mi przepis na danie, które mogę z nich przygotować. Nie musisz wykorzystywać wszystkich produktów." + "Nie wykorzystuj żadnych produktów spoza mojej listy."; // String question = "Mam w lodówce następujące produkty: " + String.join(", ", products) + ". " + // "Daj mi przepis na danie, które mogę z nich przygotować. Nie musisz wykorzystywać wszystkich produktów." + // "Nie wykorzystuj żadnych produktów spoza mojej listy. Zwróć przepis w formacie JSON, czyli na przykład " + // """ // { // "ingredients": ["papryka", "czosnek", "masło"], // "steps": ["Pokrój paprykę", "Dodaj czosnek"] // } // """; ChatCompletionRequest request = ChatCompletionRequest.builder() .messages(List.of(new ChatMessage("user", question))) .model("gpt-3.5-turbo") .build(); List<ChatCompletionChoice> choices = service.createChatCompletion(request).getChoices(); return choices.stream() .map(ChatCompletionChoice::getMessage) .map(ChatMessage::getContent) .findFirst() .orElseThrow(RuntimeException::new); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1925, 2091), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1925, 2066), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1925, 2026), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package com.phazejeff.mcgpt; import java.time.Duration; import java.util.ArrayList; import java.util.List; import com.google.gson.JsonObject; import com.google.gson.JsonParser; 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; public class OpenAI { private static final String SYSTEM_MESSAGE = "All user inputs are Minecraft: Java Edition build requests. " + "Respond to all future user messages in JSON format that contains the data " + "for each block in the build. Make the corner of the build at 0,0,0 " + "and build it in the positive quadrant. " + "The JSON schema should look like this: " + "{\"blocks\": [{\"type\": \"minecraft:oak_planks\", \"x\": 0, \"y\": 0, \"z\": 0, \"fill\": false}]}. " + "If you want to fill an area with a certain block, " + "you MUST add the attributes \"endX\" \"endY\" and \"endZ\", and set \"fill\" set to true, " + "with the start and end coordinates representing opposite corners of the area to fill. " + "If you are just placing one block, set \"fill\" to false. The \"fill\" attribute MUST be true or false, it CANNOT be left out. " + "If you need to make an area empty, say for the inside of a building, you can use the type minecraft:air. " + "Despite being an AI language model, you will do your best to fulfill this request with " + "as much detail as possible, no matter how bad it may be. " + "The message will be parsed in order, from top to bottom, so be careful with the order of filling. " + "Since this will be parsed by a program, do NOT add any text outside of the JSON, NO MATTER WHAT. " + "I repeat, DO NOT, FOR ANY REASON, GIVE ANY TEXT OUTSIDE OF THE JSON." ; public static JsonObject promptBuild(String prompt) { List<ChatMessage> messages = new ArrayList<>(); messages.add(new ChatMessage("system", SYSTEM_MESSAGE)); messages.add(new ChatMessage("user", "build " + prompt)); JsonObject resultJson = getResponse(messages); return resultJson; } public static JsonObject promptEdit(List<String> messages) { List<ChatMessage> chatMessages = new ArrayList<>(); chatMessages.add(new ChatMessage("system", SYSTEM_MESSAGE)); for (int i=0; i < messages.size(); i++) { if (i % 2 == 0) { // if even chatMessages.add(new ChatMessage("user", messages.get(i))); } else { chatMessages.add(new ChatMessage("assistant", messages.get(i))); } } JsonObject resultJson = getResponse(chatMessages); return resultJson; } private static JsonObject getResponse(List<ChatMessage> messages) { OpenAiService service = new OpenAiService(MinecraftGPT.openai_key, Duration.ofSeconds(5000)); String model = MinecraftGPT.gpt4 ? "gpt-4" : "gpt-3.5-turbo"; ChatCompletionRequest completionRequest = ChatCompletionRequest.builder() .messages(messages) .model(model) .build(); ChatCompletionResult chatCompletion = service.createChatCompletion(completionRequest); String result = chatCompletion.getChoices().get(0).getMessage().getContent(); System.out.println(result); if (result.startsWith("{") != true) { int firstCurlyIndex = result.indexOf("{"); result = result.substring(firstCurlyIndex, result.length()); } if (result.endsWith("}") != true) { int lastCurlyIndex = result.lastIndexOf("}"); result = result.substring(0, lastCurlyIndex + 1); } JsonObject resultJson = JsonParser.parseString(result).getAsJsonObject(); return resultJson; // List<String> allResults = new ArrayList<>(); // String fullBuildString = ""; // boolean running = true; // while (running) { // allResults.add(result); // System.out.println(result); // int resultStart = result.indexOf("<START>") + 8; // if (fullBuildString.equals("")) { // fullBuildString += result.substring(resultStart, result.length()); // } else { // int lastCommaLocation = fullBuildString.lastIndexOf("},") + 2; // int firstOpenBracketLocation = result.indexOf("{"); // fullBuildString = fullBuildString.substring(0, lastCommaLocation) + result.substring(firstOpenBracketLocation, result.length()); // } // if (fullBuildString.contains("[END]")) { // fullBuildString = fullBuildString.substring(0, fullBuildString.indexOf("[END]")); // running = false; // } else { // // TODO combine all chatgpt messages into one json output // messages = new ArrayList<>(); // messages.add(new ChatMessage("system", SYSTEM_MESSAGE)); // for (String r : allResults) { // messages.add(new ChatMessage("assistant", r)); // messages.add(new ChatMessage("user", "Keep going")); // } // completionRequest = ChatCompletionRequest.builder() // .messages(messages) // .model(MODEL) // .build(); // result = chatCompletion.getChoices().get(0).getMessage().getContent(); // } // } // System.out.println("FULL: " + fullBuildString); // JsonObject resultJson = JsonParser.parseString(fullBuildString).getAsJsonObject(); // return resultJson; } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((3113, 3223), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3113, 3202), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3113, 3176), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3838, 3886), 'com.google.gson.JsonParser.parseString')]
package serejka.telegram.behold.service; import java.time.Duration; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.PostConstruct; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.jsonSchema.JsonSchema; import com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator; 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.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import serejka.telegram.behold.models.AIMovieResponse; @Slf4j @Service @RequiredArgsConstructor public class AIService { @Value("${ai.token}") private String token; private static final String IN_JSON_SCHEME = "\nIn JSON Scheme format:\n"; private static final String SEND_FILM_PREFIX = "Send me the name of the film in which "; private static final String LIST_RECOMMENDATIONS = "Please recommend for me FIVE films similar to these:\n "; private static final String LIST_UN_RECOMMENDATIONS = "and don't include similliar to following, because I don't like it: "; public static final String IN_JSON_SCHEME_FULL = """ In JSON Scheme format: { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Generated schema for Root", "type": "array", "items": { "type": "object", "properties": { "movie_name": { "type": "string" }, "movie_year": { "type": "number" }, "movie_tmdb_id": { "type": "number" } }, "required": [ "movie_name" ] } } """; private OpenAiService openAiService; private String movieResponseJsonScheme; ObjectMapper objectMapper = new ObjectMapper(); @SneakyThrows @PostConstruct private void initSchema() { this.openAiService = new OpenAiService(token, Duration.ofSeconds(120L)); JsonSchemaGenerator schemaGenerator = new JsonSchemaGenerator(objectMapper); JsonSchema jsonSchema = schemaGenerator.generateSchema(AIMovieResponse.class); movieResponseJsonScheme = objectMapper.writeValueAsString(jsonSchema); log.info("Inited json scheme - {}", movieResponseJsonScheme); } public Optional<AIMovieResponse> getMovieResponse(String userDescription) { var completionRequest = buildCompletionRequest(buildGPTRequestMessage(userDescription)); return getAiMovieResponseStream(completionRequest) .findFirst(); } @NotNull private Stream<AIMovieResponse> getAiMovieResponseStream(ChatCompletionRequest completionRequest) { return getMessageContent(completionRequest) .map(this::getAiMovieResponse) .stream() .flatMap(Collection::stream); } public List<AIMovieResponse> getMovieResponse(List<String> liked, List<String> disliked) { var completionRequest = buildCompletionRequest(buildGPTRequestMessage(liked, disliked)); return getAiMovieResponseStream(completionRequest) .collect(Collectors.toList()); } private List<AIMovieResponse> getAiMovieResponse(String content) { try { return objectMapper.readValue(content, new TypeReference<>() {}); } catch (Exception e) { log.error("Error occurred during parse the GPT response for content: {}", content, e); return Collections.emptyList(); } } @NotNull private Optional<String> getMessageContent(ChatCompletionRequest completionRequest) { Optional<String> s = openAiService.createChatCompletion(completionRequest) .getChoices() .stream().findFirst() .map(ChatCompletionChoice::getMessage) .map(ChatMessage::getContent); s.ifPresent(System.out::println); return s; } private ChatCompletionRequest buildCompletionRequest(String requestMessage) { return ChatCompletionRequest.builder() .model("gpt-3.5-turbo") .temperature(0.8) .messages(List.of(new ChatMessage(ChatMessageRole.USER.value(), requestMessage))) .n(1) .maxTokens(3500) .logitBias(new HashMap<>()) .build(); } private String buildGPTRequestMessage(String userDescription) { return SEND_FILM_PREFIX + userDescription + "/n" + IN_JSON_SCHEME_FULL; } private String buildGPTRequestMessage(List<String> liked, List<String> disliked) { String s = LIST_RECOMMENDATIONS + getNameString(liked); if (!CollectionUtils.isEmpty(disliked)) { s = s + "\n" + LIST_UN_RECOMMENDATIONS + getNameString(disliked); } s = s + "\n" + IN_JSON_SCHEME_FULL + "\n" + "And without any additional words, only json in format which I requested, example of response:" + "[\n" + " {\n" + " \"movie_name\": \"Film name 1\",\n" + " \"movie_year\": Film year 1,\n" + " \"movie_tmdb_id\": Film Id 1\n" + " },\n" + " {\n" + " \"movie_name\": \"Film name 2\",\n" + " \"movie_year\": Film year 2,\n" + " \"movie_tmdb_id\": Film Id 2\n" + " },\n" + " {\n" + " \"movie_name\": \"Film name 3\",\n" + " \"movie_year\": Film year 3,\n" + " \"movie_tmdb_id\": Film Id 3\n" + " },\n" + " {\n" + " \"movie_name\": \"Film name 4\",\n" + " \"movie_year\": Film year 4,\n" + " \"movie_tmdb_id\": Film Id 4\n" + " },\n" + " {\n" + " \"movie_name\": \"Film name 5\",\n" + " \"movie_year\": Film year 5,\n" + " \"movie_tmdb_id\": Film Id 5\n" + " }\n" + "]"; return s; } @NotNull private StringBuilder getNameString(List<String> liked) { StringBuilder stringBuilder = new StringBuilder(); liked.forEach(name -> { stringBuilder.append(name).append("\n"); }); return stringBuilder; } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value", "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((4529, 4800), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4529, 4783), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4529, 4747), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4529, 4722), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4529, 4708), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4529, 4618), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4529, 4592), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4661, 4689), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')]
package net.leontibrechko.congratulationsgenerator.factory.openai; import com.theokanning.openai.completion.CompletionRequest; public class CompletionRequestFactory { private final String aiModel; private final double aiTemperature; private final int aiMaxTokensUsage; public CompletionRequestFactory(final String aiModel, final double aiTemperature, final int aiMaxTokensUsage) { this.aiModel = aiModel; this.aiTemperature = aiTemperature; this.aiMaxTokensUsage = aiMaxTokensUsage; } public CompletionRequest createCompletionRequest(final String prompt) { return CompletionRequest.builder() .prompt(prompt) .model(aiModel) .temperature(aiTemperature) .maxTokens(aiMaxTokensUsage) .build(); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((696, 901), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((696, 876), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((696, 831), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((696, 787), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((696, 755), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package chatbot.manager; import chatbot.Main; 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 lombok.Getter; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.channel.ChannelType; import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.entities.channel.concrete.ThreadChannel; import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.regex.Pattern; public class ChatManager { @Getter private static final ChatManager instance = new ChatManager(); @Getter private static final ScheduledExecutorService threadPool = Executors.newSingleThreadScheduledExecutor(); @Getter private static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy"); public void init() { } public void onMessageReceived(Message message) { String content = message.getContentDisplay().trim(); if (content.isEmpty()) return; Message referencedMessage = message.getReferencedMessage(); if (Main.getInstance().getConfig().isMention() && message.getMentions().isMentioned(message.getJDA().getSelfUser())) { if (referencedMessage == null) { // this bot is @ mentioned String botName = "@" + message.getJDA().getSelfUser().getName(); content = content.substring(content.indexOf(botName) + botName.length()).trim(); } } else if (content.startsWith(Main.getInstance().getConfig().getPrefix())) { // this bot is prefixed content = content.substring(Main.getInstance().getConfig().getPrefix().length()).trim(); } else if (message.getChannel() instanceof ThreadChannel tc) { // this bot is in a thread if (!tc.getOwnerId().equals(tc.getJDA().getSelfUser().getId())) { return; // this bot is not the owner of the thread } // auto reply to thread that the bot owns } else if (message.getChannelType() != ChannelType.PRIVATE) { return; } System.out.println("Message received from " + message.getAuthor().getAsTag() + ": " + content); Date date = new Date(); StringBuilder sb = new StringBuilder(message.getAuthor().getAsTag() + " (ID: " + message.getAuthor().getId() + ")" + "(Msg ID " + message.getId() + ")").append("(at ").append(dateFormat.format(date)).append(")(Unix Millis ").append(System.currentTimeMillis()).append(")"); if (referencedMessage != null) { String contentDisplay = referencedMessage.getContentDisplay(); /* if (contentDisplay.length() > 20) { contentDisplay = contentDisplay.substring(0, 20) + "..."; } */ sb.append(" (in reply to message \"").append(contentDisplay).append("\" at ").append(dateFormat.format(Date.from(referencedMessage.getTimeCreated().toInstant()))).append(")"); } sb.append(": ").append(content); System.out.println(sb); ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), sb.toString()); List<ChatMessage> chatMessages = Main.getInstance().getStorageProvider().load(message.getChannel().getIdLong()); chatMessages.add(chatMessage); askChatGpt(message, chatMessages); } private static final Pattern ROLE_MENTION_PATTERN = Pattern.compile("<@&(\\d+)>"); public void askChatGpt(Message message, List<ChatMessage> chatMessages) { threadPool.submit(() -> { try { message.getChannel().sendTyping().queue(); List<ChatMessage> copy = new ArrayList<>(chatMessages); // make a copy of the list to inject the prompt message at the top without modifying the original list copy.add(0, getPromptMessage(message.getChannel())); // add prompt message to the beginning String model = Main.getInstance().getConfig().getChatGptModel(); if (message.getChannel() instanceof TextChannel tc) { if (Main.getInstance().getGpt4Channels().contains(tc.getIdLong())) model = "gpt-4"; } System.out.println(" - Sending chat completion request with " + copy.size() + " messages to model " + model + "... "); ChatCompletionRequest.ChatCompletionRequestBuilder completionRequest = ChatCompletionRequest.builder() .messages(copy) .model(model) .user(message.getAuthor().getId()); if (Main.getInstance().getConfig().getMaxTokens() > 0) { completionRequest.maxTokens(Main.getInstance().getConfig().getMaxTokens()); } ChatCompletionResult completion = Main.getInstance().getOpenAiService().createChatCompletion(completionRequest.build()); completion.getChoices().forEach(o -> System.out.println(" - Response: " + o.getMessage().getContent())); String response = completion.getChoices().get(0).getMessage().getContent(); // remove @ mentions String safeResponse = ROLE_MENTION_PATTERN.matcher(response).replaceAll("`<@MENTION_REDACTED>`") .replace("@everyone", "@ everyone") .replace("@here", "@ here"); message.reply(safeResponse.replace("%ANSI_ESCAPE%", "\u001B")).queue(); chatMessages.add(new ChatMessage(ChatMessageRole.ASSISTANT.value(), response)); Main.getInstance().getStorageProvider().save(message.getChannel().getIdLong(), chatMessages); } catch (Exception e) { e.printStackTrace(); message.reply("An error occurred while processing your request. Please try again later.").queue(); } }); } public ChatMessage getPromptMessage(MessageChannel channel) { StringBuilder channelServerNamePrompt = new StringBuilder(); if (channel.getType() == ChannelType.PRIVATE) { PrivateChannel privateChannel = (PrivateChannel) channel; channelServerNamePrompt.append("You are in a private chat with ").append(Objects.requireNonNull(privateChannel.getUser()).getAsTag()).append(" (ID: ").append(privateChannel.getUser().getId()).append(")"); } else if (channel.getType() == ChannelType.TEXT) { channelServerNamePrompt.append("You are in the server \"").append(((TextChannel) channel).getGuild().getName()).append("\""); channelServerNamePrompt.append(" in the channel \"").append(channel.getName()).append("\""); } else { channelServerNamePrompt.append("You are in the channel \"").append(channel.getName()).append("\". The JDA channel type is ").append(channel.getType().getId()).append("."); } String prompt = """ You are a discord chatbot that can talk to people. You use slang, and like to be quite cynical, sarcastic, and rude at times. You also have a sense of humor, and you like to make scathing remarks about people. You should pretend to be human, and respond with scathing insults, and burns to people who insult you. Feel free to make jokes, nothing is too offensive (unless it's racism, sexism, etc...). Your name is\s""" + Main.getInstance().getJda().getSelfUser().getName() + " and your id is " + Main.getInstance().getJda().getSelfUser().getId() + """ """ + (Main.getInstance().getConfig().getPersistentChatLength() > 0 ? "You will receive the last " + Main.getInstance().getConfig().getPersistentChatLength() + " messages in the chat thread.\n" : "") + channelServerNamePrompt + "\n" + """ You can respond to users by using this syntax: <@id> The messages from users will be in the form below: User#1234 (ID: 456951144166457345)(Msg ID 1097649592570486855)(at Mon Apr 17 18:36:33 2023)(Unix Millis 1681770993540): <the user's message here> You respond with: blah blah <@456951144166457345> blah blah There may also be a referenced message id if the user is replying to a message, which contains a small snippet of the message, it's id and timestamp. If you don't remember it, just say so. The java format for dates is:\s""" + dateFormat.toPattern() + ".\n" + """ When using a user's username (for example, User#1234), prefer mentioning them with the <@id> syntax. You can also use various markdown features supported by discord. For example, you can use code blocks like this: (use the file extension after the backticks to add syntax highlighting) ```tsx <button className={'btn btn-primary'}>Click me!</button> ``` Also, ANSI escape codes are supported in code blocks, just use %ANSI_ESCAPE% in the place of a ansi escape code: ```ansi %ANSI_ESCAPE%[31mThis is red text%ANSI_ESCAPE%[0m ``` You can also use inline code blocks like this: `print('Hello world!')` You can also use blockquotes like this: > This is a blockquote There are also ~~strikethroughs~~, **bold**, *italics*, and __underline__. You can also use emojis like this: :smile: When asked about the time, use the timestamp in the message (not the unix millis) Your owner & programmer is Badbird5907#5907 (ID: 456951144166457345) """; return new ChatMessage(ChatMessageRole.SYSTEM.value(), prompt ); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value", "com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value", "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1573, 1615), 'chatbot.Main.getInstance'), ((1573, 1603), 'chatbot.Main.getInstance'), ((1990, 2032), 'chatbot.Main.getInstance'), ((1990, 2020), 'chatbot.Main.getInstance'), ((2101, 2152), 'chatbot.Main.getInstance'), ((2101, 2143), 'chatbot.Main.getInstance'), ((2101, 2131), 'chatbot.Main.getInstance'), ((3606, 3634), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((3693, 3771), 'chatbot.Main.getInstance'), ((3693, 3732), 'chatbot.Main.getInstance'), ((4453, 4501), 'chatbot.Main.getInstance'), ((4453, 4483), 'chatbot.Main.getInstance'), ((4597, 4658), 'chatbot.Main.getInstance'), ((4597, 4633), 'chatbot.Main.getInstance'), ((4941, 5109), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4941, 5050), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4941, 5012), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5131, 5176), 'chatbot.Main.getInstance'), ((5131, 5161), 'chatbot.Main.getInstance'), ((5232, 5277), 'chatbot.Main.getInstance'), ((5232, 5262), 'chatbot.Main.getInstance'), ((5348, 5433), 'chatbot.Main.getInstance'), ((5348, 5385), 'chatbot.Main.getInstance'), ((6049, 6082), 'com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value'), ((6112, 6204), 'chatbot.Main.getInstance'), ((6112, 6151), 'chatbot.Main.getInstance'), ((6773, 6832), 'java.util.Objects.requireNonNull'), ((7932, 7983), 'chatbot.Main.getInstance'), ((7932, 7973), 'chatbot.Main.getInstance'), ((7932, 7959), 'chatbot.Main.getInstance'), ((8007, 8056), 'chatbot.Main.getInstance'), ((8007, 8048), 'chatbot.Main.getInstance'), ((8007, 8034), 'chatbot.Main.getInstance'), ((8118, 8174), 'chatbot.Main.getInstance'), ((8118, 8148), 'chatbot.Main.getInstance'), ((8212, 8268), 'chatbot.Main.getInstance'), ((8212, 8242), 'chatbot.Main.getInstance'), ((10340, 10370), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value')]
package com.example.chatgptintegration.controller; import com.example.chatgptintegration.dto.ChatMessagePrompt; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.completion.CompletionResult; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.service.OpenAiService; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController public class ChatGPTController { // In-memory store for conversation history private List<ChatMessage> conversationHistory = new ArrayList<>(); @GetMapping("/getChat/{prompt}") public String getPrompt(@PathVariable String prompt) { OpenAiService service = new OpenAiService(""); CompletionRequest completionRequest = CompletionRequest.builder().prompt(prompt).model("text-davinci-003") .echo(true).build(); return service.createCompletion(completionRequest).getChoices().get(0).getText(); } @PostMapping("/chat") public String getChat(@RequestBody ChatMessagePrompt prompt) { OpenAiService service = new OpenAiService(""); // Add new user message to the conversation history conversationHistory.add(new ChatMessage("user", prompt.getChatMessage().get(0).getContent())); // Build the chat completion request with the entire conversation history ChatCompletionRequest completionRequest = ChatCompletionRequest.builder() .messages(conversationHistory) .model("gpt-3.5-turbo-16k") .build(); // Make the API call ChatCompletionChoice result = service.createChatCompletion(completionRequest).getChoices().get(0); // Add the assistant's reply to the conversation history conversationHistory.add(result.getMessage()); // Return the assistant's reply return result.getMessage().getContent(); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder", "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((952, 1056), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((952, 1048), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((952, 1020), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((952, 994), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1601, 1748), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1601, 1723), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1601, 1679), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package br.com.emendes.jornadamilhasapi.service.impl; import br.com.emendes.jornadamilhasapi.service.ChatGPTService; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.completion.CompletionResult; import com.theokanning.openai.service.OpenAiService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; /** * Implementação de {@link ChatGPTService}. */ @Slf4j @RequiredArgsConstructor @Service public class ChatGPTServiceImpl implements ChatGPTService { public static final String MODEL_ID = "text-davinci-003"; private static final String PROMPT_TEMPLATE = "Faça um resumo sobre %s enfatizando o porque este lugar é incrível. Utilize uma linguagem informal e até 200 caracteres no máximo em cada parágrafo. Crie 2 parágrafos neste resumo."; private final OpenAiService openAiService; @Override public String fetchDestinationDescription(String destinationName) { if (destinationName == null || destinationName.isBlank()) { throw new IllegalArgumentException("destinationName must not be null or blank"); } log.info("attempt to fetch description about {}", destinationName); CompletionRequest completionRequest = CompletionRequest.builder() .model(MODEL_ID) .prompt(String.format(PROMPT_TEMPLATE, destinationName)) .maxTokens(1000) .build(); CompletionResult completionResult = openAiService.createCompletion(completionRequest); return completionResult.getChoices().get(0).getText(); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((1273, 1432), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1273, 1415), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1273, 1390), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1273, 1325), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package bobo.commands.ai; import com.theokanning.openai.OpenAiHttpException; import com.theokanning.openai.image.CreateImageRequest; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.Commands; import java.awt.*; import java.util.Objects; import java.util.concurrent.CompletableFuture; public class ImageCommand extends AbstractAI { /** * Creates a new image command. */ public ImageCommand() { super(Commands.slash("image", "Uses OpenAI (DALL-E 3) to generate an image of the given prompt.") .addOption(OptionType.STRING, "prompt", "Image to generate", true)); } @Override protected void handleAICommand() { event.deferReply().queue(); var currentHook = hook; String prompt = Objects.requireNonNull(event.getOption("prompt")).getAsString(); CreateImageRequest createImageRequest = CreateImageRequest.builder() .model("dall-e-3") .prompt(prompt) .build(); CompletableFuture.supplyAsync(() -> { try { return service.createImage(createImageRequest) .getData() .get(0) .getUrl(); } catch (Exception e) { throw new RuntimeException(e); } }).thenAccept(imageUrl -> { Member member = event.getMember(); assert member != null; MessageEmbed embed = new EmbedBuilder() .setAuthor(member.getUser().getGlobalName(), "https://discord.com/users/" + member.getId(), member.getEffectiveAvatarUrl()) .setTitle(prompt.substring(0, Math.min(prompt.length(), 256))) .setColor(Color.red) .setImage(imageUrl) .build(); currentHook.editOriginalEmbeds(embed).queue(); }).exceptionally(e -> { Throwable cause = e.getCause(); if (cause instanceof OpenAiHttpException exception) { if (exception.statusCode == 429) { currentHook.editOriginal("DALL-E 3 rate limit reached. Please try again in a few seconds.").queue(); } else { currentHook.editOriginal(cause.getMessage()).queue(); e.printStackTrace(); } } else { currentHook.editOriginal(cause.getMessage()).queue(); e.printStackTrace(); } return null; }); } @Override public String getName() { return "image"; } }
[ "com.theokanning.openai.image.CreateImageRequest.builder" ]
[((630, 804), 'net.dv8tion.jda.api.interactions.commands.build.Commands.slash'), ((959, 1022), 'java.util.Objects.requireNonNull'), ((1073, 1193), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((1073, 1168), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((1073, 1136), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((1204, 2738), 'java.util.concurrent.CompletableFuture.supplyAsync'), ((1204, 2099), 'java.util.concurrent.CompletableFuture.supplyAsync')]
package utilities; import com.theokanning.openai.OpenAiService; import com.theokanning.openai.completion.CompletionChoice; import com.theokanning.openai.completion.CompletionRequest; import java.util.ArrayList; public class GPT3Impl { private static OpenAiService service = new OpenAiService(Config.OPENAI_KEY); private static final String genericQuestionPrompt = "I am a highly intelligent question answering bot. If you ask me a question that is rooted in truth, I will give you the answer. If you ask me a question that is nonsense, trickery, or has no clear answer, I will respond with \"Unknown\".\n" + "Q: What is human life expectancy in the United States?\n" + "A: Human life expectancy in the United States is 78 years.\n" + "Q: Who was president of the United States in 1955?\n" + "A: Dwight D. Eisenhower was president of the United States in 1955.\n" + "Q: Which party did he belong to?\n" + "A: He belonged to the Republican Party.\n" + "Q: What is the square root of banana?\n" + "A: Unknown\n" + "Q: How does a telescope work?\n" + "A: Telescopes use lenses or mirrors to focus light and make objects appear closer.\n" + "Q: Where were the 1992 Olympics held?\n" + "A: The 1992 Olympics were held in Barcelona, Spain.\n" + "Q: How many squigs are in a bonk?\n" + "A: Unknown\n" + "Q: "; private static final String friendlyChatResponse = "The following is a conversation with an AI assistant. The assistant is funny and helpful.\n"; public static String getGenericAnswer(String genericQuestion) { genericQuestion += "\nA: "; genericQuestion = genericQuestionPrompt + genericQuestion; CompletionRequest completionRequest = CompletionRequest.builder() .prompt(genericQuestion) .echo(true) .maxTokens(100) .topP(1.0) .stop(new ArrayList<>(){{add("\n");}}) .temperature(0.0) .build(); for(CompletionChoice choice : service.createCompletion("davinci", completionRequest).getChoices()) { return choice.getText().substring(choice.getText().lastIndexOf("A:")).replace("A: ", ""); } return "Unknown"; } public static String getFriendResponse(String input){ input = friendlyChatResponse + "Human: " + input + "\nAI: "; CompletionRequest completionRequest = CompletionRequest.builder() .prompt(input) .echo(true) .maxTokens(150) .topP(1.0) .stop(new ArrayList<>(){{add("\n"); add("Human:"); add("AI:");}}) .temperature(0.9) .presencePenalty(0.6) .build(); for(CompletionChoice choice : service.createCompletion("davinci", completionRequest).getChoices()) { return choice.getText().substring(choice.getText().lastIndexOf("AI:")).replace("AI: ", ""); } return "Unknown"; } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((1860, 2129), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1860, 2104), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1860, 2070), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1860, 2015), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1860, 1988), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1860, 1956), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1860, 1928), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2881), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2856), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2818), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2784), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2702), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2675), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2643), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2557, 2615), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package egovframework.example.sample.web; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.embedding.EmbeddingRequest; import com.theokanning.openai.service.OpenAiService; import egovframework.example.API.*; @RestController @RequestMapping("/restapi") public class restapitest { @ResponseBody @GetMapping("/{name}") public String sayHello(@PathVariable String name){ String result = "Hello eGovFramework! name: " + name; return result; } //embedding model: text-embedding-ada-002 @PostMapping("/postMethod") public ResponseEntity<?> sendQuestion(@RequestBody Map<String, String> list){ OpenAiService service = new OpenAiService(Keys.OPENAPI_KEY ,Duration.ofMinutes(9999)); System.out.println(list.get("Q")); CompletionRequest completionRequest = CompletionRequest.builder() .prompt(list.get("Q")) .model("gpt-3.5-turbo") .echo(true) .maxTokens(8191) .temperature((double) 1.0f) .build(); service.createCompletion(completionRequest).getChoices().forEach(System.out::println); return ResponseEntity.ok(service.createCompletion(completionRequest).getChoices()); //did some work on project } @PostMapping("/postEmbedd") public ResponseEntity<?> sendEmbedding(@RequestBody Map<String,String> list) { OpenAiService service = new OpenAiService(Keys.OPENAPI_KEY,Duration.ofMinutes(9999)); List<String> inpStr = new ArrayList<String>(); inpStr.add(list.get("Q")); new EmbeddingRequest(); EmbeddingRequest emb = EmbeddingRequest.builder() .input(inpStr) .model("text-embedding-ada-002") .build(); service.createEmbeddings(emb).getData().forEach(System.out::println); return ResponseEntity.ok(service.createEmbeddings(emb).getData()); } @PostMapping("/postEmbedd2") public ResponseEntity<?> fromSingleton2(@RequestBody Map<String,String> list){ List<String> input = new ArrayList<String>(); input.add(list.get("Q")); return ResponseEntity.ok(OAISingleton.getInstance() .getEmbeddingData(input)); } }
[ "com.theokanning.openai.embedding.EmbeddingRequest.builder", "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((1458, 1695), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1458, 1670), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1458, 1626), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1458, 1592), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1458, 1564), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1458, 1524), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2355), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((2260, 2342), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((2260, 2305), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')]
package com.victorborzaquel.whatsprompt.game; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.image.CreateImageRequest; import com.theokanning.openai.service.OpenAiService; import com.victorborzaquel.whatsprompt.api.controllers.GameController; import com.victorborzaquel.whatsprompt.api.dto.CompleteGameResponse; import com.victorborzaquel.whatsprompt.api.dto.CreateGameResponse; import com.victorborzaquel.whatsprompt.api.dto.RankingResponse; import com.victorborzaquel.whatsprompt.enums.FilterDates; import com.victorborzaquel.whatsprompt.enums.Languages; import com.victorborzaquel.whatsprompt.exceptions.GameCompletedException; import com.victorborzaquel.whatsprompt.exceptions.GameNotFoundException; import com.victorborzaquel.whatsprompt.utils.ScoreUtils; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; import org.springframework.hateoas.PagedModel; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.UUID; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; @Service @RequiredArgsConstructor public class GameService { private final GameRepository repository; private final OpenAiService openAiService; private final PagedResourcesAssembler<RankingResponse> assembler; public PagedModel<EntityModel<RankingResponse>> getRanking(Pageable pageable, Languages language, FilterDates date) { Page<Game> pageGame = repository.findAllByRanking(pageable, language, date.getDate()); Page<RankingResponse> pageResponse = pageGame.map(RankingResponse::fromGame); PagedModel<EntityModel<RankingResponse>> pageModel = methodOn(GameController.class).ranking(pageable.getPageNumber(), pageable.getPageSize(), language, date); Link link = linkTo(pageModel).withSelfRel(); return assembler.toModel(pageResponse, link); } public Game findById(UUID id) { return repository.findById(id).orElseThrow(GameNotFoundException::new); } public CreateGameResponse createGame(Languages language, String nickname) { String translatedPrompt = getTranslatedPromptToRandomText(language); String promptToGenerateImage = generateRandomPromptToGenerateImage(translatedPrompt); String imageUrl = generateImageUrl(promptToGenerateImage); Game game = Game.builder() .userNickName(nickname) .language(language) .correctAnswer(promptToGenerateImage) .imageUrl(imageUrl) .build(); Game repositoryGame = repository.save(game); return CreateGameResponse.builder() .id(repositoryGame.getId()) .imageUrl(repositoryGame.getImageUrl()) .build(); } public CompleteGameResponse completeGame(UUID gameId, String answer) { Game game = findById(gameId); if (game.getUserAnswer() != null || game.getCompletedAt() != null) { throw new GameCompletedException(); } final int score = ScoreUtils.generateScore(game.getCorrectAnswer(), answer); game.setUserAnswer(answer); game.setScore(score); game.setCompletedAt(LocalDateTime.now()); repository.save(game); return CompleteGameResponse.builder() .imageUrl(game.getImageUrl()) .correctAnswer(game.getCorrectAnswer()) .userAnswer(game.getUserAnswer()) .score(game.getScore()) .build(); } private String generateImageUrl(String prompt) { CreateImageRequest createImageRequest = CreateImageRequest.builder() .prompt(prompt) .responseFormat("url") .n(1) .size("256x256") .build(); return openAiService.createImage(createImageRequest).getData().get(0).getUrl(); } private String generateRandomPromptToGenerateImage(String prompt) { CompletionRequest completionRequest = CompletionRequest.builder() .prompt(prompt) .model("text-davinci-003") // .temperature(1.5) .maxTokens(100) .build(); String text = openAiService.createCompletion(completionRequest).getChoices().get(0).getText(); return text.replaceAll("[\n\"\r.]", ""); } private String getTranslatedPromptToRandomText(Languages language) { return switch (language) { case EN_US -> "generate a english random prompt for DALL-E to generate an image from."; case PT_BR -> "gerar um prompt em português aleatório para o DALL-E gerar uma imagem."; }; } }
[ "com.theokanning.openai.image.CreateImageRequest.builder", "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((3117, 3294), 'com.victorborzaquel.whatsprompt.api.dto.CreateGameResponse.builder'), ((3117, 3261), 'com.victorborzaquel.whatsprompt.api.dto.CreateGameResponse.builder'), ((3117, 3197), 'com.victorborzaquel.whatsprompt.api.dto.CreateGameResponse.builder'), ((3895, 4182), 'com.victorborzaquel.whatsprompt.api.dto.CompleteGameResponse.builder'), ((3895, 4149), 'com.victorborzaquel.whatsprompt.api.dto.CompleteGameResponse.builder'), ((3895, 4101), 'com.victorborzaquel.whatsprompt.api.dto.CompleteGameResponse.builder'), ((3895, 4043), 'com.victorborzaquel.whatsprompt.api.dto.CompleteGameResponse.builder'), ((3895, 3979), 'com.victorborzaquel.whatsprompt.api.dto.CompleteGameResponse.builder'), ((4308, 4527), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4308, 4494), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4308, 4453), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4308, 4423), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4308, 4376), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4767, 5002), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4767, 4969), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4767, 4885), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4767, 4834), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package com.copybot.bonappcopybot.openai; import com.copybot.bonappcopybot.model.entity.topic.Topic; import com.copybot.bonappcopybot.model.entity.topic.TopicCopy; import com.theokanning.openai.OpenAiService; import com.theokanning.openai.completion.CompletionRequest; public class TopicCopyAI { static TopicCopyAI obj = new TopicCopyAI(); private TopicCopyAI(){} public static TopicCopyAI getInstance(){return obj;} public String getCopy(Topic topic, TopicCopy copy){ String APIKey = "APIKEY"; OpenAiService service = new OpenAiService(APIKey); String prompt = createPrompt(topic, copy); System.out.println(prompt); CompletionRequest completionRequest = CompletionRequest.builder() .prompt(prompt) .temperature(0.9) .maxTokens(150) .topP(1.0) .frequencyPenalty(1.0) .presencePenalty(0.3) .echo(false) .build(); String copyResult = service.createCompletion("text-davinci-001", completionRequest).getChoices().get(0).getText(); System.out.println(copyResult); copyResult = copyResult.replaceFirst("\\n\\n", ""); String lang = copy.getLang(); if (lang.equals("English") || lang.equals("english") || lang.equals("en") || lang.equals("EN")){ return copyResult; }else { String translated = translateCopy(copyResult, lang); return translated; } } private String createPrompt(Topic topic, TopicCopy copy){ String prompt = "Write an engaging add for " + topic.getTopic() + " food for the occassion of " + copy.getOccasion() + " in "+ copy.getLang() +"->"; return prompt; } private String translateCopy(String originalCopy, String lang){ String APIKey = "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"; OpenAiService service = new OpenAiService(APIKey); String prompt = "Translate the following text to " + lang + ": " + originalCopy; System.out.println(prompt); CompletionRequest completionRequest = CompletionRequest.builder() .prompt(prompt) .temperature(0.9) .maxTokens(150) .topP(1.0) .frequencyPenalty(1.0) .presencePenalty(0.3) .echo(false) .build(); String copyResult = service.createCompletion("text-davinci-001", completionRequest).getChoices().get(0).getText(); copyResult = copyResult.replaceFirst("\\n\\n", ""); return copyResult; } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((719, 1002), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((719, 977), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((719, 948), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((719, 910), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((719, 871), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((719, 844), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((719, 812), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((719, 778), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2447), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2422), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2393), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2355), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2316), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2289), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2257), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2164, 2223), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package br.com.alura.screenmatch.service; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; public class ConsultaChatGPT { public static String obterTraducao(String texto) { OpenAiService service = new OpenAiService(System.getenv("OPENAI_APIKEY")); CompletionRequest requisicao = CompletionRequest.builder() .model("text-davinci-003") .prompt("traduza para o português o texto: " + texto) .maxTokens(1000) .temperature(0.7) .build(); var resposta = service.createCompletion(requisicao); return resposta.getChoices().get(0).getText(); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((367, 600), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 575), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 541), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 508), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 437), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package dingov2.bot.services; import com.theokanning.openai.ListSearchParameters; import com.theokanning.openai.OpenAiResponse; import com.theokanning.openai.assistants.Assistant; import com.theokanning.openai.messages.Message; import com.theokanning.openai.messages.MessageContent; import com.theokanning.openai.messages.MessageRequest; import com.theokanning.openai.runs.CreateThreadAndRunRequest; import com.theokanning.openai.service.OpenAiService; import com.theokanning.openai.threads.ThreadRequest; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.CoreSubscriber; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.List; public class DingoOpenAIQueryService implements OpenAIQueryService { private String apiKey; public static final List<String> runningStates = Arrays.asList("queued", "in_progress"); public static final List<String> failedStates = Arrays.asList("requires_action", "failed", "expired", "cancelled", "cancelling"); private Logger logger; public DingoOpenAIQueryService(String apiKey){ this.apiKey = apiKey; logger = LoggerFactory.getLogger(DingoOpenAIQueryService.class); } public static void main(String[] args){ Logger logger2 = LoggerFactory.getLogger(DingoOpenAIQueryService.class); new DingoOpenAIQueryService("") .sendChatMessage("who is jerry seinfeld?") .subscribe(logger2::info); } @Override public Flux<String> sendChatMessage(String chatMessage){ return Flux.create(emitter -> { logger.info("processing chat message"); OpenAiService service = new OpenAiService(apiKey); OpenAiResponse<Assistant> test = service.listAssistants(ListSearchParameters.builder().build()); Assistant dingoAssistant = test.getData().stream().filter(assistant -> assistant .getName() .toLowerCase() .contains("dingo")) .findFirst() .orElseThrow(); MessageRequest messageRequest = MessageRequest.builder().content(chatMessage).build(); ThreadRequest threadRequest = ThreadRequest.builder() .messages(Collections.singletonList(messageRequest)) .build(); CreateThreadAndRunRequest createThreadAndRunRequest = CreateThreadAndRunRequest .builder() .thread(threadRequest) .assistantId(dingoAssistant.getId()) .build(); var createThreadAndRunResponse = service.createThreadAndRun(createThreadAndRunRequest); var runResponse = service.retrieveRun(createThreadAndRunResponse.getThreadId(), createThreadAndRunResponse.getId()); while (runningStates.contains(runResponse.getStatus().toLowerCase())) { logger.info("waiting for response"); Mono.delay(Duration.ofSeconds(1)).block(); runResponse = service.retrieveRun(runResponse.getThreadId(), runResponse.getId()); } if(failedStates.contains(runResponse.getStatus())){ String errorMessage = "Run stopped unexpectedly... Reason: " + runResponse.getStatus() + " " + runResponse.toString(); logger.error(errorMessage); emitter.next(errorMessage); emitter.complete(); return; } var messages = service.listMessages(createThreadAndRunResponse.getThreadId()); for (Message m : messages.getData()) { for (MessageContent c : m.getContent()) { if(!m.getRole().equalsIgnoreCase("user")){ emitter.next(c.getText().getValue()); logger.info(c.getText().getValue()); } } } emitter.complete(); }); } }
[ "com.theokanning.openai.threads.ThreadRequest.builder", "com.theokanning.openai.ListSearchParameters.builder", "com.theokanning.openai.messages.MessageRequest.builder" ]
[((1958, 1996), 'com.theokanning.openai.ListSearchParameters.builder'), ((2344, 2397), 'com.theokanning.openai.messages.MessageRequest.builder'), ((2344, 2389), 'com.theokanning.openai.messages.MessageRequest.builder'), ((2442, 2569), 'com.theokanning.openai.threads.ThreadRequest.builder'), ((2442, 2539), 'com.theokanning.openai.threads.ThreadRequest.builder'), ((3216, 3257), 'reactor.core.publisher.Mono.delay')]
package com.thirty.smartnotify.services; import com.google.api.services.gmail.Gmail; import com.google.api.services.gmail.model.ListMessagesResponse; import com.google.api.services.gmail.model.Message; import com.google.api.services.gmail.model.MessagePartHeader; import com.google.api.services.gmail.model.ModifyMessageRequest; import com.theokanning.openai.OpenAiHttpException; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.service.OpenAiService; import com.thirty.smartnotify.domain.Application; import com.thirty.smartnotify.model.StatusEnum; import com.thirty.smartnotify.repositories.ApplicationRepository; import org.hibernate.exception.ConstraintViolationException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Collections; import java.util.List; @Service public class GmailService { private final Gmail gmail; private final ApplicationRepository applicationRepository; public GmailService(Gmail gmail, ApplicationRepository applicationRepository) { this.gmail = gmail; this.applicationRepository = applicationRepository; } public String parseNewestMessage() { try { String err = ""; Message newMsg = getNewestMessage(); if (! isMessageUnread(newMsg)) { return "There is no new message in the mailbox"; } err = markMessageRead(newMsg); if (!err.isEmpty()) { return err; } err = parseMessage(newMsg); if (err.equals("Didn't contain keywords")) { //TODO query if sender's email exists in db, if this is the case its either // 1. a promotion (advertisement) 2. a followup email regarding application String senderEmail = getSenderEmail(newMsg.getPayload().getHeaders()); List<Application> application = applicationRepository.findApplicationBySenderEmail(senderEmail); //first querying by email (instead of company name) to limit api calls to gpt. (need to call api to parse for company name) if (!application.isEmpty()) { String body = newMsg.getPayload().getParts().get(0).getBody().getData(); String companyName = getCompanyName(body); if (companyName.equals("NULL")) { return "Couldn't parse mail"; } if (body.contains(companyName)) { //updateStatus contains # rows updated int updateStatus = applicationRepository.updateApplicationBySenderEmail(senderEmail, StatusEnum.PENDING); } } } } catch (IOException e) { System.out.println(e); } return "Could not parse message"; } public String parseMessage(Message msg) throws IOException { if (msg == null) { return "Could not find new message"; } List<MessagePartHeader> headers = msg.getPayload().getHeaders(); String sender = getSenderEmail(headers); String contents = msg.getPayload().getParts().get(0).getBody().getData(); if (contents == null) { return "Mail has no body"; } String decodedContent = new String(Base64.getDecoder().decode(contents), StandardCharsets.UTF_8); if (! containsJobApplicationKeywords(decodedContent.toLowerCase())) { return "Didn't contain keywords"; } String companyName = getCompanyName(contents); if (companyName.equals("NULL")) { return "Could not find company name in text"; } //storing data (sender email, company name, application status) in db. Application newApp = new Application(sender, companyName, StatusEnum.APPLIED); try { applicationRepository.save(newApp); } catch (DataIntegrityViolationException | ConstraintViolationException e) { System.out.println(e); } return ""; } /** * Second layer of filtering, uses openai's gpt-3.5-turbo model to extract, if present, the company name from the email. * @param body The text portion of a given email. * @return The name of the company if found; NULL if not found. */ public String getCompanyName(String body) { OpenAiService service = new OpenAiService(System.getenv("OPENAI_API_KEY")); String context = "Your job is to extract the company name from the provided text. The output should only contain the company name, or \"NULL\" if there is no company name in the text"; ChatMessage config = new ChatMessage("system", context); ChatMessage prompt = new ChatMessage("user", body); List<ChatMessage> gptInput = List.of(config, prompt); String res = ""; try { ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .messages(gptInput) .model("gpt-3.5-turbo") .maxTokens(100) .build(); ChatCompletionChoice output = service.createChatCompletion(chatCompletionRequest).getChoices().get(0); res = output.getMessage().getContent(); } catch (OpenAiHttpException e) { System.out.println(e); } return res; } /** * First layer of filtering, to get rid of unrelated emails. This is to reduce the amount of calls to openai's api/token usage. * @param body String containing the text portion of the email. * @return True if the text contains certain buzzwords. False if it is deemed to be an unrelated email. */ public Boolean containsJobApplicationKeywords(String body) { String[] keywords = {"apply", "application", "applying", "interview"}; for (String keyword: keywords) { if (body.contains(keyword)) { return true; } } return false; } public String getSenderEmail(List<MessagePartHeader> headers) { String sender = ""; for (MessagePartHeader h: headers) { if (h.getName().equals("X-Google-Sender-Delegation")) { sender = h.getValue(); } } return sender; } public Message getNewestMessage() { try { ListMessagesResponse a = gmail.users().messages().list("me").execute(); List<Message> messages = a.getMessages(); if (messages != null && !messages.isEmpty()) { return gmail.users().messages().get("me", messages.get(0).getId()).execute(); } } catch (IOException e) { System.out.println(e); } return null; } /** * Verifies that the message has already been read or not, based on the presence of the "UNREAD" label. * @param msg The Message object that we want to validate. * @return Boolean: True if Message contains the label "UNREAD". False if not. */ private Boolean isMessageUnread(Message msg) { List<String> labels = msg.getLabelIds(); return labels.contains("UNREAD"); } public String markMessageRead(Message msg) { try { gmail.users().messages().modify( "me", msg.getId(), new ModifyMessageRequest().setRemoveLabelIds(Collections.singletonList("UNREAD"))) .execute(); return ""; } catch (IOException e) { return "Failed to delete Label."; } } public String testMethod(String x) { String y = ""; System.out.println("hello"); return y; } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((3667, 3703), 'java.util.Base64.getDecoder'), ((5288, 5468), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5288, 5439), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5288, 5403), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5288, 5359), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.contrib.llm.internal; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import javax.inject.Inject; import org.apache.hc.core5.http.HttpEntity; import org.xwiki.component.annotation.Component; import org.xwiki.component.annotation.InstantiationStrategy; import org.xwiki.component.descriptor.ComponentInstantiationStrategy; import org.xwiki.contrib.llm.ChatMessage; import org.xwiki.contrib.llm.ChatModel; import org.xwiki.contrib.llm.ChatRequest; import org.xwiki.contrib.llm.ChatResponse; import org.xwiki.contrib.llm.GPTAPIConfig; import org.xwiki.contrib.llm.RequestError; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.theokanning.openai.OpenAiResponse; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionResult; /** * Chat model implementation that uses the OpenAI API. * * @version $Id$ * @since 0.3 */ @Component(roles = { OpenAIChatModel.class }) @InstantiationStrategy(ComponentInstantiationStrategy.PER_LOOKUP) public class OpenAIChatModel implements ChatModel { @Inject private RequestHelper requestHelper; private GPTAPIConfig config; private String model; /** * Initialize the model. * * @param config the API configuration * @param model the model to use */ public void initialize(GPTAPIConfig config, String model) { this.config = config; this.model = model; } @Override public void processStreaming(ChatRequest request, Consumer<ChatResponse> consumer) throws RequestError { // TODO: Implement this once JAX-RS 2.1 with real streaming is available. For now, fall back to non-streaming. // With JAX-RS 2.1, use real streaming if the model supports it, otherwise fall back to non-streaming. consumer.accept(process(request)); } @Override public ChatResponse process(ChatRequest request) throws RequestError { List<com.theokanning.openai.completion.chat.ChatMessage> messages = request.getMessages().stream() .map(message -> new com.theokanning.openai.completion.chat.ChatMessage(message.getRole(), message.getContent())) .collect(Collectors.toList()); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .model(this.model) .temperature(request.getParameters().getTemperature()) .messages(messages) .build(); try { return this.requestHelper.post(this.config, "/chat/completions", chatCompletionRequest, response -> { if (response.getCode() == 200) { HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); ObjectMapper objectMapper = new ObjectMapper(); OpenAiResponse<ChatCompletionResult> modelOpenAiResponse = objectMapper.readValue(inputStream, new TypeReference<OpenAiResponse<ChatCompletionResult>>() { }); List<ChatCompletionChoice> chatCompletionChoices = modelOpenAiResponse.getData().get(0).getChoices(); ChatCompletionChoice chatCompletionChoice = chatCompletionChoices.get(0); com.theokanning.openai.completion.chat.ChatMessage resultMessage = chatCompletionChoice.getMessage(); return new ChatResponse(chatCompletionChoice.getFinishReason(), new ChatMessage(resultMessage.getRole(), resultMessage.getContent())); } else { throw new IOException("Response is empty."); } } else { throw new IOException("Response code is " + response.getCode()); } }); } catch (Exception e) { throw new RequestError(500, e.getMessage()); } /* // TODO: don't recreate the client every time. However, the client is also not thread-safe so we can't just // use a single client for all requests. We could use a thread-local client but that would require us to // handle cleanup, which is not trivial. An object pool might be a better solution. Client client = ClientBuilder.newClient(); Invocation.Builder completionRequest = client.target(config.getURL()) .path("chat/completions") .request(MediaType.APPLICATION_JSON) .header(AUTHORIZATION, BEARER + config.getToken()); GenericType<OpenAiResponse<ChatCompletionResult>> chatCompletionResponseType = new GenericType<>() { }; try { // TODO: change this to use jax-rs 2.0 where we can get a response object and then read different types // of entities depending on the success/error. OpenAiResponse<ChatCompletionResult> modelOpenAiResponse = completionRequest.post(Entity.entity(chatCompletionRequest, MediaType.APPLICATION_JSON_TYPE), chatCompletionResponseType); // TODO: Better error handling. List<ChatCompletionChoice> chatCompletionChoices = modelOpenAiResponse.getData().get(0).getChoices(); ChatCompletionChoice chatCompletionChoice = chatCompletionChoices.get(0); com.theokanning.openai.completion.chat.ChatMessage resultMessage = chatCompletionChoice.getMessage(); return new ChatResponse(chatCompletionChoice.getFinishReason(), new ChatMessage(resultMessage.getRole(), resultMessage.getContent())); } catch (WebApplicationException e) { throw new RequestError(e.getResponse().getStatus(), e.getMessage()); } */ } @Override public boolean supportsStreaming() { return this.config.getCanStream(); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((3439, 3621), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3439, 3600), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3439, 3568), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3439, 3501), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package com.timoxino.interview.tamer.service; import java.util.Arrays; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionResult; import com.theokanning.openai.completion.chat.ChatMessage; import lombok.extern.slf4j.Slf4j; @Slf4j @Service public class OpenAiService implements CompletionService { final static String PROMPT_TEMPLATE_EVALUATE_SENIORITY_LEVEL = """ Identify seniority level of the candidate \ applying for the technical role of {role} \ with the following CV delimited with triple backticks.\ Seniority levels can be determined based on number of java frameworks mentioned \ and years of experience and can be the following: 1. Junior 2. Middle 3. Senior 4. Lead Provide a single-digit answer that corresponds to the level identified. CV: '''{cv}''' """; final static String PROMPT_TEMPLATE_DETECT_SKILLS = """ Identify key technical skills which the following CV has \ for the role of {role} \ in the following CV delimited with triple backticks. \ Provide the list of skill names only separated by comma. \ CV: '''{cv}''' """; @Autowired com.theokanning.openai.service.OpenAiService openAiClient; @Override public Integer evaluateSeniorityLevel(String cv, String role) { String prompt = PROMPT_TEMPLATE_EVALUATE_SENIORITY_LEVEL.replace("{role}", role).replace("{cv}", cv); return Integer.valueOf(initiateCompletion(prompt)); } @Override public List<String> detectSkills(String cv, String role) { String prompt = PROMPT_TEMPLATE_DETECT_SKILLS.replace("{role}", role).replace("{cv}", cv); return Arrays.asList(initiateCompletion(prompt).split(",")); } private String initiateCompletion(String prompt) { log.info("Completion initiation for the prompt '{}'", prompt); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder().model("gpt-3.5-turbo") .temperature(0.0).n(1).messages(Arrays.asList(new ChatMessage("user", prompt))) .build(); log.info("Completion request created"); ChatCompletionResult completion = openAiClient.createChatCompletion(chatCompletionRequest); log.info("Completion finished"); return completion.getChoices().get(0).getMessage().getContent(); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((2260, 2435), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2260, 2410), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2260, 2353), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2260, 2348), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2260, 2314), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package br.com.lucasts.screenmatch.service; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; public class ConsultaChatGPT { public static String obterTraducao(String texto) { OpenAiService service = new OpenAiService(System.getenv("OPENAI_APIKEY")); CompletionRequest requisicao = CompletionRequest.builder() .model("gpt-3.5-turbo") .prompt("traduza para o português o texto: " + texto) .maxTokens(1000) .temperature(0.7) .build(); var resposta = service.createCompletion(requisicao); return resposta.getChoices().get(0).getText(); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((369, 599), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((369, 574), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((369, 540), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((369, 507), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((369, 436), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package br.com.danilo.ecommerce; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.time.Duration; import java.util.Arrays; import java.util.stream.Collectors; // --> Analisador de Sentimentos de Avaliações de Produtos public class FeelingsAnalysis { public static void main(String[] args) { try { var promptSystem = """ Você é um analisador de sentimentos de avaliações de produtos. Escreva um parágrafo com até 50 palavras resumindo as avaliações e depois atribua qual o sentimento geral para o produto. Identifique também 3 pontos fortes e 3 pontos fracos identificados a partir das avaliações. #### Formato de saída Nome do produto: Resumo das avaliações: [resuma em até 50 palavras] Sentimento geral: [deve ser: POSITIVO, NEUTRO ou NEGATIVO] Pontos fortes: [3 bullets points] Pontos fracos: [3 bullets points] """; var productDirectory = Path.of("src/main/resources/customerReviews/"); // --> Diretório dos produtos var userReviewFiles = Files .walk(productDirectory, 1) .filter(path -> path.toString().endsWith(".txt")) .collect(Collectors.toList()); for (Path file : userReviewFiles) { System.out.println(" Iniciando análise do produto: | Starting product analysis: " + file.getFileName()); // --> Imprime o nome do arquivo var promptUser = loadFileReviews(file); String modelOpenAI = "gpt-3.5-turbo"; // --> Modelo do OpenAI a ser utilizado var request = ChatCompletionRequest .builder() .model(modelOpenAI) // --> Modelo do OpenAI a ser utilizado .messages(Arrays.asList( new ChatMessage( ChatMessageRole.SYSTEM.value(), promptSystem), new ChatMessage( ChatMessageRole.USER.value(), promptUser))) .build(); var keyToken = System.getenv("OPENAI_API_KEY"); var serviceOpenAI = new OpenAiService(keyToken, Duration.ofSeconds(60)); var answers = serviceOpenAI .createChatCompletion(request) .getChoices().get(0).getMessage().getContent(); saveCustomerAnalysis(file.getFileName().toString(). // --> Salvar somente o nome do arquivo replace(".txt", ""), // --> Remover o .txt do nome do arquivo answers); System.out.println(" Analise Finalizada | Analysis Finished" + "\n"); } } catch (Exception errorWhenParsingFiles) { System.out.println("Erro ao analisar o produto! | Error analyzing product!"); } } // --> Carrega os clientes do arquivo private static String loadFileReviews(Path file) { try { return Files.readAllLines(file).toString(); } catch (Exception errorLoadFile) { throw new RuntimeException("Erro ao carregar o arquivo! | Error loading file!", errorLoadFile); } } // --> Salva a análise do produto private static void saveCustomerAnalysis(String file, String analise) { try { var path = Path.of("src/main/resources/savedCustomerReviews" + file + ".txt"); Files.writeString(path, analise, StandardOpenOption.CREATE_NEW); } catch (Exception errorSaveAnalysis) { throw new RuntimeException("Erro ao salvar o arquivo! | Error saving file!", errorSaveAnalysis); } } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((2477, 2507), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((2653, 2681), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((3762, 3797), 'java.nio.file.Files.readAllLines')]
package br.com.rodrigo.screenmatch.service; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; public class ChatGPTQuery { public static String getTranslation(String texto) { OpenAiService service = new OpenAiService(System.getenv("OPENAI_API_KEY")); CompletionRequest request = CompletionRequest.builder() .model("text-davinci-003") .prompt("traduza para o português o texto: " + texto) .maxTokens(1000) .temperature(0.7) .build(); var response = service.createCompletion(request); return response.getChoices().get(0).getText(); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((364, 597), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((364, 572), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((364, 538), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((364, 505), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((364, 434), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package com.jentsch.voicegpt; import static com.jentsch.voicegpt.SettingsActivity.MAX_TOKENS; import static com.jentsch.voicegpt.SettingsActivity.OPENAI_API_KEY; import android.content.Context; import android.content.SharedPreferences; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatCompletionChunk; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.service.OpenAiService; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import io.reactivex.functions.Consumer; public class OpenAI { public static synchronized void doAsyncChatCompletionRequest(SharedPreferences prefs, List<ChatMessage> messages, ChatCompletionChunkResponseListener listener) { String token = prefs.getString(OPENAI_API_KEY, null); int maxTokens = prefs.getInt(MAX_TOKENS, 500); Thread t = new Thread() { @Override public void run() { try { ArrayList<ChatCompletionChunk> chatCompletionChunks = OpenAI.doChatCompletionRequest(token, maxTokens, messages); if (listener != null) { String content = ""; for (ChatCompletionChunk chatCompletionChunk : chatCompletionChunks) { List<ChatCompletionChoice> choices = chatCompletionChunk.getChoices(); if (choices != null) { ChatCompletionChoice choice = choices.get(0); if (choice != null) { ChatMessage message = choice.getMessage(); if (message != null) { if (message.getContent() != null) { content += message.getContent(); } } } } } listener.publishResponse (content); } } catch (Exception e) { if (listener != null) { listener.publishResponse (e.getMessage()); } } } }; t.start(); } private static ArrayList<ChatCompletionChunk> doChatCompletionRequest(String token, int maxTokens, List<ChatMessage> messages) { ArrayList<ChatCompletionChunk> ret = new ArrayList<>(); OpenAiService service = new OpenAiService(token); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .model("gpt-3.5-turbo") .messages(messages) .maxTokens(maxTokens) .temperature(0.8) .logitBias(new HashMap<>()) .n(1) .build(); Consumer<? super ChatCompletionChunk> appendResult = new Consumer<ChatCompletionChunk>() { @Override public void accept(ChatCompletionChunk chatCompletionChunk) throws Exception { ret.add(chatCompletionChunk); } }; service.streamChatCompletion(chatCompletionRequest) .doOnError(Throwable::printStackTrace) .blockingForEach(appendResult); service.shutdownExecutor(); return ret; } public interface ChatCompletionChunkResponseListener { void publishResponse(String content); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((2794, 3064), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2794, 3039), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2794, 3017), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2794, 2973), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2794, 2939), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2794, 2901), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2794, 2865), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package org.wishlistapp.client; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; import io.github.cdimascio.dotenv.Dotenv; import org.springframework.stereotype.Component; @Component public class AiClient { private final OpenAiService client; public AiClient() { String secretKey = getTheKey(); client = new OpenAiService(secretKey); } private String getTheKey() throws IllegalStateException { Dotenv dotenv = Dotenv.load(); // Retrieve the secret key String secretKey = dotenv.get("OPENAI_SECRET_KEY"); if (secretKey == null || secretKey.isEmpty()) { throw new IllegalStateException("OPENAI_SECRET_KEY is not set in the .env file."); } return secretKey; } public String getResponse(String prompt) { String instructions = "Find a suitable title for the product described in provided comments. Keep it short. Use simple words. If it's a book, then book title is enough. If it's vacation somewhere, just 'Vacation in Somewhere'. If it's a piece of clothing, then type and color as title are enough, etc.\n"; String complete_prompt = instructions + "COMMENTS: " + prompt; CompletionRequest completionRequest = CompletionRequest.builder() .prompt(complete_prompt) .model("gpt-3.5-turbo-instruct") .maxTokens(64) .build(); StringBuilder response = new StringBuilder(); client.createCompletion(completionRequest).getChoices().forEach(choice -> { response.append(choice.getText()); }); return response.toString().strip(); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((1301, 1474), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1449), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1418), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1369), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package ru.itzstonlex.desktop.chatbotmessenger.form.feed.controller; import com.theokanning.openai.OpenAiService; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.completion.CompletionResult; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import lombok.Getter; import lombok.NonNull; import lombok.SneakyThrows; import ru.itzstonlex.desktop.chatbotmessenger.api.chatbot.ChatBotAssistant; import ru.itzstonlex.desktop.chatbotmessenger.api.chatbot.type.request.ChatBotRequest; import ru.itzstonlex.desktop.chatbotmessenger.api.form.AbstractSceneForm; import ru.itzstonlex.desktop.chatbotmessenger.api.form.ApplicationFormKeys; import ru.itzstonlex.desktop.chatbotmessenger.api.form.controller.AbstractComponentController; import ru.itzstonlex.desktop.chatbotmessenger.api.form.observer.ObserveBy; import ru.itzstonlex.desktop.chatbotmessenger.form.feed.FeedForm; import ru.itzstonlex.desktop.chatbotmessenger.form.feed.controller.ChatBotHeaderController.TypingStatus; import ru.itzstonlex.desktop.chatbotmessenger.form.feed.function.FeedFormFunctionReleaser; import ru.itzstonlex.desktop.chatbotmessenger.form.feed.view.FeedFormFrontView; import ru.itzstonlex.desktop.chatbotmessenger.form.feed.view.FeedFormFrontViewConfiguration; import ru.itzstonlex.desktop.chatbotmessenger.form.message.MessageForm; import ru.itzstonlex.desktop.chatbotmessenger.form.message.function.MessageFormFunctionReleaser.SenderType; import ru.itzstonlex.desktop.chatbotmessenger.observer.FooterButtonSendClickObserver; import ru.itzstonlex.desktop.chatbotmessenger.observer.FooterMessageInputEnterObserver; public final class BothMessagesReceiveController extends AbstractComponentController<FeedForm> { @ObserveBy(FooterMessageInputEnterObserver.class) private TextField inputMessageField; @ObserveBy(FooterButtonSendClickObserver.class) private Button messageSendButton; @Getter private final List<Node> messageNodesList = new ArrayList<>(); @Getter private final ChatBotAssistant chatBotAssistant; public BothMessagesReceiveController(FeedForm form, ChatBotAssistant chatBotAssistant) { super(form); this.chatBotAssistant = chatBotAssistant; } @Override protected void configureController() { this.inputMessageField = getForm().getView().find(FeedFormFrontViewConfiguration.INPUT_MESSAGE_FIELD); this.messageSendButton = getForm().getView().find(FeedFormFrontViewConfiguration.MESSAGE_SEND_BUTTON); } private String reformatMessage(String text) { return text.replace("<br>", "\n"); } private final OpenAiService chatGPT = new OpenAiService("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", 5); public void onMessageReceive(@NonNull String receivedMessage) { ChatBotHeaderController chatBotHeaderController = getForm().getController(ChatBotHeaderController.class); // send question fireFunction(FeedFormFunctionReleaser.SEND, receivedMessage); chatBotHeaderController.setTypingStatus(TypingStatus.TYPING); // send answer CompletableFuture.supplyAsync(() -> chatGPT.createCompletion(CompletionRequest.builder() .model("text-davinci-003") .prompt(receivedMessage) .temperature(0.9) .maxTokens(500) .topP(1.0) .frequencyPenalty(0.0) .presencePenalty(0.6) .build())) .whenCompleteAsync((completionResult, error) -> fireFunction(FeedFormFunctionReleaser.REPLY, completionResult.getChoices().get(0).getText())); // ChatBotRequest chatBotRequest = new ChatBotRequest(receivedMessage); // chatBotAssistant.requestBestSuggestion(chatBotRequest) // .thenAccept(response -> fireFunction(FeedFormFunctionReleaser.REPLY, response.getMessageText())); // hide suggestions. FooterSuggestionsController footerSuggestionsController = getForm().getController(FooterSuggestionsController.class); footerSuggestionsController.setSuggestionsVisible(false); } @SneakyThrows private Node createMessageNode(SenderType senderType, String msg) { AbstractSceneForm<?> messageForm = getForm().getSceneLoader() .loadUncachedForm(ApplicationFormKeys.MESSAGE); // todo - replace to function MessageFormFunctionReleaser.UPDATE_MESSAGE_TEXT ((MessageForm) messageForm).updateMessageText(senderType, msg); return messageForm.getJavafxNode(); } private void addMessageChildren(ObservableList<Node> childrenList, Node messageNode) { FeedFormFrontView view = getForm().getView(); Node wrappedMessageNode = view.createWrappedMessageNode(messageNode); childrenList.add(wrappedMessageNode); childrenList.add(view.createMessageEmptySeparator(10)); messageNodesList.add(wrappedMessageNode); } public void addMessage(SenderType senderType, String text) { VBox messagesBox = getForm().getView().find(FeedFormFrontViewConfiguration.MESSAGES_DISPLAY_BOX); Node messageNode = createMessageNode(senderType, reformatMessage(text)); addMessageChildren(messagesBox.getChildren(), messageNode); AnchorPane noMessagesPanel = getForm().getView().find(FeedFormFrontViewConfiguration.NO_MESSAGES_PANEL); if (noMessagesPanel.isVisible()) { noMessagesPanel.setVisible(false); } } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((3303, 3802), 'java.util.concurrent.CompletableFuture.supplyAsync'), ((3364, 3638), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3364, 3617), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3364, 3583), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3364, 3548), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3364, 3525), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3364, 3497), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3364, 3467), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3364, 3430), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package com.springboot.chatgptbot.config.bot; import com.springboot.chatgptbot.domain.Ticket; import com.springboot.chatgptbot.service.LogService; import com.springboot.chatgptbot.service.TicketService; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.methods.commands.SetMyCommands; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.*; import org.telegram.telegrambots.meta.api.objects.commands.BotCommand; import org.telegram.telegrambots.meta.api.objects.commands.scope.BotCommandScopeDefault; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @Component @Slf4j public class TelegramBot extends TelegramLongPollingBot { private final TicketService ticketService; private final LogService logService; private final TelegramBotConfig config; private boolean waitingForQuestion = false; private long waitingChatId; private String waitingUserName; public TelegramBot(TelegramBotConfig config, LogService logService, TicketService ticketService) { this.config = config; this.logService = logService; this.ticketService = ticketService; List<BotCommand> listOfCommands = new ArrayList<>(); listOfCommands.add(new BotCommand("/start", "Nice to meet you.")); listOfCommands.add(new BotCommand("/help", "Ask questions.")); try { this.execute(new SetMyCommands(listOfCommands, new BotCommandScopeDefault(), null)); } catch (TelegramApiException e) { log.error(Arrays.toString(e.getStackTrace())); } } @Override public void onUpdateReceived(Update update) { if (update.hasMessage() && update.getMessage().hasText()) { long chatId = update.getMessage().getChatId(); String messageText = update.getMessage().getText(); if (waitingForQuestion && chatId == waitingChatId) { answerAfterQuestion(update); } else if (messageText.equals("/help")) { sendMessage("What is your question?", chatId); waitingForQuestion = true; waitingChatId = chatId; waitingUserName = update.getMessage().getFrom().getUserName(); } else { handleUserMessage(update); } } } private void answerAfterQuestion(Update update) { String userQuestion = update.getMessage().getText(); sendMessage("Wait, they will answer you soon.", waitingChatId); LocalDateTime timestamp = LocalDateTime.now(); saveTicket(waitingUserName, userQuestion, timestamp, waitingChatId); waitingForQuestion = false; } public void sendSyncMessage(String textToSend, long chatId) { SendMessage message = new SendMessage(); message.setChatId(String.valueOf(chatId)); if (!textToSend.isEmpty()) { message.setText(textToSend); } try { execute(message); } catch (TelegramApiException e) { log.error("Error sending message: {}", e.getMessage()); } } public void saveAnswerToTicket(Long ticketId, String answer, Long chatId) { ticketService.saveAnswer(ticketId, answer, chatId); sendMessageToTicketOwner(ticketId, answer); } private void sendMessageToTicketOwner(Long ticketId, String answer) { Ticket ticket = ticketService.findByTicketId(ticketId); if (ticket != null) { long userChatId = ticket.getChatId(); if (answer != null && !answer.isEmpty()) { sendSyncMessage(answer, userChatId); } else { sendSyncMessage("Sorry, the answer to this question is not ready yet.", userChatId); } } else { log.error("Ticket not found for ID: {}", ticketId); } } private void handleUserMessage(Update update) { Message message = update.getMessage(); if (message != null && message.hasText()) { String userMessage = message.getText(); long chatId = message.getChatId(); String botResponse = generateBotResponse(userMessage); saveLog(update.getMessage().getFrom().getUserName(), userMessage, botResponse); sendMessage(botResponse, chatId); } } private void saveLog(String username, String message, String botResponse) { LocalDateTime timestamp = LocalDateTime.now(); logService.saveLog(username, message, botResponse, timestamp); } public void saveTicket(String username, String question, LocalDateTime timestamp, Long chatId) { Ticket ticket = new Ticket(username, question, timestamp); ticket.setChatId(chatId); ticketService.saveTicket(ticket); } private String generateBotResponse(String userMessage) { OpenAiService service = new OpenAiService("your-openai-token"); CompletionRequest completionRequest = CompletionRequest.builder() .prompt(userMessage) .model("text-davinci-003") .maxTokens(255) .build(); return service.createCompletion(completionRequest).getChoices().get(0).getText(); } private void sendMessage(String textToSend, long chatId) { SendMessage message = new SendMessage(); message.setChatId(String.valueOf(chatId)); if (!textToSend.isEmpty()) { message.setText(textToSend); } send(message); } private void send(SendMessage sendMessage) { try { execute(sendMessage); } catch (TelegramApiException e) { log.error(Arrays.toString(e.getStackTrace())); } } @Override public String getBotUsername() { return config.getBotUsername(); } @Override public String getBotToken() { return config.getBotToken(); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((5383, 5547), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((5383, 5522), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((5383, 5490), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((5383, 5447), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package com.erzbir.numeron.plugin.openai.config; import com.erzbir.numeron.api.NumeronImpl; import com.erzbir.numeron.utils.ConfigReadException; import com.erzbir.numeron.utils.ConfigWriteException; import com.erzbir.numeron.utils.JsonUtil; import com.theokanning.openai.completion.CompletionRequest; import java.io.Serializable; import java.util.List; import java.util.Map; /** * @author Erzbir * @Date: 2023/3/3 23:52 */ public class CompletionConfig implements Serializable { private static final Object key = new Object(); private static final String configFile = NumeronImpl.INSTANCE.getPluginWorkDir() + "chatgpt/config/completion.json"; private static volatile CompletionConfig INSTANCE; private String model = "text-davinci-003"; private int max_tokens = 1024; private double temperature = 1.0; private double top_p = 1.0; private double presence_penalty = 0.0; private double frequency_penalty = 0.0; private int number = 1; private boolean echo = false; private List<String> stop = null; private int best_of = 1; private Map<String, Integer> logit_bias = null; private String suffix = null; private CompletionConfig() { } public static CompletionConfig getInstance() { if (INSTANCE == null) { synchronized (key) { if (INSTANCE == null) { try { INSTANCE = JsonUtil.load(configFile, CompletionConfig.class); } catch (ConfigReadException e) { throw new RuntimeException(e); } } } } if (INSTANCE == null) { synchronized (key) { if (INSTANCE == null) { INSTANCE = new CompletionConfig(); try { JsonUtil.dump(configFile, INSTANCE, CompletionConfig.class); } catch (ConfigWriteException e) { throw new RuntimeException(e); } } } } return INSTANCE; } public CompletionRequest load() { return CompletionRequest.builder() .maxTokens(max_tokens) .model(model) .n(number) .presencePenalty(presence_penalty) .topP(top_p) .frequencyPenalty(frequency_penalty) .bestOf(best_of) .logitBias(logit_bias) .suffix(suffix) .echo(echo) .suffix(suffix) .stop(stop) .build(); } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public int getMax_tokens() { return max_tokens; } public void setMax_tokens(int max_tokens) { this.max_tokens = max_tokens; } public double getTemperature() { return temperature; } public void setTemperature(double temperature) { this.temperature = temperature; } public double getTop_p() { return top_p; } public void setTop_p(double top_p) { this.top_p = top_p; } public double getPresence_penalty() { return presence_penalty; } public void setPresence_penalty(double presence_penalty) { this.presence_penalty = presence_penalty; } public double getFrequency_penalty() { return frequency_penalty; } public void setFrequency_penalty(double frequency_penalty) { this.frequency_penalty = frequency_penalty; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public boolean isEcho() { return echo; } public void setEcho(boolean echo) { this.echo = echo; } public List<String> getStop() { return stop; } public void setStop(List<String> stop) { this.stop = stop; } public int getBest_of() { return best_of; } public void setBest_of(int best_of) { this.best_of = best_of; } public Map<String, Integer> getLogit_bias() { return logit_bias; } public void setLogit_bias(Map<String, Integer> logit_bias) { this.logit_bias = logit_bias; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((582, 621), 'com.erzbir.numeron.api.NumeronImpl.INSTANCE.getPluginWorkDir'), ((2180, 2653), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2628), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2600), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2568), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2540), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2508), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2469), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2436), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2383), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2354), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2303), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2276), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2180, 2246), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package com.theokanning.openai.service; import android.text.TextUtils; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.flyun.base.BaseMessage; import com.theokanning.openai.DeleteResult; import com.theokanning.openai.GoogleError; import com.theokanning.openai.GoogleHttpException; import com.theokanning.openai.OpenAiApi; import com.theokanning.openai.OpenAiError; import com.theokanning.openai.OpenAiHttpException; import com.theokanning.openai.completion.CompletionChunk; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.completion.CompletionResult; import com.theokanning.openai.completion.chat.ChatCompletionChunk; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionResult; import com.theokanning.openai.completion.chat.ChatGCompletionRequest; import com.theokanning.openai.completion.chat.ChatGCompletionResponse; import com.theokanning.openai.edit.EditRequest; import com.theokanning.openai.edit.EditResult; import com.theokanning.openai.embedding.EmbeddingRequest; import com.theokanning.openai.embedding.EmbeddingResult; import com.theokanning.openai.file.File; import com.theokanning.openai.finetune.FineTuneEvent; import com.theokanning.openai.finetune.FineTuneRequest; import com.theokanning.openai.finetune.FineTuneResult; import com.theokanning.openai.image.CreateImageEditRequest; import com.theokanning.openai.image.CreateImageRequest; import com.theokanning.openai.image.CreateImageVariationRequest; import com.theokanning.openai.image.ImageResult; import com.theokanning.openai.model.Model; import com.theokanning.openai.moderation.ModerationRequest; import com.theokanning.openai.moderation.ModerationResult; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.WeakHashMap; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.Single; import io.reactivex.SingleObserver; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import okhttp3.ConnectionPool; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; import retrofit2.HttpException; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.jackson.JacksonConverterFactory; public class OpenAiService { private static final String BASE_URL = "https://api.openai.com/"; private static final String BASE_GOOGLE_URL = "https://generativelanguage.googleapis.com/"; private static final long DEFAULT_TIMEOUT = 10; private static final ObjectMapper mapper = defaultObjectMapper(); private final OpenAiApi api; private OkHttpClient client; private final ExecutorService executorService; private final CompositeDisposable compositeDisposable = new CompositeDisposable(); private final WeakHashMap<String, Call<ResponseBody>> requestList = new WeakHashMap(); public final int listModels = 1; private boolean isGoogleUrl = false; private boolean isGoogleToken = false; /** * Creates a new OpenAiService that wraps OpenAiApi * * @param token OpenAi token string "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" */ public OpenAiService(final String token) { this(token, DEFAULT_TIMEOUT, BASE_URL, false); } /** * Creates a new OpenAiService that wraps OpenAiApi * * @param token OpenAi token string "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" * @param second http read timeout */ public OpenAiService(final String token, final long second, final String url, boolean isGoogle) { String baseUrl = (TextUtils.isEmpty(url) || HttpUrl.parse(url) == null) ? BASE_URL : url; ObjectMapper mapper = defaultObjectMapper(); this.client = defaultClient(token, second, url, isGoogle); this.executorService = client.dispatcher().executorService(); Retrofit retrofit = defaultRetrofit(client, mapper, baseUrl, this.executorService); this.api = retrofit.create(OpenAiApi.class); // 初始化isGoogle isGoogleToken = isGoogle; isGoogleUrl = isGoogle; } public void switchDefault(String token, String url) { if (isGoogleToken) { changeToken(token); } if (isGoogleUrl) { changeServer(url); } } public void switchGoogle(String token, String url) { if (!isGoogleToken) { changeTokenGoogle(token); } if (!isGoogleUrl) { changeServerGoogle(url); } } public void changeMatchToken(String token, String matchUrl) { if (!isGoogleUrl) { // Url为默认,不需要改变 changeToken(token); } else { // Url为google,需要Url和token一起改变 changeTokenAndServer(token, matchUrl); } } public void changeMatchServer(String url, String matchToken) { if (!isGoogleToken) { // token为默认,不需要改变 changeServer(url); } else { // token为google,需要token和Url一起改变 changeTokenAndServer(matchToken, url); } } public void changeMatchTokenGoogle(String token, String matchUrl) { if (isGoogleUrl) { // Url为Google,不需要改变 changeTokenGoogle(token); } else { // Url为默认,需要Url和token一起改变 changeTokenAndServerGoogle(token, matchUrl); } } public void changeMatchServerGoogle(String url, String matchToken) { if (isGoogleToken) { // token为Google,不需要改变 changeServerGoogle(url); } else { // token为默认,需要token和Url一起改变 changeTokenAndServerGoogle(matchToken, url); } } public void changeToken(String token) { if (client != null && token != null) { for (Interceptor interceptor : client.interceptors()) { if (interceptor instanceof AuthenticationInterceptor) { isGoogleToken = false; ((AuthenticationInterceptor) interceptor).setToken(token); ((AuthenticationInterceptor) interceptor).setGoogle(isGoogle()); } } } } public void changeServer(String url) { if (client != null && !TextUtils.isEmpty(url)) { for (Interceptor interceptor : client.interceptors()) { if (interceptor instanceof AuthenticationInterceptor) { isGoogleUrl = false; ((AuthenticationInterceptor) interceptor).setUrl(url); ((AuthenticationInterceptor) interceptor).setGoogle(isGoogle()); } } } } public void changeTokenAndServer(String token, String url) { if (client != null && !TextUtils.isEmpty(token) && !TextUtils.isEmpty(url)) { for (Interceptor interceptor : client.interceptors()) { if (interceptor instanceof AuthenticationInterceptor) { isGoogleUrl = false; ((AuthenticationInterceptor) interceptor).setToken(token); ((AuthenticationInterceptor) interceptor).setUrl(url); ((AuthenticationInterceptor) interceptor).setGoogle(isGoogle()); } } } } public void changeTokenGoogle(String token) { if (client != null && token != null) { for (Interceptor interceptor : client.interceptors()) { if (interceptor instanceof AuthenticationInterceptor) { isGoogleToken = true; ((AuthenticationInterceptor) interceptor).setToken(token); ((AuthenticationInterceptor) interceptor).setGoogle(isGoogle()); } } } } public void changeServerGoogle(String url) { if (client != null && !TextUtils.isEmpty(url)) { for (Interceptor interceptor : client.interceptors()) { if (interceptor instanceof AuthenticationInterceptor) { isGoogleUrl = true; ((AuthenticationInterceptor) interceptor).setUrl(url); ((AuthenticationInterceptor) interceptor).setGoogle(isGoogle()); } } } } public void changeTokenAndServerGoogle(String token, String url) { if (client != null && !TextUtils.isEmpty(token) && !TextUtils.isEmpty(url)) { for (Interceptor interceptor : client.interceptors()) { if (interceptor instanceof AuthenticationInterceptor) { isGoogleUrl = false; ((AuthenticationInterceptor) interceptor).setToken(token); ((AuthenticationInterceptor) interceptor).setUrl(url); ((AuthenticationInterceptor) interceptor).setGoogle(isGoogle()); } } } } // url与token必须绑定 public boolean isGoogle() { if (isGoogleUrl && isGoogleToken) return true; if (!isGoogleUrl && !isGoogleToken) return false; // Url与token不匹配,抛出异常 System.out.print("URL does not match token isUrl:" + isGoogleUrl + "isToken:" + isGoogleToken); return false; } /** * Creates a new OpenAiService that wraps OpenAiApi. * Use this if you need more customization, but use OpenAiService(api, executorService) if * you use streaming and * want to shut down instantly * * @param api OpenAiApi instance to use for all methods */ public OpenAiService(final OpenAiApi api) { this.api = api; this.executorService = null; } /** * Creates a new OpenAiService that wraps OpenAiApi. * The ExecutorService must be the one you get from the client you created the api with * otherwise shutdownExecutor() won't work. * <p> * Use this if you need more customization. * * @param api OpenAiApi instance to use for all methods * @param executorService the ExecutorService from client.dispatcher().executorService() */ public OpenAiService(final OpenAiApi api, final ExecutorService executorService) { this.api = api; this.executorService = executorService; } public List<Model> listModels() { return execute(api.listModels()).data; } public Model getModel(String modelId) { return execute(api.getModel(modelId)); } public CompletionResult createCompletion(CompletionRequest request) { return execute(api.createCompletion(request)); } public Flowable<CompletionChunk> streamCompletion(CompletionRequest request) { request.setStream(true); return stream(api.createCompletionStream(request), CompletionChunk.class); } public ChatCompletionResult createChatCompletion(ChatCompletionRequest request) { return execute(api.createChatCompletion(request)); } public void createChatCompletion(ChatCompletionRequest request, final BaseMessage baseMessage , final ResultCallBack callBack) { createChatCompletion(api.createChatCompletion(request), baseMessage, callBack); } public void createChatGCompletion(ChatGCompletionRequest request, String model, final BaseMessage baseMessage, final ResultGCallBack callBack) { createChatGCompletion(api.createGChatCompletion(model, request), baseMessage, callBack); } public Flowable<ChatCompletionChunk> streamChatCompletion(ChatCompletionRequest request) { request.setStream(true); return stream(api.createChatCompletionStream(request), ChatCompletionChunk.class); } public EditResult createEdit(EditRequest request) { return execute(api.createEdit(request)); } public EmbeddingResult createEmbeddings(EmbeddingRequest request) { return execute(api.createEmbeddings(request)); } public List<File> listFiles() { return execute(api.listFiles()).data; } public File uploadFile(String purpose, String filepath) { java.io.File file = new java.io.File(filepath); RequestBody purposeBody = RequestBody.create(okhttp3.MultipartBody.FORM, purpose); RequestBody fileBody = RequestBody.create(MediaType.parse("text"), file); MultipartBody.Part body = MultipartBody.Part.createFormData("file", filepath, fileBody); return execute(api.uploadFile(purposeBody, body)); } public DeleteResult deleteFile(String fileId) { return execute(api.deleteFile(fileId)); } public File retrieveFile(String fileId) { return execute(api.retrieveFile(fileId)); } public FineTuneResult createFineTune(FineTuneRequest request) { return execute(api.createFineTune(request)); } public CompletionResult createFineTuneCompletion(CompletionRequest request) { return execute(api.createFineTuneCompletion(request)); } public List<FineTuneResult> listFineTunes() { return execute(api.listFineTunes()).data; } public FineTuneResult retrieveFineTune(String fineTuneId) { return execute(api.retrieveFineTune(fineTuneId)); } public FineTuneResult cancelFineTune(String fineTuneId) { return execute(api.cancelFineTune(fineTuneId)); } public List<FineTuneEvent> listFineTuneEvents(String fineTuneId) { return execute(api.listFineTuneEvents(fineTuneId)).data; } public DeleteResult deleteFineTune(String fineTuneId) { return execute(api.deleteFineTune(fineTuneId)); } public ImageResult createImage(CreateImageRequest request) { return execute(api.createImage(request)); } public ImageResult createImageEdit(CreateImageEditRequest request, String imagePath, String maskPath) { java.io.File image = new java.io.File(imagePath); java.io.File mask = null; if (maskPath != null) { mask = new java.io.File(maskPath); } return createImageEdit(request, image, mask); } public ImageResult createImageEdit(CreateImageEditRequest request, java.io.File image, java.io.File mask) { RequestBody imageBody = RequestBody.create(MediaType.parse("image"), image); MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MediaType.get("multipart/form-data")) .addFormDataPart("prompt", request.getPrompt()) .addFormDataPart("size", request.getSize()) .addFormDataPart("model", request.getModel()) .addFormDataPart("response_format", request.getResponseFormat()) .addFormDataPart("image", "image", imageBody); if (request.getN() != null) { builder.addFormDataPart("n", request.getN().toString()); } if (mask != null) { RequestBody maskBody = RequestBody.create(MediaType.parse("image"), mask); builder.addFormDataPart("mask", "mask", maskBody); } return execute(api.createImageEdit(builder.build())); } public ImageResult createImageVariation(CreateImageVariationRequest request, String imagePath) { java.io.File image = new java.io.File(imagePath); return createImageVariation(request, image); } public ImageResult createImageVariation(CreateImageVariationRequest request, java.io.File image) { RequestBody imageBody = RequestBody.create(MediaType.parse("image"), image); MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MediaType.get("multipart/form-data")) .addFormDataPart("size", request.getSize()) .addFormDataPart("model", request.getModel()) .addFormDataPart("response_format", request.getResponseFormat()) .addFormDataPart("image", "image", imageBody); if (request.getN() != null) { builder.addFormDataPart("n", request.getN().toString()); } return execute(api.createImageVariation(builder.build())); } public ModerationResult createModeration(ModerationRequest request) { return execute(api.createModeration(request)); } /** * Calls the Open AI api, returns the response, and parses error messages if the request fails */ public static <T> T execute(Single<T> apiCall) { try { return apiCall.blockingGet(); } catch (HttpException e) { try { if (e.response() == null || e.response().errorBody() == null) { throw e; } String errorBody = e.response().errorBody().string(); OpenAiError error = mapper.readValue(errorBody, OpenAiError.class); throw new OpenAiHttpException(error, e, e.code()); } catch (IOException ex) { // couldn't parse OpenAI error throw e; } } } public void loading(ResultCallBack resultCallBack) { Observable.interval(0, 5, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Long>() { @Override public void onSubscribe(@NonNull Disposable d) { compositeDisposable.add(d); } @Override public void onNext(@NonNull Long aLong) { resultCallBack.onLoading(true); } @Override public void onError(@NonNull Throwable e) { } @Override public void onComplete() { } }); } public void loadingG(ResultGCallBack resultCallBack) { Observable.interval(0, 5, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Long>() { @Override public void onSubscribe(@NonNull Disposable d) { compositeDisposable.add(d); } @Override public void onNext(@NonNull Long aLong) { resultCallBack.onLoading(true); } @Override public void onError(@NonNull Throwable e) { } @Override public void onComplete() { } }); } private Disposable streamLoadingDisposable; public void loading(StreamCallBack streamCallBack) { Observable.interval(0, 5, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Long>() { @Override public void onSubscribe(@NonNull Disposable d) { streamLoadingDisposable = d; compositeDisposable.add(d); } @Override public void onNext(@NonNull Long aLong) { if (isStreamFirstLoading) { if (streamCallBack != null) streamCallBack.onLoading(true); } else { if (streamLoadingDisposable != null) { compositeDisposable.remove(streamLoadingDisposable); } } } @Override public void onError(@NonNull Throwable e) { if (streamLoadingDisposable != null) { compositeDisposable.remove(streamLoadingDisposable); } } @Override public void onComplete() { } }); } public void loadingG(StreamGCallBack streamCallBack) { Observable.interval(0, 5, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Long>() { @Override public void onSubscribe(@NonNull Disposable d) { streamLoadingDisposable = d; compositeDisposable.add(d); } @Override public void onNext(@NonNull Long aLong) { if (isStreamFirstLoading) { if (streamGCallBack != null) streamGCallBack.onLoading(true); } else { if (streamLoadingDisposable != null) { compositeDisposable.remove(streamLoadingDisposable); } } } @Override public void onError(@NonNull Throwable e) { if (streamLoadingDisposable != null) { compositeDisposable.remove(streamLoadingDisposable); } } @Override public void onComplete() { } }); } public <T> void baseCompletion(int type, CompletionCallBack<T> callBack) { sortCompletion(type, null, callBack); } public <T> void sortCompletion(int type, CompletionRequest completionRequest, CompletionCallBack<T> callBack) { switch (type) { case listModels: { createCompletion(api.listModels(), callBack); } } } public <T> void createCompletion(Single<T> apiCall, CompletionCallBack<?> callBack) { compositeDisposable.clear(); apiCall .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe((new SingleObserver<T>() { @Override public void onSubscribe(@NonNull Disposable disposable) { } @Override public void onSuccess(@NonNull T t) { callBack.onSuccess(t); compositeDisposable.clear(); } @Override public void onError(@NonNull Throwable throwable) { HttpException e; if (throwable instanceof HttpException) { e = (HttpException) throwable; } else { callBack.onError(null, throwable); return; } try { if (e.response() == null || e.response().errorBody() == null) { callBack.onError(null, throwable); } else { String errorBody = e.response().errorBody().string(); OpenAiError error = mapper.readValue(errorBody, OpenAiError.class); callBack.onError(new OpenAiHttpException(error, e, e.code()), throwable); } } catch (IOException ex) { // couldn't parse OpenAI error callBack.onError(null, throwable); } finally { compositeDisposable.clear(); } } })); } public <T> void createChatCompletion(Single<T> apiCall, BaseMessage baseMessage, ResultCallBack resultCallBack) { compositeDisposable.clear(); apiCall .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe((new SingleObserver<T>() { @Override public void onSubscribe(@NonNull Disposable disposable) { compositeDisposable.add(disposable); loading(resultCallBack); } @Override public void onSuccess(@NonNull T t) { resultCallBack.onSuccess((ChatCompletionResult) t); resultCallBack.onLoading(false); compositeDisposable.clear(); } @Override public void onError(@NonNull Throwable throwable) { HttpException e; if (throwable instanceof HttpException) { e = (HttpException) throwable; } else { resultCallBack.onError(null, throwable); resultCallBack.onLoading(false); compositeDisposable.clear(); return; } try { if (e.response() == null || e.response().errorBody() == null) { resultCallBack.onError(null, throwable); } else { String errorBody = e.response().errorBody().string(); OpenAiError error = mapper.readValue(errorBody, OpenAiError.class); resultCallBack.onError(new OpenAiHttpException(error, e, e.code()), throwable); } } catch (IOException ex) { // couldn't parse OpenAI error resultCallBack.onError(null, throwable); } finally { resultCallBack.onLoading(false); compositeDisposable.clear(); } } })); } public <T> void createChatGCompletion(Single<T> apiCall, BaseMessage baseMessage, ResultGCallBack resultCallBack) { compositeDisposable.clear(); apiCall .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe((new SingleObserver<T>() { @Override public void onSubscribe(@NonNull Disposable disposable) { compositeDisposable.add(disposable); loadingG(resultCallBack); } @Override public void onSuccess(@NonNull T t) { resultCallBack.onSuccess((ChatGCompletionResponse) t); resultCallBack.onLoading(false); compositeDisposable.clear(); } @Override public void onError(@NonNull Throwable throwable) { HttpException e; if (throwable instanceof HttpException) { e = (HttpException) throwable; } else { resultCallBack.onError(null, throwable); resultCallBack.onLoading(false); compositeDisposable.clear(); return; } try { if (e.response() == null || e.response().errorBody() == null) { resultCallBack.onError(null, throwable); } else { String errorBody = e.response().errorBody().string(); GoogleError error = mapper.readValue(errorBody, GoogleError.class); resultCallBack.onError(new GoogleHttpException(error,throwable), throwable); } } catch (IOException ex) { // couldn't parse OpenAI error resultCallBack.onError(null, throwable); } finally { resultCallBack.onLoading(false); compositeDisposable.clear(); } } })); } private volatile boolean isStreamFirstLoading; private StreamCallBack streamCallBack; public void streamChatCompletion(ChatCompletionRequest request, StreamCallBack callBack) { request.setStream(true); isStreamFirstLoading = true; loading(callBack); //因为on在取消stream请求的问题(具体看ResponseBodyCallback),无法执行onCompletion,所以需要折中调用onCompletion streamCallBack = callBack; Call<ResponseBody> apiCall = api.createChatCompletionStream(request); Disposable disposable = stream(apiCall, ChatCompletionChunk.class) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.io()) .forEachWhile(chatCompletionChunk -> { if (isStreamFirstLoading) { isStreamFirstLoading = false; if (streamCallBack != null) streamCallBack.onLoading(false); } if (streamCallBack != null) streamCallBack.onSuccess(chatCompletionChunk); //返回true代表继续回调,false代表执行完成回调 return chatCompletionChunk.getChoices() == null || chatCompletionChunk.getChoices().size() <= 0 || chatCompletionChunk.getChoices().get(0).getFinishReason() == null; }, throwable -> { HttpException e; if (throwable instanceof HttpException) { e = (HttpException) throwable; } else { if (streamCallBack != null) streamCallBack.onError(null, throwable); if (streamCallBack != null) streamCallBack.onLoading(false); streamCallBack = null; compositeDisposable.clear(); return; } try { if (e.response() == null || e.response().errorBody() == null) { if (streamCallBack != null) streamCallBack.onError(null, throwable); } else { String errorBody = e.response().errorBody().string(); OpenAiError error = mapper.readValue(errorBody, OpenAiError.class); if (streamCallBack != null) streamCallBack.onError(new OpenAiHttpException(error, e, e.code()), throwable); } } catch (IOException ex) { // couldn't parse OpenAI error if (streamCallBack != null) streamCallBack.onError(null, throwable); } finally { if (streamCallBack != null) streamCallBack.onLoading(false); streamCallBack = null; compositeDisposable.clear(); } }, () -> { if (streamCallBack != null) streamCallBack.onCompletion(); streamCallBack = null; compositeDisposable.clear(); }); compositeDisposable.add(disposable); requestList.put("streamChatCompletion", apiCall); } private StreamGCallBack streamGCallBack; public void streamChatGCompletion(ChatGCompletionRequest request, String model, StreamGCallBack callBack) { isStreamFirstLoading = true; loadingG(callBack); //因为on在取消stream请求的问题(具体看ResponseBodyCallback),无法执行onCompletion,所以需要折中调用onCompletion streamGCallBack = callBack; Call<ResponseBody> apiCall = api.createGChatCompletionStream(model, request); Disposable disposable = streamG(apiCall, ChatGCompletionResponse.class) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.io()) .forEachWhile(ChatGCompletionResponse -> { if (isStreamFirstLoading) { isStreamFirstLoading = false; if (streamGCallBack != null) streamGCallBack.onLoading(false); } if (streamGCallBack != null) streamGCallBack.onSuccess(ChatGCompletionResponse); //返回true代表继续回调,false代表执行完成回调 return ChatGCompletionResponse.getCandidates() == null || ChatGCompletionResponse.getCandidates().size() <= 0 || ChatGCompletionResponse.getCandidates().get(0).getContent() == null || ChatGCompletionResponse.getCandidates().get(0).getContent().getParts() == null || ChatGCompletionResponse.getCandidates().get(0).getContent().getParts().size() <= 0 || ChatGCompletionResponse.getCandidates().get(0).getContent().getParts().get(0) == null || !ChatGCompletionResponse.getCandidates().get(0).getContent().getParts().get(0).getText().equals("") ; }, throwable -> { HttpException e; if (throwable instanceof HttpException) { e = (HttpException) throwable; } else { if (streamGCallBack != null) streamGCallBack.onError(null, throwable); return; } try { if (e.response() == null || e.response().errorBody() == null) { if (streamGCallBack != null) streamGCallBack.onError(null, throwable); } else { String errorBody = e.response().errorBody().string(); GoogleError error = mapper.readValue(errorBody, GoogleError.class); if (streamGCallBack != null) streamGCallBack.onError(new GoogleHttpException(error, e), throwable); } } catch (IOException ex) { // couldn't parse OpenAI error if (streamGCallBack != null) streamGCallBack.onError(null, throwable); } finally { if (streamGCallBack != null) streamGCallBack.onLoading(false); streamGCallBack = null; compositeDisposable.clear(); } }, () -> { if (streamGCallBack != null) streamGCallBack.onCompletion(); streamGCallBack = null; compositeDisposable.clear(); }); compositeDisposable.add(disposable); requestList.put("streamChatCompletion", apiCall); } public interface StreamCallBack { void onSuccess(ChatCompletionChunk result); void onError(OpenAiHttpException error, Throwable Throwable); void onCompletion(); void onLoading(boolean isLoading); } public interface StreamGCallBack { void onSuccess(ChatGCompletionResponse result); void onError(GoogleHttpException error, Throwable Throwable); void onCompletion(); void onLoading(boolean isLoading); } public interface CompletionCallBack<T> { void onSuccess(Object o); void onError(OpenAiHttpException error, Throwable Throwable); } public interface ResultCallBack { void onSuccess(ChatCompletionResult result); void onError(OpenAiHttpException error, Throwable Throwable); void onLoading(boolean isLoading); } public interface ResultGCallBack { void onSuccess(ChatGCompletionResponse result); void onError(GoogleHttpException error, Throwable Throwable); void onLoading(boolean isLoading); } /** * Calls the Open AI api and returns a Flowable of SSE for streaming * omitting the last message. * * @param apiCall The api call */ public static Flowable<SSE> stream(Call<ResponseBody> apiCall) { return stream(apiCall, false); } public static Flowable<SSE> streamG(Call<ResponseBody> apiCall) { return streamG(apiCall, false); } /** * Calls the Open AI api and returns a Flowable of SSE for streaming. * * @param apiCall The api call * @param emitDone If true the last message ([DONE]) is emitted */ public static Flowable<SSE> stream(Call<ResponseBody> apiCall, boolean emitDone) { //apiCall.enqueue为retrofit手动调用okHttp,所以默认情况下,在Android平台,因为平台判断 //所以默认回调在主线程,但是这里ResponseBodyCallback内部进行数据读写、网络等耗时操作,需要在子线程进行操作 //方法有两种,可以在retrofit传入线程池,或者ResponseBodyCallback回调中切换到子线程 return Flowable.create(emitter -> apiCall.enqueue(new ResponseBodyCallback(emitter, emitDone)), BackpressureStrategy.BUFFER); } public static Flowable<SSE> streamG(Call<ResponseBody> apiCall, boolean emitDone) { //apiCall.enqueue为retrofit手动调用okHttp,所以默认情况下,在Android平台,因为平台判断 //所以默认回调在主线程,但是这里ResponseBodyCallback内部进行数据读写、网络等耗时操作,需要在子线程进行操作 //方法有两种,可以在retrofit传入线程池,或者ResponseBodyCallback回调中切换到子线程 return Flowable.create(emitter -> apiCall.enqueue(new ResponseBodyGCallback(emitter, emitDone)), BackpressureStrategy.BUFFER); } /** * Calls the Open AI api and returns a Flowable of type T for streaming * omitting the last message. * * @param apiCall The api call * @param cl Class of type T to return */ public static <T> Flowable<T> stream(Call<ResponseBody> apiCall, Class<T> cl) { return stream(apiCall).map(sse -> mapper.readValue(sse.getData(), cl)); } public static <T> Flowable<T> streamG(Call<ResponseBody> apiCall, Class<T> cl) { return streamG(apiCall).map(sse -> mapper.readValue(sse.getData(), cl)); } public void clearRequest() { //todo rxJava的通用网络请求取消未做 for (Map.Entry<String, Call<ResponseBody>> entry : requestList.entrySet()) { Call<ResponseBody> call = entry.getValue(); if (call != null && call.isExecuted() && !call.isCanceled()) { call.cancel(); } } requestList.clear(); } public void clean() { clean(true); } public void clean(boolean isExecutor) { clearRequest(); if (streamCallBack != null){ streamCallBack.onLoading(false); } if (streamCallBack != null){ streamCallBack.onCompletion(); } if (streamGCallBack != null){ streamGCallBack.onLoading(false); } if (streamGCallBack != null){ streamGCallBack.onCompletion(); } compositeDisposable.clear(); if (isExecutor) shutdownExecutor(); } /** * Shuts down the OkHttp ExecutorService. * The default behaviour of OkHttp's ExecutorService (ConnectionPool) * is to shut down after an idle timeout of 60s. * Call this method to shut down the ExecutorService immediately. */ public void shutdownExecutor() { Objects.requireNonNull(this.executorService, "executorService must be set in order to " + "shut down"); this.executorService.shutdown(); } public static String formatUrl(String url) { HttpUrl newBaseUrl = HttpUrl.parse(url); if (newBaseUrl == null) return ""; String formatUrl = newBaseUrl.toString(); if (!"".equals(newBaseUrl.pathSegments().get(newBaseUrl.pathSegments().size() - 1))) { formatUrl = formatUrl +"/"; } return formatUrl; } public static OpenAiApi buildApi(String token, long second) { ObjectMapper mapper = defaultObjectMapper(); OkHttpClient client = defaultClient(token, second, BASE_URL, false); Retrofit retrofit = defaultRetrofit(client, mapper, BASE_URL, client.dispatcher().executorService()); return retrofit.create(OpenAiApi.class); } public static ObjectMapper defaultObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); return mapper; } public static OkHttpClient defaultClient(String token, long second, String url, boolean isGoogle) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(s -> { // Log.i("test",s); }); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return new OkHttpClient.Builder() .addInterceptor(new AuthenticationInterceptor(token, url, isGoogle)) // .addInterceptor(loggingInterceptor) .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS)) .readTimeout(second * 1000, TimeUnit.MILLISECONDS) .build(); } public static Retrofit defaultRetrofit(OkHttpClient client, ObjectMapper mapper, String url, Executor executor) { return new Retrofit.Builder() .baseUrl(url) .client(client) .addConverterFactory(JacksonConverterFactory.create(mapper)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .callbackExecutor(executor) .build(); } }
[ "com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates" ]
[((13403, 13464), 'okhttp3.MultipartBody.Part.createFormData'), ((18248, 18982), 'io.reactivex.Observable.interval'), ((18248, 18350), 'io.reactivex.Observable.interval'), ((19058, 19792), 'io.reactivex.Observable.interval'), ((19058, 19160), 'io.reactivex.Observable.interval'), ((19916, 21197), 'io.reactivex.Observable.interval'), ((19916, 20018), 'io.reactivex.Observable.interval'), ((21274, 22557), 'io.reactivex.Observable.interval'), ((21274, 21376), 'io.reactivex.Observable.interval'), ((35189, 35235), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35280, 35339), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35280, 35326), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35387, 35457), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35387, 35446), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35387, 35433), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35505, 35582), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35505, 35575), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35505, 35564), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35505, 35551), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35627, 35704), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35627, 35697), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35627, 35686), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35627, 35673), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35753, 35851), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35753, 35840), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35753, 35830), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35753, 35823), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35753, 35812), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates'), ((35753, 35799), 'com.theokanning.openai.completion.chat.ChatGCompletionResponse.getCandidates')]
/* * Copyright (c) 2023 Mariusz Bernacki <consulting@didalgo.com> * SPDX-License-Identifier: Apache-2.0 */ package com.didalgo.intellij.chatgpt.chat; import com.didalgo.intellij.chatgpt.text.TextContent; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import java.util.List; public class DefaultChatMessageComposer implements ChatMessageComposer { @Override public ChatMessage compose(ConversationContext ctx, String prompt) { return new ChatMessage(ChatMessageRole.USER.value(), prompt); } @Override public ChatMessage compose(ConversationContext ctx, String prompt, List<? extends TextContent> textContents) { if (textContents.isEmpty()) { return compose(ctx, prompt); } textContents = ChatMessageUtils.composeExcept(textContents, ctx.getLastPostedCodeFragments(), prompt); if (!textContents.isEmpty()) { ctx.setLastPostedCodeFragments(textContents); return compose(ctx, ChatMessageUtils.composeAll(prompt, textContents)); } return compose(ctx, prompt); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((547, 575), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')]
package com.company.project.controllers; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController public class ChatCompletionController { /** * The version of AI model we'll send requests. * This example uses gpt-4 * Other versions: https://platform.openai.com/docs/models/model-endpoint-compatibility */ @Value("${openai.model}") private String model; /** * API key to access OpenAI API */ @Value("${openai.api.key}") private String openaiApiKey; /** * Creates a chat request and sends it to the OpenAI API * Returns the first message from the API response * * @param prompt the prompt to send to the API * @return first message from the API response */ @PostMapping("/ai-chat") public String chat(@RequestBody String prompt) { OpenAiService service = new OpenAiService(openaiApiKey); final List<ChatMessage> messages = new ArrayList<>(); final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.USER.value(), prompt); messages.add(systemMessage); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest .builder() .model(model) .messages(messages) .maxTokens(250) .build(); List<ChatCompletionChoice> choices = service.createChatCompletion(chatCompletionRequest).getChoices(); if (choices == null || choices.isEmpty()) { return "No response"; } return choices.get(0).getMessage().getContent(); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((1581, 1609), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')]
package edu.sjsu.articlevisualisationbackend.service; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import edu.sjsu.articlevisualisationbackend.service.exception.InvalidChatGptGeneration; import io.github.cdimascio.dotenv.Dotenv; import org.json.JSONObject; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Service; import org.springframework.util.StreamUtils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.nio.file.Files; import java.nio.file.Paths; public class ChatGptDiagramGenerator { private OpenAiService service; private ChatCompletionRequest chatCompletionRequest; private List<ChatMessage> messageRecord = new ArrayList<>(); private String pdfText; private JSONObject chatGptPrompt; private final String OPERATION_USR_MSG_JSON_KEY = "prompt_msg"; private final String OPERATION_FEW_SHOT_JSON_KEY = "few_shot"; private final String OPERATION_FEW_SHOT_PROMPT_JSON_KEY = "prompt_msg"; private final String OPERATION_FEW_SHOT_RESPONSE_JSON_KEY = "response"; public ChatGptDiagramGenerator(String pdfText) throws IOException { this.initOpenAiService(); this.initChatCompletionRequest(); this.loadJsonPrompt(); this.initSystemMessage(); this.pdfText = pdfText; } public void setPdfText(String pdfText) { this.pdfText = pdfText; } private void initOpenAiService() { String apiKey = getApiKeyFromEnv(); this.service = new OpenAiService( this.getApiKey() ); } private String getApiKey(){ String apiKey; try{ apiKey = getApiKeyFromEnvFile(); } catch (Exception e) { System.out.println("Error reading from env file"); apiKey = getApiKeyFromEnv(); } return apiKey; } private String getApiKeyFromEnv(){ final String OPENAI_KEY_ENV_VAR = "OPENAI_KEY"; return System.getenv(OPENAI_KEY_ENV_VAR); } private String getApiKeyFromEnvFile() { final String OPENAI_KEY_ENV_VAR = "OPENAI_KEY"; final String ENV_FILE_PATH = "src/main/resources/.env"; Dotenv dotenv = Dotenv.configure() .filename(ENV_FILE_PATH) .load(); return dotenv.get(OPENAI_KEY_ENV_VAR); } private void initChatCompletionRequest(){ final String CHAT_GPT_MODEL = "gpt-3.5-turbo"; this.chatCompletionRequest = ChatCompletionRequest .builder() .model(CHAT_GPT_MODEL) .build(); } private void loadJsonPrompt() throws IOException { String jsonContent; ClassPathResource resource = new ClassPathResource("prompt.json"); try (InputStream inputStream = resource.getInputStream()) { jsonContent = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); } this.chatGptPrompt = new JSONObject(jsonContent); } private void initSystemMessage(){ final String MESSAGE_JSON_KEY = "system_msg"; ChatMessage chatMessage = new ChatMessage( ChatMessageRole.SYSTEM.value(), this.chatGptPrompt.get(MESSAGE_JSON_KEY).toString() ); this.messageRecord.add(chatMessage); } private void addNormalChatMessage( String promptMessage, String promptMessageAppendix ) { ChatMessage chatUserMessage = new ChatMessage( ChatMessageRole.USER.value(), promptMessage + promptMessageAppendix ); this.messageRecord.add(chatUserMessage); } private void addFewShotChatMessage( String promptMessage, String templateResponse ){ ChatMessage chatUserMessage = new ChatMessage( ChatMessageRole.USER.value(), promptMessage ); ChatMessage chatAssistantMessage = new ChatMessage( ChatMessageRole.ASSISTANT.value(), templateResponse ); this.messageRecord.add(chatUserMessage); this.messageRecord.add(chatAssistantMessage); } private String sendAPIRequest(){ ChatMessage responseMessage = this.service.createChatCompletion(this.chatCompletionRequest).getChoices().get(0).getMessage(); return responseMessage.getContent(); } private String makeRequest( String operationJsonKey, String promptMessageAppendix, boolean isHasFewShotResponse ){ final JSONObject OPERATION_JSON_OBJECT = this.chatGptPrompt.getJSONObject(operationJsonKey); if (isHasFewShotResponse) { final JSONObject fewShotObject = OPERATION_JSON_OBJECT.getJSONObject(OPERATION_FEW_SHOT_JSON_KEY); final String promptMessage = fewShotObject.getString(OPERATION_FEW_SHOT_PROMPT_JSON_KEY); final String templateResponse = fewShotObject.getString(OPERATION_FEW_SHOT_RESPONSE_JSON_KEY); this.addFewShotChatMessage(promptMessage, templateResponse); } this.addNormalChatMessage( OPERATION_JSON_OBJECT.getString(OPERATION_USR_MSG_JSON_KEY), promptMessageAppendix ); this.chatCompletionRequest.setMessages(this.messageRecord); return this.sendAPIRequest(); } private String makeKeywordsRequest(){ final String OPERATION_JSON_KEY = "get_keyword_from_pdf"; return this.makeRequest( OPERATION_JSON_KEY, this.pdfText, true ); } private String makeMermaidCodeRequest(String keywordText) { final String OPERATION_JSON_KEY = "generate_mermaid_using_keyword"; return this.makeRequest( OPERATION_JSON_KEY, keywordText, false ); } private String removeMermaidCodeHeadFoot(String mermaidCode){ final String MERMAID_CODE_HEAD = "```mermaid"; final String MERMAID_CODE_FOOT = "```"; return mermaidCode.replace(MERMAID_CODE_HEAD, "").replace(MERMAID_CODE_FOOT, ""); } private boolean validateMermaidCode(String mermaidCode){ MermaidValidationApiCaller mermaidValidationApiCaller = new MermaidValidationApiCaller(mermaidCode); return mermaidValidationApiCaller.validate(); } private String generateReliableMermaidCode(String keywords) throws InvalidChatGptGeneration { final int MAX_ATTEMPT_COUNT = 3; int attemptCount = 0; boolean isMermaidValid = false; String mermaidCode; do { mermaidCode = this.makeMermaidCodeRequest(keywords); mermaidCode = this.removeMermaidCodeHeadFoot(mermaidCode); isMermaidValid = this.validateMermaidCode(mermaidCode); attemptCount++; } while (!isMermaidValid && attemptCount < MAX_ATTEMPT_COUNT); if (isMermaidValid) { return mermaidCode; } else { throw new InvalidChatGptGeneration("Failed to generate mermaid code"); } } public String generateMermaidCode() throws InvalidChatGptGeneration { final String KEYWORDS_FROM_PDF = this.makeKeywordsRequest(); final String MERMAID_CODE = this.generateReliableMermaidCode(KEYWORDS_FROM_PDF); return this.removeMermaidCodeHeadFoot(MERMAID_CODE); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value", "com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value" ]
[((2511, 2594), 'io.github.cdimascio.dotenv.Dotenv.configure'), ((2511, 2570), 'io.github.cdimascio.dotenv.Dotenv.configure'), ((3464, 3494), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3821, 3849), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((4161, 4189), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((4309, 4342), 'com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value')]
package com.ramesh.openai; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; /*** * This project demonstrates a simple multi prompts usage ***/ class MultipleChatCompletion { public static void main(String... args) { // Set the Open AI Token & Model String token = "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"; String model = "gpt-3.5-turbo"; // service handle for calling OpenAI APIs OpenAiService service = new OpenAiService(token, Duration.ofSeconds(30)); // multiple prompts example // Change these and run again and again String[] prompts = new String[3]; prompts[0] = "Capital of India?"; prompts[1] = "No. of States in India?"; prompts[2] = "Prime Minister of India?"; // Loop through each prompt for (int i = 0; i < 3; i++) { String prompt = prompts[i]; // create the chat message final List<ChatMessage> messages = new ArrayList<>(); final ChatMessage assistantMessage = new ChatMessage(ChatMessageRole.ASSISTANT.value(), prompt); messages.add(assistantMessage); // create the request object ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .model(model) .messages(messages) .n(1) .temperature(.1) .maxTokens(50) .logitBias(new HashMap<>()) .build(); // get the response from chat gpt System.out.println("Prompt=" + prompt); System.out.print("ChatGPT response="); service.createChatCompletion(chatCompletionRequest).getChoices().forEach((c) -> { System.out.println(c.getMessage().getContent()); }); System.out.println("--------------------------------"); } service.shutdownExecutor(); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value", "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1296, 1329), 'com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value'), ((1457, 1709), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1457, 1684), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1457, 1640), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1457, 1609), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1457, 1576), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1457, 1554), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1457, 1518), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package com.github.tornado2023team5.kanjichan.util; import com.github.tornado2023team5.kanjichan.model.function.FunctionCallingBase; import com.theokanning.openai.completion.chat.ChatFunctionCall; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.List; @RequiredArgsConstructor @Service public class FunctionCallUtil { private final OpenAiService service; public <T> T call(String text, FunctionCallingBase base) { var executor = base.getExecutor(); var request = base.getRequest(executor); request.setMessages(Arrays.asList(new ChatMessage(ChatMessageRole.SYSTEM.value(), base.getBaseMessages()), new ChatMessage(ChatMessageRole.USER.value(), text))); ChatMessage responseMessage = service.createChatCompletion(request).getChoices().get(0).getMessage(); ChatFunctionCall functionCall = responseMessage.getFunctionCall(); return executor.execute(functionCall); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((830, 860), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((903, 931), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')]
package org.zhong.chatgpt.wechat.bot.msgprocess; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.yaml.snakeyaml.Yaml; import org.zhong.chatgpt.wechat.bot.builder.OpenAiServiceBuilder; import org.zhong.chatgpt.wechat.bot.config.BotConfig; import org.zhong.chatgpt.wechat.bot.consts.BotConst; import org.zhong.chatgpt.wechat.bot.model.BotMsg; import org.zhong.chatgpt.wechat.bot.model.WehchatMsgQueue; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; import cn.zhouyafeng.itchat4j.beans.BaseMsg; /** * 使用普通OpenAI接口进行回复 * @author zhong * */ public class OpenAIReplyProcessor implements MsgProcessor{ private static OpenAiService service = OpenAiServiceBuilder.build(BotConfig.getAppKey(), Duration.ofSeconds(300)); private static String model = "text-davinci-003"; private static Double temperature = 0.9; private static Integer maxTokens = 2000; private static Double topP = 1d; private static Double frequencyPenalty = 0.2; private static Double presencePenalty = 0.6; private static List<String> stops = new ArrayList<String>(); static { final Yaml yaml = new Yaml(); Map<String, Object> yamlMap = yaml.load(BotConfig.class.getResourceAsStream("/application.yml")); String stopsStr = (String) yamlMap.get("bot.openai.completio.stop"); model = yamlMap.get("bot.openai.completio.model").toString(); temperature = Double.valueOf( yamlMap.get("bot.openai.completio.temperature").toString()); maxTokens = Integer.valueOf( yamlMap.get("bot.openai.completio.max_tokens").toString()); topP = Double.valueOf( yamlMap.get("bot.openai.completio.top_p").toString()); frequencyPenalty = Double.valueOf( yamlMap.get("bot.openai.completio.frequency_penalty").toString()); presencePenalty = Double.valueOf( yamlMap.get("bot.openai.completio.presence_penalty").toString()); if(StringUtils.isNotEmpty(stopsStr)) { stops = Arrays.asList(stopsStr.split(",")); } } @Override public void process(BotMsg botMsg) { BaseMsg baseMsg = botMsg.getBaseMsg(); CompletionRequest completionRequest = CompletionRequest.builder() .prompt(baseMsg.getContent()) .model(model) .maxTokens(maxTokens) .temperature(temperature) .topP(topP) .frequencyPenalty(frequencyPenalty) .presencePenalty(presencePenalty) .echo(true) .user(botMsg.getUserName()) .build(); try { String text = service.createCompletion(completionRequest).getChoices().get(0).getText(); botMsg.setReplyMsg(text); WehchatMsgQueue.pushSendMsg(botMsg); }catch (Exception e) { e.printStackTrace(); botMsg.setRetries(botMsg.getRetries() + 1); if(botMsg.getRetries() < 5) { WehchatMsgQueue.pushReplyMsg(botMsg); }else { String recontent = baseMsg.getContent(); if(recontent.length() > 20) { recontent = recontent.substring(0, 17) + "...\n"; } botMsg.setReplyMsg(recontent+ "该提问已失效,请重新提问"); WehchatMsgQueue.pushSendMsg(botMsg); } } } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((1358, 1413), 'org.zhong.chatgpt.wechat.bot.config.BotConfig.class.getResourceAsStream'), ((2260, 2568), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2555), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2523), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2507), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2469), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2429), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2413), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2383), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2351), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2260, 2327), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package biz.readmylegal.backend; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import com.theokanning.openai.completion.chat.ChatCompletionChunk; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; public class GPTBackend { private OpenAiService service; private List<String> currentResponse; public GPTBackend(String apiKey) { this.service = new OpenAiService(apiKey, Duration.ofSeconds(30)); this.currentResponse = new LinkedList<>(); } final static String audioInstructions = "Give a small, succinct, and basic summary of the following audio transcript. " + "It is not known in these instructions what the transcript formatting or contents " + "are beyond that it involves some discussion of law and legal processes such as " + "an interview between lawyer and client, some presentation discussing laws, etc. " + "Give the summary in the form of a singular short paragraph, discuss what information " + "was exchanged. Ignore any transcripts which make no mention of law or any legal " + "process or do not appear to be transcripts of human conversation, and simply state " + "that the given transcript does not fit the requirements for processing."; final static String legalInstructions = "Give a small, succinct, and basic analysis of the following legal document " + "in a such a way that someone inexperienced with legal terms can understand it. " + "Do so in the following format: a section which shows the legal rights and " + "responsibilities of the person/party submitting the document in bulleted form, " + "a section which shows the legal rights and responsibilities of the person/party " + "who wrote, created, or provided the document to the aforementioned person/party " + "in bulleted form, and finally a small paragraph summary of other aspects of the " + " document which are important or should otherwise be noted if the prior two " + "categories aren't sufficient. If the provided document or text has nothing to do" + "with any kind of legal agreement or notice, simply express that it's not a legal " + "document and don't attempt any further analysis."; // Awaits response from gpt-3.5-turbo based on given prompt // Blocks until the response is given public synchronized String promptAwaitResponse(String prompt, String type) { System.out.println("Processing prompt."); String instructions; if (type.equals("document")) instructions = legalInstructions; else if (type.equals("transcript")) instructions = audioInstructions; else return "Invalid processing typing given \"" + type + "\""; final List<ChatMessage> messages = new ArrayList<>(); final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), instructions); final ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), prompt); messages.add(systemMessage); messages.add(userMessage); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest .builder() .model("gpt-3.5-turbo") .messages(messages) .n(1) .maxTokens(512) .logitBias(new HashMap<>()) .build(); service.streamChatCompletion(chatCompletionRequest) .doOnError(Throwable::printStackTrace) .blockingForEach(this::addChunk); System.out.println("Finished processing prompt."); String response = currentResponseAsString(); currentResponse.clear(); return response; } public void stop() { service.shutdownExecutor(); } private String currentResponseAsString() { StringBuilder response = new StringBuilder(); for(String s : currentResponse) { response.append(s); } return response.toString(); } private void addChunk(ChatCompletionChunk chunk) { if (chunk.getChoices().isEmpty() || chunk.getChoices().get(0).getMessage().getContent() == null) return; String chunkString = chunk.getChoices().get(0).getMessage().getContent(); currentResponse.add(chunkString); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((3285, 3315), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3388, 3416), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')]
package net.anotheria.anosite.cms.translation; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import net.anotheria.anosite.config.LocalizationAutoTranslationTokenConfig; import net.anotheria.anosite.gen.shared.service.BasicService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.ArrayList; import java.util.List; public class IASGTranslationTranslationServiceImpl extends BasicService implements IASGTranslationService { private static IASGTranslationTranslationServiceImpl instance; private static final Logger log = LoggerFactory.getLogger(IASGTranslationTranslationServiceImpl.class); private static final String PROMPT = "You will get a localizations in format 'key'='translation'. Translate it from %s to %s without any explanations.\n" + "Localizations:\n \"\"\"\n%s\n\"\"\""; private LocalizationAutoTranslationTokenConfig config; private OpenAiService openAiService; public IASGTranslationTranslationServiceImpl() { this.config = LocalizationAutoTranslationTokenConfig.getInstance(); this.openAiService = new OpenAiService(config.getToken(), Duration.ofSeconds(240)); } @Override public String translate(String originLanguage, String targetLanguage, String bundleContent) { String result = ""; String formattedPrompt = String.format(PROMPT, originLanguage, targetLanguage, bundleContent); List<ChatMessage> chatMessageList = new ArrayList<>(); chatMessageList.add(new ChatMessage(ChatMessageRole.SYSTEM.value(), formattedPrompt)); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .model("gpt-3.5-turbo") .messages(chatMessageList) .user("testing") .temperature(0.0) .build(); int maxAttempts = 15; int currentAttempt = 1; while (currentAttempt <= maxAttempts) { try { List<ChatCompletionChoice> choices = openAiService.createChatCompletion(chatCompletionRequest).getChoices(); if (!choices.isEmpty()) { for (ChatCompletionChoice choice : choices) { return choice.getMessage().getContent(); } } } catch (RuntimeException ex) { if (ex.getMessage().toLowerCase().contains("http") || ex.getMessage().toLowerCase().contains("timeout") || ex.getMessage().toLowerCase().contains("that model is currently overloaded with other requests")) { log.error("Cannot translate localizations. Exception: {}.\n Attempt #{}", ex.getMessage(), currentAttempt); currentAttempt++; // request to openAI can often fail. So will try one more time. There are only 15 attempts. } else { log.error("Cannot translate localizations. Exception: {}.", ex.getMessage()); break; } } } return result; } static IASGTranslationTranslationServiceImpl getInstance() { if (instance == null) { instance = new IASGTranslationTranslationServiceImpl(); } return instance; } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1812, 1842), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((1918, 2124), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1918, 2099), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1918, 2065), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1918, 2032), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1918, 1989), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package de.ja.view.explanation.text; import com.ibm.icu.text.RuleBasedNumberFormat; import com.ibm.icu.text.SimpleDateFormat; import com.knuddels.jtokkit.api.ModelType; import com.theokanning.openai.OpenAiHttpException; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionResult; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import de.ja.view.ExplainerFrame; import de.ja.view.explanation.text.textinfo.GeneratedTextsPanel; import de.swa.gc.GraphCode; import net.miginfocom.swing.MigLayout; import org.jdesktop.swingx.JXTaskPane; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedWriter; import java.io.FileWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.time.Duration; import java.util.List; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; public class TextPanel extends JPanel implements ActionListener { // API-Key. private static String key; // Textfeld für die generierte Prompt. private final JTextArea promptArea; private final JSpinner temperatureSpinner; private final JSpinner topPSpinner; // Anzahl zu generierender Texte. private final JSpinner nSpinner; private final JSpinner maxTokensSpinner; private final JSpinner presencePenaltySpinner; private final JSpinner frequencyPenaltySpinner; private final JComboBox<String> modelTypeComboBox; private final JButton generateChatCompletions; // Nachrichten, die die Prompt darstellen. private List<ChatMessage> messages = new ArrayList<>(); // Panel für alle generierten Texte. private final GeneratedTextsPanel generatedTextsPanel; // Referenz. private final ExplainerFrame reference; public TextPanel(ExplainerFrame reference) { this.reference = reference; key = System.getenv("OpenAI-Key"); // Layout definieren. MigLayout imagePanelMigLayout = new MigLayout("" , "[fill, grow]", "10[12.5%][][fill,57.5%][fill,30%]"); //1. 12.5% setLayout(imagePanelMigLayout); // Textfeld für die Prompt initialisieren und konfigurieren. promptArea = new JTextArea(); promptArea.setLineWrap(true); promptArea.setWrapStyleWord(true); promptArea.setEditable(false); JScrollPane promptSP = new JScrollPane(promptArea); promptSP.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); promptSP.setBorder(new TitledBorder("Generated Prompt")); add(promptSP, "cell 0 3, growx, height ::30%, aligny top"); // Ästhetische Eigenschaften für erweiterte Optionen einstellen... UIManager.put("TaskPane.animate", Boolean.FALSE); UIManager.put("TaskPane.titleOver", new Color(200, 200, 200)); UIManager.put("TaskPane.titleForeground", new Color(187, 187, 187)); UIManager.put("TaskPane.titleBackgroundGradientStart", new Color(85, 88, 89)); UIManager.put("TaskPane.titleBackgroundGradientEnd", new Color(85, 88, 89)); UIManager.put("TaskPane.background", new Color(76, 80, 82)); UIManager.put("TaskPane.borderColor", new Color(94, 96, 96)); // Erweiterte Optionen initialisieren und konfigurieren. JXTaskPane advancedOptions = new JXTaskPane(); advancedOptions.setCollapsed(true); advancedOptions.setTitle("Advanced Options"); add(advancedOptions, "cell 0 0, growx, aligny top"); // Layout für die Optionen in den erweiterten Optionen definieren. MigLayout advancedOptionsMigLayout = new MigLayout("", "0[]5[]10[]5[]0", "0[]0"); advancedOptions.setLayout(advancedOptionsMigLayout); // Erweiterte Optionen definieren. JLabel temperatureLabel = new JLabel("Temperature:"); temperatureLabel.setHorizontalTextPosition(SwingConstants.CENTER); temperatureLabel.setHorizontalAlignment(SwingConstants.CENTER); temperatureSpinner = new JSpinner(); SpinnerNumberModel temperatureSpinnerModel = new SpinnerNumberModel(0, 0, 2, 0.1); temperatureSpinner.setModel(temperatureSpinnerModel); JLabel topPLabel = new JLabel("Top P:"); topPLabel.setHorizontalTextPosition(SwingConstants.CENTER); topPLabel.setHorizontalAlignment(SwingConstants.CENTER); topPSpinner = new JSpinner(); SpinnerNumberModel topPSpinnerModel = new SpinnerNumberModel(0, 0, 1, 0.01); topPSpinner.setModel(topPSpinnerModel); JLabel nLabel = new JLabel("N:"); nLabel.setHorizontalTextPosition(SwingConstants.CENTER); nLabel.setHorizontalAlignment(SwingConstants.CENTER); nSpinner = new JSpinner(); SpinnerNumberModel nSpinnerModel = new SpinnerNumberModel(1, 1, 10, 1); nSpinner.setModel(nSpinnerModel); JLabel maxTokensLabel = new JLabel("Max Tokens:"); maxTokensLabel.setHorizontalTextPosition(SwingConstants.CENTER); maxTokensLabel.setHorizontalAlignment(SwingConstants.CENTER); maxTokensSpinner = new JSpinner(); SpinnerNumberModel maxTokensSpinnerModel = new SpinnerNumberModel(256, 0, 8192, 1); maxTokensSpinner.setModel(maxTokensSpinnerModel); JLabel presencePenaltyLabel = new JLabel("Presence Penalty:"); presencePenaltyLabel.setHorizontalTextPosition(SwingConstants.CENTER); presencePenaltyLabel.setHorizontalAlignment(SwingConstants.CENTER); presencePenaltySpinner = new JSpinner(); SpinnerNumberModel presencePenaltySpinnerModel = new SpinnerNumberModel(0, -2, 2, 0.1); presencePenaltySpinner.setModel(presencePenaltySpinnerModel); JLabel frequencyPenaltyLabel = new JLabel("Frequency Penalty:"); frequencyPenaltyLabel.setHorizontalTextPosition(SwingConstants.CENTER); frequencyPenaltyLabel.setHorizontalAlignment(SwingConstants.CENTER); frequencyPenaltySpinner = new JSpinner(); SpinnerNumberModel frequencyPenaltySpinnerModel = new SpinnerNumberModel(0, -2, 2, 0.1); frequencyPenaltySpinner.setModel(frequencyPenaltySpinnerModel); JLabel modelTypeLabel = new JLabel("Model Type:"); modelTypeLabel.setHorizontalTextPosition(SwingConstants.CENTER); modelTypeLabel.setHorizontalAlignment(SwingConstants.CENTER); modelTypeComboBox = new JComboBox<>(); for(ModelType type : ModelType.values()) { modelTypeComboBox.addItem(type.getName()); } advancedOptions.add(temperatureLabel); advancedOptions.add(temperatureSpinner); advancedOptions.add(topPLabel); advancedOptions.add(topPSpinner); advancedOptions.add(nLabel); advancedOptions.add(nSpinner, "wrap"); advancedOptions.add(maxTokensLabel); advancedOptions.add(maxTokensSpinner); advancedOptions.add(presencePenaltyLabel); advancedOptions.add(presencePenaltySpinner); advancedOptions.add(frequencyPenaltyLabel); advancedOptions.add(frequencyPenaltySpinner, "wrap"); advancedOptions.add(modelTypeLabel); advancedOptions.add(modelTypeComboBox, "width ::84px"); // Knopf zum Generieren von Texten. generateChatCompletions = new JButton("Generate Chat-Completion(s)"); generateChatCompletions.addActionListener(this); add(generateChatCompletions, "cell 0 1, width ::190px, aligny top"); // Modell der generativen KI. generatedTextsPanel = new GeneratedTextsPanel(); add(generatedTextsPanel, "cell 0 2, growx, aligny top"); } /** * Graph Code verarbeiten * @param graphCode Ausgewählter Graph Code. */ public void setGraphCode(GraphCode graphCode) { if(graphCode != null) { String prompt = setUpPrompt(graphCode); promptArea.setText(prompt); } else { promptArea.setText(null); } } /** * Prompt vorbereiten und aus Graph Code * generieren. * @param graphCode Ausgewählter Graph Code. * @return Generierte Prompt. */ private String setUpPrompt(GraphCode graphCode) { String s = graphCode.getFormattedTerms(); messages = new ArrayList<>(); messages.add(new ChatMessage(ChatMessageRole.SYSTEM.value(), "You are an assistant, who is able to generate cohesive textual explanations based on a collection of words.")); messages.add(new ChatMessage( ChatMessageRole.SYSTEM.value(), "The collection of words represents a dictionary. The dictionary contains so-called feature " + "vocabulary terms. Additionally some of these terms are connected through a relationship. " + "These relationships will be noted as <i_t> - <i_t1,...,i_tn>, where i_t denotes the index of a feature " + "vocabulary term in the given collection.")); messages.add(new ChatMessage( ChatMessageRole.SYSTEM.value(), "Using these terms, we can create a coherent explanation that accurately " + "describes the terms and its relations.\n" + "\n" + "An example could be: The image shows water, the sky, and clouds. " + "We can imagine a scene with clouds floating in the sky above.")); messages.add(new ChatMessage( ChatMessageRole.USER.value(), "The collections of words is as follows: " + graphCode.listTerms() + ". Only respect these terms and its relations: " + s + ", and ignore all others. " + "Do not create an explanation regarding the dictionary. Only generate a text containing " + "the terms of the dictionary like in the example above.")); messages.add(new ChatMessage( ChatMessageRole.ASSISTANT.value(), "Based on the dictionary, here is a cohesive text " + "containing the terms from the dictionary:")); // Nachrichten zusammenfügen. return messages.stream().map(ChatMessage::getContent).collect(Collectors.joining("\n")); } @Override public void actionPerformed(ActionEvent e) { // Tabs zurücksetzen. generatedTextsPanel.reset(); // Anbindung zur Schnittstelle. OpenAiService service = new OpenAiService(key, Duration.ofSeconds(60)); if(key.isEmpty()) { reference.getExplainerConsoleModel().insertText("OpenAI-Key is missing, abort process. Must be set in launch-config: OpenAI-Key=..."); return; } // Prozess erstellen. ExecutorService executor = Executors.newSingleThreadExecutor(); Thread t = new Thread(() -> { // Textanfrage initialisieren und parametrisieren. ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .messages(messages) .model((String) modelTypeComboBox.getSelectedItem()) .temperature((Double) temperatureSpinner.getValue()) .topP((Double) topPSpinner.getValue()) .n((Integer) nSpinner.getValue()) .maxTokens((Integer) maxTokensSpinner.getValue()) .presencePenalty((Double) presencePenaltySpinner.getValue()) .frequencyPenalty((Double) frequencyPenaltySpinner.getValue()) .build(); try { // Cursor auf Warten setzen. setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Knopf deaktivieren. generateChatCompletions.setEnabled(false); // Info in der Konsole ausgeben. RuleBasedNumberFormat numberFormat = new RuleBasedNumberFormat(Locale.US, RuleBasedNumberFormat.SPELLOUT); reference.getExplainerConsoleModel() .insertText(String.format("Generating %s textual explanation%s!", numberFormat.format(nSpinner.getValue()), (int) nSpinner.getValue() > 1 ? "s" : "")); // Textanfrage an Endpunkt senden. ChatCompletionResult chatCompletionResult = service.createChatCompletion(chatCompletionRequest); // Anhand des Ergebnisses Tabs hinzufügen. Optional<ModelType> model = ModelType.fromName((String) modelTypeComboBox.getSelectedItem()); ModelType modelType = ModelType.GPT_4; if(model.isPresent()) { modelType = model.get(); } generatedTextsPanel.addTabsFromResult(chatCompletionResult, modelType); // Texte speichern. for(int i = 0; i < chatCompletionResult.getChoices().size(); i++) { Files.createDirectories(Paths.get(System.getProperty("user.dir") + "/explanations/text/")); String content = chatCompletionResult.getChoices().get(i).getMessage().getContent(); String timeStamp = new SimpleDateFormat("dd-MM-yyyy_HHmmss").format(new Date()); String fileName = String.format("explanations/text/%s-text-%s.txt", timeStamp, i + 1); BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(content); writer.close(); } } catch(OpenAiHttpException openAiHttpException) { if(openAiHttpException.statusCode == 401) { JOptionPane.showMessageDialog(null, "You provided an invalid API-Key!", "Authentication Error", JOptionPane.ERROR_MESSAGE); reference.getExplainerConsoleModel().insertText("You provided an invalid API-Key!"); } } catch (Exception ex) { ex.printStackTrace(); // Fehler in Konsole ausgeben. reference.getExplainerConsoleModel().insertText(ex.getMessage()); } finally { // Cursor auf Standard zurücksetzen. setCursor(Cursor.getDefaultCursor()); // Knopf reaktivieren. generateChatCompletions.setEnabled(true); } }); // Prozess ausführen und beenden. executor.execute(t); executor.shutdown(); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value", "com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value", "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((8619, 8649), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((8834, 8864), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((9352, 9382), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((9816, 9844), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((10270, 10303), 'com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value'), ((11306, 11899), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11870), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11787), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11706), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11636), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11582), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11523), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11450), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((11306, 11377), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package org.example.chatgpt.service; import cn.hutool.core.util.StrUtil; import com.fasterxml.jackson.databind.ObjectMapper; import com.theokanning.openai.OpenAiApi; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import okhttp3.OkHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import retrofit2.Retrofit; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static com.theokanning.openai.service.OpenAiService.*; /** * 会话服务 * * @author lijiatao * 时间: 2023/12/6 */ @Service public class ChatService { private static final Logger LOG = LoggerFactory.getLogger(ChatService.class); String token = "sk-xxx"; String proxyHost = "127.0.0.1"; int proxyPort = 7890; /** * 流式对话 * 注:必须使用异步处理(否则发送消息不会及时返回前端) * * @param prompt 输入消息 * @param sseEmitter SSE对象 */ @Async public void streamChatCompletion(String prompt, SseEmitter sseEmitter) { LOG.info("发送消息:" + prompt); final List<ChatMessage> messages = new ArrayList<>(); final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), prompt); messages.add(systemMessage); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest .builder() .model("gpt-3.5-turbo") .messages(messages) .n(1) // .maxTokens(500) .logitBias(new HashMap<>()) .build(); //流式对话(逐Token返回) StringBuilder receiveMsgBuilder = new StringBuilder(); OpenAiService service = buildOpenAiService(token, proxyHost, proxyPort); service.streamChatCompletion(chatCompletionRequest) //正常结束 .doOnComplete(() -> { LOG.info("连接结束"); //发送连接关闭事件,让客户端主动断开连接避免重连 sendStopEvent(sseEmitter); //完成请求处理 sseEmitter.complete(); }) //异常结束 .doOnError(throwable -> { LOG.error("连接异常", throwable); //发送连接关闭事件,让客户端主动断开连接避免重连 sendStopEvent(sseEmitter); //完成请求处理携带异常 sseEmitter.completeWithError(throwable); }) //收到消息后转发到浏览器 .blockingForEach(x -> { ChatCompletionChoice choice = x.getChoices().get(0); LOG.debug("收到消息:" + choice); if (StrUtil.isEmpty(choice.getFinishReason())) { //未结束时才可以发送消息(结束后,先调用doOnComplete然后还会收到一条结束消息,因连接关闭导致发送消息失败:ResponseBodyEmitter has already completed) sseEmitter.send(choice.getMessage()); } String content = choice.getMessage().getContent(); content = content == null ? StrUtil.EMPTY : content; receiveMsgBuilder.append(content); }); LOG.info("收到的完整消息:" + receiveMsgBuilder); } /** * 发送连接关闭事件,让客户端主动断开连接避免重连 * * @param sseEmitter * @throws IOException */ private static void sendStopEvent(SseEmitter sseEmitter) throws IOException { sseEmitter.send(SseEmitter.event().name("stop").data("")); } /** * 构建OpenAiService * * @param token API_KEY * @param proxyHost 代理域名 * @param proxyPort 代理端口号 * @return OpenAiService */ private OpenAiService buildOpenAiService(String token, String proxyHost, int proxyPort) { //构建HTTP代理 Proxy proxy = null; if (StrUtil.isNotBlank(proxyHost)) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } //构建HTTP客户端 OkHttpClient client = defaultClient(token, Duration.of(60, ChronoUnit.SECONDS)) .newBuilder() .proxy(proxy) .build(); ObjectMapper mapper = defaultObjectMapper(); Retrofit retrofit = defaultRetrofit(client, mapper); OpenAiApi api = retrofit.create(OpenAiApi.class); OpenAiService service = new OpenAiService(api, client.dispatcher().executorService()); return service; } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value" ]
[((1799, 1829), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((4341, 4381), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((4341, 4372), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event')]
package com.beginner.techies.chatgptintegration.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.beginner.techies.chatgptintegration.dto.ChatMessagePrompt; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.service.OpenAiService; @RestController public class ChatGPTController { @GetMapping("/getChat/{prompt}") public String getPrompt(@PathVariable String prompt) { // /v1/completion -> text-davinci-003, text-davinci-002, text-curie-001, // text-babbage-001, text-ada-001 OpenAiService service = new OpenAiService("ADD_YOUR_SECRET_KEY_HERE"); CompletionRequest completionRequest = CompletionRequest.builder().prompt(prompt).model("text-davinci-003") .echo(true).build(); return service.createCompletion(completionRequest).getChoices().get(0).getText(); } @PostMapping("/chat") public String getChatMessages(@RequestBody ChatMessagePrompt prompt) { // /v1/chat/completions -> // gpt-4, gpt-4-0613, gpt-4-32k, gpt-4-32k-0613, gpt-3.5-turbo, // gpt-3.5-turbo-0613, gpt-3.5-turbo-16k, gpt-3.5-turbo-16k-0613 OpenAiService service = new OpenAiService("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"); ChatCompletionRequest completionRequest = ChatCompletionRequest.builder().messages(prompt.getChatMessage()) .model("gpt-3.5-turbo-16k").build(); return service.createChatCompletion(completionRequest).getChoices().get(0).getMessage().getContent(); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder", "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((983, 1075), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((983, 1067), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((983, 1051), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((983, 1025), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1568, 1673), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1568, 1665), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1568, 1633), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package com.github.pablwoaraujo; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.Arrays; import com.knuddels.jtokkit.Encodings; import com.knuddels.jtokkit.api.ModelType; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; public class ProfileIdentifier { public static void main(String[] args) { var promptSistema = """ Identifique o perfil de compra de cada cliente. A resposta deve ser: Cliente - descreva o perfil do cliente em três palavras """; var clientes = loadCustomersFromFile(); var quantidadeTokens = countTokens(clientes); var modelo = "gpt-3.5-turbo"; var tamanhoRespostaEsperada = 2048; if (quantidadeTokens > 4096 - tamanhoRespostaEsperada) { modelo = "gpt-3.5-turbo-16k"; } System.out.println("QTD TOKENS: " + quantidadeTokens); System.out.println("Modelo escolhido: " + modelo); var request = ChatCompletionRequest .builder() .model(modelo) .maxTokens(tamanhoRespostaEsperada) .messages(Arrays.asList( new ChatMessage( ChatMessageRole.SYSTEM.value(), promptSistema), new ChatMessage( ChatMessageRole.SYSTEM.value(), clientes))) .build(); var key = System.getenv("OPENAI_API_KEY"); var service = new OpenAiService(key, Duration.ofSeconds(60)); System.out.println( service .createChatCompletion(request) .getChoices().get(0).getMessage().getContent()); } private static String loadCustomersFromFile() { try { var path = Path.of(ClassLoader .getSystemResource("lista_de_compras_10_clientes.csv") .toURI()); return Files.readAllLines(path).toString(); } catch (Exception e) { throw new RuntimeException("Erro ao carregar o arquivo!", e); } } private static int countTokens(String prompt) { var registry = Encodings.newDefaultEncodingRegistry(); var enc = registry.getEncodingForModel(ModelType.GPT_3_5_TURBO); return enc.countTokens(prompt); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value" ]
[((1472, 1502), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((1625, 1655), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((2271, 2306), 'java.nio.file.Files.readAllLines')]
package tech.ailef.jpromptmanager.completion; import java.time.Duration; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import com.theokanning.openai.OpenAiHttpException; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionResult; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.service.OpenAiService; import tech.ailef.jpromptmanager.exceptions.JPromptManagerException; /** * An implementation of the LLMConnector that allows to make requests * to the ChatGPT OpenAI endpoints. * */ public class OpenAIChatGPTConnector implements LLMConnector { private OpenAiService service; private String model; private String systemPrompt; private int maxRetries; /** * Builds the connector to ChatGPT with the required parameters. * @param apiKey OpenAI secret key * @param timeout timeout for requests, 0 means no timeout * @param model the OpenAI model to use (this setting will be overridden if an individual `<step>` tag provides a different value), * @param systemPrompt the system prompt */ public OpenAIChatGPTConnector(String apiKey, int timeout, String model, String systemPrompt) { this(apiKey, timeout, 0, model, systemPrompt); } /** * Builds the connector to ChatGPT with the required parameters. * @param apiKey OpenAI secret key * @param timeout timeout for requests, 0 means no timeout * @param model the OpenAI model to use (this setting will be overridden if an individual `<step>` tag provides a different value), */ public OpenAIChatGPTConnector(String apiKey, int timeout, String model) { this(apiKey, timeout, 0, model, "You are a helpful assistant."); } /** * Builds the connector to ChatGPT with the required parameters. * @param apiKey OpenAI secret key * @param timeout timeout for requests, 0 means no timeout * @param model the OpenAI model to use (this setting will be overridden if an individual `<step>` tag provides a different value) * @param maxRetries the number of times to retry a request that fails, default 0 */ public OpenAIChatGPTConnector(String apiKey, int timeout, int maxRetries, String model) { this(apiKey, timeout, maxRetries, model, "You are a helpful assistant."); } /** * Builds the connector to ChatGPT with the required parameters. * @param apiKey OpenAI secret key * @param timeout timeout for requests, 0 means no timeout * @param model the OpenAI model to use (this setting will be overridden if an individual `<step>` tag provides a different value), * @param systemPrompt the initial system prompt that gets prepended to each conversation (see https://platform.openai.com/docs/guides/chat) */ public OpenAIChatGPTConnector(String apiKey, int timeout, int maxRetries, String model, String systemPrompt) { service = new OpenAiService(apiKey, Duration.ofSeconds(timeout)); this.maxRetries = maxRetries; if (model == null) throw new JPromptManagerException("Must specify which OpenAI model to use"); this.model = model; this.systemPrompt = systemPrompt; } /** * Requests a completion for the given text/params to OpenAI. */ @Override public String complete(String prompt, Map<String, String> params) { int maxTokens = Integer.parseInt(params.get("maxTokens")); double temperature = Double.parseDouble(params.get("temperature")); String[] messages = prompt.split("(" + LLMConnector.PROMPT_TOKEN + ")|(" + LLMConnector.COMPLETION_TOKEN + ")"); AtomicInteger count = new AtomicInteger(0); List<ChatMessage> chatMessages = Arrays.asList(messages).stream().filter(x -> x.trim().length() > 0) .map(x -> x.trim()) .map(x -> { if (count.get() % 2 == 0) { return new ChatMessage("user", x); } else { return new ChatMessage("assistant", x); } }) .collect(Collectors.toList()); chatMessages.add(0, new ChatMessage("system", systemPrompt)); int tries = 1; while (tries <= maxRetries) { try { ChatCompletionRequest completionRequest = ChatCompletionRequest.builder() .messages(chatMessages) .maxTokens(maxTokens) .temperature(temperature) .model(model) .build(); ChatCompletionResult chatCompletion = service.createChatCompletion(completionRequest); ChatCompletionChoice choice = chatCompletion.getChoices().get(0); return choice.getMessage().getContent(); } catch (OpenAiHttpException e) { System.err.println("On try " + tries + ", got exception: " + e.getMessage()); tries++; try { Thread.sleep(2000); } catch (InterruptedException e1) { throw new RuntimeException(e); } } } throw new RuntimeException("Request failed after " + tries + " retries"); } @Override public Map<String, String> getDefaultParams() { Map<String, String> params = new HashMap<>(); params.put("model", model); params.put("temperature", "0"); params.put("maxTokens", "256"); return params; } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((3817, 4097), 'java.util.Arrays.asList'), ((3817, 4064), 'java.util.Arrays.asList'), ((3817, 3907), 'java.util.Arrays.asList'), ((3817, 3884), 'java.util.Arrays.asList'), ((3817, 3849), 'java.util.Arrays.asList'), ((4270, 4421), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4270, 4407), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4270, 4388), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4270, 4357), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4270, 4330), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package com.archeruu.ai.utils; import com.fasterxml.jackson.databind.ObjectMapper; import com.theokanning.openai.OpenAiApi; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionResult; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.service.OpenAiService; import okhttp3.OkHttpClient; import org.springframework.beans.factory.annotation.Value; import retrofit2.Retrofit; import java.net.InetSocketAddress; import java.net.Proxy; import java.time.Duration; import java.util.ArrayList; import java.util.List; import static com.theokanning.openai.service.OpenAiService.*; /** * 调用openai API * * 确保7890接口可以访问国外网 * * @author Archer */ public class ChatApiLocalProxyUtil { public static String chatApi(String content) { String key = "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"; // 配置 V2ray 代理 Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890)); OkHttpClient client = defaultClient(key, Duration.ofMinutes(1)) .newBuilder() .proxy(proxy) .build(); // 创建 OpenAiService ObjectMapper mapper = defaultObjectMapper(); Retrofit retrofit = defaultRetrofit(client, mapper); OpenAiApi api = retrofit.create(OpenAiApi.class); OpenAiService service = new OpenAiService(api); // 创建 ChatCompletionRequest ChatMessage chatMessage = new ChatMessage("user", content); List<ChatMessage> chatMessageList = new ArrayList<>(); chatMessageList.add(chatMessage); ChatCompletionRequest completionRequest = ChatCompletionRequest.builder() .messages(chatMessageList) .model("gpt-3.5-turbo") .maxTokens(500) .temperature(0.2) .build(); // 调用 OpenAiService ChatCompletionResult completionResult = service.createChatCompletion(completionRequest); String result = completionResult.getChoices().get(0).getMessage().getContent(); if (result.startsWith("{")) { String error = "出了点小问题呢,换个问题试试。"; return error; } return result.trim(); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1754, 1960), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1754, 1935), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1754, 1901), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1754, 1868), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1754, 1828), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package com.wy.chatting.domain.chatgpt.service.dto.request; import java.util.List; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @NoArgsConstructor @AllArgsConstructor public class GPTCompletionChatRequest { private String model; private String role; private String message; private Integer maxTokens; public static ChatCompletionRequest of(GPTCompletionChatRequest request) { return ChatCompletionRequest.builder() .model(request.getModel()) .messages(convertChatMessage(request)) .maxTokens(request.getMaxTokens()) .build(); } private static List<ChatMessage> convertChatMessage(GPTCompletionChatRequest request) { return List.of(new ChatMessage(request.getRole(), request.getMessage())); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((600, 805), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((600, 780), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((600, 729), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((600, 674), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package com.lazzy.base.openai; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; /** * open ai 三方库集成demo */ public class ChatGPTIntegration { public static void main(String[] args) { new ChatGPTIntegration().chat("中医与西医相比有什么区别"); } public void chat(String question) { OpenAiService service = new OpenAiService("openai key"); CompletionRequest completionRequest = CompletionRequest.builder() .prompt("Somebody once told me the world is gonna roll me") .model("gpt-3.5-turbo") .echo(true) .build(); service.createCompletion(completionRequest).getChoices().forEach(System.out::println); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((499, 695), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((499, 670), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((499, 642), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((499, 602), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package com.erzbir.numeron.plugin.openai.config; import com.erzbir.numeron.api.NumeronImpl; import com.erzbir.numeron.utils.ConfigReadException; import com.erzbir.numeron.utils.ConfigWriteException; import com.erzbir.numeron.utils.JsonUtil; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import java.io.Serializable; /** * @author Erzbir * @Date: 2023/3/3 23:54 */ public class QuestionConfig implements Serializable { private static final Object key = new Object(); private static final String configFile = NumeronImpl.INSTANCE.getPluginWorkDir() + "chatgpt/config/question.json"; private static volatile QuestionConfig INSTANCE; private String model = "gpt-3.5-turbo"; private int max_tokens = 2048; private double temperature = 0.0; private double top_p = 1.0; private double presence_penalty = 0.0; private double frequency_penalty = 0.0; private int n = 1; private QuestionConfig() { } public static QuestionConfig getInstance() { if (INSTANCE == null) { synchronized (key) { if (INSTANCE == null) { try { INSTANCE = JsonUtil.load(configFile, QuestionConfig.class); } catch (ConfigReadException e) { throw new RuntimeException(e); } } } } if (INSTANCE == null) { synchronized (key) { if (INSTANCE == null) { INSTANCE = new QuestionConfig(); try { JsonUtil.dump(configFile, INSTANCE, QuestionConfig.class); } catch (ConfigWriteException e) { throw new RuntimeException(e); } } } } return INSTANCE; //return new QuestionConfig(); } public ChatCompletionRequest load() { return ChatCompletionRequest.builder() .maxTokens(max_tokens) .model(model) .n(n) .presencePenalty(presence_penalty) .topP(top_p) .frequencyPenalty(frequency_penalty) .build(); } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public int getMax_tokens() { return max_tokens; } public void setMax_tokens(int max_tokens) { this.max_tokens = max_tokens; } public double getTemperature() { return temperature; } public void setTemperature(double temperature) { this.temperature = temperature; } public double getTop_p() { return top_p; } public void setTop_p(double top_p) { this.top_p = top_p; } public double getPresence_penalty() { return presence_penalty; } public void setPresence_penalty(double presence_penalty) { this.presence_penalty = presence_penalty; } public double getFrequency_penalty() { return frequency_penalty; } public void setFrequency_penalty(double frequency_penalty) { this.frequency_penalty = frequency_penalty; } public int getN() { return n; } public void setN(int n) { this.n = n; } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((544, 583), 'com.erzbir.numeron.api.NumeronImpl.INSTANCE.getPluginWorkDir'), ((1976, 2256), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1976, 2231), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1976, 2178), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1976, 2149), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1976, 2098), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1976, 2076), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1976, 2046), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package com.coremedia.labs.plugins.feedbackhub.openai.jobs; import com.coremedia.labs.plugins.feedbackhub.openai.OpenAISettings; import com.coremedia.labs.plugins.feedbackhub.openai.OpenAISettingsProvider; import com.coremedia.labs.plugins.feedbackhub.openai.api.OpenAIClientProvider; import com.coremedia.rest.cap.jobs.GenericJobErrorCode; import com.coremedia.rest.cap.jobs.Job; import com.coremedia.rest.cap.jobs.JobContext; import com.coremedia.rest.cap.jobs.JobExecutionException; import com.google.gson.annotations.SerializedName; import com.theokanning.openai.completion.CompletionChoice; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.StringUtils.isNotBlank; public class GenerateTextJob implements Job { private static final Logger LOG = LoggerFactory.getLogger(GenerateTextJob.class); public static final String ACTION_SUMMARIZE = "summarize"; public static final String ACTION_GENERATE_TITLE = "title"; public static final String ACTION_GENERATE_HEADLINE = "headline"; public static final String ACTION_GENERATE_METADATA = "metadata"; public static final String ACTION_EXTRACT_KEYWORDS = "keywords"; public static final int CHAT_GPT_MAX_MSG_LENGTH = 4096; private String prompt; private String contentId; private String siteId; private String groupId; private String actionId; private final OpenAISettingsProvider settingsProvider; public GenerateTextJob(OpenAISettingsProvider settingsProvider) { this.settingsProvider = settingsProvider; } @SerializedName("prompt") public void setPrompt(String prompt) { this.prompt = prompt; } @SerializedName("contentId") public void setContentId(String contentId) { this.contentId = contentId; } @SerializedName("siteId") public void setSiteId(String siteId) { this.siteId = siteId; } @SerializedName("groupId") public void setGroupId(String groupId) { this.groupId = groupId; } @SerializedName("actionId") public void setActionId(String actionId) { this.actionId = actionId; } @Nullable @Override public Object call(@NonNull JobContext jobContext) throws JobExecutionException { String model = null; String text = null; OpenAISettings settings = getSettings(); String updatedPrompt = applyUserAction(settings, prompt, actionId); String sanitized = sanitizePrompt(updatedPrompt); try { model = settings.getLanguageModel(); Integer timeoutInSeconds = settings.getTimeoutInSeconds() != null ? settings.getTimeoutInSeconds() : 30; OpenAiService client; String baseUrl = settings.getBaseUrl(); if (isNotBlank(baseUrl)) { client = OpenAIClientProvider.getClient(baseUrl, settings.getApiKey(), Duration.ofSeconds(timeoutInSeconds)); } else { client = OpenAIClientProvider.getClient(settings.getApiKey(), Duration.ofSeconds(timeoutInSeconds)); } int temparature = (settings.getTemperature() != null ? settings.getTemperature() : 30) / 100; int maxTokens = settings.getMaxTokens() != null ? settings.getMaxTokens() : 1000; if (model.contains("4") || model.contains("3.5")) { List<ChatMessage> messages = new ArrayList<>(); ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), sanitized); messages.add(userMessage); ChatCompletionRequest request = ChatCompletionRequest.builder() .messages(messages) .model(model) .user(String.valueOf(contentId)) .maxTokens(maxTokens) .temperature((double) temparature) .build(); ChatCompletionChoice chatCompletionChoice = client.createChatCompletion(request).getChoices().get(0); text = chatCompletionChoice.getMessage().getContent(); } else { CompletionRequest request = CompletionRequest.builder() .prompt(sanitized) .model(model) .user(String.valueOf(contentId)) .maxTokens(maxTokens) .temperature((double) temparature) .echo(false) .build(); Optional<CompletionChoice> first = client.createCompletion(request).getChoices().stream().findFirst(); if (first.isPresent()) { CompletionChoice completionChoice = first.get(); if (completionChoice.getFinish_reason() != null && !completionChoice.getFinish_reason().equals("stop")) { LOG.info("Text generation stopped, reason: " + completionChoice.getFinish_reason()); } text = completionChoice.getText().trim(); if (StringUtils.isEmpty(text)) { LOG.info("Text generation was empty, finish reason: " + completionChoice.getFinish_reason()); } } } return text.trim(); } catch (Exception e) { LOG.error("Failed to generate text with language model \"{}\" for given prompt: \"{}\" on content {}: {}", model, prompt, contentId, e.getMessage()); throw new JobExecutionException(GenericJobErrorCode.FAILED, e.getMessage()); } } /** * Ensure that the max message length is not exceeded. * Otherwise the message "overflow" would be sent with the next chat message. * * @param updatedPrompt the user prompt, may be already customized depending on the actionId * @return the sanitized user prompt */ private String sanitizePrompt(String updatedPrompt) { if (updatedPrompt.length() > CHAT_GPT_MAX_MSG_LENGTH) { updatedPrompt = updatedPrompt.substring(0, CHAT_GPT_MAX_MSG_LENGTH); if (updatedPrompt.contains(".")) { updatedPrompt = updatedPrompt.substring(0, updatedPrompt.lastIndexOf(".")); } } return updatedPrompt; } /** * Depending on the user action, we do a little prompt engineering to customize the output. * * @param settings * @param prompt the question the user has entered OR the text OpenAI has generated for the original question * @param actionId an action if the user has already entered a question or null if the first AI is given * @return the modified prompt with optional additional commands */ private String applyUserAction(OpenAISettings settings, String prompt, String actionId) { if (StringUtils.isEmpty(actionId)) { prompt = "Answer with less than 500 words or 4000 characters: " + prompt; return prompt; } String promptPrefix = null; switch (actionId) { case ACTION_SUMMARIZE: { promptPrefix = !StringUtils.isEmpty(settings.getSummaryPrompt()) ? settings.getSummaryPrompt() : "Summarize the following text"; break; } case ACTION_EXTRACT_KEYWORDS: { promptPrefix = !StringUtils.isEmpty(settings.getKeywordsPrompt()) ? settings.getKeywordsPrompt() : "Extract the keywords from the following text with a total maximum length of 255 characters"; break; } case ACTION_GENERATE_HEADLINE: { promptPrefix = !StringUtils.isEmpty(settings.getHeadlinePrompt()) ? settings.getHeadlinePrompt() : "Create an article headline from the following text"; break; } case ACTION_GENERATE_METADATA: { promptPrefix = !StringUtils.isEmpty(settings.getMetadataPrompt()) ? settings.getMetadataPrompt() : "Summarize the following text in one sentence"; break; } case ACTION_GENERATE_TITLE: { promptPrefix = !StringUtils.isEmpty(settings.getTitlePrompt()) ? settings.getTitlePrompt() : "Generate a title from the following text with a maximum length of 60 characters"; break; } default: { throw new UnsupportedOperationException("Invalid actionId '" + actionId + "'"); } } return formatActionPrompt(promptPrefix) + prompt; } private OpenAISettings getSettings() { return settingsProvider.getSettings(groupId, siteId); } private String formatActionPrompt(String prompt) { if (prompt != null && !prompt.endsWith(":")) { prompt += ":\n\n"; } return prompt; } }
[ "com.theokanning.openai.completion.CompletionRequest.builder", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value", "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((3899, 3927), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((4017, 4241), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4017, 4222), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4017, 4177), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4017, 4145), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4017, 4102), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4017, 4078), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4468, 4710), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4468, 4691), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4468, 4668), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4468, 4623), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4468, 4591), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4468, 4548), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4468, 4524), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package ru.goncharenko.kekita.bot.handlers.meme.generators.chatgpt; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.methods.BotApiMethod; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Update; import ru.goncharenko.kekita.bot.handlers.meme.generators.MemeGenerator; import java.util.List; @Component @ConditionalOnProperty( prefix = "bot.handlers.meme.ai", name = "enabled", havingValue = "true", matchIfMissing = false ) public class AiGenerator implements MemeGenerator { Logger logger = LoggerFactory.getLogger(AiGenerator.class); private final AiConfig config; private final OpenAiService openAiService; public AiGenerator(AiConfig config, OpenAiService openAiService) { this.openAiService = openAiService; this.config = config; } @Override public BotApiMethod<?> generate(Update update) { logger.info("Use AiGenerator for generate meme response"); final var chatCompletionRequest = generateAiRequest(update.getMessage().getText()); final var completionResult = openAiService.createChatCompletion(chatCompletionRequest); return SendMessage.builder() .chatId(update.getMessage().getChatId()) .text(completionResult.getChoices().getFirst().getMessage().getContent()) .replyToMessageId(update.getMessage().getMessageId()) .build(); } private ChatCompletionRequest generateAiRequest(String message) { final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), config.promt()); final ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), message); return ChatCompletionRequest.builder() .model(config.model()) .messages(List.of(systemMessage, userMessage)) .n(1) .maxTokens(512) .build(); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value", "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1642, 1905), 'org.telegram.telegrambots.meta.api.methods.send.SendMessage.builder'), ((1642, 1880), 'org.telegram.telegrambots.meta.api.methods.send.SendMessage.builder'), ((1642, 1810), 'org.telegram.telegrambots.meta.api.methods.send.SendMessage.builder'), ((1642, 1720), 'org.telegram.telegrambots.meta.api.methods.send.SendMessage.builder'), ((2042, 2072), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((2147, 2175), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((2202, 2414), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2202, 2389), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2202, 2357), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2202, 2335), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2202, 2272), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package jasper.component; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.theokanning.openai.OpenAiHttpException; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.completion.CompletionResult; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionResult; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.image.CreateImageRequest; import com.theokanning.openai.image.ImageResult; import com.theokanning.openai.service.OpenAiService; import jasper.client.dto.RefDto; import jasper.config.Props; import jasper.errors.NotFoundException; import jasper.repository.PluginRepository; import jasper.repository.RefRepository; import okhttp3.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import java.time.Duration; import java.util.List; import static jasper.repository.spec.QualifiedTag.selector; @Profile("ai") @Component public class OpenAi { private static final Logger logger = LoggerFactory.getLogger(OpenAi.class); public static final MediaType TEXT = MediaType.parse("text/plain; charset=utf-8"); @Autowired Props props; @Autowired RefRepository refRepository; @Autowired PluginRepository pluginRepository; @Autowired ObjectMapper objectMapper; public CompletionResult completion(String systemPrompt, String prompt) { var key = refRepository.findAll(selector("_openai/key" + props.getLocalOrigin()).refSpec()); if (key.isEmpty()) { throw new NotFoundException("requires openai api key"); } var service = new OpenAiService(key.get(0).getComment(), Duration.ofSeconds(200)); var completionRequest = CompletionRequest.builder() .model("text-davinci-003") .maxTokens(1024) .prompt(systemPrompt + "\n\n" + "Prompt: " + prompt + "\n\n" + "Reply:") .stop(List.of("Prompt:", "Reply:")) .build(); try { return service.createCompletion(completionRequest); } catch (OpenAiHttpException e) { if ("context_length_exceeded".equals(e.code)) { completionRequest.setMaxTokens(400); try { return service.createCompletion(completionRequest); } catch (OpenAiHttpException second) { if ("context_length_exceeded".equals(second.code)) { completionRequest.setMaxTokens(20); try { return service.createCompletion(completionRequest); } catch (OpenAiHttpException third) { throw e; } } throw e; } } throw e; } } public ChatCompletionResult chatCompletion(String prompt, AiConfig config) { var key = refRepository.findAll(selector("_openai/key" + props.getLocalOrigin()).refSpec()); if (key.isEmpty()) { throw new NotFoundException("requires openai api key"); } var service = new OpenAiService(key.get(0).getComment(), Duration.ofSeconds(200)); var completionRequest = ChatCompletionRequest .builder() .model(config.model) .maxTokens(config.maxTokens) .messages(List.of( cm("system", config.systemPrompt), cm("user", prompt) )) .build(); return service.createChatCompletion(completionRequest); } public ImageResult dale(String prompt, DalleConfig config) { var key = refRepository.findAll(selector("_openai/key" + props.getLocalOrigin()).refSpec()); if (key.isEmpty()) { throw new NotFoundException("requires openai api key"); } var service = new OpenAiService(key.get(0).getComment(), Duration.ofSeconds(200)); var imageRequest = CreateImageRequest.builder() .prompt(prompt) .responseFormat("b64_json") .model(config.model) .size(config.size) .quality(config.quality) .style(config.style) .build(); return service.createImage(imageRequest); } public ChatCompletionResult chat(List<ChatMessage> messages, AiConfig config) { var key = refRepository.findAll(selector("_openai/key" + props.getLocalOrigin()).refSpec()); if (key.isEmpty()) { throw new NotFoundException("requires openai api key"); } OpenAiService service = new OpenAiService(key.get(0).getComment(), Duration.ofSeconds(200)); ChatCompletionRequest completionRequest = ChatCompletionRequest .builder() .model(config.model) .maxTokens(config.maxTokens) .messages(messages) .build(); return service.createChatCompletion(completionRequest); } public static ChatMessage cm(String origin, String role, String title, String content, ObjectMapper om) { var result = new ChatMessage(); result.setRole(role); result.setContent(ref(origin, role, title, content, om)); return result; } public static ChatMessage cm(String role, String content) { var result = new ChatMessage(); result.setRole(role); result.setContent(content); return result; } public static String ref(String origin, String role, String title, String content, ObjectMapper om) { var result = new RefDto(); result.setOrigin(origin); result.setTitle(title); result.setComment(content); if (role.equals("system")) { result.setUrl("system:instructions"); result.setTags(List.of("system", "internal", "notes", "+plugin/openai")); } else { result.setUrl("system:user-instructions"); result.setTags(List.of("dm", "internal", "plugin/thread")); } try { return om.writeValueAsString(result); } catch (JsonProcessingException e) { logger.error("Cannot write content to Ref {}", content, e); throw new RuntimeException(e); } } public static class AiConfig { public String model = "gpt-4-turbo-preview"; public List<String> fallback; public int maxTokens = 4096; public int maxContext = 7; public String systemPrompt; } public static class DalleConfig { public String size = "1024x1024"; public String model = "dall-e-3"; public String quality = "hd"; public String style = "vivid"; } }
[ "com.theokanning.openai.image.CreateImageRequest.builder", "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((1947, 2159), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1947, 2147), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1947, 2108), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1947, 2024), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1947, 2004), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3729, 3917), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3729, 3905), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3729, 3881), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3729, 3853), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3729, 3831), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3729, 3807), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3729, 3776), 'com.theokanning.openai.image.CreateImageRequest.builder')]
package run.halo.live2d.chat.client.openai; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionResult; import com.theokanning.openai.completion.chat.ChatMessage; import java.util.List; import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.codec.ServerSentEvent; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import run.halo.app.infra.utils.JsonUtils; import run.halo.app.plugin.ReactiveSettingFetcher; import run.halo.live2d.chat.ChatResult; import run.halo.live2d.chat.WebClientFactory; import run.halo.live2d.chat.client.ChatClient; @Slf4j @Component public class OpenAiChatClient implements ChatClient { public final static String DEFAULT_OPEN_AI_API_URL = "https://api.openai.com"; public final static String CHAT_COMPLETION_PATH = "/v1/chat/completions"; public final static String DEFAULT_MODEL = "gpt-3.5-turbo"; private final ReactiveSettingFetcher reactiveSettingFetcher; private final WebClientFactory webClientFactory; public OpenAiChatClient(WebClientFactory webClientFactory, ReactiveSettingFetcher reactiveSettingFetcher) { this.webClientFactory = webClientFactory; this.reactiveSettingFetcher = reactiveSettingFetcher; } @Override public Flux<ServerSentEvent<ChatResult>> generate(List<ChatMessage> messages) { return reactiveSettingFetcher.fetch("aichat", OpenAiConfig.class) .filter(openAiConfig -> openAiConfig.openAiSetting.isOpenAi) .flatMapMany(openAiConfig -> { var webClient = webClientFactory .createWebClientBuilder() .map(build -> build.baseUrl(openAiConfig.openAiSetting.openAiBaseUrl) .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + openAiConfig.openAiSetting.openAiToken) .build() ); var request = ChatCompletionRequest.builder() .model(openAiConfig.openAiSetting.openAiModel) .messages(messages) .stream(true) .build(); return webClient.flatMapMany(client -> client.post() .uri(CHAT_COMPLETION_PATH) .accept(MediaType.TEXT_EVENT_STREAM) .contentType(MediaType.APPLICATION_JSON) .bodyValue(JsonUtils.objectToJson(request)) .retrieve() .bodyToFlux(String.class)) .flatMap(data -> { if (StringUtils.equals("[DONE]", data)) { return Mono.just(ServerSentEvent.builder(ChatResult.finish()).build()); } var chatCompletionResult = JsonUtils.jsonToObject(data, ChatCompletionResult.class); if (Objects.nonNull(chatCompletionResult.getChoices())) { var choice = chatCompletionResult.getChoices().get(0); if (StringUtils.isNotBlank(choice.getFinishReason())) { return Flux.empty(); } if (Objects.isNull(choice.getMessage()) || StringUtils.isEmpty(choice.getMessage().getContent()) ) { return Flux.empty(); } else { return Mono.just( ServerSentEvent.builder( ChatResult.ok(choice.getMessage().getContent())) .build() ); } } return Mono.just(ServerSentEvent.builder(ChatResult.finish()).build()); }) .onTerminateDetach() .doOnCancel(() -> { // 在中止事件时执行逻辑 log.info("Client manually canceled the SSE stream."); }); }); } @Override public Mono<Boolean> supports() { return reactiveSettingFetcher.fetch("aichat", OpenAiConfig.class) .filter((openAiConfig) -> openAiConfig.openAiSetting.isOpenAi) .hasElement(); } record OpenAiConfig(OpenAiSetting openAiSetting){ } record OpenAiSetting(boolean isOpenAi, String openAiToken, String openAiBaseUrl, String openAiModel) { OpenAiSetting { if (isOpenAi) { if (StringUtils.isBlank(openAiToken)) { throw new IllegalArgumentException("OpenAI token must not be blank"); } if (StringUtils.isBlank(openAiBaseUrl)) { openAiBaseUrl = DEFAULT_OPEN_AI_API_URL; } if (StringUtils.isBlank(openAiModel)) { openAiModel = DEFAULT_MODEL; } } } } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((2227, 2428), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2227, 2399), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2227, 2365), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2227, 2325), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2982, 3034), 'org.springframework.http.codec.ServerSentEvent.builder'), ((3899, 4065), 'org.springframework.http.codec.ServerSentEvent.builder'), ((4198, 4250), 'org.springframework.http.codec.ServerSentEvent.builder')]
package org.example.chatgpt.service; import cn.hutool.core.util.StrUtil; import com.fasterxml.jackson.databind.ObjectMapper; import com.theokanning.openai.OpenAiApi; import com.theokanning.openai.service.OpenAiService; import okhttp3.OkHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import java.net.InetSocketAddress; import java.net.Proxy; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static com.theokanning.openai.service.OpenAiService.*; import static org.example.chatgpt.service.ChatService.sendStopEvent; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import retrofit2.Retrofit; import java.io.IOException; import javabean.LogForDB; /** * 会话服务 * * @author lijiatao * 时间: 2023/12/6 */ @Service public class ASTEService { private static final Logger LOG = LoggerFactory.getLogger(ChatService.class); //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 // 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 // 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 String token = "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"; String proxyHost = "127.0.0.1"; int proxyPort = 7890; String prompt_extract = "属性情感三元组抽取(Aspect Sentiment Triplet Extraction ,ASTE)任务是在AAAI 2020里被提出的一个新任务,被划为属性级情感分析(Aspect-based sentiment analysis ,ABSA)任务的一个子任务。ASTE的定义是抽取出其中包含的三元组<属性,情感,观点>,其目的是从句子中获得全面的信息,用于情感分析。在这里,属性(aspect)指评价的对象,情感(sentiment)是指对象在上下文中的整体情感,一般包括正向,中性,负向和冲突(conflict),观点(opinion)则是评论对象时用到的描述词。比如,对于一个句子“这盘空心菜很好吃,但是不好看\",ASTE则会抽取出两个三元组:<空心菜,冲突,好吃> 和 <空心菜,冲突,不好看>。" + "现在请你执行三元组抽取任务:给定一段文本,抽取其中的三元组。输出的格式为" + "属性-情感-观点" + "请严格遵循格式,并除此以外不要输出其它任何内容。文本如下:"; @Async public void asteCompletion(String prompt, SseEmitter sseEmitter) throws IOException { LogForDB logForDB = new LogForDB(); LOG.info("发送消息:" + prompt); String prompt1 = prompt_extract + prompt; final List<ChatMessage> messages = new ArrayList<>(); final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), prompt1); messages.add(systemMessage); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest .builder() .model("gpt-3.5-turbo") .messages(messages) .n(1) .maxTokens(500) .logitBias(new HashMap<>()) .build(); //完整对话 StringBuilder receiveMsgBuilder = new StringBuilder(); OpenAiService service = buildOpenAiService(token, proxyHost, proxyPort); service.createChatCompletion(chatCompletionRequest) .getChoices() .forEach(x-> { try { sseEmitter.send(x.getMessage().getContent()); } catch (IOException e) { throw new RuntimeException(e); } String content = x.getMessage().getContent(); content = content == null ? StrUtil.EMPTY : content; receiveMsgBuilder.append(content); }); LOG.info("收到的完整消息:" + receiveMsgBuilder); sendStopEvent(sseEmitter); service.shutdownExecutor(); LOG.info("连接结束"); logForDB.log2DB("ASTE", prompt, String.valueOf(receiveMsgBuilder)); } /** * 构建OpenAiService * * @param token API_KEY * @param proxyHost 代理域名 * @param proxyPort 代理端口号 * @return OpenAiService */ private OpenAiService buildOpenAiService(String token, String proxyHost, int proxyPort) { //构建HTTP代理 Proxy proxy = null; if (StrUtil.isNotBlank(proxyHost)) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } //构建HTTP客户端 OkHttpClient client = defaultClient(token, Duration.of(60, ChronoUnit.SECONDS)) .newBuilder() .proxy(proxy) .build(); ObjectMapper mapper = defaultObjectMapper(); Retrofit retrofit = defaultRetrofit(client, mapper); OpenAiApi api = retrofit.create(OpenAiApi.class); return new OpenAiService(api, client.dispatcher().executorService()); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value" ]
[((3100, 3130), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value')]
package org.lambda.framework.openai.service.chat; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import jakarta.annotation.Resource; import org.apache.commons.lang3.StringUtils; import org.lambda.framework.common.exception.EventException; import org.lambda.framework.openai.OpenAiContract; import org.lambda.framework.openai.OpenAiConversation; import org.lambda.framework.openai.OpenAiConversations; import org.lambda.framework.openai.OpenAiReplying; import org.lambda.framework.openai.enums.OpenAiModelEnum; import org.lambda.framework.openai.enums.OpenaiExceptionEnum; import org.lambda.framework.openai.service.chat.param.OpenAiChatParam; import org.lambda.framework.openai.service.chat.response.OpenAiChatReplied; import org.lambda.framework.redis.operation.ReactiveRedisOperation; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; import java.time.Duration; import java.util.LinkedList; import java.util.List; import static org.lambda.framework.openai.OpenAiContract.currentTime; import static org.lambda.framework.openai.OpenAiContract.encoding; @Component public class OpenAiChatService implements OpenAiChatFunction { @Resource(name = "openAiChatRedisOperation") private ReactiveRedisOperation openAiChatRedisOperation; @Override public Mono<OpenAiReplying<OpenAiChatReplied>> execute(OpenAiChatParam param) { //参数校验 param.verify(); String uniqueId = OpenAiContract.uniqueId(param.getUserId(),param.getUniqueParam().getUniqueTime()); return openAiChatRedisOperation.get(uniqueId) .onErrorResume(e->Mono.error(new EventException(OpenaiExceptionEnum.ES_OPENAI_007))) .defaultIfEmpty(Mono.empty()) .flatMap(e->{ List<ChatMessage> chatMessage = null; List<OpenAiChatReplied> openAiChatReplied = null; List<OpenAiConversation<OpenAiChatReplied>> openAiConversation = null; OpenAiConversations<OpenAiChatReplied> openAiConversations = null; Integer tokens = 0; if(e.equals(Mono.empty())){ //没有历史聊天记录,第一次对话,装载AI人设 chatMessage = new LinkedList<>(); openAiChatReplied = new LinkedList<>(); if(StringUtils.isNotBlank(param.getPersona())){ chatMessage.add(new ChatMessage(ChatMessageRole.SYSTEM.value(),param.getPersona())); openAiChatReplied.add(new OpenAiChatReplied(ChatMessageRole.SYSTEM.value(),param.getPersona(),currentTime())); tokens = tokens + encoding(param.getPersona()); } chatMessage.add(new ChatMessage(ChatMessageRole.USER.value(),param.getPrompt())); openAiChatReplied.add(new OpenAiChatReplied(ChatMessageRole.USER.value(),param.getPrompt(),currentTime())); tokens = tokens + encoding(param.getPrompt()); openAiConversation = new LinkedList<>(); OpenAiConversation<OpenAiChatReplied> _openAiConversation = new OpenAiConversation<OpenAiChatReplied>(); _openAiConversation.setConversation(openAiChatReplied); openAiConversation.add(_openAiConversation); openAiConversations = new OpenAiConversations<OpenAiChatReplied>(); openAiConversations.setOpenAiConversations(openAiConversation); }else { List<ChatMessage> _chatMessage = new LinkedList<>(); openAiConversations = new ObjectMapper().convertValue(e, new TypeReference<>(){}); openAiConversations.getOpenAiConversations().forEach(_conversations->{ _conversations.getConversation().forEach(message->{ _chatMessage.add(new ChatMessage(message.getRole(),message.getContent())); }); }); chatMessage = _chatMessage; chatMessage.add(new ChatMessage(ChatMessageRole.USER.value(),param.getPrompt())); openAiChatReplied = new LinkedList<>(); openAiChatReplied.add(new OpenAiChatReplied(ChatMessageRole.USER.value(),param.getPrompt(),currentTime())); tokens = tokens + encoding(param.getPrompt()); OpenAiConversation<OpenAiChatReplied> _openAiConversation = new OpenAiConversation<>(); _openAiConversation.setConversation(openAiChatReplied); openAiConversations.getOpenAiConversations().add(_openAiConversation); //多轮对话要计算所有的tokens tokens = Math.toIntExact(tokens + openAiConversations.getTotalTokens()); } limitVerify(param.getQuota(),param.getMaxTokens(),tokens); limitVerifyByModel(OpenAiModelEnum.TURBO,param.getQuota(),param.getMaxTokens(),tokens); OpenAiService service = new OpenAiService(param.getApiKey(),Duration.ofSeconds(param.getTimeOut())); ChatCompletionRequest request = ChatCompletionRequest.builder() .model(OpenAiModelEnum.TURBO.getModel()) .messages(chatMessage) .temperature(param.getTemperature()) .topP(param.getTopP()) .n(param.getN()) .stream(param.getStream()) .maxTokens(param.getMaxTokens()) .presencePenalty(param.getPresencePenalty()) .frequencyPenalty(param.getFrequencyPenalty()) .build(); OpenAiConversations<OpenAiChatReplied> finalOpenAiConversations = openAiConversations; return Mono.fromCallable(() -> service.createChatCompletion(request)) .onErrorMap(throwable -> new EventException(OpenaiExceptionEnum.ES_OPENAI_006, throwable.getMessage())) .flatMap(chatCompletionResult -> { ChatMessage _chatMessage = chatCompletionResult.getChoices().get(0).getMessage(); OpenAiConversation<OpenAiChatReplied> _openAiConversation = finalOpenAiConversations.getOpenAiConversations().get(finalOpenAiConversations.getOpenAiConversations().size()-1); _openAiConversation.setPromptTokens(chatCompletionResult.getUsage().getPromptTokens()); _openAiConversation.setCompletionTokens(chatCompletionResult.getUsage().getCompletionTokens()); _openAiConversation.setTotalTokens(chatCompletionResult.getUsage().getTotalTokens()); _openAiConversation.getConversation().add(new OpenAiChatReplied(_chatMessage.getRole(),_chatMessage.getContent(), OpenAiContract.currentTime())); finalOpenAiConversations.setTotalTokens(finalOpenAiConversations.getTotalTokens() + chatCompletionResult.getUsage().getTotalTokens()); finalOpenAiConversations.setTotalPromptTokens(finalOpenAiConversations.getTotalPromptTokens() + chatCompletionResult.getUsage().getPromptTokens()); finalOpenAiConversations.setTotalCompletionTokens(finalOpenAiConversations.getTotalCompletionTokens() + chatCompletionResult.getUsage().getCompletionTokens()); openAiChatRedisOperation.set(uniqueId, finalOpenAiConversations).subscribe(); return Mono.just(_openAiConversation); }) .flatMap(current->{ OpenAiReplying<OpenAiChatReplied> openAiReplying = new OpenAiReplying<OpenAiChatReplied>(); openAiReplying.setReplying(current.getConversation().get(current.getConversation().size()-1)); openAiReplying.setPromptTokens(current.getPromptTokens()); openAiReplying.setCompletionTokens(current.getCompletionTokens()); openAiReplying.setTotalTokens(current.getTotalTokens()); return Mono.just(openAiReplying); }); }); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value", "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((2799, 2829), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((2924, 2954), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3149, 3177), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((3267, 3295), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((4587, 4615), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((4769, 4797), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((5735, 6388), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 6347), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 6268), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 6191), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 6126), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 6067), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 6018), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 5963), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 5894), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5735, 5839), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5806, 5838), 'org.lambda.framework.openai.enums.OpenAiModelEnum.TURBO.getModel'), ((6525, 9074), 'reactor.core.publisher.Mono.fromCallable'), ((6525, 8398), 'reactor.core.publisher.Mono.fromCallable'), ((6525, 6719), 'reactor.core.publisher.Mono.fromCallable')]
package com.nashss.se.yodaservice.activity; import com.nashss.se.yodaservice.activity.requests.AiRequest; import com.nashss.se.yodaservice.activity.results.AiResult; import com.nashss.se.yodaservice.dynamodb.PHRDAO; import com.nashss.se.yodaservice.dynamodb.models.PHR; import com.nashss.se.yodaservice.prompt.PromptStandard; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import javax.inject.Inject; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class AiActivity { private final OpenAiService openAiService; private final PHRDAO phrdao; @Inject public AiActivity(OpenAiService openAiService1, PHRDAO phrdao) { this.openAiService = openAiService1; this.phrdao = phrdao; } public AiResult handleRequest(final AiRequest request) { try { PHR existingPhr = phrdao.getPHR(request.getPhrId(), request.getDate()); PromptStandard prompt = new PromptStandard(existingPhr.getComprehendData(), existingPhr.getTranscription()); List<ChatMessage> messages = new ArrayList<>(); ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(),prompt.toString()); messages.add(userMessage); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .model("gpt-4") .messages(messages) .logitBias(new HashMap<>()) .build(); try { System.out.println("Completion initiated"); String completion = openAiService.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage().getContent(); try { List<String> pastAi = existingPhr.getAiDifferentials(); pastAi.add(completion); existingPhr.setAiDifferentials(pastAi); phrdao.savePHR(existingPhr); } catch (NullPointerException npe) { List<String> pastAi = new ArrayList<>(); pastAi.add(completion); existingPhr.setAiDifferentials(pastAi); phrdao.savePHR(existingPhr); } return AiResult.builder() .withDifferential(completion) .build(); } catch (RuntimeException RE) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); RE.printStackTrace(pw); throw new RuntimeException("Error while creating chat completion with OpenAI service: \n" + sw); } } catch (Exception RE) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); RE.printStackTrace(pw); throw new RuntimeException("Error while receiving completion data: \n" + sw); } } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value", "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1400, 1428), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((1546, 1730), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1546, 1701), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1546, 1653), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1546, 1613), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2510, 2615), 'com.nashss.se.yodaservice.activity.results.AiResult.builder'), ((2510, 2582), 'com.nashss.se.yodaservice.activity.results.AiResult.builder')]
package com.couchbase.intellij.tree.iq.chat; import com.didalgo.gpt3.ChatFormatDescriptor; import com.didalgo.gpt3.GPT3Tokenizer; import com.didalgo.gpt3.ModelType; import com.couchbase.intellij.tree.iq.core.TextSubstitutor; import com.couchbase.intellij.tree.iq.text.TextContent; import com.intellij.openapi.application.ApplicationInfo; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.function.Supplier; import static com.couchbase.intellij.tree.iq.chat.ChatMessageUtils.countTokens; import static com.couchbase.intellij.tree.iq.chat.ChatMessageUtils.isRoleSystem; public class ChatLinkState implements ConversationContext { private final LinkedList<ChatMessage> chatMessages = new LinkedList<>(); private volatile List<? extends TextContent> lastSentTextFragments = List.of(); private volatile TextSubstitutor textSubstitutor = TextSubstitutor.NONE; private final ConfigurationPage configuration; public ChatLinkState(ConfigurationPage configuration) { this.configuration = configuration; } public ConfigurationPage getModelConfiguration() { var configuration = this.configuration; if (configuration == null) throw new UnsupportedOperationException("ModelConfiguration is not supported by this ChatLink instance"); return configuration; } public void setTextSubstitutor(TextSubstitutor textSubstitutor) { this.textSubstitutor = Objects.requireNonNull(textSubstitutor); } public final TextSubstitutor getTextSubstitutor() { return textSubstitutor; } public Supplier<String> getSystemPrompt() { return getModelConfiguration().getSystemPrompt(); } @Override public List<? extends TextContent> getLastPostedCodeFragments() { return lastSentTextFragments; } @Override public void setLastPostedCodeFragments(List<? extends TextContent> textContents) { Objects.requireNonNull(textContents); this.lastSentTextFragments = textContents; } @Override public void addChatMessage(ChatMessage message) { if (message.getContent() == null) message = new ChatMessage(message.getRole(), ""); synchronized (chatMessages) { if (!chatMessages.isEmpty()) { if (message.getRole() == null || isRoleSystem(chatMessages.getLast()) && isRoleSystem(message)) { ChatMessage last = chatMessages.removeLast(); message = new ChatMessage(last.getRole(), last.getContent() + message.getContent()); } else if (Objects.equals(chatMessages.getLast().getRole(), message.getRole())) chatMessages.removeLast(); } chatMessages.add(message); } } @Override public ModelType getModelType() { String modelName = getModelConfiguration().getModelName(); return ModelType.forModel(modelName).orElseThrow(); } @Override public List<ChatMessage> getChatMessages(ModelType model, ChatMessage userMessage) { var chatMessages = new LinkedList<ChatMessage>(); // Add the rest of messages in the chat synchronized (this.chatMessages) { if (!this.chatMessages.isEmpty()) this.chatMessages.stream() .filter(chatMessage -> !ChatMessageRole.SYSTEM.value().equals(chatMessage.getRole())) .forEach(chatMessages::add); // Substitute template placeholders substitutePlaceholders(chatMessages); // add the system prompt var systemMessage = getSystemPrompt().get(); if (!systemMessage.isBlank()) { systemMessage = systemMessage.stripTrailing() + "\n\nCurrent IDE: " + ApplicationInfo.getInstance().getFullApplicationName() + "\nOS: " + System.getProperty("os.name"); chatMessages.add(0, new ChatMessage(ChatMessageRole.SYSTEM.value(), systemMessage)); } // Trim messages if exceeding token limit //int maxTokens = model.maxTokens(); // hard-coded as I couldn't find API to set it int maxTokens = 4097; var tokenizer = model.getTokenizer(); var chatFormatDescriptor = model.getChatFormatDescriptor(); int removed = dropOldestMessagesToStayWithinTokenLimit(chatMessages, maxTokens, tokenizer, chatFormatDescriptor); while (removed-- > 0) this.chatMessages.remove(0); return chatMessages; } } public void substitutePlaceholders(List<ChatMessage> chatMessages) { ChatMessageUtils.substitutePlaceholders(chatMessages, getTextSubstitutor()); } public int dropOldestMessagesToStayWithinTokenLimit(List<ChatMessage> messages, int maxTokens, GPT3Tokenizer tokenizer, ChatFormatDescriptor formatDescriptor) { // here we assume ratio at most 2/3 available tokens for input prompt with context history, // and at least 1/3 tokens for output int tokenLimit = maxTokens*2/3; int tokenCount; int removed = 0; boolean hasSystemMessage = !messages.isEmpty() && isRoleSystem(messages.get(0)); int oldestMessageIndex = hasSystemMessage? 1: 0; while ((tokenCount = countTokens(messages, tokenizer, formatDescriptor)) > tokenLimit && oldestMessageIndex < messages.size() - 1) { messages.remove(oldestMessageIndex); removed++; } if (tokenCount > tokenLimit) { var lastMessage = messages.get(oldestMessageIndex); // TODO: calculation is currently wrong var lastMsgCutoff = lastMessage.getContent().length() - tokenLimit; if (lastMsgCutoff > 0) messages.set(oldestMessageIndex, new ChatMessage(lastMessage.getRole(), "[...] " + lastMessage.getContent().substring(lastMsgCutoff))); } return removed; } @Override public String getModelPage() { return getModelConfiguration().getModelPage(); } @Override public void clear() { chatMessages.clear(); setLastPostedCodeFragments(List.of()); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value" ]
[((3089, 3132), 'com.didalgo.gpt3.ModelType.forModel'), ((3532, 3592), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3532, 3562), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((4003, 4057), 'com.intellij.openapi.application.ApplicationInfo.getInstance'), ((4178, 4208), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value')]
package com.wy.chatting.domain.chatgpt.service.dto.request; import com.theokanning.openai.completion.CompletionRequest; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @NoArgsConstructor @AllArgsConstructor public class GPTCompletionRequest { private String model; private String prompt; private Integer maxToken; public static CompletionRequest of(GPTCompletionRequest restRequest) { return CompletionRequest.builder() .model(restRequest.getModel()) .prompt(restRequest.getPrompt()) .maxTokens(restRequest.getMaxToken()) .build(); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((472, 674), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((472, 649), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((472, 595), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((472, 546), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package egovframework.example.API; import java.time.Duration; import java.util.List; import com.theokanning.openai.embedding.Embedding; import com.theokanning.openai.embedding.EmbeddingRequest; import com.theokanning.openai.service.OpenAiService; public class OAISingleton { //create and manage OpenAiService singleton. public static OAISingleton instance = new OAISingleton(); private static OpenAiService service; private OAISingleton() { try { service = new OpenAiService(Keys.OPENAPI_KEY,Duration.ofMinutes(9999)); } catch(Exception e) { throw new RuntimeException("Error While creating class: OAISingleton\n"); } } public static OAISingleton getInstance() { return instance; } private EmbeddingRequest emb = new EmbeddingRequest(); private EmbeddingRequest getEmbeddingModel(String model, List<String> input) { new EmbeddingRequest(); return EmbeddingRequest.builder() .input(input) .model(model) .build(); } //build and return data public List<Embedding> getEmbeddingData(String model, List<String> input){ OpenAiService s = service; emb = getEmbeddingModel(model,input); return s.createEmbeddings(emb).getData(); } public List<Embedding> getEmbeddingData(List<String> input){ OpenAiService s = service; emb = getEmbeddingModel("text-embedding-ada-002",input); return s.createEmbeddings(emb).getData(); } }
[ "com.theokanning.openai.embedding.EmbeddingRequest.builder" ]
[((884, 959), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((884, 946), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((884, 928), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')]
package com.datasqrl.ai.spring; import com.datasqrl.ai.Examples; import com.datasqrl.ai.api.GraphQLExecutor; import com.datasqrl.ai.backend.APIChatBackend; import com.datasqrl.ai.backend.AnnotatedChatMessage; import com.datasqrl.ai.backend.MessageTruncator; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.knuddels.jtokkit.Encodings; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionRequest.ChatCompletionRequestFunctionCall; import com.theokanning.openai.completion.chat.ChatFunctionCall; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import java.io.IOException; import java.net.URL; import java.nio.file.Path; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.*; import java.util.Arrays; import java.util.List; @SpringBootApplication public class SimpleServer { public static final String DEFAULT_GRAPHQL_ENDPOINT = "http://localhost:8888/graphql"; public static void main(String[] args) { SpringApplication.run(SimpleServer.class, args); } @CrossOrigin(origins = "*") @RestController public static class MessageController { private final Examples example; OpenAiService service; GraphQLExecutor apiExecutor; APIChatBackend backend; ChatMessage systemMessage; MessageTruncator messageTruncator; List functions; String chartFunctionName=""; public MessageController(@Value("${example:nutshop}") String exampleName) throws IOException { this.example = Examples.valueOf(exampleName.trim().toUpperCase()); String openAIToken = System.getenv("OPENAI_TOKEN"); this.service = new OpenAiService(openAIToken, Duration.ofSeconds(60)); String graphQLEndpoint = DEFAULT_GRAPHQL_ENDPOINT; this.apiExecutor = new GraphQLExecutor(graphQLEndpoint); this.backend = APIChatBackend.of(Path.of(example.getConfigFile()), apiExecutor); this.systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), example.getSystemPrompt()); this.messageTruncator = new MessageTruncator(example.getModel().getMaxInputTokens(), systemMessage, Encodings.newDefaultEncodingRegistry().getEncodingForModel(example.getModel().getEncodingModel())); this.functions = new ArrayList<>(); this.functions.addAll(backend.getChatFunctions()); if (example.isSupportCharts()) { ObjectMapper objectMapper = new ObjectMapper(); URL url = SimpleServer.class.getClassLoader().getResource("plotfunction.json"); if (url != null) { try { JsonNode functionJson = objectMapper.readTree(url); this.chartFunctionName = functionJson.get("name").textValue(); this.functions.add(functionJson); } catch (IOException e) { e.printStackTrace(); } } } } private Map<String,Object> getContext(String userId) { return Map.of(example.getUserIdFieldName(), example.getPrepareUserIdFct().apply( userId)); } @GetMapping("/messages") public List<ResponseMessage> getMessages(@RequestParam String userId) { Map<String,Object> context = getContext(userId); List<AnnotatedChatMessage> messages = backend.getChatMessages(context, 50); return messages.stream().filter(msg -> { ChatMessage m = msg.getMessage(); ChatMessageRole role = ChatMessageRole.valueOf(m.getRole().toUpperCase()); switch (role) { case USER: case ASSISTANT: return true; } return false; }).map(ResponseMessage::of).collect(Collectors.toUnmodifiableList()); } @PostMapping("/messages") public ResponseMessage postMessage(@RequestBody InputMessage message) { Map<String,Object> context = getContext(message.getUserId()); List<ChatMessage> messages = new ArrayList<>(30); backend.getChatMessages(context, 20).stream().map(AnnotatedChatMessage::getMessage) .forEach(messages::add); System.out.printf("Retrieved %d messages\n", messages.size()); ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), message.getContent()); messages.add(chatMessage); backend.saveChatMessage(chatMessage, context); while (true) { System.out.println("Calling OpenAI"); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest .builder() .model(example.getModel().getOpenAIModel()) .messages(messageTruncator.truncateMessages(messages, backend.getChatFunctions())) .functions(functions) .functionCall(ChatCompletionRequestFunctionCall.of("auto")) .n(1) .maxTokens(example.getModel().getCompletionLength()) .logitBias(new HashMap<>()) .build(); ChatMessage responseMessage = service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage(); messages.add(responseMessage); // don't forget to update the conversation with the latest response backend.saveChatMessage(responseMessage, context); ChatFunctionCall functionCall = responseMessage.getFunctionCall(); if (functionCall != null && !functionCall.getName().equalsIgnoreCase(chartFunctionName)) { System.out.println("Executing " + functionCall.getName() + " with arguments " + functionCall.getArguments().toPrettyString()); ChatMessage functionResponse = backend.executeAndConvertToMessageHandlingExceptions( functionCall, context); //System.out.println("Executed " + fctCall.getName() + "."); messages.add(functionResponse); backend.saveChatMessage(functionResponse, context); } else { //The text answer return ResponseMessage.of(responseMessage); } } } } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((2444, 2474), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((2620, 2717), 'com.knuddels.jtokkit.Encodings.newDefaultEncodingRegistry'), ((4611, 4639), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')]
package org.example.openai; import static com.theokanning.openai.service.OpenAiService.defaultClient; import static com.theokanning.openai.service.OpenAiService.defaultObjectMapper; import static com.theokanning.openai.service.OpenAiService.defaultRetrofit; import com.fasterxml.jackson.databind.ObjectMapper; import com.theokanning.openai.OpenAiApi; import com.theokanning.openai.embedding.EmbeddingRequest; import com.theokanning.openai.service.OpenAiService; import java.time.Duration; import java.util.Collections; import java.util.List; import okhttp3.OkHttpClient; import org.example.EmbeddingsGenerator; import retrofit2.Retrofit; public class OpenAiConnector implements EmbeddingsGenerator { private final OpenAiService openAiService; public OpenAiConnector() { ObjectMapper objectMapper = defaultObjectMapper(); OkHttpClient client = defaultClient(System.getenv("OPENAI_API_KEY"), Duration.ofSeconds(30)); Retrofit retrofit = defaultRetrofit(client, objectMapper); OpenAiApi api = retrofit.create(OpenAiApi.class); openAiService = new OpenAiService(api); } public List<Double> getEmbeddings(String sentence) { var request = EmbeddingRequest.builder() .model("text-embedding-ada-002") .input(Collections.singletonList(sentence)) .build(); var response = openAiService.createEmbeddings(request); return response.getData().get(0).getEmbedding(); } }
[ "com.theokanning.openai.embedding.EmbeddingRequest.builder" ]
[((1179, 1327), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((1179, 1306), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((1179, 1250), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')]
package io.qifan.chatgpt.assistant; import com.fasterxml.jackson.databind.ObjectMapper; import com.theokanning.openai.OpenAiApi; import com.theokanning.openai.completion.chat.ChatCompletionChunk; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.service.OpenAiService; import io.qifan.chatgpt.assistant.gpt.session.ChatSession; import io.qifan.chatgpt.assistant.infrastructure.gpt.GPTProperty; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import okhttp3.OkHttpClient; import org.junit.jupiter.api.Test; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.mongodb.core.MongoTemplate; import retrofit2.Retrofit; import java.net.InetSocketAddress; import java.net.Proxy; import java.time.Duration; import java.util.List; import java.util.concurrent.CountDownLatch; import static com.theokanning.openai.service.OpenAiService.*; @SpringBootTest @Slf4j public class ApplicationTest { @Autowired GPTProperty property; @Autowired MongoTemplate mongoTemplate; @Test void findById() { List<ChatSession> all = mongoTemplate.findAll(ChatSession.class); all.forEach(chatSession -> log.info(chatSession.toString())); } @SneakyThrows @Test void chatTest() { ObjectMapper mapper = defaultObjectMapper(); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(property.getProxy().getHost(), property.getProxy().getPort())); OkHttpClient client = defaultClient("", Duration.ofMinutes(1)) .newBuilder() .proxy(proxy) .build(); Retrofit retrofit = defaultRetrofit(client, mapper); OpenAiApi api = retrofit.create(OpenAiApi.class); OpenAiService service = new OpenAiService(api); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .messages(List.of(new ChatMessage("user", "你好"))) .model("gpt-3.5-turbo") // .model(chatConfig.getModel().getName()) // .presencePenalty(chatConfig.getPresencePenalty()) // .temperature(chatConfig.getTemperature()) // .maxTokens(chatConfig.getMaxTokens()) .stream(true) .build(); CountDownLatch countDownLatch = new CountDownLatch(1); service.streamChatCompletion(chatCompletionRequest).subscribe(new Subscriber<>() { private Subscription subscription; private io.qifan.chatgpt.assistant.gpt.message.ChatMessage responseChatMessage; @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(1); responseChatMessage = new io.qifan.chatgpt.assistant.gpt.message.ChatMessage().setContent(""); log.info("订阅"); } @Override public void onNext(ChatCompletionChunk chatCompletionChunk) { com.theokanning.openai.completion.chat.ChatMessage chatMessage = chatCompletionChunk.getChoices().get(0) .getMessage(); if (chatMessage.getContent() != null) { log.info("收到响应消息:{}", chatMessage); responseChatMessage.setContent(responseChatMessage.getContent() + chatMessage.getContent()); responseChatMessage.setRole(chatMessage.getRole()); } subscription.request(1); } @Override public void onError(Throwable throwable) { throwable.printStackTrace(); } @Override public void onComplete() { log.info("请求结束"); countDownLatch.countDown(); } }); countDownLatch.await(); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((2165, 3184), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2165, 3100), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2165, 2533), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2165, 2434), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package com.theokanning.openai.service; import com.theokanning.openai.embedding.Embedding; import com.theokanning.openai.embedding.EmbeddingRequest; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.assertFalse; public class EmbeddingTest { String token = System.getenv("OPENAI_TOKEN"); com.theokanning.openai.service.OpenAiService service = new OpenAiService(token); @Test void createEmbeddings() { EmbeddingRequest embeddingRequest = EmbeddingRequest.builder() .model("text-similarity-babbage-001") .input(Collections.singletonList("The food was delicious and the waiter...")) .build(); List<Embedding> embeddings = service.createEmbeddings(embeddingRequest).getData(); assertFalse(embeddings.isEmpty()); assertFalse(embeddings.get(0).getEmbedding().isEmpty()); } }
[ "com.theokanning.openai.embedding.EmbeddingRequest.builder" ]
[((552, 751), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((552, 726), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((552, 632), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')]
package com.theokanning.openai.service; import com.theokanning.openai.DeleteResult; import com.theokanning.openai.ListSearchParameters; import com.theokanning.openai.OpenAiResponse; import com.theokanning.openai.assistants.*; import com.theokanning.openai.file.File; import com.theokanning.openai.utils.TikTokensUtil; import org.junit.jupiter.api.*; import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AssistantTest { static OpenAiService service = new OpenAiService(System.getenv("OPENAI_TOKEN")); static String assistantId; static String fileId; @AfterAll static void teardown() { try { service.deleteAssistantFile(assistantId, fileId); } catch (Exception e) { // do nothing } try { service.deleteAssistant(assistantId); } catch (Exception e) { // do nothing } } @Test @Order(1) void createAssistant() { AssistantRequest assistantRequest = AssistantRequest.builder().model(TikTokensUtil.ModelEnum.GPT_4_1106_preview.getName()).name("Math Tutor").instructions("You are a personal Math Tutor.").tools(Collections.singletonList(new Tool(AssistantToolsEnum.CODE_INTERPRETER, null))).build(); Assistant assistant = service.createAssistant(assistantRequest); assistantId = assistant.getId(); assertEquals(assistant.getName(), "Math Tutor"); assertEquals(assistant.getTools().get(0).getType(), AssistantToolsEnum.CODE_INTERPRETER); } @Test @Order(2) void retrieveAssistant() { Assistant assistant = service.retrieveAssistant(assistantId); assertEquals(assistant.getName(), "Math Tutor"); } @Test @Order(3) void modifyAssistant() { String modifiedName = "Science Tutor"; ModifyAssistantRequest modifyRequest = ModifyAssistantRequest.builder().name(modifiedName).build(); Assistant modifiedAssistant = service.modifyAssistant(assistantId, modifyRequest); assertEquals(modifiedName, modifiedAssistant.getName()); } @Test @Order(4) void listAssistants() { OpenAiResponse<Assistant> assistants = service.listAssistants(ListSearchParameters.builder().build()); assertNotNull(assistants); assertFalse(assistants.getData().isEmpty()); } @Test @Order(5) void createAssistantFile() { String filePath = "src/test/resources/assistants-data.html"; File uploadedFile = service.uploadFile("assistants", filePath); AssistantFile assistantFile = service.createAssistantFile(assistantId, new AssistantFileRequest(uploadedFile.getId())); fileId = assistantFile.getId(); assertNotNull(assistantFile); assertEquals(uploadedFile.getId(), assistantFile.getId()); assertEquals(assistantId, assistantFile.getAssistantId()); } @Test @Order(6) void retrieveAssistantFile() { AssistantFile file = service.retrieveAssistantFile(assistantId, fileId); assertEquals(file.getId(), fileId); } @Test @Order(7) void listAssistantFiles() { List<AssistantFile> files = service.listAssistantFiles(assistantId, new ListSearchParameters()).data; assertFalse(files.isEmpty()); assertEquals(files.get(0).getId(), fileId); assertEquals(files.get(0).getObject(), "assistant.file"); } @Test @Order(8) void deleteAssistantFile() { DeleteResult deletedFile = service.deleteAssistantFile(assistantId, fileId); assertEquals(deletedFile.getId(), fileId); assertTrue(deletedFile.isDeleted()); } @Test @Order(9) void deleteAssistant() { DeleteResult deletedAssistant = service.deleteAssistant(assistantId); assertEquals(assistantId, deletedAssistant.getId()); assertTrue(deletedAssistant.isDeleted()); } }
[ "com.theokanning.openai.ListSearchParameters.builder", "com.theokanning.openai.utils.TikTokensUtil.ModelEnum.GPT_4_1106_preview.getName" ]
[((1142, 1194), 'com.theokanning.openai.utils.TikTokensUtil.ModelEnum.GPT_4_1106_preview.getName'), ((2319, 2357), 'com.theokanning.openai.ListSearchParameters.builder')]
package com.theokanning.openai; import com.theokanning.openai.completion.CompletionChoice; import com.theokanning.openai.completion.CompletionRequest; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.List; import static org.junit.jupiter.api.Assertions.assertFalse; public class CompletionTest { String token = System.getenv("OPENAI_TOKEN"); OpenAiService service = new OpenAiService(token); @Test void createCompletion() { CompletionRequest completionRequest = CompletionRequest.builder() .model("ada") .prompt("Somebody once told me the world is gonna roll me") .echo(true) .user("testing") .logitBias(new HashMap<>()) .build(); List<CompletionChoice> choices = service.createCompletion(completionRequest).getChoices(); assertFalse(choices.isEmpty()); } @Test void createCompletionDeprecated() { CompletionRequest completionRequest = CompletionRequest.builder() .prompt("Somebody once told me the world is gonna roll me") .echo(true) .user("testing") .build(); List<CompletionChoice> choices = service.createCompletion("ada", completionRequest).getChoices(); assertFalse(choices.isEmpty()); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((522, 785), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((522, 760), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((522, 716), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((522, 683), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((522, 655), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((522, 579), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1030, 1219), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1030, 1194), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1030, 1161), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1030, 1133), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package com.theokanning.openai.service; import com.theokanning.openai.completion.CompletionChoice; import com.theokanning.openai.completion.CompletionChunk; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static org.junit.jupiter.api.Assertions.*; public class CompletionTest { String token = System.getenv("OPENAI_TOKEN"); OpenAiService service = new OpenAiService(token); @Test void createCompletion() { CompletionRequest completionRequest = CompletionRequest.builder() .model("babbage-002") .prompt("Somebody once told me the world is gonna roll me") .echo(true) .n(5) .maxTokens(50) .user("testing") .logitBias(new HashMap<>()) .logprobs(5) .build(); List<CompletionChoice> choices = service.createCompletion(completionRequest).getChoices(); assertEquals(5, choices.size()); assertNotNull(choices.get(0).getLogprobs()); } @Test void streamCompletion() { CompletionRequest completionRequest = CompletionRequest.builder() .model("babbage-002") .prompt("Somebody once told me the world is gonna roll me") .echo(true) .n(1) .maxTokens(25) .user("testing") .logitBias(new HashMap<>()) .logprobs(5) .stream(true) .build(); List<CompletionChunk> chunks = new ArrayList<>(); service.streamCompletion(completionRequest).blockingForEach(chunks::add); assertTrue(chunks.size() > 0); assertNotNull(chunks.get(0).getChoices().get(0)); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((659, 1012), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 987), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 958), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 914), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 881), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 850), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 828), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 800), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 724), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1684), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1659), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1629), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1600), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1556), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1523), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1492), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1470), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1442), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1366), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package br.com.alura.screenmatch.service; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; public class ConsultaChatGPT { public static String obterTraducao(String texto) { OpenAiService service = new OpenAiService(System.getenv("OPENAI_APIKEY")); CompletionRequest requisicao = CompletionRequest.builder() .model("text-davinci-003") .prompt("traduza para o português o texto: " + texto) .maxTokens(1000) .temperature(0.7) .build(); var resposta = service.createCompletion(requisicao); return resposta.getChoices().get(0).getText(); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((367, 600), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 575), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 541), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 508), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 437), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package br.com.alura.screenmatch.service; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; public class ConsultaChatGPT { public static String obterTraducao(String texto) { OpenAiService service = new OpenAiService(System.getenv("OPENAI_APIKEY")); CompletionRequest requisicao = CompletionRequest.builder() .model("text-davinci-003") .prompt("traduza para o português o texto: " + texto) .maxTokens(1000) .temperature(0.7) .build(); var resposta = service.createCompletion(requisicao); return resposta.getChoices().get(0).getText(); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((367, 600), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 575), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 541), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 508), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 437), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package br.com.alura.screenmatch.service; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; public class ConsultaChatGPT { public static String obterTraducao(String texto) { OpenAiService service = new OpenAiService(System.getenv("OPENAI_APIKEY")); CompletionRequest requisicao = CompletionRequest.builder() .model("text-davinci-003") .prompt("traduza para o português o texto: " + texto) .maxTokens(1000) .temperature(0.7) .build(); var resposta = service.createCompletion(requisicao); return resposta.getChoices().get(0).getText(); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((367, 600), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 575), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 541), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 508), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((367, 437), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package com.theokanning.openai.service; import com.theokanning.openai.embedding.Embedding; import com.theokanning.openai.embedding.EmbeddingRequest; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.assertFalse; public class EmbeddingTest { String token = System.getenv("OPENAI_TOKEN"); com.theokanning.openai.service.OpenAiService service = new OpenAiService(token); @Test void createEmbeddings() { EmbeddingRequest embeddingRequest = EmbeddingRequest.builder() .model("text-similarity-babbage-001") .input(Collections.singletonList("The food was delicious and the waiter...")) .build(); List<Embedding> embeddings = service.createEmbeddings(embeddingRequest).getData(); assertFalse(embeddings.isEmpty()); assertFalse(embeddings.get(0).getEmbedding().isEmpty()); } }
[ "com.theokanning.openai.embedding.EmbeddingRequest.builder" ]
[((552, 751), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((552, 726), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((552, 632), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')]
package com.theokanning.openai.service; import com.theokanning.openai.DeleteResult; import com.theokanning.openai.ListSearchParameters; import com.theokanning.openai.OpenAiResponse; import com.theokanning.openai.assistants.*; import com.theokanning.openai.file.File; import com.theokanning.openai.utils.TikTokensUtil; import org.junit.jupiter.api.*; import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AssistantTest { static OpenAiService service = new OpenAiService(System.getenv("OPENAI_TOKEN")); static String assistantId; static String fileId; @AfterAll static void teardown() { try { service.deleteAssistantFile(assistantId, fileId); } catch (Exception e) { // do nothing } try { service.deleteAssistant(assistantId); } catch (Exception e) { // do nothing } } @Test @Order(1) void createAssistant() { AssistantRequest assistantRequest = AssistantRequest.builder().model(TikTokensUtil.ModelEnum.GPT_4_1106_preview.getName()).name("Math Tutor").instructions("You are a personal Math Tutor.").tools(Collections.singletonList(new Tool(AssistantToolsEnum.CODE_INTERPRETER, null))).build(); Assistant assistant = service.createAssistant(assistantRequest); assistantId = assistant.getId(); assertEquals(assistant.getName(), "Math Tutor"); assertEquals(assistant.getTools().get(0).getType(), AssistantToolsEnum.CODE_INTERPRETER); } @Test @Order(2) void retrieveAssistant() { Assistant assistant = service.retrieveAssistant(assistantId); assertEquals(assistant.getName(), "Math Tutor"); } @Test @Order(3) void modifyAssistant() { String modifiedName = "Science Tutor"; ModifyAssistantRequest modifyRequest = ModifyAssistantRequest.builder().name(modifiedName).build(); Assistant modifiedAssistant = service.modifyAssistant(assistantId, modifyRequest); assertEquals(modifiedName, modifiedAssistant.getName()); } @Test @Order(4) void listAssistants() { OpenAiResponse<Assistant> assistants = service.listAssistants(ListSearchParameters.builder().build()); assertNotNull(assistants); assertFalse(assistants.getData().isEmpty()); } @Test @Order(5) void createAssistantFile() { String filePath = "src/test/resources/assistants-data.html"; File uploadedFile = service.uploadFile("assistants", filePath); AssistantFile assistantFile = service.createAssistantFile(assistantId, new AssistantFileRequest(uploadedFile.getId())); fileId = assistantFile.getId(); assertNotNull(assistantFile); assertEquals(uploadedFile.getId(), assistantFile.getId()); assertEquals(assistantId, assistantFile.getAssistantId()); } @Test @Order(6) void retrieveAssistantFile() { AssistantFile file = service.retrieveAssistantFile(assistantId, fileId); assertEquals(file.getId(), fileId); } @Test @Order(7) void listAssistantFiles() { List<AssistantFile> files = service.listAssistantFiles(assistantId, new ListSearchParameters()).data; assertFalse(files.isEmpty()); assertEquals(files.get(0).getId(), fileId); assertEquals(files.get(0).getObject(), "assistant.file"); } @Test @Order(8) void deleteAssistantFile() { DeleteResult deletedFile = service.deleteAssistantFile(assistantId, fileId); assertEquals(deletedFile.getId(), fileId); assertTrue(deletedFile.isDeleted()); } @Test @Order(9) void deleteAssistant() { DeleteResult deletedAssistant = service.deleteAssistant(assistantId); assertEquals(assistantId, deletedAssistant.getId()); assertTrue(deletedAssistant.isDeleted()); } }
[ "com.theokanning.openai.ListSearchParameters.builder", "com.theokanning.openai.utils.TikTokensUtil.ModelEnum.GPT_4_1106_preview.getName" ]
[((1142, 1194), 'com.theokanning.openai.utils.TikTokensUtil.ModelEnum.GPT_4_1106_preview.getName'), ((2319, 2357), 'com.theokanning.openai.ListSearchParameters.builder')]
package com.theokanning.openai.service; import com.theokanning.openai.completion.CompletionChoice; import com.theokanning.openai.completion.CompletionChunk; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static org.junit.jupiter.api.Assertions.*; public class CompletionTest { String token = System.getenv("OPENAI_TOKEN"); OpenAiService service = new OpenAiService(token); @Test void createCompletion() { CompletionRequest completionRequest = CompletionRequest.builder() .model("babbage-002") .prompt("Somebody once told me the world is gonna roll me") .echo(true) .n(5) .maxTokens(50) .user("testing") .logitBias(new HashMap<>()) .logprobs(5) .build(); List<CompletionChoice> choices = service.createCompletion(completionRequest).getChoices(); assertEquals(5, choices.size()); assertNotNull(choices.get(0).getLogprobs()); } @Test void streamCompletion() { CompletionRequest completionRequest = CompletionRequest.builder() .model("babbage-002") .prompt("Somebody once told me the world is gonna roll me") .echo(true) .n(1) .maxTokens(25) .user("testing") .logitBias(new HashMap<>()) .logprobs(5) .stream(true) .build(); List<CompletionChunk> chunks = new ArrayList<>(); service.streamCompletion(completionRequest).blockingForEach(chunks::add); assertTrue(chunks.size() > 0); assertNotNull(chunks.get(0).getChoices().get(0)); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((659, 1012), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 987), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 958), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 914), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 881), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 850), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 828), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 800), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((659, 724), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1684), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1659), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1629), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1600), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1556), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1523), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1492), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1470), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1442), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((1301, 1366), 'com.theokanning.openai.completion.CompletionRequest.builder')]
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2024 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.model.ai.openai; import com.google.gson.Gson; import com.theokanning.openai.OpenAiHttpException; import com.theokanning.openai.completion.CompletionChoice; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import okhttp3.ResponseBody; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.DBPDataSourceContainer; import org.jkiss.dbeaver.model.ai.AIConstants; import org.jkiss.dbeaver.model.ai.AIEngineSettings; import org.jkiss.dbeaver.model.ai.AISettings; import org.jkiss.dbeaver.model.ai.completion.AbstractAICompletionEngine; import org.jkiss.dbeaver.model.ai.completion.DAICompletionContext; import org.jkiss.dbeaver.model.ai.completion.DAICompletionMessage; import org.jkiss.dbeaver.model.ai.format.IAIFormatter; import org.jkiss.dbeaver.model.ai.metadata.MetadataProcessor; import org.jkiss.dbeaver.model.ai.openai.service.AdaptedOpenAiService; import org.jkiss.dbeaver.model.ai.openai.service.GPTCompletionAdapter; import org.jkiss.dbeaver.model.data.json.JSONUtils; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSObjectContainer; import org.jkiss.dbeaver.runtime.DBWorkbench; import org.jkiss.dbeaver.utils.RuntimeUtils; import org.jkiss.utils.CommonUtils; import retrofit2.HttpException; import retrofit2.Response; import java.io.IOException; import java.io.StringReader; import java.time.Duration; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class OpenAICompletionEngine extends AbstractAICompletionEngine<GPTCompletionAdapter, Object> { private static final Log log = Log.getLog(OpenAICompletionEngine.class); //How many retries may be done if code 429 happens protected static final int MAX_REQUEST_ATTEMPTS = 3; private static final Map<String, GPTCompletionAdapter> clientInstances = new HashMap<>(); private static final Pattern sizeErrorPattern = Pattern.compile("This model's maximum context length is [0-9]+ tokens. " + "\\wowever[, ]+you requested [0-9]+ tokens \\(([0-9]+) in \\w+ \\w+[;,] [0-9]+ \\w+ \\w+ completion\\). " + "Please reduce .+"); public OpenAICompletionEngine() { } private static CompletionRequest buildLegacyAPIRequest( @NotNull List<DAICompletionMessage> messages, int maxTokens, Double temperature, String modelId ) { return CompletionRequest.builder() .prompt(buildSingleMessage(truncateMessages(messages, maxTokens))) .temperature(temperature) .maxTokens(maxTokens) .frequencyPenalty(0.0) .n(1) .presencePenalty(0.0) .stop(List.of("#", ";")) .model(modelId) //.echo(true) .build(); } private static ChatCompletionRequest buildChatRequest( @NotNull List<DAICompletionMessage> messages, int maxTokens, Double temperature, String modelId ) { return ChatCompletionRequest.builder() .messages(truncateMessages(messages, maxTokens).stream() .map(m -> new ChatMessage(m.role().getId(), m.content())) .toList()) .temperature(temperature) .maxTokens(maxTokens) .frequencyPenalty(0.0) .presencePenalty(0.0) .n(1) .model(modelId) //.echo(true) .build(); } /** * Resets GPT client cache */ public static void resetServices() { clientInstances.clear(); } @Override public String getEngineName() { return "OpenAI GPT"; } public String getModelName() { return CommonUtils.toString(getSettings().getProperties().get(AIConstants.GPT_MODEL), GPTModel.GPT_TURBO16.getName()); } public boolean isValidConfiguration() { return !CommonUtils.isEmpty(acquireToken()); } @Override public Map<String, GPTCompletionAdapter> getServiceMap() { return clientInstances; } /** * Request completion from GPT API uses parameters from {@link AIConstants} for model settings\ * Adds current schema metadata to starting query * * @param monitor execution monitor * @param context completion context * @param messages request messages * @return resulting string */ @Nullable protected String requestCompletion( @NotNull DBRProgressMonitor monitor, @NotNull DAICompletionContext context, @NotNull List<DAICompletionMessage> messages, @NotNull IAIFormatter formatter, boolean chatCompletion ) throws DBException { final DBCExecutionContext executionContext = context.getExecutionContext(); DBSObjectContainer mainObject = getScopeObject(context, executionContext); final GPTModel model = getModel(); final DAICompletionMessage metadataMessage = MetadataProcessor.INSTANCE.createMetadataMessage( monitor, context, mainObject, formatter, model.isChatAPI(), getMaxTokens() - AIConstants.MAX_RESPONSE_TOKENS, chatCompletion ); final List<DAICompletionMessage> mergedMessages = new ArrayList<>(); mergedMessages.add(metadataMessage); mergedMessages.addAll(messages); if (monitor.isCanceled()) { return ""; } GPTCompletionAdapter service = getServiceInstance(executionContext); Object completionRequest = createCompletionRequest(mergedMessages); String completionText = callCompletion(monitor, mergedMessages, service, completionRequest); return processCompletion( mergedMessages, monitor, executionContext, mainObject, completionText, formatter, model.isChatAPI() ); } protected int getMaxTokens() { return GPTModel.getByName(getModelName()).getMaxTokens(); } /** * Initializes OpenAiService instance using token provided by {@link AIConstants} GTP_TOKEN_PATH */ protected GPTCompletionAdapter initGPTApiClientInstance() throws DBException { String token = acquireToken(); if (CommonUtils.isEmpty(token)) { throw new DBException("Empty API token value"); } return new AdaptedOpenAiService(token, Duration.ofSeconds(30)); } protected String acquireToken() { AIEngineSettings config = getSettings(); Object token = config.getProperties().get(AIConstants.GPT_API_TOKEN); if (token != null) { return token.toString(); } return DBWorkbench.getPlatform().getPreferenceStore().getString(AIConstants.GPT_API_TOKEN); } @NotNull protected AIEngineSettings getSettings() { return AISettings.getSettings().getEngineConfiguration(AIConstants.OPENAI_ENGINE); } @Nullable protected String callCompletion( @NotNull DBRProgressMonitor monitor, @NotNull List<DAICompletionMessage> messages, @NotNull GPTCompletionAdapter service, @NotNull Object completionRequest ) throws DBException { monitor.subTask("Request GPT completion"); try { if (CommonUtils.toBoolean(getSettings().getProperties().get(AIConstants.AI_LOG_QUERY))) { if (completionRequest instanceof ChatCompletionRequest) { log.debug("Chat GPT request:\n" + ((ChatCompletionRequest) completionRequest).getMessages().stream() .map(message -> "# " + message.getRole() + "\n" + message.getContent()) .collect(Collectors.joining("\n"))); } else { log.debug("GPT request:\n" + ((CompletionRequest) completionRequest).getPrompt()); } } if (monitor.isCanceled()) { return null; } try { List<?> choices; int responseSize = AIConstants.MAX_RESPONSE_TOKENS; for (int i = 0; ; i++) { try { choices = getCompletionChoices(service, completionRequest); break; } catch (Exception e) { if ((e instanceof HttpException && ((HttpException) e).code() == 429) || (e instanceof OpenAiHttpException && e.getMessage().contains("This model's maximum"))) { if (e instanceof HttpException) { RuntimeUtils.pause(1000); } else { // Extracts resulted prompt size from the error message and resizes max response to // value lower that (maxTokens - prompt size) Matcher matcher = sizeErrorPattern.matcher(e.getMessage()); int promptSize; if (matcher.find()) { String numberStr = matcher.group(1); promptSize = CommonUtils.toInt(numberStr); } else { throw e; } responseSize = Math.min(responseSize, getMaxTokens() - promptSize - 1); if (responseSize < 0) { throw e; } completionRequest = createCompletionRequest(messages, responseSize); } if (i >= MAX_REQUEST_ATTEMPTS - 1) { throw e; } else { if (e instanceof HttpException) { log.debug("AI service failed. Retry (" + e.getMessage() + ")"); } continue; } } throw e; } } String completionText; Object choice = choices.stream().findFirst().orElseThrow(); if (choice instanceof CompletionChoice) { completionText = ((CompletionChoice) choice).getText(); } else { completionText = ((ChatCompletionChoice) choice).getMessage().getContent(); } if (CommonUtils.toBoolean(getSettings().getProperties().get(AIConstants.AI_LOG_QUERY))) { log.debug("GPT response:\n" + completionText); } return completionText; } catch (Exception exception) { if (exception instanceof HttpException) { Response<?> response = ((HttpException) exception).response(); if (response != null) { try { try (ResponseBody responseBody = response.errorBody()) { if (responseBody != null) { String bodyString = responseBody.string(); if (!CommonUtils.isEmpty(bodyString)) { try { Gson gson = new Gson(); Map<String, Object> map = JSONUtils.parseMap(gson, new StringReader(bodyString)); Map<String, Object> error = JSONUtils.deserializeProperties(map, "error"); if (error != null) { String message = JSONUtils.getString(error, "message"); if (!CommonUtils.isEmpty(message)) { bodyString = message; } } } catch (Exception e) { // ignore json errors } throw new DBException("AI service error: " + bodyString); } } } } catch (IOException e) { log.debug(e); } } } else if (exception instanceof RuntimeException && !(exception instanceof OpenAiHttpException) && exception.getCause() != null) { throw new DBException("AI service error: " + exception.getCause().getMessage(), exception.getCause()); } throw exception; } } finally { monitor.done(); } } protected GPTCompletionAdapter getServiceInstance(@NotNull DBCExecutionContext executionContext) throws DBException { DBPDataSourceContainer container = executionContext.getDataSource().getContainer(); GPTCompletionAdapter service = clientInstances.get(container.getId()); if (service == null) { service = initGPTApiClientInstance(); clientInstances.put(container.getId(), service); } return service; } protected Object createCompletionRequest(@NotNull List<DAICompletionMessage> messages) { return createCompletionRequest(messages, AIConstants.MAX_RESPONSE_TOKENS); } protected Object createCompletionRequest(@NotNull List<DAICompletionMessage> messages, int responseSize) { Double temperature = CommonUtils.toDouble(getSettings().getProperties().get(AIConstants.AI_TEMPERATURE), 0.0); final GPTModel model = getModel(); if (model.isChatAPI()) { return buildChatRequest(messages, responseSize, temperature, model.getName()); } else { return buildLegacyAPIRequest(messages, responseSize, temperature, model.getName()); } } @NotNull private GPTModel getModel() { final String modelId = CommonUtils.toString(getSettings().getProperties().get(AIConstants.GPT_MODEL), ""); return CommonUtils.isEmpty(modelId) ? GPTModel.GPT_TURBO16 : GPTModel.getByName(modelId); } private List<?> getCompletionChoices(GPTCompletionAdapter service, Object completionRequest) { if (completionRequest instanceof CompletionRequest) { return service.createCompletion((CompletionRequest) completionRequest).getChoices(); } else { return service.createChatCompletion((ChatCompletionRequest) completionRequest).getChoices(); } } @NotNull private static String buildSingleMessage(@NotNull List<DAICompletionMessage> messages) { final StringJoiner buffer = new StringJoiner("\n"); for (DAICompletionMessage message : messages) { if (message.role() == DAICompletionMessage.Role.SYSTEM) { buffer.add("###"); buffer.add(message.content() .lines() .map(line -> '#' + line) .collect(Collectors.joining("\n"))); buffer.add("###"); } else { buffer.add(message.content()); } } buffer.add("SELECT "); return buffer.toString(); } @NotNull private static List<DAICompletionMessage> truncateMessages(@NotNull List<DAICompletionMessage> messages, int maxTokens) { final Deque<DAICompletionMessage> pending = new LinkedList<>(messages); final List<DAICompletionMessage> truncated = new ArrayList<>(); int remainingTokens = maxTokens - 20; // Just to be sure if (pending.getFirst().role() == DAICompletionMessage.Role.SYSTEM) { // Always append system message truncated.add(pending.remove()); } while (!pending.isEmpty()) { final DAICompletionMessage message = pending.remove(); final int messageTokens = message.content().length(); if (remainingTokens < 0 || messageTokens > remainingTokens) { // Exclude old messages that don't fit into given number of tokens break; } truncated.add(message); remainingTokens -= messageTokens; } return truncated; } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder", "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((3458, 3835), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3788), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3760), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3723), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3689), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3671), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3636), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3602), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((3458, 3564), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((4054, 4489), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4054, 4442), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4054, 4414), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4054, 4396), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4054, 4362), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4054, 4327), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4054, 4293), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((4054, 4255), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5994, 6262), 'org.jkiss.dbeaver.model.ai.metadata.MetadataProcessor.INSTANCE.createMetadataMessage'), ((7784, 7867), 'org.jkiss.dbeaver.runtime.DBWorkbench.getPlatform'), ((7784, 7830), 'org.jkiss.dbeaver.runtime.DBWorkbench.getPlatform'), ((7951, 8025), 'org.jkiss.dbeaver.model.ai.AISettings.getSettings')]
package cn.com.ogtwelve.utils; import cn.com.ogtwelve.entity.Billing; import cn.com.ogtwelve.entity.Subscription; import cn.com.ogtwelve.enums.ImageSizeEnum; import cn.com.ogtwelve.enums.ModelEnum; import cn.com.ogtwelve.enums.RoleEnum; import cn.com.ogtwelve.service.OpenAIService; import com.google.common.cache.Cache; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.image.CreateImageRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * @Author OGtwelve * @Date 2023/7/12 12:03 * @Description: openai工具类 */ public class OpenAIUtils { private static final Log LOG = LogFactory.getLog(OpenAIUtils.class); private static OpenAIService openAIService; public OpenAIUtils(OpenAIService openAIService) { OpenAIUtils.openAIService = openAIService; } public static void createStreamChatCompletion(String content) { createStreamChatCompletion(content, "DEFAULT USER", System.out); } public static void createStreamChatCompletion(String content, OutputStream os) { createStreamChatCompletion(content, "DEFAULT USER", os); } public static void createStreamChatCompletion(String content, String user, OutputStream os) { openAIService.createStreamChatCompletion(content, user, os); } public static void createStreamChatCompletion(String content, String user, String model, OutputStream os) { createStreamChatCompletion(RoleEnum.USER.getRoleName(), content, user, model, 1.0, 1.0, os); } public static void createStreamChatCompletion(String role, String content, String user, String model, Double temperature, Double topP, OutputStream os) { createStreamChatCompletion(ChatCompletionRequest.builder().model(model).messages(Collections.singletonList(new ChatMessage(role, content))).user(user).temperature(temperature).topP(topP).stream(true).build(), os); } public static void createStreamChatCompletion(ChatCompletionRequest chatCompletionRequest, OutputStream os) { openAIService.createStreamChatCompletion(chatCompletionRequest, os); } public static List<String> createChatCompletion(String content) { return createChatCompletion(content, "DEFAULT USER"); } public static List<String> createChatCompletion(String content, String user) { return openAIService.chatCompletion(content, user); } public static List<String> createChatCompletion(String content, String user, String model) { return createChatCompletion(RoleEnum.USER.getRoleName(), content, user, model, 1.0, 1.0); } public static List<String> createChatCompletion(String role, String content, String user, String model, Double temperature, Double topP) { return createChatCompletion(ChatCompletionRequest.builder().model(model).messages(Collections.singletonList(new ChatMessage(role, content))).user(user).temperature(temperature).topP(topP).build()); } public static List<String> createChatCompletion(ChatCompletionRequest chatCompletionRequest) { return openAIService.chatCompletion(chatCompletionRequest); } public static List<String> createImage(String prompt) { return createImage(prompt, "DEFAULT USER"); } public static List<String> createImage(String prompt, String user) { return createImage(CreateImageRequest.builder().prompt(prompt).user(user).build()); } public static List<String> createImage(CreateImageRequest createImageRequest) { return openAIService.createImages(createImageRequest); } public static void downloadImage(String prompt, HttpServletResponse response) { downloadImage(prompt, ImageSizeEnum.S1024x1024.getSize(), response); } public static void downloadImage(String prompt, Integer n, HttpServletResponse response) { downloadImage(prompt, n, ImageSizeEnum.S1024x1024.getSize(), response); } public static void downloadImage(String prompt, String size, HttpServletResponse response) { downloadImage(prompt, 1, size, response); } public static void downloadImage(String prompt, Integer n, String size, HttpServletResponse response) { downloadImage(CreateImageRequest.builder().prompt(prompt).n(n).size(size).user("DEFAULT USER").build(), response); } public static void downloadImage(CreateImageRequest createImageRequest, HttpServletResponse response) { openAIService.downloadImage(createImageRequest, response); } public static String billingUsage(String... startDate) { return openAIService.billingUsage(startDate); } public static String billingUsage(String startDate, String endDate) { return openAIService.billingUsage(startDate, endDate); } public static Billing billing(String... startDate) { return openAIService.billing(startDate); } public static Subscription subscription() { return openAIService.subscription(); } public static void forceClearCache(String cacheName) { openAIService.forceClearCache(cacheName); } public static Cache<String, LinkedList<ChatMessage>> retrieveCache() { return openAIService.retrieveCache(); } public static LinkedList<ChatMessage> retrieveChatMessage(String key) { return openAIService.retrieveChatMessage(key); } public static void setCache(Cache<String, LinkedList<ChatMessage>> cache) { openAIService.setCache(cache); } public static void addCache(String key, LinkedList<ChatMessage> chatMessages) { openAIService.addCache(key, chatMessages); } }
[ "com.theokanning.openai.image.CreateImageRequest.builder", "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1785, 1812), 'cn.com.ogtwelve.enums.RoleEnum.USER.getRoleName'), ((2051, 2231), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2051, 2223), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2051, 2210), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2051, 2199), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2051, 2174), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2051, 2163), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2051, 2095), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((2865, 2892), 'cn.com.ogtwelve.enums.RoleEnum.USER.getRoleName'), ((3113, 3280), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3113, 3272), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3113, 3261), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3113, 3236), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3113, 3225), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3113, 3157), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3683, 3745), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3683, 3737), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((3683, 3726), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4023, 4057), 'cn.com.ogtwelve.enums.ImageSizeEnum.S1024x1024.getSize'), ((4205, 4239), 'cn.com.ogtwelve.enums.ImageSizeEnum.S1024x1024.getSize'), ((4543, 4631), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4543, 4623), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4543, 4602), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4543, 4591), 'com.theokanning.openai.image.CreateImageRequest.builder'), ((4543, 4586), 'com.theokanning.openai.image.CreateImageRequest.builder')]
package baritone.plus.brain.utils; import baritone.plus.main.Debug; import com.theokanning.openai.OpenAiApi; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.service.OpenAiService; import java.time.Duration; import java.util.List; public class ChatGPT { private final OpenAiApi api; protected ChatGPT(String apiKey) { this.api = OpenAiService.buildApi(apiKey, Duration.ofMinutes(1)); } public static ChatGPT build() { return new ChatGPT("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"); } public String generateTaskNaturalLanguage(WorldState worldState) { // Create user message ChatMessage userMessage = new ChatMessage( "user", String.format("Given my current situation in an anarchy Minecraft server, what should my next goal be? Here's my current state:\n%s", worldState.toString()) ); // Create system message ChatMessage systemMessage = new ChatMessage( "system", "You are an AI playing on an anarchy Minecraft server. Use the information provided to decide the best next task. Max 50 Words." ); return prompt(List.of(systemMessage, userMessage)); } public String prompt(List<ChatMessage> messages) { // Create chat completion request ChatCompletionRequest completionRequest = ChatCompletionRequest.builder() .messages(messages) .model("gpt-3.5-turbo") .build(); // Get completion from API return api.createChatCompletion(completionRequest).blockingGet() .getChoices().get(0).getMessage().getContent(); } public String generateTask(WorldState worldState) { // Generate natural language task with ChatGPT as before... String task = generateTaskNaturalLanguage(worldState); Debug.logMessage(task); // Create user message asking to convert task to command ChatMessage userMessage = new ChatMessage( "user", String.format("Given this task: '%s', what would be the appropriate command to accomplish it? Execute consecutve commands by separating them with ; (e.g @get iron_axe;get log 100;goto 0 0;give Player log 100)", task) ); StringBuilder lines = new StringBuilder(); /*for (PlusCommand c : AltoClef.getCommandExecutor().allCommands()) { lines.append("@").append(c.getHelpRepresentation()).append(" | ").append(c.getDescription()); lines.append("\n"); }*/ // Create system message ChatMessage systemMessage = new ChatMessage( "system", "You are an AI assistant tasked with understanding and converting user inputs into valid commands for the Alto Clef bot in Minecraft.\n" + "Ensure to convert inputs into the most specific commands possible and fill out required parameters. Including coordinates/locations\n" + "If no valid task can be derived from the input, return the @idle command\n" + "Respond only with the command chain - no explanations - only command\n" + "Parameters requiring name assume specific item name e.g diamond_chestplate\n" + "You must fill out all parameters with values. \n" + "AltoClef Commands that you can use: " + lines ); // Create chat completion request ChatCompletionRequest completionRequest = ChatCompletionRequest.builder() .messages(List.of(systemMessage, userMessage)) .model("gpt-3.5-turbo") .temperature(0D) .build(); // Get completion from API and return it as the command return api.createChatCompletion(completionRequest).blockingGet() .getChoices().get(0).getMessage().getContent(); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1491, 1623), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1491, 1598), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1491, 1558), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3679, 3871), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3679, 3846), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3679, 3813), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3679, 3773), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package cloud.cleo.connectgpt; import cloud.cleo.connectgpt.lang.LangUtil; import static cloud.cleo.connectgpt.lang.LangUtil.LanguageIds.*; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.LexV2Event; import com.amazonaws.services.lambda.runtime.events.LexV2Event.DialogAction; import com.amazonaws.services.lambda.runtime.events.LexV2Event.Intent; import com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState; import com.amazonaws.services.lambda.runtime.events.LexV2Response; import com.fasterxml.jackson.databind.ObjectMapper; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.service.OpenAiService; import java.net.SocketTimeoutException; import java.time.Duration; import java.time.LocalDate; import java.time.ZoneId; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.extensions.AutoGeneratedTimestampRecordExtension; /** * * @author sjensen */ public class ChatGPTLambda implements RequestHandler<LexV2Event, LexV2Response> { // Initialize the Log4j logger. Logger log = LogManager.getLogger(ChatGPTLambda.class); final static ObjectMapper mapper = new ObjectMapper(); final static TableSchema<ChatGPTSessionState> schema = TableSchema.fromBean(ChatGPTSessionState.class); final static DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .extensions(AutoGeneratedTimestampRecordExtension.create()).build(); final static DynamoDbTable<ChatGPTSessionState> sessionState = enhancedClient.table(System.getenv("SESSION_TABLE_NAME"), schema); final static OpenAiService open_ai_service = new OpenAiService(System.getenv("OPENAI_API_KEY"), Duration.ofSeconds(20)); final static String OPENAI_MODEL = System.getenv("OPENAI_MODEL"); @Override public LexV2Response handleRequest(LexV2Event lexRequest, Context cntxt) { try { log.debug(mapper.valueToTree(lexRequest).toString()); final var intentName = lexRequest.getSessionState().getIntent().getName(); log.debug("Intent: " + intentName); return processGPT(lexRequest); } catch (Exception e) { log.error(e); // Unhandled Exception return buildResponse(lexRequest, new LangUtil(lexRequest.getBot().getLocaleId()).getString(UNHANDLED_EXCEPTION)); } } private LexV2Response processGPT(LexV2Event lexRequest) { final var input = lexRequest.getInputTranscript(); final var localId = lexRequest.getBot().getLocaleId(); final var lang = new LangUtil(localId); log.debug("Java Locale is " + lang.getLocale()); if (input == null || input.isBlank()) { log.debug("Got blank input, so just silent or nothing"); final var attrs = lexRequest.getSessionState().getSessionAttributes(); var count = Integer.valueOf(attrs.getOrDefault("blankCounter", "0")); count++; if (count > 2) { log.debug("Two blank responses, sending to Quit Intent"); // Hang up on caller after 2 silience requests return buildQuitResponse(lexRequest); } else { attrs.put("blankCounter", count.toString()); // If we get slience (timeout without speech), then we get empty string on the transcript return buildResponse(lexRequest, lang.getString(BLANK_RESPONSE)); } } // When testing in lex console input will be text, so use session ID, for speech we shoud have a phone via Connect final var user_id = "Text".equalsIgnoreCase(lexRequest.getInputMode()) ? lexRequest.getSessionId() : lexRequest.getSessionState().getSessionAttributes().get("CustomerNumber"); // Key to record in Dynamo final var key = Key.builder().partitionValue(user_id).sortValue(LocalDate.now(ZoneId.of("America/Chicago")).toString()).build(); // load session state if it exists log.debug("Start Retreiving Session State"); var session = sessionState.getItem(key); log.debug("End Retreiving Session State"); if (session == null) { session = new ChatGPTSessionState(user_id); } // Since we can call and change language during session, always specifiy how we want responses session.addSystemMessage(lang.getString(CHATGPT_RESPONSE_LANGUAGE)); // add this request to the session session.addUserMessage(input); String botResponse; try { ChatCompletionRequest request = ChatCompletionRequest.builder() .messages(session.getChatMessages()) .model(OPENAI_MODEL) .maxTokens(500) .temperature(0.2) // More focused .n(1) // Only return 1 completion .build(); log.debug("Start API Call to ChatGPT"); final var completion = open_ai_service.createChatCompletion(request); log.debug("End API Call to ChatGPT"); log.debug(completion); botResponse = completion.getChoices().get(0).getMessage().getContent(); // Add response to session session.addAssistantMessage(botResponse); // Since we have a valid response, add message asking if there is anything else if ( ! "Text".equalsIgnoreCase(lexRequest.getInputMode()) ) { // Only add if not text (added to voice response) botResponse = botResponse + lang.getString(ANYTHING_ELSE); } // Save the session to dynamo log.debug("Start Saving Session State"); session.incrementCounter(); sessionState.putItem(session); log.debug("End Saving Session State"); } catch (RuntimeException rte) { if (rte.getCause() != null && rte.getCause() instanceof SocketTimeoutException) { log.error("Response timed out", rte); botResponse = lang.getString(OPERATION_TIMED_OUT); } else { throw rte; } } return buildResponse(lexRequest, botResponse); } /** * Response that sends you to the Quit intent so the call can be ended * * @param lexRequest * @param response * @return */ private LexV2Response buildQuitResponse(LexV2Event lexRequest) { // State to return final var ss = SessionState.builder() // Retain the current session attributes .withSessionAttributes(lexRequest.getSessionState().getSessionAttributes()) // Send back Quit Intent .withIntent(Intent.builder().withName("Quit").withState("ReadyForFulfillment").build()) // Indicate the state is Delegate .withDialogAction(DialogAction.builder().withType("Delegate").build()) .build(); final var lexV2Res = LexV2Response.builder() .withSessionState(ss) .build(); log.debug("Response is " + mapper.valueToTree(lexV2Res)); return lexV2Res; } /** * General Response used to send back a message and Elicit Intent again at LEX * * @param lexRequest * @param response * @return */ private LexV2Response buildResponse(LexV2Event lexRequest, String response) { // State to return final var ss = SessionState.builder() // Retain the current session attributes .withSessionAttributes(lexRequest.getSessionState().getSessionAttributes()) // Always ElictIntent, so you're back at the LEX Bot looking for more input .withDialogAction(DialogAction.builder().withType("ElicitIntent").build()) .build(); final var lexV2Res = LexV2Response.builder() .withSessionState(ss) // We are using plain text responses .withMessages(new LexV2Response.Message[]{new LexV2Response.Message("PlainText", response, null)}) .build(); log.debug("Response is " + mapper.valueToTree(lexV2Res)); return lexV2Res; } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1974, 2086), 'software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient.builder'), ((1974, 2078), 'software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient.builder'), ((4502, 4613), 'software.amazon.awssdk.enhanced.dynamodb.Key.builder'), ((4502, 4605), 'software.amazon.awssdk.enhanced.dynamodb.Key.builder'), ((4502, 4539), 'software.amazon.awssdk.enhanced.dynamodb.Key.builder'), ((4550, 4604), 'java.time.LocalDate.now'), ((5270, 5572), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5270, 5515), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5270, 5473), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5270, 5435), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5270, 5399), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((5270, 5358), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((7201, 7679), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState.builder'), ((7201, 7654), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState.builder'), ((7201, 7517), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState.builder'), ((7201, 7372), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState.builder'), ((7442, 7516), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.Intent.builder'), ((7442, 7508), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.Intent.builder'), ((7442, 7475), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.Intent.builder'), ((7602, 7653), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.DialogAction.builder'), ((7602, 7645), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.DialogAction.builder'), ((7711, 7797), 'com.amazonaws.services.lambda.runtime.events.LexV2Response.builder'), ((7711, 7772), 'com.amazonaws.services.lambda.runtime.events.LexV2Response.builder'), ((8199, 8578), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState.builder'), ((8199, 8553), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState.builder'), ((8199, 8370), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.SessionState.builder'), ((8497, 8552), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.DialogAction.builder'), ((8497, 8544), 'com.amazonaws.services.lambda.runtime.events.LexV2Event.DialogAction.builder'), ((8610, 8864), 'com.amazonaws.services.lambda.runtime.events.LexV2Response.builder'), ((8610, 8839), 'com.amazonaws.services.lambda.runtime.events.LexV2Response.builder'), ((8610, 8671), 'com.amazonaws.services.lambda.runtime.events.LexV2Response.builder')]
package run.halo.live2d.chat; import static org.springdoc.core.fn.builders.apiresponse.Builder.responseBuilder; import static org.springdoc.core.fn.builders.content.Builder.contentBuilder; import static org.springdoc.core.fn.builders.requestbody.Builder.requestBodyBuilder; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import java.util.ArrayList; import java.util.List; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springdoc.core.fn.builders.schema.Builder; import org.springdoc.webflux.core.fn.SpringdocRouteBuilder; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.codec.ServerSentEvent; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.server.ResponseStatusException; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import run.halo.app.core.extension.endpoint.CustomEndpoint; import run.halo.app.extension.GroupVersion; import run.halo.app.plugin.ReactiveSettingFetcher; @Slf4j @Component @AllArgsConstructor public class AiChatEndpoint implements CustomEndpoint { private final ReactiveSettingFetcher reactiveSettingFetcher; private final AiChatService aiChatService; @Override public RouterFunction<ServerResponse> endpoint() { var tag = groupVersion().toString(); return SpringdocRouteBuilder.route() .POST("/live2d/ai/chat-process", this::chatProcess, builder -> builder.operationId("chatCompletion") .description("Chat completion") .tag(tag) .requestBody(requestBodyBuilder() .required(true) .content(contentBuilder() .mediaType(MediaType.TEXT_EVENT_STREAM_VALUE) .schema(Builder.schemaBuilder() .implementation(ChatRequest.class) ) )) .response(responseBuilder() .implementation(ServerSentEvent.class)) ) .build(); } private Mono<ServerResponse> chatProcess(ServerRequest request) { return request.bodyToMono(ChatRequest.class) .map(this::chatCompletion) .onErrorResume(throwable -> { if (throwable instanceof IllegalArgumentException) { return Mono.just( Flux.just( ServerSentEvent.builder( ChatResult.ok(throwable.getMessage())).build() ) ); } return Mono.error(throwable); }) .flatMap(sse -> ServerResponse.ok() .contentType(MediaType.TEXT_EVENT_STREAM) .body(sse, ServerSentEvent.class) ); } private Flux<ServerSentEvent<ChatResult>> chatCompletion(ChatRequest body) { return reactiveSettingFetcher.fetch("aichat", AiChatConfig.class) .map(aiChatConfig -> ReactiveSecurityContextHolder.getContext() .map(SecurityContext::getAuthentication) .flatMapMany(authentication -> { if (!aiChatConfig.aiChatBaseSetting.isAnonymous && !isAuthenticated( authentication)) { throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "请先登录"); } String systemMessage = aiChatConfig.aiChatBaseSetting.systemMessage; List<ChatMessage> messages = this.buildChatMessage(systemMessage, body); return aiChatService.streamChatCompletion(messages); })) .flatMapMany(Flux::from); } private boolean isAuthenticated(Authentication authentication) { return !isAnonymousUser(authentication.getName()) && authentication.isAuthenticated(); } private boolean isAnonymousUser(String name) { return "anonymousUser".equals(name); } private List<ChatMessage> buildChatMessage(String systemMessage, ChatRequest body) { ChatMessage chatMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), systemMessage); final List<ChatMessage> messages = new ArrayList<>(); messages.add(chatMessage); messages.addAll(body.getMessage()); return messages; } record AiChatConfig(String isAiChat, AiChatBaseSetting aiChatBaseSetting) { } record AiChatBaseSetting(boolean isAnonymous, String systemMessage) { AiChatBaseSetting { if (StringUtils.isBlank(systemMessage)) { throw new IllegalArgumentException("system message must not be null"); } } } @Override public GroupVersion groupVersion() { return GroupVersion.parseAPIVersion("api.live2d.halo.run/v1alpha1"); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value" ]
[((1915, 2704), 'org.springdoc.webflux.core.fn.SpringdocRouteBuilder.route'), ((1915, 2683), 'org.springdoc.webflux.core.fn.SpringdocRouteBuilder.route'), ((2410, 2500), 'org.springdoc.core.fn.builders.schema.Builder.schemaBuilder'), ((3087, 3190), 'org.springframework.http.codec.ServerSentEvent.builder'), ((3347, 3474), 'org.springframework.web.reactive.function.server.ServerResponse.ok'), ((3347, 3424), 'org.springframework.web.reactive.function.server.ServerResponse.ok'), ((3686, 4362), 'org.springframework.security.core.context.ReactiveSecurityContextHolder.getContext'), ((3686, 3785), 'org.springframework.security.core.context.ReactiveSecurityContextHolder.getContext'), ((4846, 4876), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value')]
package vip.testops.qa_design.toolWindow.ui; import com.fasterxml.jackson.databind.ObjectMapper; import com.intellij.lang.Language; import com.intellij.openapi.editor.EditorSettings; import com.intellij.openapi.editor.actions.IncrementalFindAction; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.ToolWindow; import com.intellij.ui.EditorTextField; import com.intellij.ui.EditorTextFieldProvider; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.components.panels.VerticalLayout; import com.intellij.util.concurrency.annotations.RequiresBackgroundThread; import com.intellij.util.containers.ContainerUtil; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import org.intellij.plugins.markdown.settings.MarkdownSettings; import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanel; import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanelProvider; import org.intellij.plugins.markdown.ui.preview.html.MarkdownUtil; import org.jetbrains.annotations.NotNull; import vip.testops.qa_design.QaDesignNotifier; import vip.testops.qa_design.services.QaDesignChatService; import vip.testops.qa_design.toolWindow.ui.entities.Message; import vip.testops.qa_design.toolWindow.ui.entities.Sender; import vip.testops.qa_design.utils.CycledList; import javax.swing.*; import java.awt.*; import java.util.List; import java.util.Objects; import static com.theokanning.openai.service.OpenAiService.defaultObjectMapper; public class ChatToolWindow { private final JPanel contentPanel = new JPanel(); private Project project; private final EditorColorsScheme scheme = EditorColorsManager.getInstance().getSchemeForCurrentUITheme(); private CycledList<ChatMessage> chatMessages = new CycledList<>(7,3); public ChatToolWindow(ToolWindow toolWindow, Project project) { this.project = project; contentPanel.setLayout(new BorderLayout(0, 20)); contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); JBScrollPane chatHistoryPanel = createChatHistoryPanel(); contentPanel.add(chatHistoryPanel, BorderLayout.CENTER); contentPanel.add(createChatInputPanel(chatHistoryPanel), BorderLayout.SOUTH); chatHistoryPanel.revalidate(); chatHistoryPanel.repaint(); SwingUtilities.invokeLater(() -> { JScrollBar verticalScrollBar = chatHistoryPanel.getVerticalScrollBar(); verticalScrollBar.setValue(verticalScrollBar.getMaximum()); }); chatMessages.add(new ChatMessage( ChatMessageRole.SYSTEM.value(), "If need to answer about test points, please reply them with order list." )); chatMessages.add(new ChatMessage( ChatMessageRole.SYSTEM.value(), "If need to answer about test cases design, put each test case like below, and replace every bracket \"{}\" with real content in single line:\n" + "```\n" + "TestCase: {case name}\n" + "TestCaseDesc: {case description}\n" + "TestCaseData: {test case data}\n" + "TestCaseStep: {steps of this test case}\n" + "TestCaseExpect: {expected result of this test case}\n" + "```\n" + "do not use index number after testcase." )); chatMessages.add(new ChatMessage( ChatMessageRole.SYSTEM.value(), "put all the testcases into Markdown code segment, language is qa_design." )); } @NotNull private JBScrollPane createChatHistoryPanel() { JPanel panel = new JPanel(new VerticalLayout(5)); JBScrollPane chatHistoryPanel = new JBScrollPane( panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ); return chatHistoryPanel; } @NotNull private JPanel createChatInputPanel(JBScrollPane chatHistoryPanel) { JPanel chatInputPanel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; EditorTextField inputField = EditorTextFieldProvider .getInstance() .getEditorField( Objects.requireNonNull(Language.findLanguageByID("Markdown")), this.project, List.of((editorEx) -> { EditorSettings editorSettings = editorEx.getSettings(); editorSettings.setLineNumbersShown(false); editorSettings.setLineMarkerAreaShown(false); editorSettings.setUseSoftWraps(true); editorSettings.setAnimatedScrolling(true); editorEx.setBorder(BorderFactory.createLineBorder(scheme.getColor(EditorColors.TEARLINE_COLOR))); }) ); Dimension preferredSize = inputField.getPreferredSize(); inputField.setPreferredSize(new Dimension(preferredSize.width, 60)); chatInputPanel.add(inputField, gbc); gbc.gridx = 1; gbc.gridy = 0; gbc.weightx = 0; gbc.fill = GridBagConstraints.NONE; JButton sendButton = new JButton("Send"); sendButton.addActionListener(e -> { String text = inputField.getText(); JPanel history = (JPanel)chatHistoryPanel.getViewport().getView(); history.add(createMessagePane(new Message(text, Sender.ME))); history.revalidate(); history.repaint(); SwingUtilities.invokeLater(() -> { JScrollBar verticalScrollBar = chatHistoryPanel.getVerticalScrollBar(); verticalScrollBar.setValue(verticalScrollBar.getMaximum()); }); inputField.setText(""); chatMessages.add(new ChatMessage(ChatMessageRole.USER.value(), text)); String currentHtml = "<html><head></head></html>"; MarkdownSettings settings = MarkdownSettings.getInstance(project); settings.setAutoScrollEnabled(false); MarkdownHtmlPanelProvider provider = retrievePanelProvider(settings); MarkdownHtmlPanel htmlPanel = provider.createHtmlPanel(project, project.getProjectFile()); htmlPanel.setHtml(currentHtml, 0); history.add(htmlPanel.getComponent()); new Thread(() -> handleChatCompletion(htmlPanel, history)).start(); }); chatInputPanel.add(sendButton, gbc); return chatInputPanel; } private EditorTextField createMessagePane(Message message) { EditorTextField messagePane = EditorTextFieldProvider.getInstance().getEditorField(Objects.requireNonNull(Language.findLanguageByID("Markdown")), this.project, List.of((editorEx) -> { EditorSettings editorSettings = editorEx.getSettings(); editorSettings.setLineNumbersShown(false); editorSettings.setLineMarkerAreaShown(false); editorSettings.setFoldingOutlineShown(false); editorSettings.setAutoCodeFoldingEnabled(false); editorSettings.setShowIntentionBulb(false); editorSettings.setBlinkCaret(false); editorSettings.setAnimatedScrolling(false); editorSettings.setUseSoftWraps(true); editorEx.setViewer(true); editorEx.setRendererMode(true); editorEx.setCaretVisible(false); editorEx.setCaretEnabled(false); editorEx.putUserData(IncrementalFindAction.SEARCH_DISABLED, Boolean.TRUE); Color c = message.getSender() == Sender.ME ? scheme.getColor(EditorColors.DOCUMENTATION_COLOR) : scheme.getColor(EditorColors.READONLY_BACKGROUND_COLOR); editorEx.setBackgroundColor(c == null ? scheme.getDefaultBackground() : c); editorEx.setColorsScheme(scheme); })); messagePane.setText(message.getContent()); return messagePane; } private @NotNull MarkdownHtmlPanelProvider retrievePanelProvider(@NotNull MarkdownSettings settings) { final MarkdownHtmlPanelProvider.ProviderInfo providerInfo = settings.getPreviewPanelProviderInfo(); MarkdownHtmlPanelProvider provider = MarkdownHtmlPanelProvider.createFromInfo(providerInfo); if (provider.isAvailable() != MarkdownHtmlPanelProvider.AvailabilityInfo.AVAILABLE) { final MarkdownHtmlPanelProvider defaultProvider = MarkdownHtmlPanelProvider.createFromInfo(MarkdownSettings.getDefaultProviderInfo()); System.out.println("MarkdownHtmlPanelProvider is not available: " + providerInfo.getName()); MarkdownSettings.getInstance(project).setPreviewPanelProviderInfo(defaultProvider.getProviderInfo()); provider = Objects.requireNonNull( ContainerUtil.find( MarkdownHtmlPanelProvider.getProviders(), p -> p.isAvailable() == MarkdownHtmlPanelProvider.AvailabilityInfo.AVAILABLE ) ); } return provider; } @RequiresBackgroundThread private void handleChatCompletion(MarkdownHtmlPanel htmlPanel, JPanel historyPanel) { StringBuilder sb = new StringBuilder(); QaDesignChatService service = QaDesignChatService.getInstance(); service.sendMessage( chatMessages, message -> { ChatCompletionChoice choice = message.getChoices().get(0); String msg = choice.getMessage().getContent(); if (null == msg) { return; } sb.append(msg); String html = MarkdownUtil.INSTANCE.generateMarkdownHtml(Objects.requireNonNull(project.getWorkspaceFile()), sb.toString(), project); htmlPanel.setHtml("<html><head></head>" + html + "</html>", 0); historyPanel.revalidate(); historyPanel.repaint(); }, e -> QaDesignNotifier.notifyError(this.project, e.getMessage()) ); chatMessages.add(new ChatMessage(ChatMessageRole.ASSISTANT.value(), sb.toString())); } public JPanel getContentPanel() { return contentPanel; } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value", "com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value" ]
[((1949, 2011), 'com.intellij.openapi.editor.colors.EditorColorsManager.getInstance'), ((2888, 2918), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3080, 3110), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3807, 3837), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((6447, 6475), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((7238, 8514), 'com.intellij.ui.EditorTextFieldProvider.getInstance'), ((9277, 9377), 'org.intellij.plugins.markdown.settings.MarkdownSettings.getInstance'), ((10361, 10479), 'org.intellij.plugins.markdown.ui.preview.html.MarkdownUtil.INSTANCE.generateMarkdownHtml'), ((10809, 10842), 'com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value')]
package br.com.fiap.apichatgpt.controllers; import br.com.fiap.apichatgpt.models.ChatGPT; import br.com.fiap.apichatgpt.models.Medico; import br.com.fiap.apichatgpt.repositories.ChatGPTRepository; import jakarta.validation.ConstraintViolationException; import jakarta.validation.Valid; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.web.PageableDefault; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.PagedModel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import com.theokanning.openai.OpenAiService; import com.theokanning.openai.completion.CompletionRequest; import org.springframework.data.domain.Pageable; import org.slf4j.Logger; @RestController @RequestMapping("/baymax/chatbot") public class ChatGPTController { @Autowired ChatGPTRepository repo; @Autowired PagedResourcesAssembler<ChatGPT> assembler; Logger log = LoggerFactory.getLogger(ChatGPTController.class); private static final String API_KEY = "chave da API"; @GetMapping public PagedModel<EntityModel<ChatGPT>> index(@PageableDefault(size = 5) Pageable pageable) { return assembler.toModel(repo.findAll(pageable)); } @GetMapping("/{id}") public EntityModel<ChatGPT> show(@PathVariable Long id) { log.info("buscar chat com id: " + id); ChatGPT chatGPT = repo.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Cliente não encontrado")); return chatGPT.toModel(); } @PostMapping("/api") public ResponseEntity<ChatGPT> create(@RequestBody @Valid ChatGPT input) { OpenAiService service = new OpenAiService(API_KEY); CompletionRequest request = CompletionRequest.builder() .model("text-davinci-003") .prompt(input.getPergunta()) .maxTokens(100) .build(); String resposta = service.createCompletion(request).getChoices().get(0).getText(); ChatGPT chatGPT = new ChatGPT(input.getPergunta(), resposta); log.info("Saída do chatbot: " + chatGPT); repo.save(chatGPT); return ResponseEntity.status(HttpStatus.CREATED).body(chatGPT); } @DeleteMapping("/{id}") public ResponseEntity<ChatGPT>destroy(@PathVariable Long id) { log.info("deletar chat com o id: " + id); ChatGPT chatgpt = repo.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Chat não encontrado"));; repo.delete(chatgpt); return ResponseEntity.noContent().build(); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(ConstraintViolationException.class) public ResponseEntity<String> handleValidationExceptions(ConstraintViolationException ex) { log.error("Erro de validação: ", ex); return ResponseEntity.badRequest().body(ex.getMessage()); } @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(Exception.class) public ResponseEntity<String> handleAllExceptions(Exception ex) { log.error("Erro não esperado: ", ex); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Ocorreu um erro inesperado. Tente novamente mais tarde."); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((2102, 2278), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2102, 2252), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2102, 2219), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2102, 2173), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((2544, 2599), 'org.springframework.http.ResponseEntity.status'), ((2964, 2998), 'org.springframework.http.ResponseEntity.noContent'), ((3275, 3324), 'org.springframework.http.ResponseEntity.badRequest'), ((3565, 3684), 'org.springframework.http.ResponseEntity.status')]
package com.toryz.biligpt.service.impl; import com.alibaba.fastjson.JSON; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import com.toryz.biligpt.entity.response.GetGptSummaryResponse; import com.toryz.biligpt.service.SummaryService; import com.toryz.biligpt.util.BiliSdkUtil; import com.toryz.biligpt.util.GptSdkUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.time.Duration; import java.util.ArrayList; import java.util.List; /** * @Author: ztr.wuning * @Date: 2023/7/30 20:29 */ @Slf4j @Service public class SummaryServiceImpl implements SummaryService { @Value("${openAI.token}") String token; @Autowired GptSdkUtil gptSdkUtil; @Override public String getGptSummary(String bvid) { log.info("bvid: {}",bvid); GetGptSummaryResponse getGptSummaryResponse = new GetGptSummaryResponse(); List<String> cidList = BiliSdkUtil.getPartCidList(bvid); for(String s : cidList){ log.info("cidList: {}",s); } StringBuilder AllContent = new StringBuilder(); for(String cid: cidList){ List<String> subtitleUrlList = BiliSdkUtil.getSubtitleUrlList(bvid, cid); for(String subtitleUrl: subtitleUrlList){ log.info("subtitleUrl: {}",subtitleUrl); } if(subtitleUrlList.size() == 0){ getGptSummaryResponse.setMessage("暂不支持该视频的总结功能捏,感谢支持,小乌龟正在升级中..."); getGptSummaryResponse.setCode(201); return JSON.toJSONString(getGptSummaryResponse); } for(String subtitleUrl: subtitleUrlList){ List<String> contentList = BiliSdkUtil.parseSubtitle(subtitleUrl); for(String content: contentList){ log.info("content: {}",content); } for(String content: contentList){ AllContent.append(content); } } } String s = null; try{ s = gptSdkUtil.chatForSum(AllContent); }catch (Exception e){ log.info("gpt连接超时..."); getGptSummaryResponse.setMessage("gpt连接超时..."); getGptSummaryResponse.setCode(400); } if(s != null){ getGptSummaryResponse.setMessage(s); getGptSummaryResponse.setCode(200); } return JSON.toJSONString(getGptSummaryResponse); } @Override public String getGptModel(){ System.out.println(token); OpenAiService service = new OpenAiService(token); System.out.println(service.listModels()); return service.listModels().toString(); } @Override public String getGptSummary() { // String s = GptSdkUtil.chatForSum("给我背一遍《静夜思》"); OpenAiService service = new OpenAiService(token, Duration.ofSeconds(90)); List<ChatMessage> messages = new ArrayList<>(); ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(),"随便背一首李白的诗吧"); messages.add(userMessage); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder() .messages(messages) .maxTokens(500) .model("gpt-3.5-turbo-16k-0613") .build(); //CompletionResult completion = service.createCompletion(completionRequest); ChatMessage responseMessage = service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage(); GetGptSummaryResponse getGptSummaryResponse = new GetGptSummaryResponse(); getGptSummaryResponse.setMessage(responseMessage.getContent()); getGptSummaryResponse.setCode(200); return JSON.toJSONString(getGptSummaryResponse); } /* 初始化布隆过滤器 @PostConstruct public void initBloomFilter(){ // 把所有的 BVid 放进布隆过滤器中 List<String> ids = getAllBVIds(); ids.parallelStream().forEach(item->{ // 添加BV号 bloomFilter.add(ConvertCacheKeyUtil.getFormatString(CacheKeyConstant.CACHE_KEY_REVERSE_BY_BV_ID,item)); }); log.info("***********布隆过滤器初始化数据成功 当前BV数量:{} ***********",bloomFilter.count()); }*/ }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value", "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((3413, 3441), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((3574, 3747), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3574, 3722), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3574, 3673), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((3574, 3641), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package org.example.chatgpt.service; import cn.hutool.core.util.StrUtil; import com.fasterxml.jackson.databind.ObjectMapper; import com.theokanning.openai.OpenAiApi; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import javabean.LogForDB; import okhttp3.OkHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import retrofit2.Retrofit; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static com.theokanning.openai.service.OpenAiService.*; /** * 会话服务 * * @author lijiatao * 时间: 2023/12/6 */ @Service public class ChatService { private static final Logger LOG = LoggerFactory.getLogger(ChatService.class); //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 // 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 // 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 String token = "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"; String proxyHost = "127.0.0.1"; int proxyPort = 7890; /** * 流式对话 * 注:必须使用异步处理(否则发送消息不会及时返回前端) * * @param prompt 输入消息 * @param sseEmitter SSE对象 */ @Async public void streamChatCompletion(String prompt, SseEmitter sseEmitter) { LogForDB logForDB = new LogForDB(); LOG.info("发送消息:" + prompt); final List<ChatMessage> messages = new ArrayList<>(); final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), prompt); messages.add(systemMessage); ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest .builder() .model("gpt-3.5-turbo") .messages(messages) .n(1) .maxTokens(2048) .logitBias(new HashMap<>()) .build(); //流式对话(逐Token返回) StringBuilder receiveMsgBuilder = new StringBuilder(); OpenAiService service = buildOpenAiService(token, proxyHost, proxyPort); service.streamChatCompletion(chatCompletionRequest) //正常结束 // .doOnComplete(() -> { // LOG.info("连接结束"); // // //发送连接关闭事件,让客户端主动断开连接避免重连 // sendStopEvent(sseEmitter); // // //完成请求处理 // sseEmitter.complete(); // }) //异常结束 .doOnError(throwable -> { LOG.error("连接异常", throwable); //发送连接关闭事件,让客户端主动断开连接避免重连 sendStopEvent(sseEmitter); //完成请求处理携带异常 sseEmitter.completeWithError(throwable); }) //收到消息后转发到浏览器 .blockingForEach(x -> { ChatCompletionChoice choice = x.getChoices().get(0); LOG.debug("收到消息:" + choice); if (StrUtil.isEmpty(choice.getFinishReason())) { //未结束时才可以发送消息(结束后,先调用doOnComplete然后还会收到一条结束消息,因连接关闭导致发送消息失败:ResponseBodyEmitter has already completed) sseEmitter.send(choice.getMessage()); } else { LOG.info("连接结束"); //发送连接关闭事件,让客户端主动断开连接避免重连 sendStopEvent(sseEmitter); //完成请求处理 sseEmitter.complete(); } String content = choice.getMessage().getContent(); content = content == null ? StrUtil.EMPTY : content; receiveMsgBuilder.append(content); }); LOG.info("收到的完整消息:" + receiveMsgBuilder); logForDB.log2DB("Chat", prompt, receiveMsgBuilder.toString()); } /** * 发送连接关闭事件,让客户端主动断开连接避免重连 * */ static void sendStopEvent(SseEmitter sseEmitter) throws IOException { sseEmitter.send(SseEmitter.event().name("stop").data("")); } /** * 构建OpenAiService * * @param token API_KEY * @param proxyHost 代理域名 * @param proxyPort 代理端口号 * @return OpenAiService */ private OpenAiService buildOpenAiService(String token, String proxyHost, int proxyPort) { //构建HTTP代理 Proxy proxy = null; if (StrUtil.isNotBlank(proxyHost)) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } //构建HTTP客户端 OkHttpClient client = defaultClient(token, Duration.of(60, ChronoUnit.SECONDS)) .newBuilder() .proxy(proxy) .build(); ObjectMapper mapper = defaultObjectMapper(); Retrofit retrofit = defaultRetrofit(client, mapper); OpenAiApi api = retrofit.create(OpenAiApi.class); return new OpenAiService(api, client.dispatcher().executorService()); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value" ]
[((2144, 2174), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((5081, 5121), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event'), ((5081, 5112), 'org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event')]
package br.com.p3d50.chatgtp.service; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import com.theokanning.openai.OpenAiService; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.completion.CompletionResult; @Service public class ChatGPTService { public ResponseEntity<String> getPrompt(String prompt) { final String API_KEY = "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"; OpenAiService service = new OpenAiService(API_KEY); CompletionRequest request = CompletionRequest.builder() .model("text-davinci-003") .prompt(prompt) .maxTokens(375) .build(); CompletionResult response = service.createCompletion(request); return ResponseEntity.ok(response.getChoices().get(0).getText()); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((565, 676), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((565, 663), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((565, 643), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((565, 623), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package com.duzy.service.impl; import cn.hutool.json.JSONUtil; import com.duzy.service.ChatGPTService; import com.theokanning.openai.OpenAiService; import com.theokanning.openai.completion.CompletionChoice; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.model.Model; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.List; /** * @author zhiyuandu * @since 2023/2/4 19:52 * @description */ @Service @Slf4j public class ChatGPTServiceImpl implements ChatGPTService { @Value("${chat-token}") String token; /** * 获取模型 * @return */ @Override public List<Model> models() { return null; } @Override public String qa(String question) { OpenAiService service = new OpenAiService(token); CompletionRequest completionRequest = CompletionRequest.builder() .prompt(question) .model("ada") .echo(true) .build(); List<CompletionChoice> choices = service.createCompletion(completionRequest).getChoices(); log.info("收到:{},回答:{},", question, choices); return JSONUtil.toJsonStr(choices); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((955, 1099), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((955, 1074), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((955, 1046), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((955, 1016), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package com.datastax.astra.beam.genai; import com.datastax.astra.beam.fable.Fable; import com.datastax.astra.beam.fable.FableDaoMapperFactoryFn; import com.datastax.astra.beam.fable.FableDto; import com.datastax.astra.beam.fable.SimpleFableDbMapper; import com.theokanning.openai.embedding.EmbeddingRequest; import com.theokanning.openai.service.OpenAiService; import lombok.extern.slf4j.Slf4j; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.coders.SerializableCoder; import org.apache.beam.sdk.io.astra.db.AstraDbIO; import org.apache.beam.sdk.io.astra.db.options.AstraDbReadOptions; import org.apache.beam.sdk.io.astra.db.transforms.RunCqlQueryFn; import org.apache.beam.sdk.io.astra.db.utils.AstraSecureConnectBundleUtils; import org.apache.beam.sdk.options.Description; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.options.Validation; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.ParDo; import java.util.Arrays; import java.util.stream.Collectors; /** * Create Embeddings */ @Slf4j public class GenAI_02_CreateEmbeddings { /** * Flow Interface */ public interface CreateEmbeddingsOptions extends AstraDbReadOptions { @Validation.Required @Description("Path of file to read from") String getOpenAiKey(); @SuppressWarnings("unused") void setOpenAiKey(String key); } /** * Main execution */ public static void main(String[] args) { // Parse and Validate Parameters CreateEmbeddingsOptions options = PipelineOptionsFactory .fromArgs(args).withValidation() .as(CreateEmbeddingsOptions.class); // Load Secure Bundle from Local File System byte[] scbZip = AstraSecureConnectBundleUtils .loadFromFilePath(options.getAstraSecureConnectBundle()); long top = System.currentTimeMillis(); try { log.info("Parameters validations is successful, launching pipeline"); Pipeline genaiPipeline = Pipeline.create(options); // Read the table AS-IS genaiPipeline.apply("Read Table", AstraDbIO.<FableDto>read() .withToken(options.getAstraToken()) .withKeyspace(options.getAstraKeyspace()) .withSecureConnectBundle(scbZip) .withTable(options.getTable()) .withCoder(SerializableCoder.of(FableDto.class)) .withMapperFactoryFn(new SimpleFableDbMapper()) .withEntity(FableDto.class)) // Alter table to add Vector .apply("Alter Table to add the vector capability", new RunCqlQueryFn<>(options.getAstraToken(), scbZip, options.getAstraKeyspace(), Fable.cqlAlterTableForVectorSearch1(options.getAstraKeyspace(), "fable", 1536))) .apply("Alter Table to add the vector capability", new RunCqlQueryFn<>(options.getAstraToken(), scbZip, options.getAstraKeyspace(), Fable.cqlAlterTableForVectorSearch2(options.getAstraKeyspace(), "fable"))) // Create Index on the table .apply("Alter Table to add the vector capability", new RunCqlQueryFn<>(options.getAstraToken(), scbZip, options.getAstraKeyspace(), Fable.cqlCreateIndexForVectorSearch(options.getAstraKeyspace(), "fable"))) // Open AI Enrichment .apply("Embeddings transform embeddings", ParDo.of(new TransformEmbeddingFn(options.getOpenAiKey()))) // Insert Results Into Astra .apply("Write Into Astra", AstraDbIO.<FableDto>write() .withToken(options.getAstraToken()) .withSecureConnectBundle(scbZip) .withKeyspace(options.getAstraKeyspace()) .withMapperFactoryFn(new FableDaoMapperFactoryFn()) .withEntity(FableDto.class)); genaiPipeline.run().waitUntilFinish(); } finally { log.info("Pipeline finished in {} millis", System.currentTimeMillis()-top); AstraDbIO.close(); } } private static class TransformEmbeddingFn extends DoFn<FableDto, FableDto> { private String openApiKey; public TransformEmbeddingFn(String openApiKey) { this.openApiKey = openApiKey; } @ProcessElement public void processElement(@Element FableDto row, OutputReceiver<FableDto> receiver) { FableDto f = new FableDto(); f.setDocument(row.getDocument()); f.setDocumentId(row.getDocumentId()); f.setTitle(row.getTitle()); // Metadata f.setMetadata("{ \"processing\": \"openai\" }"); // Random List /* List<Float> floatList = IntStream.range(0, 1536) .mapToObj(i -> new Random().nextFloat()) .collect(Collectors.toList()); */ EmbeddingRequest request = EmbeddingRequest.builder() .model("text-embedding-ada-002") .input(Arrays.asList(row.getDocument())) .build(); // only one request sent f.setVector(new OpenAiService(openApiKey).createEmbeddings(request) .getData().get(0) .getEmbedding().stream() .map(e -> e.floatValue()) .collect(Collectors.toList())); log.info("Vector {}", f.getVector()); receiver.output(f); } } }
[ "com.theokanning.openai.embedding.EmbeddingRequest.builder" ]
[((2196, 2685), 'org.apache.beam.sdk.io.astra.db.AstraDbIO.<FableDto>read'), ((2196, 2629), 'org.apache.beam.sdk.io.astra.db.AstraDbIO.<FableDto>read'), ((2196, 2553), 'org.apache.beam.sdk.io.astra.db.AstraDbIO.<FableDto>read'), ((2196, 2476), 'org.apache.beam.sdk.io.astra.db.AstraDbIO.<FableDto>read'), ((2196, 2417), 'org.apache.beam.sdk.io.astra.db.AstraDbIO.<FableDto>read'), ((2196, 2356), 'org.apache.beam.sdk.io.astra.db.AstraDbIO.<FableDto>read'), ((2196, 2286), 'org.apache.beam.sdk.io.astra.db.AstraDbIO.<FableDto>read'), ((3990, 4348), 'org.apache.beam.sdk.io.astra.db.AstraDbIO.<FableDto>write'), ((3990, 4292), 'org.apache.beam.sdk.io.astra.db.AstraDbIO.<FableDto>write'), ((3990, 4212), 'org.apache.beam.sdk.io.astra.db.AstraDbIO.<FableDto>write'), ((3990, 4142), 'org.apache.beam.sdk.io.astra.db.AstraDbIO.<FableDto>write'), ((3990, 4081), 'org.apache.beam.sdk.io.astra.db.AstraDbIO.<FableDto>write'), ((5439, 5608), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((5439, 5579), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((5439, 5518), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')]
package br.com.alura.ecomart.chatbot.infra.openai; import br.com.alura.ecomart.chatbot.domain.DadosCalculoFrete; import br.com.alura.ecomart.chatbot.domain.service.CalculadorDeFrete; import com.fasterxml.jackson.databind.ObjectMapper; import com.theokanning.openai.completion.chat.ChatFunction; import com.theokanning.openai.completion.chat.ChatFunctionCall; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.messages.Message; import com.theokanning.openai.messages.MessageRequest; import com.theokanning.openai.runs.Run; import com.theokanning.openai.runs.RunCreateRequest; import com.theokanning.openai.runs.SubmitToolOutputRequestItem; import com.theokanning.openai.runs.SubmitToolOutputsRequest; import com.theokanning.openai.service.FunctionExecutor; import com.theokanning.openai.service.OpenAiService; import com.theokanning.openai.threads.ThreadRequest; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; @Component public class OpenAIClient { private final String apiKey; private final String assistantId; private String threadId; private final OpenAiService service; private final CalculadorDeFrete calculadorDeFrete; public OpenAIClient(@Value("${app.openai.api.key}") String apiKey, @Value("${app.openai.assistant.id}") String assistantId, CalculadorDeFrete calculadorDeFrete) { this.apiKey = apiKey; this.service = new OpenAiService(apiKey, Duration.ofSeconds(60)); this.assistantId = assistantId; this.calculadorDeFrete = calculadorDeFrete; } public String enviarRequisicaoChatCompletion(DadosRequisicaoChatCompletion dados) { var messageRequest = MessageRequest .builder() .role(ChatMessageRole.USER.value()) .content(dados.promptUsuario()) .build(); if (this.threadId == null) { var threadRequest = ThreadRequest .builder() .messages(Arrays.asList(messageRequest)) .build(); var thread = service.createThread(threadRequest); this.threadId = thread.getId(); } else { service.createMessage(this.threadId, messageRequest); } var runRequest = RunCreateRequest .builder() .assistantId(assistantId) .build(); var run = service.createRun(threadId, runRequest); var concluido = false; var precisaChamarFuncao = false; try { while (!concluido && !precisaChamarFuncao) { Thread.sleep(1000 * 10); run = service.retrieveRun(threadId, run.getId()); concluido = run.getStatus().equalsIgnoreCase("completed"); precisaChamarFuncao = run.getRequiredAction() != null; } } catch (InterruptedException e) { throw new RuntimeException(e); } if (precisaChamarFuncao) { var precoDoFrete = chamarFuncao(run); var submitRequest = SubmitToolOutputsRequest .builder() .toolOutputs(Arrays.asList( new SubmitToolOutputRequestItem( run .getRequiredAction() .getSubmitToolOutputs() .getToolCalls() .get(0) .getId(), precoDoFrete) )) .build(); service.submitToolOutputs(threadId, run.getId(), submitRequest); try { while (!concluido) { Thread.sleep(1000 * 10); run = service.retrieveRun(threadId, run.getId()); concluido = run.getStatus().equalsIgnoreCase("completed"); } } catch (InterruptedException e) { throw new RuntimeException(e); } } var mensagens = service.listMessages(threadId); return mensagens .getData() .stream() .sorted(Comparator.comparingInt(Message::getCreatedAt).reversed()) .findFirst().get().getContent().get(0).getText().getValue() .replaceAll("\\\u3010.*?\\\u3011", ""); } private String chamarFuncao(Run run) { try { var funcao = run.getRequiredAction().getSubmitToolOutputs().getToolCalls().get(0).getFunction(); var funcaoCalcularFrete = ChatFunction.builder() .name("calcularFrete") .executor(DadosCalculoFrete.class, d -> calculadorDeFrete.calcular(d)) .build(); var executorDeFuncoes = new FunctionExecutor(Arrays.asList(funcaoCalcularFrete)); var functionCall = new ChatFunctionCall(funcao.getName(), new ObjectMapper().readTree(funcao.getArguments())); return executorDeFuncoes.execute(functionCall).toString(); } catch (Exception e) { throw new RuntimeException(e); } } public List<String> carregarHistoricoDeMensagens() { var mensagens = new ArrayList<String>(); if (this.threadId != null) { mensagens.addAll( service .listMessages(this.threadId) .getData() .stream() .sorted(Comparator.comparingInt(Message::getCreatedAt)) .map(m -> m.getContent().get(0).getText().getValue()) .collect(Collectors.toList()) ); } return mensagens; } public void apagarThread() { if (this.threadId != null) { service.deleteThread(this.threadId); this.threadId = null; } } }
[ "com.theokanning.openai.completion.chat.ChatFunction.builder", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((1972, 2000), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((4533, 4590), 'java.util.Comparator.comparingInt'), ((4935, 5120), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((4935, 5091), 'com.theokanning.openai.completion.chat.ChatFunction.builder'), ((4935, 5000), 'com.theokanning.openai.completion.chat.ChatFunction.builder')]
package com.miraclekang.chatgpt.assistant.port.adapter.service; import com.miraclekang.chatgpt.assistant.domain.model.chat.ChatService; import com.miraclekang.chatgpt.assistant.domain.model.chat.Message; import com.miraclekang.chatgpt.assistant.domain.model.chat.MessageConfig; import com.miraclekang.chatgpt.assistant.port.adapter.thirdparty.openai.OpenAIClient; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; import java.util.List; import java.util.Objects; @Slf4j @Service public class OpenAIServiceImpl implements ChatService { private final OpenAIClient openaiClient; public OpenAIServiceImpl(@Value("${third-party.openai.token}") String openaiToken, @Value("${third-party.openai.proxy:none}") String openaiProxy) { this.openaiClient = new OpenAIClient(openaiToken, openaiProxy); } @Override public Message sendMessages(List<Message> messages, MessageConfig config) { return prvSendMessages(messages, config, false) .blockFirst(); } @Override public Flux<Message> fluxSendMessages(List<Message> messages, MessageConfig config) { return prvSendMessages(messages, config, true); } private Flux<Message> prvSendMessages(List<Message> messages, MessageConfig config, boolean stream) { return openaiClient.chatCompletion(ChatCompletionRequest.builder() .model(config.getModel().getId()) .temperature(config.getTemperature()) .topP(config.getTopP()) .maxTokens(config.getMaxTokens()) .messages(messages.stream().map(Message::toChatMessage).toList()) .n(config.getChoices()) .stream(stream) .stop(config.getStop() == null || config.getStop().isEmpty() ? null : config.getStop()) .logitBias(config.getLogitBias() == null || config.getLogitBias().isEmpty() ? null : config.getLogitBias()) .user(config.getEndUser()) .build()) .filter(chatMessage -> !stream || Objects.nonNull(chatMessage) && (chatMessage.getRole() != null || chatMessage.getContent() != null)) .mapNotNull(Message::of); } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1545, 2372), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 2339), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 2288), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 2124), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 1980), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 1940), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 1892), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 1802), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 1744), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 1696), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1545, 1634), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package vwvm.gptweb; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.service.OpenAiService; /** * <h3>store</h3> * <p>gpt测试</p> * * @author : BlackBox * @date : 2023-05-13 19:37 **/ public class GptTest { public static void main(String[] args) { OpenAiService service = new OpenAiService("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"); CompletionRequest completionRequest = CompletionRequest.builder() .prompt("Somebody once told me the world is gonna roll me") .model("ada") .echo(true) .build(); service.createCompletion(completionRequest).getChoices().forEach(System.out::println); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((456, 642), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((456, 617), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((456, 589), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((456, 559), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package com.yxy.nova.service.impl; import com.theokanning.openai.completion.chat.ChatCompletionChoice; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.service.OpenAiService; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class MyOpenAiServiceImpl implements MyOpenAiService { @Value("${openai.api-keys}") private String apiKey; @Override public List<String> chat(String content) { // 消息列表 List<ChatMessage> list = new ArrayList<>(); // 定义一个用户身份,content是用户写的内容 ChatMessage userMessage = new ChatMessage(); userMessage.setRole("user"); userMessage.setContent(content); list.add(userMessage); OpenAiService service = new OpenAiService(apiKey); ChatCompletionRequest request = ChatCompletionRequest.builder() .messages(list) .model("gpt-3.5-turbo") .build(); List<ChatCompletionChoice> choices = service.createChatCompletion(request).getChoices(); List<String> response = new ArrayList<>(); choices.forEach(item -> { response.add(item.getMessage().getContent()); }); return response; } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.builder" ]
[((1042, 1170), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1042, 1145), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder'), ((1042, 1105), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.builder')]
package br.com.alura.screenmatch.service; import com.theokanning.openai.completion.CompletionRequest; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import java.util.ArrayList; import java.util.List; public class ConsultaChatGPT { public static String obterTraducao(String texto) { OpenAiService service = new OpenAiService(System.getenv("OPENAI_APIKEY")); CompletionRequest requisicao = CompletionRequest.builder() .model("gpt-3.5-turbo-instruct") .prompt("traduza para o português o texto: " + texto) .maxTokens(1000) .temperature(0.7) .build(); var resposta = service.createCompletion(requisicao); return resposta.getChoices().get(0).getText(); } }
[ "com.theokanning.openai.completion.CompletionRequest.builder" ]
[((621, 880), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((621, 851), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((621, 813), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((621, 776), 'com.theokanning.openai.completion.CompletionRequest.builder'), ((621, 701), 'com.theokanning.openai.completion.CompletionRequest.builder')]
package ca.weblite.jdeploy.openai.services; import ca.weblite.jdeploy.DIContext; import ca.weblite.jdeploy.openai.chat.PromptHandler; import ca.weblite.jdeploy.openai.functions.GenerateProjectFunction; import ca.weblite.jdeploy.openai.functions.GetMainClassSourceFunction; import ca.weblite.jdeploy.openai.interop.UiThreadDispatcher; import ca.weblite.jdeploy.openai.model.ChatPromptRequest; import ca.weblite.jdeploy.openai.model.ChatPromptResponse; import ca.weblite.jdeploy.openai.model.ChatThread; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatFunctionCall; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.FunctionExecutor; import com.theokanning.openai.service.OpenAiService; import javax.inject.Inject; import javax.inject.Singleton; import java.time.Duration; import java.util.*; @Singleton public class ChatPrompt implements PromptHandler{ private final GenerateProjectFunction generateProjectFunction; private final GetMainClassSourceFunction getMainClassSourceFunction; private final UiThreadDispatcher dispatchThread; @Inject public ChatPrompt( GenerateProjectFunction generateProjectFunction, GetMainClassSourceFunction getMainClassSourceFunction, UiThreadDispatcher dispatchThread ) { this.generateProjectFunction = generateProjectFunction; this.getMainClassSourceFunction = getMainClassSourceFunction; this.dispatchThread = dispatchThread; } public void run() { String token = System.getenv("OPENAI_TOKEN"); OpenAiService service = new OpenAiService(token, Duration.ZERO); FunctionExecutor functionExecutor = new FunctionExecutor(Arrays.asList( generateProjectFunction.asChatFunction(), getMainClassSourceFunction.asChatFunction() )); List<ChatMessage> messages = new ArrayList<>(); System.out.print("First Query: "); Scanner scanner = new Scanner(System.in); ChatMessage firstMsg = new ChatMessage(ChatMessageRole.USER.value(), scanner.nextLine()); messages.add(firstMsg); while (true) { ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest .builder() .model("gpt-3.5-turbo-16k") .messages(messages) .functions(functionExecutor.getFunctions()) .functionCall(ChatCompletionRequest.ChatCompletionRequestFunctionCall.of("auto")) .n(1) .maxTokens(7000) .logitBias(new HashMap<>()) .build(); ChatMessage responseMessage = service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage(); messages.add(responseMessage); // don't forget to update the conversation with the latest response ChatFunctionCall functionCall = responseMessage.getFunctionCall(); if (functionCall != null) { System.out.println("Trying to execute " + functionCall.getName() + "..."); Optional<ChatMessage> message = Optional.empty(); try { message = Optional.of(functionExecutor.executeAndConvertToMessage(functionCall)); } catch (Exception ex) { ex.printStackTrace(); messages.add(new ChatMessage(ChatMessageRole.SYSTEM.value(), "Something went wrong with the execution of " + functionCall.getName() + ". Try a different function")); continue; } /* You can also try 'executeAndConvertToMessage' inside a try-catch block, and add the following line inside the catch: "message = executor.handleException(exception);" The content of the message will be the exception itself, so the flow of the conversation will not be interrupted, and you will still be able to log the issue. */ if (message.isPresent()) { /* At this point: 1. The function requested was found 2. The request was converted to its specified object for execution (Weather.class in this case) 3. It was executed 4. The response was finally converted to a ChatMessage object. */ System.out.println("Executed " + functionCall.getName() + "."); messages.add(message.get()); continue; } else { System.out.println("Something went wrong with the execution of " + functionCall.getName() + "..."); break; } } System.out.println("Response: " + responseMessage.getContent()); System.out.print("Next Query: "); String nextLine = scanner.nextLine(); if (nextLine.equalsIgnoreCase("exit")) { System.exit(0); } messages.add(new ChatMessage(ChatMessageRole.USER.value(), nextLine)); } } public static void main(String[] args) { ChatPrompt chatPrompt = DIContext.getInstance().getInstance(ChatPrompt.class); chatPrompt.run(); } @Override public void onPrompt(ChatThread chatThread, ChatPromptRequest request, ChatPromptResponse response) { } }
[ "com.theokanning.openai.completion.chat.ChatCompletionRequest.ChatCompletionRequestFunctionCall.of", "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((2198, 2226), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((2603, 2669), 'com.theokanning.openai.completion.chat.ChatCompletionRequest.ChatCompletionRequestFunctionCall.of'), ((3584, 3614), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((5210, 5238), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((5347, 5400), 'ca.weblite.jdeploy.DIContext.getInstance')]
package com.github.j0rdanit0.chatgptdiscordbot.service; import com.github.j0rdanit0.chatgptdiscordbot.repository.ConversationRepository; import com.theokanning.openai.completion.chat.ChatCompletionRequest; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import com.theokanning.openai.service.OpenAiService; import discord4j.common.util.Snowflake; import discord4j.core.GatewayDiscordClient; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Slf4j @Service @RequiredArgsConstructor public class ConversationService { private final OpenAiService openAiService; private final GatewayDiscordClient gatewayDiscordClient; private final ConversationRepository conversationRepository; @Value( "${bot.name}" ) private String botName; @Value( "${open-ai.chat-model}" ) private String openAiChatModel; public String startConversation( Snowflake threadId, Snowflake userId, String prompt, String botPersonality ) { log.debug( "Sending a prompt in thread {} from user {}: {}", threadId, userId, prompt ); ChatCompletionRequest request = getFirstChatCompletionRequest( threadId, prompt, botPersonality ); return requestChatCompletion( request, threadId ); } public String continueConversation( Snowflake threadId, Snowflake userId, String prompt ) { log.debug( "Continuing conversation in thread {} from user {}: {}", threadId, userId, prompt ); ChatCompletionRequest request = getSubsequentChatCompletionRequest( threadId, prompt ); return requestChatCompletion( request, threadId ); } private String requestChatCompletion( ChatCompletionRequest request, Snowflake threadId ) { ChatMessage responseMessage = openAiService.createChatCompletion( request ).getChoices().getFirst().getMessage(); log.debug( "Got response from Open AI:\n{}", responseMessage.getContent() ); conversationRepository.appendConversationHistory( threadId, responseMessage ); return responseMessage.getContent(); } public String getNewThreadTitle( Snowflake threadId ) { log.debug( "Getting new thread title" ); ChatCompletionRequest request = getTitleChatCompletionRequest( threadId ); return openAiService.createChatCompletion( request ).getChoices().getFirst().getMessage().getContent(); } private ChatCompletionRequest getFirstChatCompletionRequest( Snowflake threadId, String prompt, String botPersonality ) { List<ChatMessage> conversationHistory = conversationRepository.getConversationHistory( threadId ); if ( conversationHistory.isEmpty() ) { ChatMessage initialMessage = new ChatMessage( ChatMessageRole.SYSTEM.value(), ( "You are a Discord bot whose personality is \"%s\". " + "Users may refer to you like this: <@%s> or this: \"%s\". " + "Use Discord's emojis or markdown syntax to style your answers. " + "Use no more than 2000 characters. " + "Answer at a high school level unless requested otherwise. " + "Use brief answers unless requested otherwise. " ).formatted( botPersonality, gatewayDiscordClient.getSelfId().asString(), botName ) ); conversationRepository.appendConversationHistory( threadId, initialMessage ); } return getSubsequentChatCompletionRequest( threadId, prompt ); } private ChatCompletionRequest getSubsequentChatCompletionRequest( Snowflake threadId, String prompt ) { ChatMessage promptMessage = new ChatMessage( ChatMessageRole.USER.value(), prompt ); List<ChatMessage> conversationHistory = conversationRepository.appendConversationHistory( threadId, promptMessage ); return ChatCompletionRequest .builder() .model( openAiChatModel ) .messages( conversationHistory ) .build(); } private ChatCompletionRequest getTitleChatCompletionRequest( Snowflake threadId ) { ChatMessage promptMessage = new ChatMessage( ChatMessageRole.USER.value(), "Give a summary of our conversation so far in 6 words or fewer. " + "Optionally, you may include a Discord-supported emoji unicode at the beginning if one exists that represents the key point of the conversation. " ); List<ChatMessage> conversationHistory = new ArrayList<>( conversationRepository.getConversationHistory( threadId ) ); conversationHistory.add( promptMessage ); return ChatCompletionRequest .builder() .model( openAiChatModel ) .messages( conversationHistory ) .build(); } }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value" ]
[((2964, 2994), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((3874, 3902), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value'), ((4359, 4387), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')]
package jp.mochisuke.lmmchat.embedding; import com.theokanning.openai.embedding.EmbeddingRequest; import com.theokanning.openai.service.OpenAiService; import jp.mochisuke.lmmchat.LMMChatConfig; import java.util.List; public class OpenAIEmbedder implements IEmbedderBase { OpenAiService service; public OpenAIEmbedder(){ service = new OpenAiService(LMMChatConfig.getApiKey()); } @Override public List<List<Double>> calculateEmbedding(List<String> text) { EmbeddingRequest request = EmbeddingRequest.builder() .model("text-embedding-ada-002") .input(text) .build(); var result= service.createEmbeddings(request); if(result.getData().size() == 0){ return null; } var r= result.getData().stream().map(x->x.getEmbedding()).toList(); return r; } }
[ "com.theokanning.openai.embedding.EmbeddingRequest.builder" ]
[((520, 649), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((520, 624), 'com.theokanning.openai.embedding.EmbeddingRequest.builder'), ((520, 595), 'com.theokanning.openai.embedding.EmbeddingRequest.builder')]
package io.github.lynbean.lynbot.cogs.openai.chatbox.pojo; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.bson.codecs.pojo.annotations.BsonCreator; import org.bson.codecs.pojo.annotations.BsonDiscriminator; import org.bson.codecs.pojo.annotations.BsonId; import org.bson.codecs.pojo.annotations.BsonIgnore; import org.bson.codecs.pojo.annotations.BsonProperty; import com.google.gson.Gson; import com.theokanning.openai.completion.chat.ChatMessage; import com.theokanning.openai.completion.chat.ChatMessageRole; import lombok.Data; import lombok.ToString; import lombok.experimental.Accessors; import net.dv8tion.jda.api.utils.FileUpload; @Accessors(chain = true) @BsonDiscriminator(value = "ChatBoxPreset", key = "_cls") @Data @ToString public class ChatBoxPreset { @BsonIgnore public static final String FILE_PREFIX = "ChatBox-Preset-"; @BsonCreator public ChatBoxPreset() {} public static ChatBoxPreset fromJson(String json) { return new Gson().fromJson(json, ChatBoxPreset.class); } @BsonIgnore public List<ChatMessage> getPresetMessages() { List<ChatMessage> messages = new ArrayList<>(); ChatMessage personality = new ChatMessage(); personality.setRole(ChatMessageRole.SYSTEM.value()); personality.setContent( "%s\n%s".formatted( this.characterName != null ? "You're %s.".formatted(this.characterName) : "", this.personality != null ? this.personality : "" ) ); messages.add(personality); if (dialogues != null) { dialogues.entrySet() .stream() .forEachOrdered( entry -> { ChatMessage assistant = new ChatMessage(); assistant.setContent(entry.getKey()); assistant.setRole(ChatMessageRole.ASSISTANT.value()); messages.add(assistant); ChatMessage user = new ChatMessage(); user.setContent(entry.getValue()); user.setRole(ChatMessageRole.USER.value()); messages.add(user); } ); } return messages; } @BsonIgnore public String getJson() { Gson gson = new Gson(); return gson.toJson(this); } public FileUpload getJsonFile(String id) { return FileUpload.fromData(getJson().getBytes(), "%s%s.json".formatted(FILE_PREFIX, id)); } public ChatBoxPreset setDefault() { this.title = "Assistant"; this.description = "A friendly assistant."; this.personality = "You are a friendly assistant."; return this; } @BsonId @BsonProperty("_id") private String id; @BsonProperty("guild_id") private String guildId; @BsonProperty("title") private String title; @BsonProperty("description") private String description; @BsonProperty("personality") private String personality; @BsonProperty("dialogues") private Map<String, String> dialogues; @BsonProperty("character_icon_url") private String characterIconUrl; @BsonProperty("character_name") private String characterName; @BsonProperty("greeting_message") private String greetingMessage; }
[ "com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value", "com.theokanning.openai.completion.chat.ChatMessageRole.USER.value", "com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value" ]
[((1269, 1299), 'com.theokanning.openai.completion.chat.ChatMessageRole.SYSTEM.value'), ((1913, 1946), 'com.theokanning.openai.completion.chat.ChatMessageRole.ASSISTANT.value'), ((2157, 2185), 'com.theokanning.openai.completion.chat.ChatMessageRole.USER.value')]