Skip to content

Instantly share code, notes, and snippets.

@benigumocom
Last active June 8, 2023 00:18
Show Gist options
  • Save benigumocom/7d92ab91464439d82ec29f1bb5da3f57 to your computer and use it in GitHub Desktop.
Save benigumocom/7d92ab91464439d82ec29f1bb5da3f57 to your computer and use it in GitHub Desktop.
val listener = object : EventSourceListener() {
override fun onEvent(
eventSource: EventSource,
id: String?,
type: String?,
data: String
) {
if (data != "[DONE]") {
val d = Json.decodeFromString<Data>(data)
val c = d.choices[0].delta.content
println(c)
}
}
}
val body = """{
| "model": "gpt-3.5-turbo",
| "messages": [{"role": "user", "content": "Server-Sent Events とは"}],
| "stream": true
|}""".trimMargin().toRequestBody("application/json".toMediaType())
val client = OkHttpClient.Builder().build()
val request = Request.Builder()
.url("https://api.openai.com/v1/chat/completions")
.addHeader("Accept", "text/event-stream")
.addHeader("Authorization", "Bearer ${OPENAI_API_KEY}")
.addHeader("Content-Type", "application/json")
.post(body)
.build()
val response = client.newCall(request).execute()
EventSources.processResponse(response, listener)
@Serializable
data class Data(
val id: String,
@SerialName("object")
val _object: String,
val created: Long,
val model: String,
val choices: List<Choice>
)
@Serializable
data class Choice(
val delta: Delta,
val index: Long,
@SerialName("finish_reason")
val reason: String?
)
@Serializable
data class Delta(
val role: String = "",
val content: String = ""
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment