-
-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #13 from CJCrafter/completions
Completions
- Loading branch information
Showing
19 changed files
with
1,240 additions
and
307 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
package com.cjcrafter.openai | ||
|
||
import com.cjcrafter.openai.exception.OpenAIError | ||
import com.cjcrafter.openai.exception.WrappedIOError | ||
import com.google.gson.JsonObject | ||
import com.google.gson.JsonParseException | ||
import com.google.gson.JsonParser | ||
import okhttp3.Call | ||
import okhttp3.Callback | ||
import okhttp3.Response | ||
import java.io.IOException | ||
import java.util.function.Consumer | ||
|
||
internal class OpenAICallback( | ||
private val isStream: Boolean, | ||
private val onFailure: Consumer<OpenAIError>, | ||
private val onResponse: Consumer<JsonObject> | ||
) : Callback { | ||
|
||
override fun onFailure(call: Call, e: IOException) { | ||
onFailure.accept(WrappedIOError(e)) | ||
} | ||
|
||
override fun onResponse(call: Call, response: Response) { | ||
onResponse(response) | ||
} | ||
|
||
fun onResponse(response: Response) { | ||
if (isStream) { | ||
handleStream(response) | ||
return | ||
} | ||
|
||
val rootObject = JsonParser.parseString(response.body!!.string()).asJsonObject | ||
|
||
// Sometimes OpenAI will respond with an error code for malformed | ||
// requests, timeouts, rate limits, etc. We need to let the dev | ||
// know that an error occurred. | ||
if (rootObject.has("error")) { | ||
onFailure.accept(OpenAIError.fromJson(rootObject.get("error").asJsonObject)) | ||
return | ||
} | ||
|
||
onResponse.accept(rootObject) | ||
} | ||
|
||
private fun handleStream(response: Response) { | ||
response.body?.source()?.use { source -> | ||
|
||
while (!source.exhausted()) { | ||
var jsonResponse = source.readUtf8Line() | ||
|
||
// Or data is separated by empty lines, ignore them. The final | ||
// line is always "data: [DONE]", ignore it. | ||
if (jsonResponse.isNullOrEmpty() || jsonResponse == "data: [DONE]") | ||
continue | ||
|
||
// The CHAT API returns a json string, but they prepend the content | ||
// with "data: " (which is not valid json). In order to parse this | ||
// into a JsonObject, we have to strip away this extra string. | ||
if (jsonResponse.startsWith("data: ")) | ||
jsonResponse = jsonResponse.substring("data: ".length) | ||
|
||
lateinit var rootObject: JsonObject | ||
try { | ||
rootObject = JsonParser.parseString(jsonResponse).asJsonObject | ||
} catch (ex: JsonParseException) { | ||
println(jsonResponse) | ||
ex.printStackTrace() | ||
continue | ||
} | ||
|
||
// Sometimes OpenAI will respond with an error code for malformed | ||
// requests, timeouts, rate limits, etc. We need to let the dev | ||
// know that an error occurred. | ||
if (rootObject.has("error")) { | ||
onFailure.accept(OpenAIError.fromJson(rootObject.get("error").asJsonObject)) | ||
continue | ||
} | ||
|
||
// Developer defined code to run | ||
onResponse.accept(rootObject) | ||
} | ||
} | ||
} | ||
} |
This file contains 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
This file contains 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
This file contains 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
This file contains 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
28 changes: 28 additions & 0 deletions
28
src/main/kotlin/com/cjcrafter/openai/completions/CompletionChoice.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package com.cjcrafter.openai.completions | ||
|
||
import com.cjcrafter.openai.FinishReason | ||
import com.google.gson.annotations.SerializedName | ||
|
||
/** | ||
* The OpenAI API returns a list of `CompletionChoice`. Each choice has a | ||
* generated message ([CompletionChoice.text]) and a finish reason | ||
* ([CompletionChoice.finishReason]). For most use cases, you only need the | ||
* generated text. | ||
* | ||
* By default, only 1 choice is generated (since [CompletionRequest.n] == 1). | ||
* When you increase `n` or provide a list of prompts (called batching), | ||
* there will be multiple choices. | ||
* | ||
* @property text The generated text. | ||
* @property index The index in the list... This is 0 for most use cases. | ||
* @property logprobs List of logarithmic probabilities for each token in the generated text. | ||
* @property finishReason The reason the bot stopped generating tokens. | ||
* @constructor Create empty Completion choice, for internal usage. | ||
* @see FinishReason | ||
*/ | ||
data class CompletionChoice( | ||
val text: String, | ||
val index: Int, | ||
val logprobs: List<Float>?, | ||
@field:SerializedName("finish_reason") val finishReason: FinishReason | ||
) |
35 changes: 35 additions & 0 deletions
35
src/main/kotlin/com/cjcrafter/openai/completions/CompletionChoiceChunk.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package com.cjcrafter.openai.completions | ||
|
||
import com.cjcrafter.openai.FinishReason | ||
import com.cjcrafter.openai.chat.ChatChoiceChunk | ||
import com.google.gson.annotations.SerializedName | ||
|
||
/** | ||
* The OpenAI API returns a list of `CompletionChoice`. Each choice has a | ||
* generated message ([CompletionChoice.text]) and a finish reason | ||
* ([CompletionChoice.finishReason]). For most use cases, you only need the | ||
* generated text. | ||
* | ||
* By default, only 1 choice is generated (since [CompletionRequest.n] == 1). | ||
* When you increase `n` or provide a list of prompts (called batching), | ||
* there will be multiple choices. | ||
* | ||
* @property text The few generated tokens. | ||
* @property index The index in the list... This is 0 for most use cases. | ||
* @property logprobs List of logarithmic probabilities for each token in the generated text. | ||
* @property finishReason The reason the bot stopped generating tokens. | ||
* @constructor Create empty Completion choice, for internal usage. | ||
* @see FinishReason | ||
*/ | ||
data class CompletionChoiceChunk( | ||
val text: String, | ||
val index: Int, | ||
val logprobs: List<Float>?, | ||
@field:SerializedName("finish_reason") val finishReason: FinishReason? | ||
) { | ||
/** | ||
* Returns `true` if this message chunk is complete. Once complete, no more | ||
* tokens will be generated. | ||
*/ | ||
fun isFinished() = finishReason != null | ||
} |
Oops, something went wrong.