Skip to content
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

Chore Support base64 embedding format #485

Merged
110 changes: 100 additions & 10 deletions embeddings.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package openai

import (
"context"
"encoding/base64"
"encoding/binary"
"math"
"net/http"
)

Expand Down Expand Up @@ -129,15 +132,83 @@ type EmbeddingResponse struct {
Usage Usage `json:"usage"`
}

type base64String string

func (b base64String) Decode() ([]float32, error) {
decodedData, err := base64.StdEncoding.DecodeString(string(b))
if err != nil {
return nil, err
}

const sizeOfFloat32 = 4
floats := make([]float32, len(decodedData)/sizeOfFloat32)
for i := 0; i < len(floats); i++ {
floats[i] = math.Float32frombits(binary.LittleEndian.Uint32(decodedData[i*4 : (i+1)*4]))
}

return floats, nil
}

// Base64Embedding is a container for base64 encoded embeddings.
type Base64Embedding struct {
Object string `json:"object"`
Embedding base64String `json:"embedding"`
Index int `json:"index"`
}

// EmbeddingResponseBase64 is the response from a Create embeddings request with base64 encoding format.
type EmbeddingResponseBase64 struct {
Object string `json:"object"`
Data []Base64Embedding `json:"data"`
Model EmbeddingModel `json:"model"`
Usage Usage `json:"usage"`
}

// ToEmbeddingResponse converts an embeddingResponseBase64 to an EmbeddingResponse.
func (r *EmbeddingResponseBase64) ToEmbeddingResponse() (EmbeddingResponse, error) {
data := make([]Embedding, len(r.Data))

for i, base64Embedding := range r.Data {
embedding, err := base64Embedding.Embedding.Decode()
if err != nil {
return EmbeddingResponse{}, err
}

data[i] = Embedding{
Object: base64Embedding.Object,
Embedding: embedding,
Index: base64Embedding.Index,
}
}

return EmbeddingResponse{
Object: r.Object,
Model: r.Model,
Data: data,
Usage: r.Usage,
}, nil
}

type EmbeddingRequestConverter interface {
// Needs to be of type EmbeddingRequestStrings or EmbeddingRequestTokens
Convert() EmbeddingRequest
}

// EmbeddingEncodingFormat is the format of the embeddings data.
// Currently, only "float" and "base64" are supported, however, "base64" is not officially documented.
// If not specified OpenAI will use "float".
type EmbeddingEncodingFormat string

const (
EmbeddingEncodingFormatFloat EmbeddingEncodingFormat = "float"
EmbeddingEncodingFormatBase64 EmbeddingEncodingFormat = "base64"
)

type EmbeddingRequest struct {
Input any `json:"input"`
Model EmbeddingModel `json:"model"`
User string `json:"user"`
Input any `json:"input"`
Model EmbeddingModel `json:"model"`
User string `json:"user"`
EncodingFormat EmbeddingEncodingFormat `json:"encoding_format,omitempty"`
}

func (r EmbeddingRequest) Convert() EmbeddingRequest {
Expand All @@ -158,13 +229,18 @@ type EmbeddingRequestStrings struct {
Model EmbeddingModel `json:"model"`
// A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
User string `json:"user"`
// EmbeddingEncodingFormat is the format of the embeddings data.
// Currently, only "float" and "base64" are supported, however, "base64" is not officially documented.
// If not specified OpenAI will use "float".
EncodingFormat EmbeddingEncodingFormat `json:"encoding_format,omitempty"`
}

func (r EmbeddingRequestStrings) Convert() EmbeddingRequest {
return EmbeddingRequest{
Input: r.Input,
Model: r.Model,
User: r.User,
Input: r.Input,
Model: r.Model,
User: r.User,
EncodingFormat: r.EncodingFormat,
}
}

Expand All @@ -181,13 +257,18 @@ type EmbeddingRequestTokens struct {
Model EmbeddingModel `json:"model"`
// A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse.
User string `json:"user"`
// EmbeddingEncodingFormat is the format of the embeddings data.
// Currently, only "float" and "base64" are supported, however, "base64" is not officially documented.
// If not specified OpenAI will use "float".
EncodingFormat EmbeddingEncodingFormat `json:"encoding_format,omitempty"`
}

func (r EmbeddingRequestTokens) Convert() EmbeddingRequest {
return EmbeddingRequest{
Input: r.Input,
Model: r.Model,
User: r.User,
Input: r.Input,
Model: r.Model,
User: r.User,
EncodingFormat: r.EncodingFormat,
}
}

Expand All @@ -203,7 +284,16 @@ func (c *Client) CreateEmbeddings(ctx context.Context, conv EmbeddingRequestConv
return
}

err = c.sendRequest(req, &res)
var embeddingResponse any = &EmbeddingResponse{}
if baseReq.EncodingFormat == EmbeddingEncodingFormatBase64 {
embeddingResponse = &EmbeddingResponseBase64{}
}

err = c.sendRequest(req, embeddingResponse)

if baseReq.EncodingFormat == EmbeddingEncodingFormatBase64 {
res, err = embeddingResponse.(*EmbeddingResponseBase64).ToEmbeddingResponse()
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we update res otherwise?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, yes! My bad! I'll fix it

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the update! It's a bit hard to figure out res manipulations here. Could we please get rid of the named res return here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah! It wasn't so clear, but I left it as I found it to minimize the modifications. However, now named returns have been removed.

Copy link
Owner

@sashabaranov sashabaranov Sep 7, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahhh, I didn't realize how much more problematic would it make if err != nil returns!

Sorry for bothering you so much, feelks like we've stumbled upon a tricky piece here :D I think that the var embeddingResponse any = &response creates a level of indirection which is not trivial to understand.

What do you think of this approach?

func (c *Client) CreateEmbeddings(
	ctx context.Context,
	conv EmbeddingRequestConverter
) (res EmbeddingResponse, err error) {
	baseReq := conv.Convert()
	req, err := c.newRequest(ctx, http.MethodPost, c.fullURL("/embeddings", baseReq.Model.String()), withBody(baseReq))
	if err != nil {
		return
	}

	if baseReq.EncodingFormat != EmbeddingEncodingFormatBase64 {
		err = c.sendRequest(req, &res)
		return
	}

	base64Response := &EmbeddingResponseBase64{}
	err = c.sendRequest(req, base64Response)
	if err != nil {
		return
	}

	res, err = base64Response.ToEmbeddingResponse()
	return
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was one of my first ideas. Even though it will duplicate the code on calling twice sendRequest is the one with a good readability.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code and tests have been refactored.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you so much!


return
}
Loading