-
Notifications
You must be signed in to change notification settings - Fork 0
/
jtkServer.kts
225 lines (208 loc) · 7.92 KB
/
jtkServer.kts
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
//usr/bin/env echo '
/**** BOOTSTRAP kscript ****\'>/dev/null
command -v kscript >/dev/null 2>&1 || source /dev/stdin <<< "$(curl -L https://git.io/fpF1K)"
exec kscript $0 "$@"
\*** IMPORTANT: Any code including imports and annotations must come after this line ***/
@file:DependsOn("io.ktor:ktor-server-core-jvm:2.0.2")
@file:DependsOn("io.ktor:ktor-client-core-jvm:2.0.2")
@file:DependsOn("io.ktor:ktor-client-cio-jvm:2.0.2")
@file:DependsOn("io.ktor:ktor-server-netty-jvm:2.0.2")
@file:DependsOn("io.ktor:ktor-network-tls-certificates-jvm:2.0.2")
@file:DependsOn("ch.qos.logback:logback-classic:1.2.11")
@file:DependsOn("io.ktor:ktor-server-freemarker:2.0.2")
@file:DependsOn("com.squareup.moshi:moshi:1.12.0")
@file:DependsOn("com.squareup.moshi:moshi-kotlin:1.12.0")
@file:CompilerOpts("-jvm-target 11")
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.http.content.*
import io.ktor.server.netty.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.slf4j.LoggerFactory
import java.io.File
import java.security.KeyStore
import java.text.SimpleDateFormat
import java.util.*
val homeDir = System.getProperty("user.home")
val jtkServerExceptionLogDir = File(homeDir, "JSONToKotlinClass/Exceptions")
jtkServerExceptionLogDir.mkdirs()
val sslFilePassWord = System.getenv("JTK_SSL_PASSWORD")
val hostName = if (System.getenv("GITHUB_USER_NAME").isNullOrBlank()) "jsontokotlin.sealwu.com:8443" else "localhost"
val protocal = if (System.getenv("GITHUB_USER_NAME").isNullOrBlank()) "https" else "http"
val client = HttpClient(CIO){
install(HttpTimeout){
requestTimeoutMillis = 60000 * 5
}
}
val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
fun writeExceptionLog(exceptionInfo: String) {
val day = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date())
val dayDir = File(jtkServerExceptionLogDir, day)
if (!dayDir.exists()) {
dayDir.mkdirs()
}
File(dayDir, Date().time.toString() + ".log").writeText(exceptionInfo)
}
data class Message(
val role: String, val content: String, val name: String? = null
)
data class Error(
val code: Any?,
val message: String,
val `param`: Any?,
val type: String
)
data class ChatCompletion(
val model: String,
val messages: List<Message>,
val temperature: Double? = null,
val top_p: Double? = null,
val n: Int? = null,
val stream: Boolean? = null,
val stop: List<String>? = null,
val max_tokens: Int? = null,
val presence_penalty: Double? = null,
val frequency_penalty: Double? = null,
val logit_bias: Map<String, Double>? = null,
val user: String? = null
)
data class ResponseData(
val id: String?,
val `object`: String?,
val created: Long?,
val choices: List<Choice>?,
val usage: Usage?,
val error: Error? = null
)
data class Choice(
val index: Int,
val message: Message,
val finish_reason: String
)
data class Usage(
val prompt_tokens: Int,
val completion_tokens: Int,
val total_tokens: Int
)
val apiModule: Application.() -> Unit = {
routing {
post("/sendExceptionInfo") {
println("Deal with api sendExceptionInfo")
val exceptionLog = call.receive<String>()
writeExceptionLog(exceptionLog)
call.respond(HttpStatusCode.OK)
}
post("/gpt4"){
val question = call.receive<String>()
val message = Message("user", question)
val chatCompletion = ChatCompletion("gpt-4-1106-preview", listOf(message), max_tokens = 4096, temperature = 0.1)
try {
client.post("https://api.openai.com/v1/chat/completions"){
headers {
append("Content-Type", "application/json")
append("Authorization", "Bearer ${System.getenv("OPENAI_API_KEY")}")
}
val jsonAdapter = moshi.adapter(ChatCompletion::class.java)
val chatCompletionJson = jsonAdapter.toJson(chatCompletion)
setBody(chatCompletionJson)
}.let {
println(it)
val jsonAdapter = moshi.adapter(ResponseData::class.java)
val responseData = jsonAdapter.fromJson(it.bodyAsText())
val reply = if (responseData?.error?.message != null) {
responseData.error.message
} else {
responseData?.choices?.first()?.message?.content
}
call.respondText(reply?: "Sorry, I don't receive any response from GPT-4.")
}
} catch (e: Exception) {
call.respondText("Error: ${e.message} \n exception log: ${e.stackTraceToString()}")
}
}
get("/") {
val responseContent =
"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSONToKotlinClass Error Log</title>
</head>
<body style="text-align: center; font-family: sans-serif">
${
jtkServerExceptionLogDir.listFiles().joinToString("\n") {
"""
<br> <a href="$protocal://$hostName/listLogs/${it.name}">${it.name}</a></br>
""".trimIndent()
}
}
</body>
</html>
""".trimIndent()
call.respondText(responseContent, ContentType.Text.Html)
}
get("/listLogs/{logDate}") {
val dateDay = call.parameters["logDate"]
val exceptionLogNum = File(jtkServerExceptionLogDir, dateDay).listFiles().size
val responseContent = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSONToKotlinClass Error Log</title>
</head>
<body style="text-align: center; font-family: sans-serif">
<h1>There are $exceptionLogNum errors in $dateDay</h1>
${
File(jtkServerExceptionLogDir, dateDay).listFiles().joinToString("\n") {
"""
<br> <a href="$protocal://$hostName/static/$dateDay/${it.name}">${it.name}</a> </br>
""".trimIndent()
}
}
</body>
</html>
""".trimIndent()
call.respondText(responseContent, ContentType.Text.Html)
}
}
}
val webModule: Application.() -> Unit = {
routing {
static("/static") {
files(jtkServerExceptionLogDir)
}
}
}
val environment = applicationEngineEnvironment {
log = LoggerFactory.getLogger("ktor.application")
val keyStoreFile = File(homeDir, "jtkserver.jks")
if (keyStoreFile.exists().not()) {
throw IllegalStateException("ssl certificator must exist!")
}
connector {
port = 80
}
sslConnector(
keyStore = KeyStore.getInstance(keyStoreFile, sslFilePassWord.toCharArray()),
keyAlias = "alias-key",
keyStorePassword = { sslFilePassWord.toCharArray() },
privateKeyPassword = { sslFilePassWord.toCharArray() }) {
port = 8443
keyStorePath = keyStoreFile
}
module(apiModule)
module(webModule)
}
embeddedServer(Netty, environment).start(wait = true)