openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
examples/Embeddings/Example04_EmbeddingProtocol.cs
44lines · modeblame
39941cacJose Arriaga Maldonado2 years ago | 1 | using NUnit.Framework; |
| 2 | using OpenAI.Embeddings; | |
| 3 | using System; | |
| 4 | using System.ClientModel; | |
| 5 | using System.Text.Json; | |
| 6 | | |
| 7 | namespace OpenAI.Examples; | |
| 8 | | |
| 9 | public partial class EmbeddingExamples | |
| 10 | { | |
| 11 | [Test] | |
7a8bc8beJose Arriaga Maldonado1 years ago | 12 | public void Example04_EmbeddingProtocol() |
39941cacJose Arriaga Maldonado2 years ago | 13 | { |
| 14 | EmbeddingClient client = new("text-embedding-3-small", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); | |
| 15 | | |
| 16 | string description = "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa," | |
| 17 | + " and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist" | |
| 18 | + " attractions. We highly recommend this hotel."; | |
| 19 | | |
79014abcShivangiReja1 years ago | 20 | BinaryData input = BinaryData.FromObjectAsJson(new |
| 21 | { | |
| 22 | model = "text-embedding-3-small", | |
| 23 | input = description, | |
| 24 | encoding_format = "float" | |
| 25 | }); | |
39941cacJose Arriaga Maldonado2 years ago | 26 | |
| 27 | using BinaryContent content = BinaryContent.Create(input); | |
| 28 | ClientResult result = client.GenerateEmbeddings(content); | |
| 29 | BinaryData output = result.GetRawResponse().Content; | |
| 30 | | |
| 31 | using JsonDocument outputAsJson = JsonDocument.Parse(output.ToString()); | |
| 32 | JsonElement vector = outputAsJson.RootElement | |
| 33 | .GetProperty("data"u8)[0] | |
| 34 | .GetProperty("embedding"u8); | |
| 35 | | |
| 36 | Console.WriteLine($"Dimension: {vector.GetArrayLength()}"); | |
| 37 | Console.WriteLine($"Floats: "); | |
| 38 | int i = 0; | |
| 39 | foreach (JsonElement element in vector.EnumerateArray()) | |
| 40 | { | |
| 41 | Console.WriteLine($" [{i++,4}] = {element.GetDouble()}"); | |
| 42 | } | |
| 43 | } | |
| 44 | } |