openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.4.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

docs/MigrationGuide.md

341lines · modecode

1# Guide for migrating to OpenAI 2.0.0-beta.1 or higher from OpenAI 1.11.0
2
3This guide is intended to assist in the migration to the official OpenAI library (2.0.0-beta.1 or higher) from [OpenAI 1.11.0][openai_1110], focusing on side-by-side comparisons for similar operations between libraries. Version 2.0.0-beta.1 will be used for comparison with 1.11.0 but this guide can still be safely used when migrating to higher versions.
4
5Prior to 2.0.0-beta.1, the OpenAI package was a community library not officially supported by OpenAI. See the [CHANGELOG][changelog] for more details.
6
7Familiarity with the OpenAI 1.11.0 package is assumed. For those new to any OpenAI library for .NET, see the [README][readme] rather than this guide.
8
9## Table of contents
10- [Client usage](#client-usage)
11- [Authentication](#authentication)
12- [Highlighted scenarios](#highlighted-scenarios)
13 - [Chat Completions: Text generation](#chat-completions-text-generation)
14 - [Chat Completions: Streaming](#chat-completions-streaming)
15 - [Chat Completions: JSON mode](#chat-completions-json-mode)
16 - [Chat Completions: Vision](#chat-completions-vision)
17 - [Audio: Speech-to-text](#audio-speech-to-text)
18 - [Audio: Text-to-speech](#audio-text-to-speech)
19 - [Image: Image generation](#image-image-generation)
20- [Additional examples](#additional-examples)
21
22## Client usage
23
24The client usage has considerably changed between libraries. While the OpenAI 1.11.0 had a single client, `OpenAIAPI`, from which multiple APIs could be accessed, OpenAI 2.0.0-beta.1 keeps a separate client per API. The following snippets illustrate this difference when invoking the image generation capability from the Image API:
25
26OpenAI 1.11.0:
27```cs
28OpenAIAPI api = new OpenAIAPI("<api-key>");
29ImageResult result = await api.ImageGenerations.CreateImageAsync("Draw a quick brown fox jumping over a lazy dog.", Model.DALLE3);
30```
31
32OpenAI 2.0.0-beta.1:
33```cs
34ImageClient client = new ImageClient("dall-e-3", "<api-key>");
35ClientResult<GeneratedImage> result = await client.GenerateImageAsync("Draw a quick brown fox jumping over a lazy dog.");
36```
37
38Another major difference highlighted in the snippets above is that OpenAI 2.0.0-beta.1 requires the model to be explicitly set during client instantiation, while the `OpenAIAPI` client allows a model to be specified per call.
39
40The table below illustrates to which client each endpoint of `OpenAIAPI` was ported. Note that the deprecated Completions API is not supported in 2.0.0-beta.1:
41
42Old library's endpoint|New library's client
43|-|-
44|Chat | ChatClient
45|ImageGenerations | ImageClient
46|TextToSpeech | AudioClient
47|Transcriptions | AudioClient
48|Translations | AudioClient
49|Moderation | ModerationClient
50|Embeddings | EmbeddingClient
51|Files | OpenAIFileClient
52|Models | OpenAIModelClient
53|Completions | Not supported
54
55## Authentication
56
57To authenticate to OpenAI, you must set an API key when creating a client.
58
59OpenAI 1.11.0 allowed setting the API key in 3 different ways:
60- Directly from a string
61- From an environment variable
62- From a configuration file
63
64```cs
65OpenAIAPI api;
66
67// Sets the API key directly from a string.
68api = new OpenAIAPI("<api-key>");
69
70// Attempts to load the API key from environment variables OPENAI_KEY and OPENAI_API_KEY.
71api = new OpenAIAPI(APIAuthentication.LoadFromEnv());
72
73// Attempts to load the API key from a configuration file.
74api = new OpenAIAPI(APIAuthentication.LoadFromPath("<directory>", "<filename>"));
75```
76
77OpenAI 2.0.0-beta.1 only supports setting it from a string or from an environment variable. The following snippet illustrates the behavior with the `ChatClient`, but other clients behave the same:
78
79```cs
80ChatClient client;
81
82// Sets the API key directly from a string.
83client = new ChatClient("gpt-3.5-turbo", "<api-key>");
84
85// When no API key string is specified, attempts to load the API key from the environment variable OPENAI_API_KEY.
86client = new ChatClient("gpt-3.5-turbo");
87```
88
89Note that, unlike the OpenAI 1.11.0, OpenAI 2.0.0-beta.1 will never attempt to load the API key from the `OPENAI_KEY` environment variable. Only `OPENAI_API_KEY` is supported.
90
91## Highlighted scenarios
92
93The following sections illustrate side-by-side comparisons for similar operations between the two libraries, highlighting common scenarios.
94
95### Chat Completions: Text generation
96
97OpenAI 1.11.0:
98```cs
99OpenAIAPI api = new OpenAIAPI("<api-key>");
100Conversation conversation = api.Chat.CreateConversation();
101
102conversation.Model = Model.ChatGPTTurbo;
103conversation.AppendSystemMessage("You are a helpful assistant.");
104conversation.AppendUserInput("When was the Nobel Prize founded?");
105
106await conversation.GetResponseFromChatbotAsync();
107
108conversation.AppendUserInput("Who was the first person to be awarded one?");
109
110await conversation.GetResponseFromChatbotAsync();
111
112foreach (ChatMessage message in conversation.Messages)
113{
114 Console.WriteLine($"{message.Role}: {message.TextContent}");
115}
116```
117
118OpenAI 2.0.0-beta.1:
119```cs
120ChatClient client = new ChatClient("gpt-3.5-turbo", "<api-key>");
121List<ChatMessage> messages = new List<ChatMessage>()
122{
123 new SystemChatMessage("You are a helpful assistant."),
124 new UserChatMessage("When was the Nobel Prize founded?")
125};
126
127ClientResult<ChatCompletion> result = await client.CompleteChatAsync(messages);
128
129messages.Add(new AssistantChatMessage(result));
130messages.Add(new UserChatMessage("Who was the first person to be awarded one?"));
131
132result = await client.CompleteChatAsync(messages);
133
134messages.Add(new AssistantChatMessage(result));
135
136foreach (ChatMessage message in messages)
137{
138 string role = message.GetType().Name;
139 string text = message.Content[0].Text;
140
141 Console.WriteLine($"{role}: {text}");
142}
143```
144
145### Chat Completions: Streaming
146
147OpenAI 1.11.0:
148```cs
149OpenAIAPI api = new OpenAIAPI("<api-key>");
150Conversation conversation = api.Chat.CreateConversation();
151
152conversation.Model = Model.ChatGPTTurbo;
153conversation.AppendUserInput("Give me a list of Nobel Prize winners of the last 5 years.");
154
155await foreach (string response in conversation.StreamResponseEnumerableFromChatbotAsync())
156{
157 Console.Write(response);
158}
159```
160
161OpenAI 2.0.0-beta.1:
162```cs
163ChatClient client = new ChatClient("gpt-3.5-turbo", "<api-key>");
164List<ChatMessage> messages = new List<ChatMessage>()
165{
166 new UserChatMessage("Give me a list of Nobel Prize winners of the last 5 years.")
167};
168
169await foreach (StreamingChatCompletionUpdate chatUpdate in client.CompleteChatStreamingAsync(messages))
170{
171 if (chatUpdate.ContentUpdate.Count > 0)
172 {
173 Console.Write(chatUpdate.ContentUpdate[0].Text);
174 }
175}
176```
177
178### Chat Completions: JSON mode
179
180OpenAI 1.11.0:
181```cs
182OpenAIAPI api = new OpenAIAPI("<api-key>");
183ChatRequest request = new ChatRequest()
184{
185 Model = Model.ChatGPTTurbo,
186 ResponseFormat = request.ResponseFormats.JsonObject,
187 Messages = new List<ChatMessage>()
188 {
189 new ChatMessage(ChatMessageRole.System, "You are a helpful assistant designed to output JSON."),
190 new ChatMessage(ChatMessageRole.User, "Give me a JSON object listing Nobel Prize winners of the last 5 years.")
191 }
192};
193
194ChatResult result = await api.Chat.CreateChatCompletionAsync(request);
195
196Console.WriteLine(result);
197```
198
199OpenAI 2.0.0-beta.1:
200```cs
201ChatClient client = new ChatClient("gpt-3.5-turbo", "<api-key>");
202List<ChatMessage> messages = new List<ChatMessage>()
203{
204 new SystemChatMessage("You are a helpful assistant designed to output JSON."),
205 new UserChatMessage("Give me a JSON object listing Nobel Prize winners of the last 5 years.")
206};
207ChatCompletionOptions options = new ChatCompletionOptions()
208{
209 ResponseFormat = ChatResponseFormat.JsonObject
210};
211
212ClientResult<ChatCompletion> result = await client.CompleteChatAsync(messages, options);
213string text = result.Value.Content[0].Text;
214
215Console.WriteLine(text);
216```
217
218### Chat Completions: Vision
219
220OpenAI 1.11.0:
221```cs
222OpenAIAPI api = new OpenAIAPI("<api-key>");
223Conversation conversation = api.Chat.CreateConversation();
224byte[] imageData = await File.ReadAllBytesAsync("<file-path>");
225
226conversation.Model = Model.GPT4_Vision;
227conversation.AppendUserInput("Describe this image.", ImageInput.FromImageBytes(imageData));
228
229string response = await conversation.GetResponseFromChatbotAsync();
230
231Console.WriteLine(response);
232```
233
234OpenAI 2.0.0-beta.1:
235```cs
236ChatClient client = new ChatClient("gpt-4-vision-preview", "<api-key>");
237using FileStream file = File.OpenRead("<file-path>");
238BinaryData imageData = await BinaryData.FromStreamAsync(file);
239List<ChatMessage> messages = new List<ChatMessage>()
240{
241 new UserChatMessage(
242 ChatMessageContentPart.CreateTextMessageContentPart("Describe this image."),
243 ChatMessageContentPart.CreateImageMessageContentPart(imageData, "image/png"))
244};
245
246ClientResult<ChatCompletion> result = await client.CompleteChatAsync(messages);
247string text = result.Value.Content[0].Text;
248
249Console.WriteLine(text);
250```
251
252### Audio: Speech-to-text
253
254OpenAI 1.11.0:
255```cs
256OpenAIAPI api = new OpenAIAPI("<api-key>");
257string result = await api.Transcriptions.GetTextAsync("<file-path>", "fr");
258
259Console.WriteLine(result);
260```
261
262OpenAI 2.0.0-beta.1:
263```cs
264AudioClient client = new AudioClient("whisper-1", "<api-key>");
265AudioTranscriptionOptions options = new AudioTranscriptionOptions()
266{
267 Language = "fr"
268};
269
270ClientResult<AudioTranscription> result = await client.TranscribeAudioAsync("<file-path>", options);
271string text = result.Value.Text;
272
273Console.WriteLine(text);
274```
275
276### Audio: Text-to-speech
277
278OpenAI 1.11.0:
279```cs
280OpenAIAPI api = new OpenAIAPI("<api-key>");
281TextToSpeechRequest request = new TextToSpeechRequest()
282{
283 Input = "Hasta la vista, baby.",
284 Model = Model.TTS_Speed,
285 Voice = "alloy"
286};
287
288await api.TextToSpeech.SaveSpeechToFileAsync(request, "<file-path>");
289```
290
291OpenAI 2.0.0-beta.1:
292```cs
293AudioClient client = new AudioClient("tts-1", "<api-key>");
294
295ClientResult<BinaryData> result = await client.GenerateSpeechFromTextAsync("Hasta la vista, baby.", GeneratedSpeechVoice.Alloy);
296BinaryData data = result.Value;
297
298await File.WriteAllBytesAsync("<file-path>", data.ToArray());
299```
300
301### Image: Image generation
302
303OpenAI 1.11.0:
304```cs
305OpenAIAPI api = new OpenAIAPI("<api-key>");
306ImageGenerationRequest request = new ImageGenerationRequest()
307{
308 Prompt = "Draw a quick brown fox jumping over a lazy dog.",
309 Model = Model.DALLE3,
310 Quality = "standard",
311 Size = ImageSize._1024
312};
313
314ImageResult result = await api.ImageGenerations.CreateImageAsync(request);
315
316Console.WriteLine(result.Data[0].Url);
317```
318
319OpenAI 2.0.0-beta.1:
320```cs
321ImageClient client = new ImageClient("dall-e-3", "<api-key>");
322ImageGenerationOptions options = new ImageGenerationOptions()
323{
324 Quality = GeneratedImageQuality.Standard,
325 Size = GeneratedImageSize.W1024xH1024
326};
327
328ClientResult<GeneratedImage> result = await client.GenerateImageAsync("Draw a quick brown fox jumping over a lazy dog.", options);
329Uri imageUri = result.Value.ImageUri;
330
331Console.WriteLine(imageUri.AbsoluteUri);
332```
333
334## Additional examples
335
336For additional examples, see [OpenAI Examples][examples].
337
338[readme]: https://github.com/openai/openai-dotnet/blob/main/README.md
339[changelog]: https://github.com/openai/openai-dotnet/blob/main/CHANGELOG.md
340[examples]: https://github.com/openai/openai-dotnet/tree/main/examples
341[openai_1110]: https://aka.ms/openai1110
342