openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
jsquire-patch-1

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/Embeddings/Example04_EmbeddingProtocol.cs

44lines · modecode

1using NUnit.Framework;
2using OpenAI.Embeddings;
3using System;
4using System.ClientModel;
5using System.Text.Json;
6
7namespace OpenAI.Examples;
8
9public partial class EmbeddingExamples
10{
11 [Test]
12 public void Example04_EmbeddingProtocol()
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
20 BinaryData input = BinaryData.FromObjectAsJson(new
21 {
22 model = "text-embedding-3-small",
23 input = description,
24 encoding_format = "float"
25 });
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}
45