Skip to content

Instantly share code, notes, and snippets.

@dontpaniclabsgists
Created May 6, 2024 14:46
Show Gist options
  • Save dontpaniclabsgists/c2537f828c2dd9195f487d9ac0967528 to your computer and use it in GitHub Desktop.
Save dontpaniclabsgists/c2537f828c2dd9195f487d9ac0967528 to your computer and use it in GitHub Desktop.
class AmazonReviewQueryMatch
{
public AmazonReview Review { get; set; }
public double Relatedness { get; set; }
}
async Task<AmazonReviewQueryMatch[]> Search(string query, int topN = 5)
{
float[] queryEmbeddings;
using (var api = new OpenAIClient(apiKey))
{
var response = await api.EmbeddingsEndpoint
.CreateEmbeddingAsync(query, model, dimensions: 512);
queryEmbeddings = response.Data.First().Embedding
.Select(e => (float)e).ToArray();
}
var matches = reviews.Select(review => new AmazonReviewQueryMatch
{
Review = review,
Relatedness = TensorPrimitives.CosineSimilarity(
new ReadOnlySpan<float>(review.Embeddings),
new ReadOnlySpan<float>(queryEmbeddings)
)
})
.OrderByDescending(match => match.Relatedness)
.Take(topN)
.ToArray();
return matches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment