Why C# and AI Are the Perfect Pair?
\n\nWhen we talk about artificial intelligence and development, Python usually comes to mind. That's logical: TensorFlow, PyTorch, transformers... But what if your stack is C#, .NET, and you don't want to change your familiar toolkit? The good news: C# and neural networks combine perfectly, especially when it comes to using ready-made models via an API.
\n\nChatGPT is not just a trendy toy. It's a powerful tool that can generate code, write documentation, analyze data, and even help with debugging. In this article, we'll break down how to connect ChatGPT to a C# project, write real code, and see what opportunities open up for .NET developers.
\n\nWhat You Need to Know Before Starting?
\n\nTo work with the OpenAI API in C#, you will need:
\n\n- \n
- An account on platform.openai.com (an API key is required) \n
- Visual Studio 2022 or JetBrains Rider \n
- .NET 6.0 or higher (.NET 8 is recommended) \n
- The
OpenAIlibrary (NuGet package) \n
Don't be scared: the whole process will take no more than 15 minutes. Let's go step-by-step through creating a console application that will communicate with ChatGPT.
\n\nStep 1. Create the Project and Install the Library
\n\nOpen your terminal or Package Manager Console and run the command:
\n\ndotnet new console -n ChatGPTDemo\ncd ChatGPTDemo\ndotnet add package OpenAI --version 1.11.0\n\n\nThe OpenAI package for C# is an official client that supports all the latest models, including GPT-4 and GPT-4 Turbo. It's actively developed, so it's best to use the latest version.
\n\nSetting Up the API Key
\n\nNever store keys in your code. Use environment variables or a configuration file. For this example, let's create appsettings.json:
{\n "OpenAiApiKey": "your_super_secret_key"\n}\n\n\nAdd the NuGet package Microsoft.Extensions.Configuration.Json to the project and load the key like this:
var config = new ConfigurationBuilder()\n .AddJsonFile("appsettings.json")\n .Build();\n\nstring apiKey = config["OpenAiApiKey"];\n\n\nNow we are ready for the most interesting part.
\n\nStep 2. First Request to ChatGPT in C#
\n\nLet's write a simple method that sends a message to the model and gets a response. Here is the full code:
\n\nusing OpenAI;\nusing OpenAI.Chat;\n\nvar client = new OpenAIClient(apiKey); // apiKey from config\n\nvar chatClient = client.GetChatClient("gpt-4o-mini");\n\nvar messages = new List<ChatMessage>\n{\n new SystemChatMessage("You are a helpful assistant who responds in Russian."),\n new UserChatMessage("Write an example of C# code for reading a JSON file.")\n};\n\nvar response = await chatClient.CompleteChatAsync(messages);\nvar reply = response.Value.Content[0].Text;\n\nConsole.WriteLine(reply);\n\n\nWhat's happening here? We create a client, specify the gpt-4o-mini model (fast and cheap), set a system prompt (the assistant's role), and send the user's request. The response comes back as structured text.
\n\nThis is the basics. From here, you can make it more complex: add conversation history, handle errors, make asynchronous calls.
\n\nStep 3. Creating a Smart Assistant for Working with Code
\n\nOne of the most useful functions of ChatGPT in C# development is code review and documentation generation. Let's create a class that will analyze our code and suggest improvements.
\n\npublic class CodeReviewer\n{\n private readonly ChatClient _chatClient;\n\n public CodeReviewer(string apiKey)\n {\n var client = new OpenAIClient(apiKey);\n _chatClient = client.GetChatClient("gpt-4o-mini");\n }\n\n public async Task<string> ReviewCodeAsync(string code)\n {\n