-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathProgram.cs
More file actions
52 lines (43 loc) · 1.95 KB
/
Program.cs
File metadata and controls
52 lines (43 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// This sample demonstrates RAG using Azure OpenAI for embeddings with simple in-memory cosine similarity search.
// To use Ollama instead, replace the Azure OpenAI code with:
// new OllamaEmbeddingGenerator(new Uri("http://localhost:11434/"), "all-minilm")
// Or see RAGSimple-01SK or RAGSimple-10SKOllama samples for complete Ollama examples.
using Azure.AI.OpenAI;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Configuration;
using System.ClientModel;
using System.Numerics.Tensors;
// get movie list and prepare in-memory storage
var movieData = MovieFactory<int>.GetMovieVectorList();
// get embeddings generator and generate embeddings for movies
var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
var endpoint = config["endpoint"];
var apiKey = new ApiKeyCredential(config["apikey"]);
var embeddingModelName = config["embeddingModelName"] ?? "text-embedding-3-small";
IEmbeddingGenerator<string, Embedding<float>> generator =
new AzureOpenAIClient(new Uri(endpoint), apiKey)
.GetEmbeddingClient(embeddingModelName)
.AsIEmbeddingGenerator();
// generate embeddings for all movies and store them in memory
foreach (var movie in movieData)
{
movie.Vector = await generator.GenerateVectorAsync(movie.Description);
}
// perform the search using cosine similarity
var query = "A family friendly movie that includes ogres and dragons";
var queryEmbedding = await generator.GenerateVectorAsync(query);
var results = movieData
.Select(movie => (Movie: movie, Score: CosineSimilarity(queryEmbedding.Span, movie.Vector.Span)))
.OrderByDescending(x => x.Score)
.Take(2);
foreach (var (movie, score) in results)
{
Console.WriteLine($"Title: {movie.Title}");
Console.WriteLine($"Description: {movie.Description}");
Console.WriteLine($"Score: {score}");
Console.WriteLine();
}
static float CosineSimilarity(ReadOnlySpan<float> a, ReadOnlySpan<float> b)
{
return TensorPrimitives.CosineSimilarity(a, b);
}