Last active
June 8, 2023 00:18
-
-
Save benigumocom/7d92ab91464439d82ec29f1bb5da3f57 to your computer and use it in GitHub Desktop.
【OpenAI】Kotlin OkHttp で Server-Sent Events (SSE) 👉 https://android.benigumo.com/20230606/%e3%80%90openai%e3%80%91kotlin-okhttp-%e3%81%a7-server-sent-events-sse/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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