openai/openai-dotnet

Public

mirrored from https://github.com/openai/openai-dotnetAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
mailinhphan/clientOptions

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

examples/Embeddings/Example04_EmbeddingProtocolAsync.cs

45lines · modecode

1using NUnit.Framework;
2using OpenAI.Embeddings;
3using System;
4using System.ClientModel;
5using System.Text.Json;
6using System.Threading.Tasks;
7
8namespace OpenAI.Examples;
9
10public 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