├── .gitignore ├── .idea ├── .gitignore ├── gradle.xml ├── inspectionProfiles │ └── Project_Default.xml ├── jpa-buddy.xml ├── kotlinc.xml ├── misc.xml ├── uiDesigner.xml └── vcs.xml ├── README.md ├── assets ├── api-key.png └── chatbot.png ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── kotlin │ └── org │ │ └── ivance │ │ └── chatbot │ │ ├── ChatBotPluginConfig.kt │ │ ├── ChatBotPluginListener.kt │ │ └── ChatBotPluginMain.kt └── resources │ ├── META-INF │ └── services │ │ └── net.mamoe.mirai.console.plugin.jvm.JvmPlugin │ └── plugin.yml └── test ├── java └── OpenAiTest.java └── resources └── .gitignore /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/**/build/ 5 | !**/src/test/**/build/ 6 | 7 | ### IntelliJ IDEA ### 8 | .idea/modules.xml 9 | .idea/jarRepositories.xml 10 | .idea/compiler.xml 11 | .idea/libraries/ 12 | *.iws 13 | *.iml 14 | *.ipr 15 | out/ 16 | !**/src/main/**/out/ 17 | !**/src/test/**/out/ 18 | 19 | ### Eclipse ### 20 | .apt_generated 21 | .classpath 22 | .factorypath 23 | .project 24 | .settings 25 | .springBeans 26 | .sts4-cache 27 | bin/ 28 | !**/src/main/**/bin/ 29 | !**/src/test/**/bin/ 30 | 31 | ### NetBeans ### 32 | /nbproject/private/ 33 | /nbbuild/ 34 | /dist/ 35 | /nbdist/ 36 | /.nb-gradle/ 37 | 38 | ### VS Code ### 39 | .vscode/ 40 | 41 | ### Mac OS ### 42 | .DS_Store -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 16 | 17 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | -------------------------------------------------------------------------------- /.idea/jpa-buddy.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/kotlinc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 11 | -------------------------------------------------------------------------------- /.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Mirai OpenAI GPT-3 ChatBot Plugin 2 | 3 | **This is a Mirai ChatBot plugin based on OpenAI GPT-3 API.** 4 | 5 | chatbot 6 | 7 | 8 | 9 | ## Installation 10 | 11 | 1. Download the JAR file from https://github.com/RIvance/mirai-openai-gpt-chatbot/releases 12 | 13 | 2. Copy the JAR file to `$MCL_ROOT/plugins` 14 | 15 | 3. Start MCL 16 | 17 | 4. Replace `YOUR_OPENAI_API_KEY_HERE` in the `$MCL_ROOT/config/org.ivance.chatbot/ChatBotPluginConfig.yml` config file with your OpenAI API key, like: 18 | 19 | ```yml 20 | # Your OpenAI API key, starts with `sk-`. 21 | # See https://beta.openai.com/account/api-keys 22 | token: sk-kA6y0qWzk6lFEq7SVTr7bpHoduNI9bheqUNkbQm7ZJjG39BA 23 | ``` 24 | 25 | 5. Add the trigger prefixes / trigger keywords to the `triggerPrefixes` / `triggerWords` list, for example: 26 | 27 | ```yml 28 | # Prefixes used to trigger the response. 29 | # e.g. "/chat How are you today?" 30 | triggerPrefixes: 31 | - '/chat' 32 | - '/聊天' 33 | # Keywords used to trigger the response. 34 | # e.g. "What is GPT3?" 35 | triggerWords: 36 | - 'what is' 37 | - 'how to' 38 | - '为什么' 39 | - '怎样' 40 | ``` 41 | 42 | 6. Restart MCL 43 | 44 | 45 | 46 | ## Q & A 47 | 48 | ### How to register an OpenAI account in China? 49 | 50 | See https://zhuanlan.zhihu.com/p/589287744 51 | 52 | ### How to get an OpenAI API Key? 53 | 54 | Visit https://beta.openai.com/account/api-keys 55 | 56 | ![](./assets/api-key.png) 57 | 58 | ### Why is the reply incomplete? 59 | 60 | Please change the `maxToken` attribute in the config file: 61 | ```yml 62 | # The maximum number of tokens to generate. 63 | # Requests can use up to 2048 tokens shared between prompt and completion. 64 | # (One token is roughly 4 characters for normal English text) 65 | # Notice that a large `maxToken` value may cause request timeout. 66 | maxTokens: 500 67 | ``` -------------------------------------------------------------------------------- /assets/api-key.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RIvance/mirai-openai-gpt-chatbot/3da94a006b4124ccd4c8c9162e5d6babb43f9bcb/assets/api-key.png -------------------------------------------------------------------------------- /assets/chatbot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RIvance/mirai-openai-gpt-chatbot/3da94a006b4124ccd4c8c9162e5d6babb43f9bcb/assets/chatbot.png -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.jetbrains.kotlin.jvm' version '1.6.10' 4 | id "com.github.johnrengelman.shadow" version "7.1.2" 5 | } 6 | 7 | group 'org.ivance' 8 | version 'v0.3' 9 | 10 | repositories { 11 | mavenCentral() 12 | } 13 | 14 | dependencies { 15 | /* Main */ 16 | compileOnly 'net.mamoe:mirai-core:2.14.0' 17 | compileOnly 'net.mamoe:mirai-console:2.14.0' 18 | 19 | implementation 'com.theokanning.openai-gpt3-java:api:0.12.0' 20 | implementation 'com.theokanning.openai-gpt3-java:client:0.12.0' 21 | implementation 'com.theokanning.openai-gpt3-java:service:0.12.0' 22 | implementation 'com.fasterxml.jackson.core:jackson-core:2.13.4' 23 | implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.4' 24 | implementation 'com.fasterxml.jackson.core:jackson-annotations:2.13.4' 25 | 26 | /* Test */ 27 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.0' 28 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.0' 29 | testCompileOnly 'org.junit.jupiter:junit-jupiter-params:5.9.0' 30 | } 31 | 32 | shadowJar { 33 | dependencies { 34 | exclude 'net.mamoe:mirai-core:2.14.0' 35 | exclude 'net.mamoe:mirai-console:2.14.0' 36 | } 37 | } 38 | 39 | test { 40 | useJUnitPlatform() 41 | } 42 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RIvance/mirai-openai-gpt-chatbot/3da94a006b4124ccd4c8c9162e5d6babb43f9bcb/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'mirai-openai-chatbot' 2 | 3 | -------------------------------------------------------------------------------- /src/main/kotlin/org/ivance/chatbot/ChatBotPluginConfig.kt: -------------------------------------------------------------------------------- 1 | package org.ivance.chatbot 2 | 3 | import net.mamoe.mirai.console.data.ReadOnlyPluginConfig 4 | import net.mamoe.mirai.console.data.ValueDescription 5 | import net.mamoe.mirai.console.data.value 6 | 7 | object ChatBotPluginConfig : ReadOnlyPluginConfig("ChatBotPluginConfig") { 8 | 9 | @ValueDescription(""" 10 | Your OpenAI API key, starts with `sk-`. 11 | See https://beta.openai.com/account/api-keys 12 | """) 13 | val token: String by value("YOUR_OPENAI_API_KEY_HERE") 14 | 15 | @ValueDescription(""" 16 | Proxy to use when sending requests. 17 | """) 18 | val proxy: String by value("") 19 | 20 | @ValueDescription(""" 21 | Prefixes used to trigger the response. 22 | e.g. "/chat How are you today?" 23 | """) 24 | val triggerPrefixes: List by value(listOf("/chat")) 25 | 26 | @ValueDescription(""" 27 | Keywords used to trigger the response. 28 | e.g. "What is GPT-3?" 29 | """) 30 | val triggerWords: List by value(listOf("what is", "how to")) 31 | 32 | @ValueDescription(""" 33 | Http request timeout in seconds, 0 means no timeout. 34 | """) 35 | val socketTimeout: Int by value(20) 36 | 37 | @ValueDescription(""" 38 | Number of retries on request timeout 39 | """) 40 | val numRetries: Int by value(3) 41 | 42 | @ValueDescription(""" 43 | Message sent when a request fails after `numRetries` retries. 44 | An empty string means do not send fail message. 45 | """) 46 | val requestFailureErrorMessage: String by value("") 47 | 48 | @ValueDescription(""" 49 | Quote the orignal message when sending reply. 50 | """) 51 | val quoteWhenReply: Boolean by value(true) 52 | 53 | @ValueDescription(""" 54 | The name of the model to use. 55 | Required if specifying a fine tuned model or if using the new v1/completions endpoint. 56 | """) 57 | val model: String by value("text-davinci-003") 58 | 59 | @ValueDescription(""" 60 | The maximum number of tokens to generate. 61 | Requests can use up to 2048 tokens shared between prompt and completion. 62 | (One token is roughly 4 characters for normal English text) 63 | Notice that a large `maxToken` value may cause request timeout. 64 | """) 65 | val maxTokens: Int by value(300) 66 | 67 | @ValueDescription(""" 68 | What sampling temperature to use. Higher values means the model will take more risks. 69 | Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer. 70 | """) 71 | val temperature: Double by value(0.9) 72 | 73 | @ValueDescription(""" 74 | An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of 75 | the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are 76 | considered. 77 | """) 78 | val topProb: Double by value(1.0) 79 | 80 | @ValueDescription(""" 81 | Number between 0 and 1 (default 0) that penalizes new tokens based on whether they appear in the text so far. 82 | Increases the model's likelihood to talk about new topics. 83 | """) 84 | val frequencyPenalty: Double by value(0.0) 85 | 86 | @ValueDescription(""" 87 | Number between 0 and 1 (default 0) that penalizes new tokens based on their existing frequency in the text so far. 88 | Decreases the model's likelihood to repeat the same line verbatim. 89 | """) 90 | val presencePenalty: Double by value(0.6) 91 | } 92 | -------------------------------------------------------------------------------- /src/main/kotlin/org/ivance/chatbot/ChatBotPluginListener.kt: -------------------------------------------------------------------------------- 1 | package org.ivance.chatbot 2 | 3 | import com.theokanning.openai.OpenAiApi 4 | import com.theokanning.openai.completion.CompletionRequest 5 | import com.theokanning.openai.service.OpenAiService 6 | import com.theokanning.openai.service.OpenAiService.* 7 | import net.mamoe.mirai.event.GlobalEventChannel 8 | import net.mamoe.mirai.event.events.MessageEvent 9 | import net.mamoe.mirai.event.subscribeAlways 10 | import net.mamoe.mirai.message.data.* 11 | import org.ivance.chatbot.ChatBotPluginConfig.frequencyPenalty 12 | import org.ivance.chatbot.ChatBotPluginConfig.maxTokens 13 | import org.ivance.chatbot.ChatBotPluginConfig.model 14 | import org.ivance.chatbot.ChatBotPluginConfig.numRetries 15 | import org.ivance.chatbot.ChatBotPluginConfig.presencePenalty 16 | import org.ivance.chatbot.ChatBotPluginConfig.quoteWhenReply 17 | import org.ivance.chatbot.ChatBotPluginConfig.requestFailureErrorMessage 18 | import org.ivance.chatbot.ChatBotPluginConfig.socketTimeout 19 | import org.ivance.chatbot.ChatBotPluginConfig.temperature 20 | import org.ivance.chatbot.ChatBotPluginConfig.token 21 | import org.ivance.chatbot.ChatBotPluginConfig.topProb 22 | import org.ivance.chatbot.ChatBotPluginConfig.triggerPrefixes 23 | import org.ivance.chatbot.ChatBotPluginConfig.triggerWords 24 | import retrofit2.HttpException 25 | import java.net.InetSocketAddress 26 | import java.net.Proxy 27 | import java.net.SocketTimeoutException 28 | import java.time.Duration 29 | 30 | internal object ChatBotPluginListener { 31 | 32 | private lateinit var service: OpenAiService 33 | private lateinit var context: ChatBotPluginMain 34 | 35 | fun init(context: ChatBotPluginMain) { 36 | this.context = context 37 | context.logger.info("Initializing OpenAI service") 38 | val timeout = Duration.ofSeconds(socketTimeout.toLong()) 39 | if (ChatBotPluginConfig.proxy.isNotBlank()) { 40 | val proxy = parseProxy(ChatBotPluginConfig.proxy) 41 | context.logger.info("Using proxy $proxy") 42 | val client = defaultClient(token, timeout).newBuilder().proxy(proxy).build() 43 | val retrofit = defaultRetrofit(client, defaultObjectMapper()) 44 | this.service = OpenAiService(retrofit.create(OpenAiApi::class.java)) 45 | } else { 46 | this.service = OpenAiService(token, timeout) 47 | } 48 | try { 49 | context.logger.info("Available models: ${this.service.listModels().map { it.root }}") 50 | } catch (exception: HttpException) { 51 | context.logger.error("Unable to fetch models, please check your API token") 52 | throw exception 53 | } 54 | subscribeEvents() 55 | } 56 | 57 | private fun parseProxy(address: String): Proxy { 58 | return if (address.startsWith("http://") || address.startsWith("https://")) { 59 | val (host, port) = parseProxyAddress(address.substring(7)) 60 | Proxy(Proxy.Type.HTTP, InetSocketAddress(host, port.toInt())) 61 | } else if (address.startsWith("socks://")) { 62 | val (host, port) = parseProxyAddress(address.substring(8)) 63 | Proxy(Proxy.Type.SOCKS, InetSocketAddress(host, port.toInt())) 64 | } else { 65 | val (host, port) = parseProxyAddress(address) 66 | Proxy(Proxy.Type.HTTP, InetSocketAddress(host, port.toInt())) 67 | } 68 | } 69 | 70 | private fun parseProxyAddress(address: String): Pair { 71 | val parts = address.trim().split(':') 72 | if (parts.size != 2) { 73 | throw IllegalArgumentException("Invalid proxy address: $address") 74 | } 75 | val host = parts[0].trim() 76 | val port = parts[1].trim().toUShort() 77 | return Pair(host, port) 78 | } 79 | 80 | private fun shouldTriggerReply(message: MessageEvent): Boolean { 81 | return ( 82 | triggerPrefixes.any { message.message.contentToString().startsWith(it) } || 83 | triggerWords.any { message.message.contentToString().contains(it) } || 84 | message.message.any { it is At && it.target == message.bot.id } || 85 | message.message.any { it is QuoteReply && it.source.targetId == message.bot.id } 86 | ) 87 | } 88 | 89 | private fun subscribeEvents() { 90 | GlobalEventChannel.subscribeAlways { 91 | if (shouldTriggerReply(this)) { 92 | val prompt = this.message.contentToString().trim() 93 | context.logger.info("Prompt: $prompt") 94 | for (i in 0 until numRetries) { 95 | try { 96 | chat(prompt, sender.nick) ?.let { 97 | if (quoteWhenReply) { 98 | subject.sendMessage(QuoteReply(this.source) + it) 99 | } else { 100 | subject.sendMessage(it) 101 | } 102 | return@subscribeAlways 103 | } ?: run { 104 | context.logger.warning("Failed to fetch response, retrying") 105 | } 106 | } catch (exception: RuntimeException) { 107 | if (exception.cause is SocketTimeoutException) { 108 | context.logger.info("Request timeout, retrying") 109 | } else { 110 | context.logger.warning("${exception.cause}") 111 | context.logger.warning("Failed to fetch response, retrying") 112 | } 113 | } 114 | } 115 | 116 | context.logger.warning("Failed to fetch response after $numRetries retries") 117 | if (requestFailureErrorMessage.trim().isNotEmpty()) { 118 | subject.sendMessage(requestFailureErrorMessage) 119 | } 120 | } 121 | } 122 | } 123 | 124 | private fun chat(prompt: String, user: String? = null): String? { 125 | return service.createCompletion (with(CompletionRequest.builder()) { 126 | this.echo(false) 127 | this.model(model) 128 | this.user(user) 129 | this.prompt(prompt) 130 | this.temperature(temperature) 131 | this.maxTokens(maxTokens) 132 | this.topP(topProb) 133 | this.frequencyPenalty(frequencyPenalty) 134 | this.presencePenalty(presencePenalty) 135 | this.stop(listOf(" Human:", " AI:")) 136 | this.build() 137 | }).choices.firstOrNull()?.text?.replace(prompt, "")?.trim() 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/main/kotlin/org/ivance/chatbot/ChatBotPluginMain.kt: -------------------------------------------------------------------------------- 1 | package org.ivance.chatbot 2 | 3 | import net.mamoe.mirai.console.plugin.jvm.JvmPluginDescription 4 | import net.mamoe.mirai.console.plugin.jvm.KotlinPlugin 5 | import java.lang.RuntimeException 6 | 7 | object ChatBotPluginMain : KotlinPlugin( 8 | JvmPluginDescription( 9 | id = "org.ivance.chatbot", 10 | name = "OpenAiGPT3Chatbot", 11 | version = "0.1" 12 | ) { 13 | author("RIvance") 14 | info("A Chatbot based on OpenAI GPT3 API") 15 | } 16 | ) { 17 | private val tokenPattern = "sk-(?:[A-Za-z0-9+]{4})*(?:[A-Za-z0-9+]{2}==|[A-Za-z0-9+]{3}=)?".toRegex() 18 | 19 | override fun onEnable() { 20 | try { 21 | ChatBotPluginConfig.reload() 22 | if (ChatBotPluginConfig.token == "YOUR_OPENAI_API_KEY_HERE") { 23 | logger.error("You have not set your OpenAI API key yet") 24 | logger.error("Please set your API key in `$configFolder/ChatBotPluginConfig.yml`") 25 | throw RuntimeException("Invalid token: ${ChatBotPluginConfig.token}") 26 | } else if (!ChatBotPluginConfig.token.matches(tokenPattern)) { 27 | logger.error("Invalid API key format, please check your key in `$configFolder/ChatBotPluginConfig.yml`") 28 | logger.error("A valid key is a base64 string with `sk-` prefix") 29 | throw RuntimeException("Invalid token: ${ChatBotPluginConfig.token}") 30 | } 31 | ChatBotPluginListener.init(this) 32 | logger.info("OpenAI GPT3 chatbot plugin loaded") 33 | } catch (exception: Exception) { 34 | logger.error("Unable to load OpenAI GPT3 chatbot plugin") 35 | throw exception 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/services/net.mamoe.mirai.console.plugin.jvm.JvmPlugin: -------------------------------------------------------------------------------- 1 | org.ivance.chatbot.ChatBotPluginMain -------------------------------------------------------------------------------- /src/main/resources/plugin.yml: -------------------------------------------------------------------------------- 1 | name: OpenAiGPTChatBot 2 | main: org.ivance.chatbot.ChatBotPluginMain 3 | version: 1.0 -------------------------------------------------------------------------------- /src/test/java/OpenAiTest.java: -------------------------------------------------------------------------------- 1 | import com.theokanning.openai.OpenAiService; 2 | import com.theokanning.openai.completion.CompletionRequest; 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.io.IOException; 6 | import java.nio.charset.StandardCharsets; 7 | import java.util.List; 8 | import java.util.Objects; 9 | 10 | public class OpenAiTest { 11 | 12 | @Test 13 | void openAiTest() throws IOException { 14 | 15 | String token = new String( 16 | Objects.requireNonNull(getClass().getResourceAsStream("openai-token") 17 | ).readAllBytes(), StandardCharsets.UTF_8); 18 | 19 | OpenAiService service = new OpenAiService(token, 15); 20 | System.out.println(service.listModels()); 21 | 22 | var completionRequest = CompletionRequest.builder() 23 | .model("text-davinci-003").echo(true) 24 | .prompt("What is GPT-3?") 25 | .temperature(0.9) 26 | .maxTokens(200) 27 | .topP(1.0) 28 | .frequencyPenalty(0.0) 29 | .presencePenalty(0.6) 30 | .stop(List.of(" Human:", " AI:")) 31 | .build(); 32 | service.createCompletion(completionRequest).getChoices().forEach(completionChoice -> { 33 | System.out.println(completionChoice.getText()); 34 | }); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/test/resources/.gitignore: -------------------------------------------------------------------------------- 1 | openai-token --------------------------------------------------------------------------------