A self-contained library that talks directly to the OpenAI HTTP API without major dependencies with explicit support for:
- OpenAI
- Azure OpenAI
- GitHub Models
- Gemini
- Mistral
- OpenRouter
- Ollama (Local)
- Ollama Cloud
- Perplexity
- DeepSeek
- xAI/Grok
- Nvidia
- Any OpenAI-compatible API
The purpose of this library is to provide a minimal dependencies client for raw OpenAi Completions and Image Generation operations. It also provides a simple connection configuration interface that facilitates managing multiple connections to different in applications via simple Json configuration.
This is meant for lightweight integrations into existing applications that have simple, one-off AI integration needs and don't need advanced features although it's also possible to build more sophisticated interfaces like a chat Ui.
This library supports:
- Generic Completions and Chat History via
GenericAiChatClient - Several pre-configured Text operations via
AiTextOperations- Text Summary
- Translation
- Grammar Check
- Image Generation via
ImageGeneration - Text to Speech via
TextToSpeechGeneration - Chat History for multi-request context
- Easy connection creation and multiple connection management
- Connection information JSON storage and encryption
- Basic Request/Response API only - no streaming APIs
.NET Targets:
- .NET10.0
- .NET8.0
- .NET472
If you need streaming interfaces or want to do extended processing on your AI results with custom functions, MCP integration or other add-on operations, then using one of the more powerful and heavy dependencies tools like Microsoft.Extensions.AI makes good sense.
You can use manual configuration like this for connecting to the OpenAI API:
var connection = new OpenAiConnection() {
ApiKey = myApiKey,
ModelId = "gpt-4o-mini",
// OperationMode = AiOperationModes.Completions // default
};For image generation:
var connection = new OpenAiConnection() {
ApiKey = myApiKey,
ModelId = "dall-e-3",
OperationMode = AiOperationModes.ImageGeneration
};More info on the various different connection providers (OpenAI, Azure, Ollama, and other OpenAI-compatible providers) and how to create multiple providers to choose from and store them is discussed below in more detail.
This library provides basic Chat Completions that directly pass messages to the API and return the result. If you need more sophisticated functionality for adding custom processing or additional training data, use Microsoft Semantic Kernel. It provides all the features used here, but at a significantly bigger footprint.
This library is geared towards simple interactions that provide small and fast local application integrations especially for working with local models.
// Load pre-configured connection
// var config = OpenAiConnectionConfiguration.Load();
// var connection = config.ActiveConnection;
// Manual Connection
var connection = new OpenAiConnection() {
ApiKey = myApiKey,
ModelId = "gpt-4o-mini",
OperationMode = AiOperationModes.Completions
};
var completion = new GenericAiChatClient(connection);
completion.CaptureRequestData = true;
string resultText = await completion.Complete(
"Translate the following from English to German:\nThe sky is below, the ground is above",
"You are a translator that translates between languages. Return only the translated text.");
Assert.IsFalse(completion.HasError, completion.ErrorMessage);
Assert.IsFalse(string.IsNullOrEmpty(resultText),
"No completion response was returned (null or empty).");
Console.WriteLine(resultText);
// optionally captured request and response data
Console.WriteLine(completion.LastRequestJson);
Console.WriteLine("\n\n" + completion.LastResponseJson);Alternately you can pass a collection of prompts:
var completion = new GenericAiChatClient(connection);
completion.CaptureRequestData = true;
var prompts = new List<OpenAiChatMessage>
{
new OpenAiChatMessage {
content = "You are a translator that translates between languages. Return only the translated text.",
role = "system"
},
new OpenAiChatMessage {
content = "Translate the following from English to German:\nThe sky is below, the ground is above",
role = "user"
},
};
var resultText = await completion.Complete(prompts);
Assert.IsFalse(completion.HasError, completion.ErrorMessage);
Assert.IsFalse(string.IsNullOrEmpty(resultText), "No completion response was returned (null or empty).");
Console.WriteLine(resultText);
// optionally captured request and response data
Console.WriteLine(completion.LastRequestJson);
Console.WriteLine("\n\n" + completion.LastResponseJson);You can keep track of the Chat History if you keep the AiChatClient around and use IncludeHistory:
string bornDate = DateTime.Now.AddYears(-30).ToString("MMMM yyyy");
string currentDate = DateTime.Now.ToString("MMMM yyyy");
Console.WriteLine("Born on: " + bornDate);
var completion = new GenericAiChatClient(connection)
{
CaptureRequestData = true
};
// We have to provide the start date, otherwise it uses the AI training date 🤣
string result = await completion.Complete([
new OpenAiChatMessage {
content = "You are a helpful assistant that answers generic everyday questions precisely",
role = "system"
},
new OpenAiChatMessage {
content = "My name is Rick and I was born in 1966 in Berlin, Germany.\nHow old am I on " + currentDate,
role = "user"
},
]);
Assert.IsNotNull(result, completion.ErrorMessage);
Console.WriteLine(result);
// continue conversion with the previous in chat history (uses completion.HttpClient.ChatHistory)
result = await completion.Complete("Tell me about my birth city.",
includeHistory: true);
Assert.IsNotNull(result, completion.ErrorMessage);
Console.WriteLine(result);
Console.WriteLine("---\n" +completion.LastRequestJson);
Console.WriteLine("---\n" + completion.LastResponseJson);You can use OpenAI image generation APIs using OpenAi and Azure OpenAi to generate images from prompt text. Images are generated and captured along with revised prompts that you can save.
ImageGeneration works through an ImagePrompt class that acts as input and output for an individual image generation request.
Capturing to a Url
// Load pre-configured connection
// var config = OpenAiConnectionConfiguration.Load();
// var connection = config.ActiveImageConnection;
// Manual Connection
var connection = new OpenAiConnection() {
ApiKey = myApiKey,
ModelId = "dall-e-3",
OperationMode = AiOperationModes.ImageGeneration
};
var generator = new OpenAiImageGeneration(connection);
// Optionally capture raw request data for debugging
generator.AiHttpClient.CaptureRequestData = true;
var imagePrompt = new ImagePrompt()
{
Prompt = "A bear holding on to a snowy mountain peak, waving a beer glass in the air. Poster style, with a black background in goldenrod line art",
ImageSize = "1024x1024",
ImageQuality = "standard",
ImageStyle = "vivid"
};
// Generate and set properties on `imagePrompt` instance
bool result = await generator.Generate(imagePrompt), generator.ErrorMessage);
Assert.IsTrue(result, generator.ErrorMessage);
// prompt returns an array of images, but for Dall-e-3 it's always one
// so FirstImage returns the first image and FirstImageUrl returns the url.
var imageUrl = imagePrompt.FirstImageUrl;
Console.WriteLine(imageUrl);
Console.WriteLine(imagePrompt.RevisedPrompt);
// Display the image as a Url
ShellUtils.GoUrl(imageUrl);
// You can optionally download the image from the captured URL to a local file
// Default folder is %temp%\openai-images\images or specify `ImageFolderPath`
// imagePrompt.ImageFolderPath = "c:\\temp\\openai-images\\";
Assert.IsTrue(await imagePrompt.DownloadImageToFile(), "Image saving failed: " + generator.ErrorMessage);
string imageFile = imagePrompt.ImageFilePath;
Console.WriteLine(imageFile);
Console.WriteLine(JsonSerializationUtils.Serialize(imagePrompt, formatJsonOutput: true));Capture binary image as base64
var config = OpenAiConnectionConfiguration.Load();
var connection = config.ActiveImageConnection;
var generator = new OpenAiImageGeneration(connection);
var imagePrompt = new ImagePrompt()
{
Prompt = "A bear holding on to a snowy mountain peak, waving a beer glass in the air. Poster style, with a black background in goldenrod line art",
ImageSize = "1024x1024",
ImageQuality = "standard",
ImageStyle = "vivid"
};
bool result = await generator.Generate(imagePrompt,
outputFormat: ImageGenerationOutputFormats.Base64);
// Generate and set properties on `imagePrompt` instance
Assert.IsTrue(result, generator.ErrorMessage);
// prompt returns an array of images, but for Dall-e-3 it's always one
// so FirstImage returns the first image.
byte[] bytes = imagePrompt.GetBytesFromBase64();
Assert.IsNotNull(bytes);
string file = await imagePrompt.SaveImageFromBase64();
Assert.IsTrue(File.Exists(file));
// show image in OS viewer
Console.WriteLine("File generated: " + file);
ShellUtils.GoUrl(file);Set BaseImageFiles to combine reference images with written instructions.
Generate automatically uses the image editing API when reference images are supplied;
without them, it continues to use the text-to-image generation API.
Both requests use JSON; reference files are embedded as base64 data URLs in the
editing request's images array.
Use a GPT image model that supports editing, such as gpt-image-1.5.
Reference files can be PNG, JPEG, or WebP.
var generator = new OpenAiImageGeneration(connection);
var imagePrompt = new ImagePrompt
{
Model = connection.ModelId,
Prompt = "Use the first image as the landscape. Place the stylized sun from " +
"the second image in its sky, harmonizing the colors into one cohesive scene.",
BaseImageFiles = new[]
{
Path.GetFullPath(@"Images\ArlingtonBackLoop.png"),
Path.GetFullPath(@"Images\StylizedSun.png")
},
ImageSize = "1024x1024"
};
if (!await generator.Generate(imagePrompt))
throw new InvalidOperationException(generator.ErrorMessage);
string file = imagePrompt.SaveImageFromBase64();This library has a few common operations that you can use for:
- Text Summary
- Translation
- Grammar Checking
There's a custom helper for summarizing input text.
Summarize from string
var completion = new AiTextOperations(connection);
string result = await completion.Summarize(
textToSummarize,
numberOfSentences: 3);
Assert.IsNotNull(result, completion.ErrorMessage);
Console.WriteLine(result);var translator = new AiTextOperations(connection);
translator.AiHttpClient.CaptureRequestData = true;
Console.WriteLine("Using: " + connection.Name);
string result = await translator.TranslateText(
"The sky is below, the ground is above", "en", "de");
Assert.IsNotNull(result, translator.ErrorMessage);
Console.WriteLine(result);var orig = "Long story short one of the use cases that usually made me grab for the Newtonsoft library was dynamic parsing, but I'm glad to see that at some time at least some minimal support for dynamic parsing was added to the `System.Text.Json.JsonSerializer` class";
var checker = new AiTextOperations(connection);
var result = await checker.CheckGrammar(orig);
Assert.IsNotNull(result, checker.ErrorMessage);
Console.WriteLine("Original:\n" + orig);
Console.WriteLine("\nAdjusted:\n");
Console.WriteLine(result);The library uses a single configuration mechanism via two classes:
-
OpenAiConnection / AzureOpenAiConnection / OllamaOpenAiConnection
A specific configuration for an AI connection that contains an endpoint, model Id and Api keys. You can create these individually to configure a connection or use the configuration class that holds multiple connections that can be stored to disk. -
OpenAiConnectionConfiguration
This class can be used as a container for multiple connections that you can easily switch between. There's anActiveConnectionthat is selected based on anActiveConnectionIndexto make it easy to switch between connections and models. The container can also be saved to disk for easy storage.
{
"ActiveConnectionIndex": 0,
"ActiveImageConnectionIndex": 4,
"Connections": [
{
"Name": "OpenAI",
"EncryptedApiKey": "18064FE1...12E@|-|@",
"ApiKeyHeaderName": "Authorization",
"ApiKeyHeaderScheme": "Bearer",
"Endpoint": "https://api.openai.com/v1/",
"EndpointTemplate": "{0}/{1}",
"ModelId": "gpt-3.5-turbo",
"ApiVersion": null,
"ProviderMode": "OpenAi",
"OperationMode": "Completions"
},
{
"Name": "Azure OpenAi",
"EncryptedApiKey": "01BA5CC...442@|-|@",
"Endpoint": "https://rasopenaisample.openai.azure.com",
"EndpointTemplate": "{0}/openai/v1/{1}",
"ModelId": "Gpt35",
"ApiVersion": null,
"ProviderMode": "AzureOpenAi",
"OperationMode": "Completions"
},
{
"Name": "NVidia",
"EncryptedApiKey": "02AC6CD...342@|-|@",
"Endpoint": "https://integrate.api.nvidia.com/v1/",
"EndpointTemplate": "{0}/{1}",
"ModelId": "meta/llama-3.1-405b-instruct",
"ApiVersion": null,
"ProviderMode": "Nvidia",
"OperationMode": "Completions"
},
{
"Name": "Ollama llama3",
"EncryptedApiKey": "",
"Endpoint": "http://127.0.0.1:11434/v1/",
"EndpointTemplate": "{0}/{1}",
"ModelId": "llama3",
"ApiVersion": null,
"ProviderMode": "Ollama",
"OperationMode": "Completions"
},
{
"Name": "Ollama Phi3",
"EncryptedApiKey": "",
"Endpoint": "http://127.0.0.1:11434/v1/",
"EndpointTemplate": "{0}/{1}",
"ModelId": "phi3",
"ApiVersion": null,
"ProviderMode": "Ollama",
"OperationMode": "Completions"
},
{
"Name": "OpenAI Dall-E",
"EncryptedApiKey": "1806416...2ACE@|-|@",
"Endpoint": "https://api.openai.com/v1/",
"EndpointTemplate": "{0}/{1}",
"ModelId": "dall-e-3",
"ApiVersion": null,
"ProviderMode": "OpenAi",
"OperationMode": "ImageGeneration"
},
{
"Name": "Azure OpenAi Dall-E",
"EncryptedApiKey": "01B2C29E...E9EA@|-|@",
"Endpoint": "https://rasopenaisample.openai.azure.com",
"EndpointTemplate": "{0}/openai/v1/{1}",
"ModelId": "ImageGenerations",
"ApiVersion": null,
"ProviderMode": "AzureOpenAi",
"OperationMode": "ImageGeneration"
}
]
}By default API keys are internally encrypted once assigned but you can always access the key via the
conn.ApiKeyproperty. However, then the value is stored or written it's written encrypted.Stored JSON configuration however can accept an unencrypted API key in the
EncryptedApiKeyproperty to allow setting a key there, but the key will be encrypted the next time the configuration is saved.You can disable key encryption at the application level with the static
OpenAiConnectionConfiguration.UseApiKeyEncryption = falseproperty.
The values used depend on whether you're accessing OpenAI or an OpenAI-compatible API or Azure OpenAI. The API key remains encrypted in configuration while ApiKeyHeaderName and ApiKeyHeaderScheme control how it is sent. Most providers use the defaults, Authorization: Bearer <key>. For a provider that requires the raw key in a custom header:
var connection = new OpenAiConnection
{
Endpoint = "https://provider.example/v1/",
ModelId = "provider-image-model",
ApiKey = myApiKey,
ApiKeyHeaderName = "x-goog-api-key",
ApiKeyHeaderScheme = null,
OperationMode = AiOperationModes.ImageGeneration
};This configuration applies to image, voice, and direct HTTP chat requests. Chat connections with custom authentication automatically use the HTTP transport because the OpenAI SDK transport only supports bearer authentication.
For reasoning models you can set the reasoning level per connection with ReasoningEffort. The value is sent as reasoning_effort with each chat request; when it's empty (the default) nothing is sent and the model default applies:
var connection = new OpenAiConnection
{
ModelId = "gpt-5-mini",
ApiKey = myApiKey,
ReasoningEffort = ReasoningEffortLevels.Low // "minimal", "low", "medium", "high", "xhigh"
};The value is stored in the configuration file as "ReasoningEffort": "low". Not every model supports every level - check the provider's model documentation.
To debug a chat request, enable capture on the chat client before calling Complete:
var chat = connection.GetChatClient();
chat.CaptureRequestData = true;
var reply = await chat.Complete("Hello");
Console.WriteLine(chat.LastRequestJson);
Console.WriteLine(chat.LastResponseJson);
Console.WriteLine(chat.ErrorMessage);
Console.WriteLine(chat.LastUsage?.total_tokens); // available even without JSON capture
Console.WriteLine(chat.LastResponseTime); // milliseconds, available even on errorsThis works for both SDK-backed and HTTP fallback chat connections. The request and response JSON are available on the chat client even for HTTP error responses. Capture is disabled by default, and the JSON values are cleared for each call (and are null when disabled). LastUsage is populated from the SDK or HTTP response on successful calls even when JSON capture is off; it exposes prompt_tokens, completion_tokens, total_tokens, and reasoning_tokens (zero if not reported). LastResponseTime is the elapsed milliseconds (double) for the latest attempt, including failures, and does not require JSON capture.
Request/response bodies may contain private prompt or provider data; treat them as sensitive. Direct OpenAiHttpClient requests retain their own diagnostics; for GenericAiChatClient.Complete read LastRequestJson, LastResponseJson, and LastUsage from the chat client.
You can also create the connections directly in code if you prefer.
You can create manual provider connections, but the easiest way to create a new provider connection manually is to use:
var apiKey = "sk-superseekrit";
var connection = OpenAiConnection.Create(AiProviderModes.OpenAi, "Open AI Connection");
connection.ApiKey = apiKey;
Assert.IsTrue(connection.ProviderMode == AiProviderModes.OpenAi,"Incorrect Provider Mode");
Assert.IsTrue(connection.OperationMode == AiOperationModes.Completions,"Incorrect Operation Mode");
Assert.IsTrue(connection.ModelId == "gpt-4.1-nano","Incorrect Model"); // default
// Important - API key is encrypted for storage but returned decrypted from ApiKey
Assert.AreEqual(connection.ApiKey, apiKey,"Incorrect ApiKey");Alternately you can use the name as a string (easier to use from UI):
var connection = OpenAiConnection.Create("OpenAi", "Open AI Connection");The provider modes are:
- OpenAi
- AzureOpenAi
- Ollama
- OllamaCloud
- Nvidia
- XOpenAi
- DeepSeek
- GitHubModels
- OpenRouterAi
- Gemini
- Mistral
- Perplexity
- Other
Anything else defaults to unconfigured OpenAi.
You can of course also use manually create connections by specifying either the default OpenAiConnection provider and setting all properties manually, or by using a specific provider subclass that sets defaults based on the provider.
This is the default connection that is used as the base configuration.
This is the easiest configuration as you only need to set the ApiKey and ModelId and for images specify AiOperationModes.ImageGeneration:
For Completions
var config = new OpenAiConnection() {
ApiKey = myApiKey,
ModelId = "gpt-4"
};For Images
var config = new OpenAiConnection() {
ApiKey = myApiKey,
ModelId = "dall-e-3",
OperationMode = AiOperationModes.ImageGeneration
};Azure uses a different logon mechanism and requires that you set up an Azure site and separate deployments for each of the models you want to use.
You need to specify the Deployment Name as the ModelId - Azure has a fixed model per deployment so the deployment is fixed to a model.
You need to specify the Endpoint which is the Base Url for the Azure Site (without any site relative paths).
And you need an ApiKey to access the API. Api versions are optional when you use the /openai/v1/ endpoint format.
For Completions or Images
var config = new AzureOpenAiConnection() {
ApiKey = myApiKey,
ModelId = "Gtp4oMiniDeployment",
Endpoint = "https://myAzureSite.openai.azure.com",
OperationMode = AiOperationModes.Completions
};You can also use any local LLMs that support OpenAI. If you use the popular Ollama AI Client locally you can host any of its models by running ollama serve after ollama pull <model> the model desired.
Using Ollama you only specify the ModelId which references any of the models that are installed in your local Ollama setup (llama3, phi3.5, mistral etc.)
For Completions
var config = new OllamaOpenAiConnection() {
ModelId = "phi3.5" // "llama3"
};Note that Ollama can easily switch between models with the ModelId, but be aware that switching models is very slow as the model gets first loaded.
You can also connect to most other APIs that are using OpenAI's API. In these scenarios you'll need to provide all the relevant connection information including endpoint, api key and model id.
Here's an example using NVIDIA's OpenAI API:
// nvidia OpenAI
var config = new OpenAiConnection() {
ApiKey = nvidiaApiKey,
ModelId = "meta/llama-3.1-405b-instruct",
Endpoint = "https://integrate.api.nvidia.com/v1/"
};