Sprinkling AI Magic into Your .NET Applications: A Practical Guide

M.F.M Fazrin
4 min readJun 22, 2024

--

The world of software development is buzzing with excitement over generative AI. From generating realistic images to crafting human-like text, the possibilities seem endless. But how do you move beyond the hype and integrate this technology into your .NET applications?

This article dives into the practical side of leveraging large language models (LLMs) like ChatGPT within your .NET projects. We’ll explore key concepts like prompt engineering, the OpenAI API, and even delve into advanced techniques like GPT functions and the new Assistants API.

Understanding the Building Blocks

Before we start coding, let’s clarify some terminology:

  • Generative AI: This branch of AI focuses on creating added content (text, images, code, etc.) based on patterns learned from massive datasets.
  • Large Language Models (LLMs): These are deep learning algorithms trained on vast amounts of text data, enabling them to understand and generate human-like language. ChatGPT is a prime example.
  • Prompt Engineering: The art of crafting effective instructions (prompts) to guide AI models towards generating desired outputs.

Starting Simple: The Completions API

OpenAI provides a powerful API to interact with its models. Let’s begin with the Completions API, perfect for basic text generation tasks.

Imagine we’re building a simple chatbot in ASP.NET Core. A user might ask, “What is the weather in Sydney?”. Here’s how we can use the Completions API to get a response:

// Assuming you have an OpenAI API key and a client setup
var client = new OpenAIClient("YOUR_API_KEY");
var completionRequest = new ChatCompletionCreateRequest
{
Messages = new List<ChatMessage>
{
new ChatMessage { Role = "user", Content = "What is the weather in Sydney?" }
},
Model = "gpt-3.5-turbo" // Or your preferred model
};

var completionResponse = await client.ChatCompletion.CreateAsync(completionRequest);
string response = completionResponse.Choices[0].Message.Content;
Console.WriteLine(response);

This code snippet sends a request to the Completions API, prompting it with the user’s question. The API processes the prompt and returns a text response, which we then display.

Maintaining Context: Remembering the Conversation

One limitation of the basic Completions API is that it’s stateless. Each request is treated independently. To build a more engaging chatbot, we need to maintain the context of the conversation.

We can achieve this by storing previous messages in a queue and including them in subsequent API requests:

// ... (previous code)
// In your message handling logic:
var messageHistory = new Queue<ChatMessage>(20); // Store last 20 messages
// ... Add new user messages to messageHistory
// Update the API request:
completionRequest.Messages = messageHistory.ToList();
// ... (rest of the API call and response handling)
// Add the assistant's response to the history
messageHistory.Enqueue(new ChatMessage { Role = "assistant", Content = response });

By sending the entire conversation history with each request, we give the model the context it needs to provide more relevant and coherent responses.

Tapping into Live Data: GPT Functions

What if you want to go beyond general knowledge and integrate your application’s live data with ChatGPT? This is where GPT functions come in.

GPT functions allow you to define custom actions that the model can execute. For instance, you could create a function to fetch real-time weather data from an external API. Let’s illustrate this with a simplified example:

// Define a function to get weather data
[ChatFunction("get_weather", "Get the current weather for a location.")]
public class GetWeatherFunction
{
[ChatFunctionParameter("location", "The city or location to check.")]
public string Location { get; set; }

public async Task<dynamic> InvokeAsync()
{
// Call your weather API to fetch data for the given location
// ...
var weatherData = await GetWeatherFromApiAsync(Location);
// Return the relevant information
return new {
Temperature = weatherData.Temperature,
Condition = weatherData.Condition
};
}
}

Next, we register this function with our OpenAI client and modify our API requests to include function definitions:

// ... (previous code)
// Register the function
client.RegisterFunction(typeof(GetWeatherFunction));
// In your message handling logic:
completionRequest.Functions = client.GetRegisteredFunctions();
// ... (rest of the API call)
// Handle function call responses
if (completionResponse.Choices[0].FinishReason == "function_call")
{
var functionCall = completionResponse.Choices[0].Message.FunctionCall;
var functionArgs = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(functionCall.Arguments);
// Call the appropriate function based on functionCall.Name
// ...
}

Now, when a user asks about the weather, ChatGPT can intelligently decide to invoke our GetWeatherFunction, retrieve live data, and incorporate it into the response.

Building Your Own AI Helpers: The Assistants API

Taking things a step further, OpenAI’s beta Assistants API allows you to create specialized AI assistants tailored for specific domains or tasks within your application.

Imagine you have a complex legal document and want to provide users with an AI-powered way to query its content. Here’s how you can use the Assistants API:

  1. Upload Your Data: Upload the legal document to your OpenAI account.
  2. Create an Assistant: Define an assistant and associate it with the uploaded document.
  3. Interact via Threads: Create a thread for the conversation and start sending user queries as messages.
  4. Run and Retrieve Responses: Run the assistant on the thread, periodically polling for responses.

The key advantage here is that the assistant retains context across the entire thread, eliminating the need to manually manage message history. Moreover, it can provide grounded references within the uploaded document, citing specific sections to support its answers.

Conclusion

Integrating generative AI into your .NET applications is no longer a futuristic concept. The OpenAI API provides the tools, and with a sprinkle of creativity and the techniques outlined in this article, you can build truly intelligent and engaging user experiences.

From simple chatbots to sophisticated AI assistants, the possibilities are vast. Experiment, explore, and let your imagination run wild as you unlock the power of AI in your .NET projects!

--

--

M.F.M Fazrin

Senior Software Development Specialist @ Primary Health Care Corporation (Qatar)