Add DotProduct Method and README Example for Embedding Similarity Search (#492)
* Add DotProduct Method and README Example for Embedding Similarity Search - Implement a DotProduct() method for the Embedding struct to calculate the dot product between two embeddings. - Add a custom error type for vector length mismatch. - Update README.md with a complete example demonstrating how to perform an embedding similarity search for user queries. - Add unit tests to validate the new DotProduct() method and error handling. * Update README to focus on Embedding Semantic Similarity
This commit is contained in:
@@ -4,10 +4,13 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"math"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var ErrVectorLengthMismatch = errors.New("vector length mismatch")
|
||||
|
||||
// EmbeddingModel enumerates the models which can be used
|
||||
// to generate Embedding vectors.
|
||||
type EmbeddingModel int
|
||||
@@ -124,6 +127,23 @@ type Embedding struct {
|
||||
Index int `json:"index"`
|
||||
}
|
||||
|
||||
// DotProduct calculates the dot product of the embedding vector with another
|
||||
// embedding vector. Both vectors must have the same length; otherwise, an
|
||||
// ErrVectorLengthMismatch is returned. The method returns the calculated dot
|
||||
// product as a float32 value.
|
||||
func (e *Embedding) DotProduct(other *Embedding) (float32, error) {
|
||||
if len(e.Embedding) != len(other.Embedding) {
|
||||
return 0, ErrVectorLengthMismatch
|
||||
}
|
||||
|
||||
var dotProduct float32
|
||||
for i := range e.Embedding {
|
||||
dotProduct += e.Embedding[i] * other.Embedding[i]
|
||||
}
|
||||
|
||||
return dotProduct, nil
|
||||
}
|
||||
|
||||
// EmbeddingResponse is the response from a Create embeddings request.
|
||||
type EmbeddingResponse struct {
|
||||
Object string `json:"object"`
|
||||
|
||||
Reference in New Issue
Block a user