| Muhammad Waseem

About Newsletter
Books
30 .NET Tips
Sponsorship
Setting Up OpenAI Chat in a .NET API
Nov 2, 2024
2 min read

Setting Up OpenAI Chat in a .NET API

Sponsor this Newsletter

AI is everywhere!

Let’s walk through three simple steps to add it to your Web App or Web API :

Get your API Key

Retrieve your API key from the OpenAI website. Make sure you have already created the account.

Install the Required NuGet Package

Add the OpenAI NuGet package to your .NET API project :

dotnet add package OpenAI

Configure Your Code

Set up your code to initialize and use the OpenAI API, this is the sample code

 public async Task<string> Chat(string query)
 {
     ChatClient client = new(model: "gpt-4o", apiKey: API_KEY);

     ChatCompletion completion = await client.CompleteChatAsync(query);

     string response = completion.Content[0].Text;

     return response;
 }

This code’s purpose is to demonstrate how we can connect the Open AI, we will see in the next sections how we can improve this code.

Available Methods and Properties

ChatClient comes from the OpenAI.Chat and the ChatClient constructor can take:

  • Model and ApiKey

  • Model and ApiKeyCredential

  • Model, ApiKeyCredential and OpenAIClientOptions

It has the following methods:

Task<ClientResult<ChatCompletion>>CompleteChatAsync(
   IEnumerable<ChatMessage> messages, 
   ChatCompletionOptions options = null, 
   CancellationToken cancellationToken = default);
ClientResult<ChatCompletion> CompleteChat(
   IEnumerable<ChatMessage> messages, 
   ChatCompletionOptions options = null, 
   CancellationToken cancellationToken = default);
Task<ClientResult<ChatCompletion>> CompleteChatAsync(
params ChatMessage[] messages);

ClientResult<ChatCompletion> CompleteChat(params ChatMessage[] messages);

Each method has its Async version as well we can use the one according to our need.

There is an additional asynchronous method called CompleteChatStreaming. Unlike CompleteChatAsync, this method streams the completion back token by token as it is generated.

ChatCompletion contains Id, Model, SystemFingerprint, Role, Content , ToolCalls and Usage details.

Listing every detail isn’t feasible, but our response is found within the Content object. This object includes Text, Refusal, and additional properties related to images if the response contains one.

Best Practices

Let’s improve this code :

public async Task<string> Chat(string query)
 {
     ChatClient client = new(model: "gpt-4o", apiKey: API_KEY);

     ChatCompletion completion = await client.CompleteChatAsync(query);

     string response = completion.Content[0].Text;

     return response;
 }
  1. Create an Enum to define the available models rather than passing the model as a string.

  2. Retrieve the API_Key from app settings or a secure vault.

  3. Implement a dedicated service for OpenAI features to ensure reusability.

  4. Provide separate methods for asynchronous and synchronous calls.

  5. Perform NULL checks to validate the query.

  6. Use try-catch blocks to handle exceptions.

  7. Refer to OpenAI’s documentation to display detailed error messages for each error code :

Setting Up OpenAI Chat in a .NET API

Common Errors in Package Configuration

While setting up the library you can get this error :

The model gpt-4o does not exist or you do not have access to it.

To resolve this you must have a five USS balance in your Open API account.

This article was originally published at https://mwaseemzakir.substack.com/ on Nov 2, 2024 .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place
Previous Next

Subscribe to Newsletter

Join 9,000 Software Engineers

Buy Me a Coffee

Enjoy my articles? Support me by buying a coffee!

Buy Me a Coffee

Muhammad Waseem

Resources
  • Books
  • Courses
Newsletter
  • Articles
  • Sponsorship
Books
  • 30 .NET Tips
  • 100 .NET Tips (Soon)
Author
  • About Us
  • Contact Us
Policy
  • Privacy Policy
  • Terms and Conditions
Interview
  • C# & .NET
  • Web API

Join my .NET newsletter and stay updated!

© 2025 Muhammad Waseem. All rights reserved.