-
Notifications
You must be signed in to change notification settings - Fork 119
Fix Issue #211 : Improved Embedding Performance by Handling Base64 Encoding #303
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
yoshioterada
wants to merge
2
commits into
openai:main
Choose a base branch
from
yoshioterada:fix-issue-211-update
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
81 changes: 81 additions & 0 deletions
81
openai-java-core/src/main/kotlin/com/openai/models/embeddings/EmbeddingValue.kt
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
package com.openai.models.embeddings | ||
|
||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize | ||
import java.nio.ByteBuffer | ||
import java.nio.ByteOrder | ||
import java.util.Base64 | ||
import java.util.Optional | ||
import kotlin.collections.MutableList | ||
|
||
/** Represents an embedding vector returned by embedding endpoint. */ | ||
@JsonDeserialize(using = EmbeddingValueDeserializer::class) | ||
class EmbeddingValue( | ||
var base64Embedding: Optional<String> = Optional.empty(), | ||
floatEmbedding: Optional<MutableList<Double>> = Optional.empty(), | ||
) { | ||
|
||
/** | ||
* The embedding vector, which is a list of float32. | ||
* [embedding guide](https://platform.openai.com/docs/guides/embeddings). | ||
*/ | ||
var floatEmbedding: Optional<MutableList<Double>> = Optional.empty() | ||
get() { | ||
if (field.isPresent) { | ||
return field | ||
} | ||
if (base64Embedding.isPresent) { | ||
field = convertBase64ToFloat(base64Embedding) | ||
} | ||
return field | ||
} | ||
set(value) { | ||
field = value | ||
} | ||
|
||
/** | ||
* Converting Base64 float32 array to Optional<MutableList> | ||
* | ||
* To improve performance, requests are made in Base64 by default. However, not all developers | ||
* need to decode Base64. Therefore, when a request is made in Base64, the system will | ||
* internally convert the Base64 data to MutableList<Double> and make this converted data | ||
* available, allowing developers to obtain both the Base64 data and the MutableList<Double> | ||
* data by default. | ||
*/ | ||
private fun convertBase64ToFloat( | ||
base64Embedding: Optional<String> | ||
): Optional<MutableList<Double>> { | ||
// The response of Embedding returns a List<Float>(float32), | ||
// but the Kotlin API handles MutableList<Double>. | ||
// If we directly convert from List<Float> to MutableList<Double>, | ||
// it increases the precision and changing it from float32 to double. | ||
// | ||
// Since JSON is assigned to MutableList<Double> from a String of JSON Value, | ||
// the precision does not increase. | ||
// Therefore, by first converting the Base64-decoded List<Float> to a String, | ||
// and then converting the String to Double, | ||
// we can handle it as MutableList<Double> without increasing the precision. | ||
return base64Embedding.map { base64String -> | ||
val decoded = Base64.getDecoder().decode(base64String) | ||
val byteBuffer = ByteBuffer.wrap(decoded).order(ByteOrder.LITTLE_ENDIAN) | ||
|
||
val floatList = mutableListOf<String>() | ||
while (byteBuffer.hasRemaining()) { | ||
floatList.add(byteBuffer.float.toString()) | ||
} | ||
floatList.map { it.replace("f", "").toDouble() }.toMutableList() | ||
} | ||
} | ||
|
||
/** | ||
* Output the embedding vector as a string. By default, it will be output as both list of floats | ||
* and Base64 string. if user specifies floatEmbedding, it will be output as list of floats | ||
* only. | ||
*/ | ||
override fun toString(): String { | ||
return if (base64Embedding.isPresent) { | ||
"base64: $base64Embedding, float: [${floatEmbedding.get().joinToString(", ")}]" | ||
} else { | ||
"float: [${floatEmbedding.get().joinToString(", ")}]" | ||
} | ||
} | ||
} |
32 changes: 32 additions & 0 deletions
32
openai-java-core/src/main/kotlin/com/openai/models/embeddings/EmbeddingValueDeserializer.kt
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
package com.openai.models.embeddings | ||
|
||
import com.fasterxml.jackson.core.JsonParser | ||
import com.fasterxml.jackson.databind.DeserializationContext | ||
import com.fasterxml.jackson.databind.JsonDeserializer | ||
import com.fasterxml.jackson.databind.JsonNode | ||
import com.fasterxml.jackson.databind.node.ArrayNode | ||
import java.io.IOException | ||
import java.util.Optional | ||
|
||
/** JsonDeserializer for EmbeddingValue */ | ||
class EmbeddingValueDeserializer : JsonDeserializer<EmbeddingValue>() { | ||
@Throws(IOException::class) | ||
|
||
/* | ||
* Deserialize the JSON representation of an EmbeddingValue. | ||
* The JSON can either be an array of floats or a base64 string. | ||
*/ | ||
override fun deserialize(jp: JsonParser, ctxt: DeserializationContext): EmbeddingValue { | ||
val node = jp.codec.readTree<JsonNode>(jp) | ||
val embeddingValue = EmbeddingValue() | ||
|
||
if (node.isArray) { | ||
val floats = mutableListOf<Double>() | ||
(node as ArrayNode).forEach { item -> floats.add(item.asDouble()) } | ||
embeddingValue.floatEmbedding = Optional.of(floats) | ||
} else if (node.isTextual) { | ||
embeddingValue.base64Embedding = Optional.of(node.asText()) | ||
} | ||
return embeddingValue | ||
} | ||
} |
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
15 changes: 12 additions & 3 deletions
15
openai-java-core/src/test/kotlin/com/openai/models/embeddings/EmbeddingTest.kt
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,26 @@ | ||
// File generated from our OpenAPI spec by Stainless. | ||
|
||
package com.openai.models.embeddings | ||
|
||
import java.util.Optional | ||
import org.assertj.core.api.Assertions.assertThat | ||
import org.junit.jupiter.api.Test | ||
|
||
class EmbeddingTest { | ||
|
||
@Test | ||
fun createEmbedding() { | ||
val embedding = Embedding.builder().addEmbedding(0.0).index(0L).build() | ||
val embedding = | ||
Embedding.builder() | ||
.addEmbedding( | ||
EmbeddingValue( | ||
floatEmbedding = Optional.of(mutableListOf(0.0)), | ||
base64Embedding = Optional.empty(), | ||
) | ||
) | ||
.build() | ||
assertThat(embedding).isNotNull | ||
assertThat(embedding.embedding()).containsExactly(0.0) | ||
// assertThat(embedding.embedding()).containsExactly(0.0) | ||
assertThat(embedding.embedding().floatEmbedding).containsSame(mutableListOf(0.0)) | ||
assertThat(embedding.index()).isEqualTo(0L) | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I suggest that you replace all the
Optional
type declarations in this class with Kotlin's nullable type which is more natively supported, built into the language, and is more idiomatic and efficient.E.g.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@essien and @TomerAberbach, Thank you so much, I will update the codes.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@yoshioterada just an FYI that @essien is not a maintainer on this repo
I don't agree with his suggestion because this library is meant to be consumed by Java users (hence OpenAI Java) so we should be exposing optional fields as
Optional
instead of nullableThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the feedback, @TomerAberbach. I understand the concern about maintaining Java compatibility. However, I noticed that this repo already uses Kotlin's nullable types quite extensively (e.g., in HttpRequest, SseMessage, etc.). Given that context, my suggestion aligns with current conventions in the repo and avoids introducing Optional, which is redundant and less idiomatic in Kotlin.