{"id":13641560,"url":"https://github.com/OkGoDoIt/OpenAI-API-dotnet","last_synced_at":"2025-04-20T11:31:12.110Z","repository":{"id":37652817,"uuid":"281805770","full_name":"OkGoDoIt/OpenAI-API-dotnet","owner":"OkGoDoIt","description":"An unofficial C#/.NET SDK for accessing the OpenAI GPT-3 API","archived":false,"fork":false,"pushed_at":"2024-08-07T00:56:14.000Z","size":2069,"stargazers_count":1886,"open_issues_count":127,"forks_count":431,"subscribers_count":63,"default_branch":"master","last_synced_at":"2025-04-18T12:38:17.510Z","etag":null,"topics":["c-sharp","chatgpt","csharp","dall-e","dalle2","dotnet","dotnet-core","dotnet-standard","gpt-3","gpt-4","gpt3","gpt35","gpt4","machine-learning","ml","openai","sdk"],"latest_commit_sha":null,"homepage":"https://www.nuget.org/packages/OpenAI/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/OkGoDoIt.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-07-22T23:42:03.000Z","updated_at":"2025-04-18T09:40:04.000Z","dependencies_parsed_at":"2022-08-08T21:15:24.873Z","dependency_job_id":"265c1d25-8712-4b24-afd9-8072a176bf4c","html_url":"https://github.com/OkGoDoIt/OpenAI-API-dotnet","commit_stats":{"total_commits":83,"total_committers":10,"mean_commits":8.3,"dds":"0.40963855421686746","last_synced_commit":"6661723d5c908533f0cf1fb4466ef844b3e60cc1"},"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OkGoDoIt%2FOpenAI-API-dotnet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OkGoDoIt%2FOpenAI-API-dotnet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OkGoDoIt%2FOpenAI-API-dotnet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/OkGoDoIt%2FOpenAI-API-dotnet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/OkGoDoIt","download_url":"https://codeload.github.com/OkGoDoIt/OpenAI-API-dotnet/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249587824,"owners_count":21295664,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["c-sharp","chatgpt","csharp","dall-e","dalle2","dotnet","dotnet-core","dotnet-standard","gpt-3","gpt-4","gpt3","gpt35","gpt4","machine-learning","ml","openai","sdk"],"created_at":"2024-08-02T01:01:21.781Z","updated_at":"2025-04-20T11:31:11.328Z","avatar_url":"https://github.com/OkGoDoIt.png","language":"C#","readme":"Microsoft reached out to me about transitioning this library into a new official C# OpenAI library and now it's ready to go!  Starting with [v2.0.0-beta.3](https://www.nuget.org/packages/OpenAI/2.0.0-beta.3), the official library now has full coverage and will stay up-to-date.  More details in the blog post here: https://devblogs.microsoft.com/dotnet/openai-dotnet-library\n\nThis github repo will remain here to document my original version of the library through [version 1.11, which is still available on Nuget as well](https://www.nuget.org/packages/OpenAI/1.11.0).\n🎉 \n\n# C#/.NET SDK for accessing the OpenAI APIs, including GPT-3.5/4, GPT-3.5/4-Turbo, and DALL-E 2/3\n\nA simple C# .NET wrapper library to use with OpenAI's API.  More context [on my blog](https://rogerpincombe.com/openai-dotnet-api).  **This is my original unofficial wrapper library around the OpenAI API.**\n\n## Quick Example\n\n```csharp\nvar api = new OpenAI_API.OpenAIAPI(\"YOUR_API_KEY\");\nvar result = await api.Chat.CreateChatCompletionAsync(\"Hello!\");\nConsole.WriteLine(result);\n// should print something like \"Hi! How can I help you?\"\n```\n\n## Readme\n\n * [Status](#Status)\n * [Requirements](#requirements)\n * [Installation](#install-from-nuget)\n * [Authentication](#authentication)\n * [Chat API](#chat-api)\n\t* [Conversations](#chat-conversations)\n\t* [Streaming Results](#chat-streaming)\n\t* [GPT Vision](#gpt-vision)\n\t* [Chat Endpoint](#chat-endpoint-requests)\n\t* [Conversation History Context Length Management](#Conversation-History-Context-Length-Management)\n\t* [JSON Mode](#json-mode)\n * [Completions API](#completions-api)\n\t* [Streaming completion results](#streaming)\n * [Audio](#audio)\n\t* [Text to Speech](#text-to-speech-tts)\n\t* [Transcribe Audio to Text](#transcription-speech-to-text)\n\t* [Translate Audio to English Text](#translations-non-english-speech-to-english-text)\n * [Embeddings API](#embeddings)\n * [Moderation API](#moderation)\n * [Files API](#files-for-fine-tuning)\n * [Image APIs (DALL-E)](#images)\n\t* [DALLE-E 3](#dall-e-3)\n * [Azure](#azure)\n * [Additional Documentation](#documentation)\n * [License](#license)\n\n## Status\n[![OpenAI](https://badgen.net/nuget/v/OpenAI)](https://www.nuget.org/packages/OpenAI/)\n\nStarting with [v2.0.0-beta](https://www.nuget.org/packages/OpenAI/2.0.0-beta.3), this library has been adopted by Microsoft.  The new official version of the library will have full coverage and will stay fully up-to-date. More details in the blog post here: [https://devblogs.microsoft.com/dotnet/openai-dotnet-library/](https://devblogs.microsoft.com/dotnet/openai-dotnet-library/)\nThis github repo will remain here to document my original version of the library through [version 1.11, which is still available on Nuget as well](https://www.nuget.org/packages/OpenAI/1.11.0).\n\n## Requirements\n\nThis library is based on .NET Standard 2.0, so it should work across all versions of .Net, from the traditional .NET Framework \u003e=4.7.2 to .NET (Core) \u003e= 3.0.  It should work across console apps, winforms, wpf, asp.net, unity, Xamarin, etc.  It should work across Windows, Linux, and Mac, and possibly even mobile.  There are minimal dependencies, and it's licensed in the public domain.\n\n## Getting started\n\n### Install from NuGet\n\nInstall package [`OpenAI` v1.11 from Nuget](https://www.nuget.org/packages/OpenAI/1.11.0).  Here's how via commandline:\n```powershell\nInstall-Package OpenAI -Version 1.11.0\n```\n\n### Authentication\nThere are 3 ways to provide your API keys, in order of precedence:\n1.  Pass keys directly to `APIAuthentication(string key)` constructor\n2.  Set environment var for OPENAI_API_KEY (or OPENAI_KEY for backwards compatibility)\n3.  Include a config file in the local directory or in your user directory named `.openai` and containing the line:\n```shell\nOPENAI_API_KEY=sk-aaaabbbbbccccddddd\n```\n\nYou use the `APIAuthentication` when you initialize the API as shown:\n```csharp\n// for example\nOpenAIAPI api = new OpenAIAPI(\"YOUR_API_KEY\"); // shorthand\n// or\nOpenAIAPI api = new OpenAIAPI(new APIAuthentication(\"YOUR_API_KEY\")); // create object manually\n// or\nOpenAIAPI api = new OpenAIAPI(APIAuthentication LoadFromEnv()); // use env vars\n// or\nOpenAIAPI api = new OpenAIAPI(APIAuthentication LoadFromPath()); // use config file (can optionally specify where to look)\n// or\nOpenAIAPI api = new OpenAIAPI(); // uses default, env, or config file\n```\n\nYou may optionally include an openAIOrganization (OPENAI_ORGANIZATION in env or config file) specifying which organization is used for an API request. Usage from these API requests will count against the specified organization's subscription quota.  Organization IDs can be found on your [Organization settings](https://beta.openai.com/account/org-settings) page.\n```csharp\n// for example\nOpenAIAPI api = new OpenAIAPI(new APIAuthentication(\"YOUR_API_KEY\",\"org-yourOrgHere\"));\n```\n\n### Chat API\nThe Chat API is accessed via `OpenAIAPI.Chat`.  There are two ways to use the Chat Endpoint, either via simplified conversations or with the full Request/Response methods.\n\n#### Chat Conversations\nThe Conversation Class allows you to easily interact with ChatGPT by adding messages to a chat and asking ChatGPT to reply.\n```csharp\nvar chat = api.Chat.CreateConversation();\nchat.Model = Model.GPT4_Turbo;\nchat.RequestParameters.Temperature = 0;\n\n/// give instruction as System\nchat.AppendSystemMessage(\"You are a teacher who helps children understand if things are animals or not.  If the user tells you an animal, you say \\\"yes\\\".  If the user tells you something that is not an animal, you say \\\"no\\\".  You only ever respond with \\\"yes\\\" or \\\"no\\\".  You do not say anything else.\");\n\n// give a few examples as user and assistant\nchat.AppendUserInput(\"Is this an animal? Cat\");\nchat.AppendExampleChatbotOutput(\"Yes\");\nchat.AppendUserInput(\"Is this an animal? House\");\nchat.AppendExampleChatbotOutput(\"No\");\n\n// now let's ask it a question\nchat.AppendUserInput(\"Is this an animal? Dog\");\n// and get the response\nstring response = await chat.GetResponseFromChatbotAsync();\nConsole.WriteLine(response); // \"Yes\"\n\n// and continue the conversation by asking another\nchat.AppendUserInput(\"Is this an animal? Chair\");\n// and get another response\nresponse = await chat.GetResponseFromChatbotAsync();\nConsole.WriteLine(response); // \"No\"\n\n// the entire chat history is available in chat.Messages\nforeach (ChatMessage msg in chat.Messages)\n{\n\tConsole.WriteLine($\"{msg.Role}: {msg.Content}\");\n}\n```\n\n#### Chat Streaming\n\nStreaming allows you to get results are they are generated, which can help your application feel more responsive.\n\nUsing the new C# 8.0 async iterators:\n```csharp\nvar chat = api.Chat.CreateConversation();\nchat.AppendUserInput(\"How to make a hamburger?\");\n\nawait foreach (var res in chat.StreamResponseEnumerableFromChatbotAsync())\n{\n\tConsole.Write(res);\n}\n```\n\nOr if using classic .NET Framework or C# \u003c8.0:\n```csharp\nvar chat = api.Chat.CreateConversation();\nchat.AppendUserInput(\"How to make a hamburger?\");\n\nawait chat.StreamResponseFromChatbotAsync(res =\u003e\n{\n\tConsole.Write(res);\n});\n```\n\n#### GPT Vision\n\nYou can send images to the chat to use the new GPT-4 Vision model.  This only works with the `Model.GPT4_Vision` model.  Please see https://platform.openai.com/docs/guides/vision for more information and limitations.\n\n```csharp\n// the simplest form\nvar result = await api.Chat.CreateChatCompletionAsync(\"What is the primary non-white color in this logo?\", ImageInput.FromFile(\"path/to/logo.png\"));\n\n// or in a conversation\nvar chat = api.Chat.CreateConversation();\nchat.Model = Model.GPT4_Vision;\nchat.AppendSystemMessage(\"You are a graphic design assistant who helps identify colors.\");\nchat.AppendUserInput(\"What are the primary non-white colors in this logo?\", ImageInput.FromFile(\"path/to/logo.png\"));\nstring response = await chat.GetResponseFromChatbotAsync();\nConsole.WriteLine(response); // \"Blue and purple\"\nchat.AppendUserInput(\"What are the primary non-white colors in this logo?\", ImageInput.FromImageUrl(\"https://rogerpincombe.com/templates/rp/center-aligned-no-shadow-small.png\"));\nresponse = await chat.GetResponseFromChatbotAsync();\nConsole.WriteLine(response); // \"Blue, red, and yellow\"\n\n// or when manually creating the ChatMessage\nmessageWithImage = new ChatMessage(ChatMessageRole.User, \"What colors do these logos have in common?\");\nmessageWithImage.images.Add(ImageInput.FromFile(\"path/to/logo.png\"));\nmessageWithImage.images.Add(ImageInput.FromImageUrl(\"https://rogerpincombe.com/templates/rp/center-aligned-no-shadow-small.png\"));\n\n// you can specify multiple images at once\nchat.AppendUserInput(\"What colors do these logos have in common?\", ImageInput.FromFile(\"path/to/logo.png\"), ImageInput.FromImageUrl(\"https://rogerpincombe.com/templates/rp/center-aligned-no-shadow-small.png\"));\n```\n\n\n#### Conversation History Context Length Management\nIf the chat conversation history gets too long, it may not fit into the context length of the model.  By default, the earliest non-system message(s) will be removed from the chat history and the API call will be retried.  You may disable this by setting `chat.AutoTruncateOnContextLengthExceeded = false`, or you can override the truncation algorithm like this:\n\n```csharp\nchat.OnTruncationNeeded += (sender, args) =\u003e\n{\n\t// args is a List\u003cChatMessage\u003e with the current chat history.  Remove or edit as nessisary.\n\t// replace this with more sophisticated logic for your use-case, such as summarizing the chat history\n\tfor (int i = 0; i \u003c args.Count; i++)\n\t{\n\t\tif (args[i].Role != ChatMessageRole.System)\n\t\t{\n\t\t\targs.RemoveAt(i);\n\t\t\treturn;\n\t\t}\n\t}\n};\n```\n\nYou may also wish to use a new model with a larger context length.  You can do this by setting `chat.Model = Model.GPT4_Turbo` or `chat.Model = Model.ChatGPTTurbo_16k`, etc.\n\nYou can see token usage via `chat.MostRecentApiResult.Usage.PromptTokens` and related properties. \n\n#### Chat Endpoint Requests\nYou can access full control of the Chat API by using the `OpenAIAPI.Chat.CreateChatCompletionAsync()` and related methods.\n\n```csharp\nasync Task\u003cChatResult\u003e CreateChatCompletionAsync(ChatRequest request);\n\n// for example\nvar result = await api.Chat.CreateChatCompletionAsync(new ChatRequest()\n\t{\n\t\tModel = Model.ChatGPTTurbo,\n\t\tTemperature = 0.1,\n\t\tMaxTokens = 50,\n\t\tMessages = new ChatMessage[] {\n\t\t\tnew ChatMessage(ChatMessageRole.User, \"Hello!\")\n\t\t}\n\t})\n// or\nvar result = api.Chat.CreateChatCompletionAsync(\"Hello!\");\n\nvar reply = results.Choices[0].Message;\nConsole.WriteLine($\"{reply.Role}: {reply.Content.Trim()}\");\n// or\nConsole.WriteLine(results);\n```\n\nIt returns a `ChatResult` which is mostly metadata, so use its `.ToString()` method to get the text if all you want is assistant's reply text.\n\nThere's also an async streaming API which works similarly to the [Completions endpoint streaming results](#streaming). \n\n#### JSON Mode\n\nWith the new `Model.GPT4_Turbo` or `gpt-3.5-turbo-1106` models, you can set the `ChatRequest.ResponseFormat` to `ChatRequest.ResponseFormats.JsonObject` to enable JSON mode.\nWhen JSON mode is enabled, the model is constrained to only generate strings that parse into valid JSON object.\nSee https://platform.openai.com/docs/guides/text-generation/json-mode for more details.\n\n```csharp\nChatRequest chatRequest = new ChatRequest()\n{\n\tModel = model,\n\tTemperature = 0.0,\n\tMaxTokens = 500,\n\tResponseFormat = ChatRequest.ResponseFormats.JsonObject,\n\tMessages = new ChatMessage[] {\n\t\tnew ChatMessage(ChatMessageRole.System, \"You are a helpful assistant designed to output JSON.\"),\n\t\tnew ChatMessage(ChatMessageRole.User, \"Who won the world series in 2020?  Return JSON of a 'wins' dictionary with the year as the numeric key and the winning team as the string value.\")\n\t}\n};\n\nvar results = await api.Chat.CreateChatCompletionAsync(chatRequest);\nConsole.WriteLine(results);\n/* prints:\n{\n  \"wins\": {\n\t2020: \"Los Angeles Dodgers\"\n  }\n}\n*/\n```\n\n\n\n### Completions API\nCompletions are considered legacy by OpenAI.  The Completion API is accessed via `OpenAIAPI.Completions`:\n\n```csharp\nasync Task\u003cCompletionResult\u003e CreateCompletionAsync(CompletionRequest request);\n\n// for example\nvar result = await api.Completions.CreateCompletionAsync(new CompletionRequest(\"One Two Three One Two\", model: Model.CurieText, temperature: 0.1));\n// or\nvar result = await api.Completions.CreateCompletionAsync(\"One Two Three One Two\", temperature: 0.1);\n// or other convenience overloads\n```\nYou can create your `CompletionRequest` ahead of time or use one of the helper overloads for convenience.  It returns a `CompletionResult` which is mostly metadata, so use its `.ToString()` method to get the text if all you want is the completion.\n\n#### Streaming\nStreaming allows you to get results are they are generated, which can help your application feel more responsive, especially on slow models like Davinci.\n\nUsing the new C# 8.0 async iterators:\n```csharp\nIAsyncEnumerable\u003cCompletionResult\u003e StreamCompletionEnumerableAsync(CompletionRequest request);\n\n// for example\nawait foreach (var token in api.Completions.StreamCompletionEnumerableAsync(new CompletionRequest(\"My name is Roger and I am a principal software engineer at Salesforce.  This is my resume:\", Model.DavinciText, 200, 0.5, presencePenalty: 0.1, frequencyPenalty: 0.1)))\n{\n\tConsole.Write(token);\n}\n```\n\nOr if using classic .NET framework or C# \u003c8.0:\n```csharp\nasync Task StreamCompletionAsync(CompletionRequest request, Action\u003cCompletionResult\u003e resultHandler);\n\n// for example\nawait api.Completions.StreamCompletionAsync(\n\tnew CompletionRequest(\"My name is Roger and I am a principal software engineer at Salesforce.  This is my resume:\", Model.DavinciText, 200, 0.5, presencePenalty: 0.1, frequencyPenalty: 0.1),\n\tres =\u003e ResumeTextbox.Text += res.ToString());\n```\n\n### Audio\nThe Audio API's are Text to Speech, Transcription (speech to text), and Translation (non-English speech to English text).\n\n#### Text to Speech (TTS)\nThe TTS API is accessed via `OpenAIAPI.TextToSpeech`:\n\n```csharp\nawait api.TextToSpeech.SaveSpeechToFileAsync(\"Hello, brave new world!  This is a test.\", outputPath);\n// You can open it in the defaul audio player like this:\nProcess.Start(outputPath);\n```\n\nYou can also specify all of the request parameters with a `TextToSpeechRequest` object:\n\n```csharp\nvar request = new TextToSpeechRequest()\n{\n\tInput = \"Hello, brave new world!  This is a test.\",\n\tResponseFormat = ResponseFormats.AAC,\n\tModel = Model.TTS_HD,\n\tVoice = Voices.Nova,\n\tSpeed = 0.9\n};\nawait api.TextToSpeech.SaveSpeechToFileAsync(request, \"test.aac\");\n```\n\nInstead of saving to a file, you can get audio byte stream with `api.TextToSpeech.GetSpeechAsStreamAsync(request)`:\n\n```csharp\nusing (Stream result = await api.TextToSpeech.GetSpeechAsStreamAsync(\"Hello, brave new world!\", Voices.Fable))\nusing (StreamReader reader = new StreamReader(result))\n{\n\t// do something with the audio stream here\n}\n```\n\n#### Transcription (Speech to Text)\n\nThe Audio Transcription API allows you to generate text from audio, in any of the supported languages.  It is accessed via `OpenAIAPI.Transcriptions`:\n\n```csharp\nstring resultText = await api.Transcriptions.GetTextAsync(\"path/to/file.mp3\");\n```\n\nYou can ask for verbose results, which will give you segment and token-level information, as well as the standard OpenAI metadata such as processing time:\n\n```csharp\nAudioResultVerbose result = await api.Transcriptions.GetWithDetailsAsync(\"path/to/file.m4a\");\nConsole.WriteLine(result.ProcessingTime.TotalMilliseconds); // 496ms\nConsole.WriteLine(result.text); // \"Hello, this is a test of the transcription function.\"\nConsole.WriteLine(result.language); // \"english\"\nConsole.WriteLine(result.segments[0].no_speech_prob); // 0.03712\n// etc\n```\n\nYou can also ask for results in SRT or VTT format, which is useful for generating subtitles for videos:\n\n```csharp\nstring result = await api.Transcriptions.GetAsFormatAsync(\"path/to/file.m4a\", AudioRequest.ResponseFormats.SRT);\n```\n\nAdditional parameters such as temperature, prompt, language, etc can be specified either per-request or as a default:\n\n```csharp\n// inline\nresult = await api.Transcriptions.GetTextAsync(\"conversation.mp3\", \"en\", \"This is a transcript of a conversation between a medical doctor and her patient: \", 0.3);\n\n// set defaults\napi.Transcriptions.DefaultTranscriptionRequestArgs.Language = \"en\";\n```\n\nInstead of providing a local file on disk, you can provide a stream of audio bytes.  This can be useful for streaming audio from the microphone or another source without having to first write to disk.  Please not you must specify a filename, which does not have to exist, but which must have an accurate extension for the type of audio that you are sending.  OpenAI uses the filename extension to determine what format your audio stream is in.\n\n```csharp\nusing (var audioStream = File.OpenRead(\"path-here.mp3\"))\n{\n\treturn await api.Transcriptions.GetTextAsync(audioStream, \"file.mp3\");\n}\n```\n\n#### Translations (Non-English Speech to English Text)\n\nTranslations allow you to transcribe text from any of the supported languages to English.  OpenAI does not support translating into any other language, only English.  It is accessed via `OpenAIAPI.Translations`.\nIt supports all of the same functionality as the Transcriptions.\n\n```csharp\nstring result = await api.Translations.GetTextAsync(\"chinese-example.m4a\");\n```\n\n### Embeddings\nThe Embedding API is accessed via `OpenAIAPI.Embeddings`:\n\n```csharp\nasync Task\u003cEmbeddingResult\u003e CreateEmbeddingAsync(EmbeddingRequest request);\n\n// for example\nvar result = await api.Embeddings.CreateEmbeddingAsync(new EmbeddingRequest(\"A test text for embedding\", model: Model.AdaTextEmbedding));\n// or\nvar result = await api.Embeddings.CreateEmbeddingAsync(\"A test text for embedding\");\n```\n\nThe embedding result contains a lot of metadata, the actual vector of floats is in result.Data[].Embedding.\n\nFor simplicity, you can directly ask for the vector of floats and disgard the extra metadata with `api.Embeddings.GetEmbeddingsAsync(\"test text here\")`\n\n\n### Moderation\nThe Moderation API is accessed via `OpenAIAPI.Moderation`:\n\n```csharp\nasync Task\u003cModerationResult\u003e CreateEmbeddingAsync(ModerationRequest request);\n\n// for example\nvar result = await api.Moderation.CallModerationAsync(new ModerationRequest(\"A test text for moderating\", Model.TextModerationLatest));\n// or\nvar result = await api.Moderation.CallModerationAsync(\"A test text for moderating\");\n\nConsole.WriteLine(result.results[0].MainContentFlag);\n```\n\nThe results are in `.results[0]` and have nice helper methods like `FlaggedCategories` and `MainContentFlag`.\n\n\n### Files (for fine-tuning)\nThe Files API endpoint is accessed via `OpenAIAPI.Files`:\n\n```csharp\n// uploading\nasync Task\u003cFile\u003e UploadFileAsync(string filePath, string purpose = \"fine-tune\");\n\n// for example\nvar response = await api.Files.UploadFileAsync(\"fine-tuning-data.jsonl\");\nConsole.Write(response.Id); //the id of the uploaded file\n\n// listing\nasync Task\u003cList\u003cFile\u003e\u003e GetFilesAsync();\n\n// for example\nvar response = await api.Files.GetFilesAsync();\nforeach (var file in response)\n{\n\tConsole.WriteLine(file.Name);\n}\n```\n\nThere are also methods to get file contents, delete a file, etc.\n\nThe fine-tuning endpoint itself has not yet been implemented, but will be added soon.\n\n### Images\nThe DALL-E Image Generation API is accessed via `OpenAIAPI.ImageGenerations`:\n\n```csharp\nasync Task\u003cImageResult\u003e CreateImageAsync(ImageGenerationRequest request);\n\n// for example\nvar result = await api.ImageGenerations.CreateImageAsync(new ImageGenerationRequest(\"A drawing of a computer writing a test\", 1, ImageSize._512));\n// or\nvar result = await api.ImageGenerations.CreateImageAsync(\"A drawing of a computer writing a test\");\n\nConsole.WriteLine(result.Data[0].Url);\n```\n\nThe image result contains a URL for an online image or a base64-encoded image, depending on the ImageGenerationRequest.ResponseFormat (url is the default).\n\n#### DALL-E 3\n\nUse DALL-E 3 like this:\n\n```csharp\nasync Task\u003cImageResult\u003e CreateImageAsync(ImageGenerationRequest request);\n\n// for example\nvar result = await api.ImageGenerations.CreateImageAsync(new ImageGenerationRequest(\"A drawing of a computer writing a test\", OpenAI_API.Models.Model.DALLE3, ImageSize._1024x1792, \"hd\"));\n// or\nvar result = await api.ImageGenerations.CreateImageAsync(\"A drawing of a computer writing a test\", OpenAI_API.Models.Model.DALLE3);\n\nConsole.WriteLine(result.Data[0].Url);\n```\n\n## Azure\n\nFor using the Azure OpenAI Service, you need to specify the name of your Azure OpenAI resource as well as your model deployment id.\n\n_I do not have access to the Microsoft Azure OpenAI service, so I am unable to test this functionality.  If you have access and can test, please submit an issue describing your results.  A PR with integration tests would also be greatly appreciated.  Specifically, it is unclear to me that specifying models works the same way with Azure._\n\nRefer the [Azure OpenAI documentation](https://learn.microsoft.com/en-us/azure/cognitive-services/openai/reference) and [detailed screenshots in #64](https://github.com/OkGoDoIt/OpenAI-API-dotnet/issues/64#issuecomment-1479276020) for further information.\n\nConfiguration should look something like this for the Azure service:\n\n```csharp\nOpenAIAPI api = OpenAIAPI.ForAzure(\"YourResourceName\", \"deploymentId\", \"api-key\");\napi.ApiVersion = \"2023-03-15-preview\"; // needed to access chat endpoint on Azure\n```\n\nYou may then use the `api` object like normal.  You may also specify the `APIAuthentication` is any of the other ways listed in the [Authentication](#authentication) section above.  Currently this library only supports the api-key flow, not the AD-Flow.\n\nAs of April 2, 2023, you need to manually select api version `2023-03-15-preview` as shown above to access the chat endpoint on Azure.  Once this is out of preview I will update the default.\n\n## IHttpClientFactory\nYou may specify an `IHttpClientFactory` to be used for HTTP requests, which allows for tweaking http request properties, connection pooling, and mocking.  Details in [#103](https://github.com/OkGoDoIt/OpenAI-API-dotnet/pull/103).\n\n```csharp\nOpenAIAPI api = new OpenAIAPI();\napi.HttpClientFactory = myIHttpClientFactoryObject;\n```\n\n## Documentation\n\nEvery single class, method, and property has extensive XML documentation, so it should show up automatically in IntelliSense.  That combined with the official OpenAI documentation should be enough to get started.  Feel free to open an issue here if you have any questions.  Better documentation may come later.\n\n## License\n\nCC-0 Public Domain\n\nThis library is licensed CC-0, in the public domain.  You can use it for whatever you want, publicly or privately, without worrying about permission or licensing or whatever.  It's just a wrapper around the OpenAI API, so you still need to get access to OpenAI from them directly.  I am not affiliated with OpenAI and this library is not endorsed by them, I just have beta access and wanted to make a C# library to access it more easily.  Hopefully others find this useful as well.  Feel free to open a PR if there's anything you want to contribute.\n","funding_links":[],"categories":["A01_文本生成_文本对话","Open API","SDK, Libraries, Frameworks"],"sub_categories":["大语言对话模型及数据","提示语（魔法）","C# library, sdk or frameworks"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FOkGoDoIt%2FOpenAI-API-dotnet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FOkGoDoIt%2FOpenAI-API-dotnet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FOkGoDoIt%2FOpenAI-API-dotnet/lists"}