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