openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.1.0-beta.2

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/Embeddings/Example04_EmbeddingProtocolAsync.cs

45lines · modeblame

39941cacJose Arriaga Maldonado2 years ago1using 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]
7a8bc8beJose Arriaga Maldonado1 years ago13public async Task Example04_EmbeddingProtocolAsync()
39941cacJose Arriaga Maldonado2 years ago14{
15EmbeddingClient client = new("text-embedding-3-small", Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
16
17string 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
21BinaryData input = BinaryData.FromObjectAsJson(new
22{
23model = "text-embedding-3-small",
24input = description,
25encoding_format = "float"
26});
27
28using BinaryContent content = BinaryContent.Create(input);
29ClientResult result = await client.GenerateEmbeddingsAsync(content);
30BinaryData output = result.GetRawResponse().Content;
31
32using JsonDocument outputAsJson = JsonDocument.Parse(output.ToString());
33JsonElement vector = outputAsJson.RootElement
34.GetProperty("data"u8)[0]
35.GetProperty("embedding"u8);
36
37Console.WriteLine($"Dimension: {vector.GetArrayLength()}");
38Console.WriteLine($"Floats: ");
39int i = 0;
40foreach (JsonElement element in vector.EnumerateArray())
41{
42Console.WriteLine($" [{i++,4}] = {element.GetDouble()}");
43}
44}
45}