-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
45 lines (37 loc) · 1.62 KB
/
Copy pathProgram.cs
File metadata and controls
45 lines (37 loc) · 1.62 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
using Microsoft.Extensions.AI;
using OllamaSharp;
IEmbeddingGenerator<string, Embedding<float>> embedder = new OllamaApiClient(
new Uri(Environment.GetEnvironmentVariable("OLLAMA_ENDPOINT") ?? "http://localhost:11434"),
Environment.GetEnvironmentVariable("OLLAMA_EMBED_MODEL") ?? "nomic-embed-text");
string[] catalog =
[
"Wireless earbuds with active noise cancellation, 30-hour battery, sweat-resistant.",
"Bone-conduction running headphones with open ear design.",
"Studio over-ear headphones with planar magnetic drivers and detachable cable.",
"Mechanical keyboard with hot-swappable switches and RGB backlight.",
"Ergonomic vertical mouse with thumb buttons and adjustable DPI.",
"Aluminum laptop stand with adjustable height for ergonomic typing.",
];
var docVectors = await embedder.GenerateAsync(catalog);
while (true)
{
Console.Write("\nQuery (blank to quit): ");
var q = Console.ReadLine();
if (string.IsNullOrWhiteSpace(q)) break;
var qEmbedding = (await embedder.GenerateAsync([q])).First();
var ranked = catalog
.Select((text, i) => (text, score: Cosine(qEmbedding.Vector.Span, docVectors[i].Vector.Span)))
.OrderByDescending(x => x.score)
.Take(3);
Console.WriteLine("Top 3 matches:");
foreach (var (text, score) in ranked)
{
Console.WriteLine($" {score:F3} {text}");
}
}
static float Cosine(ReadOnlySpan<float> a, ReadOnlySpan<float> b)
{
float dot = 0, ma = 0, mb = 0;
for (int i = 0; i < a.Length; i++) { dot += a[i] * b[i]; ma += a[i] * a[i]; mb += b[i] * b[i]; }
return dot / (MathF.Sqrt(ma) * MathF.Sqrt(mb));
}