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,7 +4,9 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"testing"
|
||||
@@ -233,3 +235,39 @@ func TestEmbeddingResponseBase64_ToEmbeddingResponse(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDotProduct(t *testing.T) {
|
||||
v1 := &Embedding{Embedding: []float32{1, 2, 3}}
|
||||
v2 := &Embedding{Embedding: []float32{2, 4, 6}}
|
||||
expected := float32(28.0)
|
||||
|
||||
result, err := v1.DotProduct(v2)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if math.Abs(float64(result-expected)) > 1e-12 {
|
||||
t.Errorf("Unexpected result. Expected: %v, but got %v", expected, result)
|
||||
}
|
||||
|
||||
v1 = &Embedding{Embedding: []float32{1, 0, 0}}
|
||||
v2 = &Embedding{Embedding: []float32{0, 1, 0}}
|
||||
expected = float32(0.0)
|
||||
|
||||
result, err = v1.DotProduct(v2)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if math.Abs(float64(result-expected)) > 1e-12 {
|
||||
t.Errorf("Unexpected result. Expected: %v, but got %v", expected, result)
|
||||
}
|
||||
|
||||
// Test for VectorLengthMismatchError
|
||||
v1 = &Embedding{Embedding: []float32{1, 0, 0}}
|
||||
v2 = &Embedding{Embedding: []float32{0, 1}}
|
||||
_, err = v1.DotProduct(v2)
|
||||
if !errors.Is(err, ErrVectorLengthMismatch) {
|
||||
t.Errorf("Expected Vector Length Mismatch Error, but got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user