How to Integrate OpenAI Models via OpenRouter in C# Using the Microsoft Agent Framework
![]() |
Vivek Jaiswal |
24 |
{{e.like}} |
{{e.dislike}} |
Watch Video Download SourceCode
Introduction
Building intelligent applications has become a core requirement for modern software. However, hardcoding your applications to a single AI provider's endpoint can lead to rigid architectures and vendor lock-in.
Having spent over a decade architecting and building robust .NET applications, I’ve learned that flexibility is just as important as functionality. When building AI agents, you want the ability to hot-swap language models (like moving from GPT-4o to Claude 3.5 or Llama) without rewriting your entire integration layer.
This is where OpenRouter shines. By combining OpenRouter with the new Microsoft Agent Framework, we can create powerful, model-agnostic AI agents in C#. In this tutorial, I'll walk you through a clean, practical implementation of exactly how to achieve this.
Why OpenRouter and Microsoft Agent Framework?
-
Microsoft Agent Framework (
Microsoft.Agents.AI): Provides a standardized, elegant abstraction for defining AI agents, their personas, and their capabilities within the .NET ecosystem. -
OpenRouter: Acts as a unified API gateway. You use the standard OpenAI SDK format, but point it at OpenRouter to instantly unlock access to dozens of different LLMs (OpenAI, Anthropic, Meta, Google, etc.).
Account & Credentials
- OpenRouter Account — Sign up at https://openrouter.ai/
- OpenRouter API Key — Found in your account settings
Step 1: Setting Up the Configuration
First, we need to securely store our OpenRouter API key. Avoid hardcoding credentials directly into your C# files. Instead, add your API key to your appsettings.json file.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"OpenRouter": {
"ApiKey": "YOUR_OPENROUTER_API_KEY_HERE"
}
}
Step 2: Create Your .NET 10 Project
Let's start by creating a new ASP.NET Core Web API project. Open your terminal and execute the following command:
dotnet new webapi -n Agenframework -f net10.0
cd Agenframework
This command creates a new .NET 10 Web API project named "Agenframework".
Step 3: Install Required NuGet Packages
Navigate to your project directory and install the necessary NuGet packages:
dotnet add package OpenAI
dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.Agents.AI
dotnet add package Swashbuckle.AspNetCore
Package Overview
| Package | Purpose |
|---|---|
| OpenAI | Official OpenAI .NET SDK with support for OpenAI-compatible endpoints |
| Microsoft.Extensions.AI | Microsoft's abstraction for AI services |
| Microsoft.Agents.AI | Framework for building AI agents in .NET |
| Swashbuckle.AspNetCore | Swagger/OpenAPI documentation for your API |
Step 4: Create the Chat Controller with OpenRouter Integration
Create a new file called ChatController.cs in the Controllers folder:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.AI;
using Microsoft.Agents.AI;
using OpenAI;
using OpenAI.Chat;
using System.ClientModel;
namespace Agenframework.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ChatController : ControllerBase
{
IConfiguration _configuration;
public ChatController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpPost("Chat")]
public async Task<string> ChatAsync([FromBody] string UserInput)
{
string key = _configuration["OpenRouter:ApiKey"] ?? string.Empty;
IChatClient chatClient =
new ChatClient(
"openai/gpt-4o-mini",
new ApiKeyCredential(key),
new OpenAIClientOptions
{
Endpoint = new Uri("https://openrouter.ai/api/v1/")
})
.AsIChatClient();
AIAgent writer = new ChatClientAgent(
chatClient,
new ChatClientAgentOptions
{
Name = "Writer",
Description = "Write stories that are engaging and creative."
});
var response = await writer.RunAsync(UserInput ?? "Write a short story about a haunted house.");
return response.ToString();
}
}
}
Code Explanation
- Endpoint Configuration: The
https://openrouter.ai/api/v1/endpoint tells the OpenAI client to route requests through OpenRouter instead of OpenAI's direct endpoint. - Model Selection:
"openai/gpt-4o-mini"specifies that we want to use OpenAI's GPT-4o-mini model through OpenRouter. - API Key Management: We're using configuration value instead of hardcoding the key for better security.
- AI Agent: The
ChatClientAgentwraps the chat client with agent capabilities, allowing for more sophisticated interactions.
Step 6: Test Your API
Using Swagger UI
- Run your application:
dotnet run - Navigate to
https://localhost:5001/swagger/index.html - Find the
POST /api/chat/Chatendpoint - Click "Try it out"
- Enter a prompt like:
"Write a funny poem about programming" - Click "Execute"
Popular Model Options
"openai/gpt-4o"— Most capable OpenAI model"openai/gpt-4-turbo"— Faster, more affordable GPT-4"openai/gpt-4o-mini"— Lightweight and cost-effective"anthropic/claude-3-opus"— Anthropic's most capable model"anthropic/claude-3-haiku"— Fast and lightweight Claude model"google/gemini-pro"— Google's Gemini model
FAQ: OpenRouter Integration with .NET 10
Q: What is the difference between using OpenRouter and calling OpenAI directly?
A: OpenRouter provides a unified interface for multiple providers, making it easier to switch models and manage costs. It also offers fallback routing if your preferred model is unavailable.
Q: Can I use different models for different requests?
A: Yes! As shown in the advanced configuration section, you can accept the model name as a parameter in your request.
Q: Is OpenRouter more expensive than calling OpenAI directly?
A: Pricing is typically comparable. OpenRouter sometimes offers better rates due to competitive pricing between providers.
Q: How do I handle rate limiting?
A: Implement rate limiting middleware in your ASP.NET Core application, as shown in the security best practices section.
Q: Can I use OpenRouter in a production environment?
A: Absolutely! OpenRouter is production-ready and used by many organizations. Ensure you follow the security best practices outlined in this guide.
Q: What other AI models can I use besides ChatGPT?
A: OpenRouter supports models from Anthropic (Claude), Google (Gemini), Meta (Llama), and many others. Check https://openrouter.ai/ for the complete list.
Resources
- OpenRouter Documentation
- OpenAI .NET SDK
- Microsoft.Extensions.AI Documentation
- ASP.NET Core Documentation
Final Thoughts
If you have any questions or run into issues, feel free to leave a comment below. I'm here to help!
Happy coding, and enjoy building AI-powered applications!
Comments
|
|
|
| Follow up comments |
| {{e.Name}} {{e.Comments}} |
{{e.days}} | |
|
|
||
|
|
||
| {{r.Name}} {{r.Comments}} |
{{r.days}} | |
|
|
||
