### Installing OpenRouter.NET SDK via dotnet CLI
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/getting-started.md
This snippet shows how to install the OpenRouter.NET SDK using the .NET command-line interface. It adds the OpenRouter.NET NuGet package reference to the project file, enabling SDK usage.
```bash
dotnet add package OpenRouter.NET
```
--------------------------------
### Installing OpenRouter.NET SDK via Package Manager Console
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/getting-started.md
This snippet demonstrates how to install the OpenRouter.NET SDK using the NuGet Package Manager Console. It adds the OpenRouter.NET package to the current project, making its functionalities available for use.
```powershell
Install-Package OpenRouter.NET
```
--------------------------------
### Configuring OpenRouter.NET SDK in appsettings.json
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/getting-started.md
This JSON snippet provides an example of how to configure OpenRouter.NET SDK settings within an appsettings.json file. It includes properties for the API key, base URL, HTTP referer, and X-Title, which are automatically loaded by the .NET configuration system.
```json
{
"OpenRouter": {
"ApiKey": "your_openrouter_api_key_here",
"BaseUrl": "https://openrouter.ai/api/v1",
"HttpReferer": "https://your-site-or-app.com",
"XTitle": "Your App Name"
}
}
```
--------------------------------
### Programmatic Configuration of OpenRouter.NET SDK in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/getting-started.md
This C# snippet illustrates how to configure the OpenRouter.NET SDK options directly in code when adding services to the Dependency Injection container. It allows for setting the API key, HTTP referer, and X-Title programmatically.
```csharp
services.AddOpenRouter(options =>
{
options.ApiKey = "your_openrouter_api_key_here";
options.HttpReferer = "https://your-site-or-app.com";
options.XTitle = "Your App Name";
// options.BaseUrl = "https://custom.openrouter.proxy/api/v1"; // If needed
});
```
--------------------------------
### Adding OpenRouter.NET SDK PackageReference to .csproj
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/getting-started.md
This XML snippet illustrates how to manually add a PackageReference for the OpenRouter.NET SDK directly into a .NET project's .csproj file. This method requires specifying the package name and version.
```xml
```
--------------------------------
### Configuring OpenRouter.NET with Options Action in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/advanced/dependency-injection.md
This C# example demonstrates how to set up the OpenRouter.NET SDK using `AddOpenRouter()` with an options action. It shows how to retrieve the API key from environment variables or configuration, and how to programmatically set various `OpenRouterOptions` like `ApiKey`, `HttpReferer`, `XTitle`, and `DefaultHeaders`. It also includes a placeholder for registering application services.
```C#
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OpenRouter.Extensions; // Crucial using directive
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
// Retrieve API Key from environment or configuration
var apiKey = Environment.GetEnvironmentVariable("OPENROUTER_API_KEY") ??
hostContext.Configuration["OpenRouter:ApiKey"];
services.AddOpenRouter(options =>
{
options.ApiKey = apiKey;
options.HttpReferer = hostContext.Configuration["OpenRouter:HttpReferer"] ?? "https://myapp.com/docs";
options.XTitle = hostContext.Configuration["OpenRouter:XTitle"] ?? "My Application";
options.DefaultHeaders["User-Agent"] = "MyApp/1.0 (via OpenRouter.NET)";
// Configure retry policy if needed
// options.RetryPolicyOptions.MaxRetries = 5;
});
// Register your application services that depend on IOpenRouterClient or its services
services.AddTransient();
});
}
```
--------------------------------
### Registering OpenRouterClient with Dependency Injection in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/getting-started.md
This C# snippet demonstrates how to register the OpenRouter.NET SDK services, specifically OpenRouterClient, with the .NET Core Dependency Injection container. It shows how to configure options using IConfiguration from appsettings.json and how to set default headers.
```csharp
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OpenRouter.Extensions; // Add this using directive
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
// ... other services
// Add OpenRouter services
services.AddOpenRouter(options =>
{
// API Key can be sourced from IConfiguration
options.ApiKey = hostContext.Configuration["OpenRouter:ApiKey"];
// Or directly if not using IConfiguration for the key
// options.ApiKey = Environment.GetEnvironmentVariable("OPENROUTER_API_KEY") ?? "your_fallback_key";
options.BaseUrl = hostContext.Configuration["OpenRouter:BaseUrl"];
options.HttpReferer = hostContext.Configuration["OpenRouter:HttpReferer"];
options.XTitle = hostContext.Configuration["OpenRouter:XTitle"];
// You can also set default headers
var userAgent = hostContext.Configuration["OpenRouter:UserAgent"] ?? "MyApp/1.0.0";
options.DefaultHeaders["User-Agent"] = userAgent;
});
// Or more simply by binding from configuration
// services.AddOpenRouter(hostContext.Configuration.GetSection("OpenRouter"));
// ... other services
});
```
--------------------------------
### Sending Simple Chat Message with OpenRouter Client (C#)
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/getting-started.md
This C# class demonstrates how to inject and use `IOpenRouterClient` and `IChatService` to send a basic chat completion request. It constructs a `ChatCompletionRequest` with a user message, calls `CreateChatCompletionAsync`, and logs the response or any errors encountered during the process.
```C#
using OpenRouter.Core;
using OpenRouter.Services.Chat;
using OpenRouter.Models.Requests;
using OpenRouter.Models.Common;
public class MyService
{
private readonly IOpenRouterClient _openRouterClient;
private readonly IChatService _chatService;
private readonly ILogger _logger;
public MyService(IOpenRouterClient openRouterClient, IChatService chatService, ILogger logger)
{
_openRouterClient = openRouterClient;
_chatService = chatService;
_logger = logger;
}
public async Task SendSimpleChatMessageAsync()
{
_logger.LogInformation("Attempting to send a chat message...");
try
{
var request = new ChatCompletionRequest
{
Model = "openai/gpt-3.5-turbo", // Choose a model
Messages = new List
{
new Message { Role = "user", Content = "Hello, OpenRouter!" }
}
};
var response = await _chatService.CreateChatCompletionAsync(request);
if (response.Choices != null && response.Choices.Any())
{
_logger.LogInformation("Received response: {Content}", response.Choices.First().Message?.Content);
}
else
{
_logger.LogWarning("No choices returned in the response.");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending chat message");
}
}
}
```
--------------------------------
### Binding OpenRouter.NET Options from IConfiguration in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/advanced/dependency-injection.md
This C# snippet shows a concise way to configure the OpenRouter.NET SDK by directly binding an `IConfiguration` section (e.g., "OpenRouter") to `OpenRouterOptions` using an `AddOpenRouter()` overload. This method simplifies setup when all options are defined in a configuration file like `appsettings.json`.
```C#
services.AddOpenRouter(hostContext.Configuration.GetSection("OpenRouter"));
```
--------------------------------
### Retrieving OpenRouter API Key from Environment Variable in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/getting-started.md
This C# snippet demonstrates how to retrieve the OpenRouter API key from an environment variable (specifically OPENROUTER_API_KEY) or fall back to a configuration value. It shows how to then use this key when configuring the OpenRouter.NET SDK services.
```csharp
var apiKey = context.Configuration["OpenRouter:ApiKey"] ??
Environment.GetEnvironmentVariable("OPENROUTER_API_KEY");
services.AddOpenRouter(options =>
{
options.ApiKey = apiKey;
// ... other options
});
```
--------------------------------
### Injecting and Using OpenRouter.NET Services in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/advanced/dependency-injection.md
This C# example demonstrates how to inject `IOpenRouterClient` and `IChatService` into an application service's constructor using Dependency Injection. It shows how to then use these injected services to fetch models and create chat completions, leveraging the SDK's functionality within a structured application.
```csharp
using OpenRouter.Core;
using OpenRouter.Services.Chat;
using Microsoft.Extensions.Logging;
public class MyApplicationService
{
private readonly IOpenRouterClient _openRouterClient;
private readonly IChatService _chatService; // Can inject specific service too
private readonly ILogger _logger;
public MyApplicationService(
IOpenRouterClient openRouterClient,
IChatService chatService,
ILogger logger)
{
_openRouterClient = openRouterClient;
_chatService = chatService;
_logger = logger;
}
public async Task DoSomethingWithOpenRouter()
{
_logger.LogInformation("Fetching models using IOpenRouterClient...");
var modelsResponse = await _openRouterClient.Models.GetModelsAsync();
// ... process models
_logger.LogInformation("Sending chat message using IChatService...");
var chatRequest = new OpenRouter.Models.Requests.ChatCompletionRequest { /* ... */ };
var chatResponse = await _chatService.CreateChatCompletionAsync(chatRequest);
// ... process chat response
}
}
```
--------------------------------
### Configuring OpenRouterOptions from IConfiguration in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/core-concepts/client-and-options.md
This C# example demonstrates how to configure `OpenRouterOptions` by binding them to an `IConfiguration` section, typically from `appsettings.json`. This approach allows for externalized and environment-specific configuration of the OpenRouter client.
```C#
// Assuming "OpenRouter" section in appsettings.json
services.AddOpenRouter(hostContext.Configuration.GetSection("OpenRouter"));
```
--------------------------------
### OpenRouter Configuration in appsettings.json
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/advanced/dependency-injection.md
This JSON snippet illustrates the structure for configuring `OpenRouterOptions` within an `appsettings.json` file. It defines properties such as `ApiKey`, `BaseUrl`, `HttpReferer`, `XTitle`, and `DefaultHeaders`, which can then be bound to the `OpenRouterOptions` class using `IConfiguration`.
```JSON
{
"OpenRouter": {
"ApiKey": "your_api_key_here",
"BaseUrl": "https://openrouter.ai/api/v1",
"HttpReferer": "https://myotherapp.com",
"XTitle": "My Other App",
"DefaultHeaders": {
"User-Agent": "MyOtherApp/2.0"
}
// RetryPolicyOptions can also be configured here if the JSON structure matches
}
}
```
--------------------------------
### Accessing Services with IOpenRouterClient in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/core-concepts/client-and-options.md
This C# example demonstrates how to access various OpenRouter API services (like Chat and Models) through an `IOpenRouterClient` instance, typically obtained via Dependency Injection. It shows how to retrieve specific service interfaces to make API requests.
```C#
using OpenRouter.Core;
using OpenRouter.Services.Chat;
using OpenRouter.Services.Models;
public class ExampleService
{
private readonly IOpenRouterClient _client;
public ExampleService(IOpenRouterClient client)
{
_client = client;
}
public async Task UseServicesAsync()
{
// Access the Chat service
IChatService chatService = _client.Chat;
// Use chatService to make chat completion requests...
// Access the Models service
IModelsService modelsService = _client.Models;
// Use modelsService to list models, get details, etc...
}
}
```
--------------------------------
### Performing Basic Chat Completion with OpenRouter.NET SDK in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/features/chat-completions.md
This example demonstrates how to perform a basic, blocking chat completion using the OpenRouter.NET SDK. It initializes a `ChatCompletionRequest` with a specified model and a list of messages (system and user roles), then calls `CreateChatCompletionAsync` to get the model's response. It logs the response content, finish reason, and token usage, handling potential errors.
```csharp
using OpenRouter.Services.Chat;
using OpenRouter.Models.Requests;
using OpenRouter.Models.Common;
using Microsoft.Extensions.Logging; // For ILogger
public class ChatExample
{
private readonly IChatService _chatService;
private readonly ILogger _logger;
public ChatExample(IChatService chatService, ILogger logger)
{
_chatService = chatService;
_logger = logger;
}
public async Task RunBasicChatAsync()
{
_logger.LogInformation("--- Basic Chat Example ---");
var request = new ChatCompletionRequest
{
Model = "openai/gpt-3.5-turbo", // Or any preferred model
Messages = new List
{
new Message { Role = "system", Content = "You are a helpful assistant." },
new Message { Role = "user", Content = "What is the weather like in London today?" }
},
MaxTokens = 150
};
try
{
var response = await _chatService.CreateChatCompletionAsync(request);
var firstChoice = response.Choices?.FirstOrDefault();
if (firstChoice != null)
{
_logger.LogInformation("Model Response: {Content}", firstChoice.Message?.Content);
_logger.LogInformation("Finish Reason: {Reason}", firstChoice.FinishReason);
}
else
{
_logger.LogWarning("No response choices received.");
}
LogUsage(response.Usage);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during basic chat completion");
}
}
private void LogUsage(Usage? usage)
{
if (usage != null)
{
_logger.LogInformation("Usage: Prompt Tokens={Prompt}, Completion Tokens={Completion}, Total Tokens={Total}",
usage.PromptTokens, usage.CompletionTokens, usage.TotalTokens);
}
}
}
```
--------------------------------
### Listing Available Models using OpenRouter.NET SDK in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/features/model-management.md
This C# example demonstrates how to use the `IModelsService` from the OpenRouter.NET SDK to asynchronously fetch a list of available AI models from the OpenRouter API. It iterates through the retrieved models, logging their ID, Name, and ContextLength, and includes robust error handling for API calls. The `IModelsService` and `ILogger` are injected via the constructor.
```C#
using OpenRouter.Services.Models;
using OpenRouter.Models.Responses; // For ModelResponse and nested Model class
using Microsoft.Extensions.Logging;
using System.Linq;
public class ModelManagementExample
{
private readonly IModelsService _modelsService;
private readonly ILogger _logger;
public ModelManagementExample(IModelsService modelsService, ILogger logger)
{
_modelsService = modelsService;
_logger = logger;
}
public async Task RunListModelsAsync()
{
_logger.LogInformation("--- List Models Example ---");
try
{
var modelsResponse = await _modelsService.GetModelsAsync(); // This returns ModelsResponse
if (modelsResponse?.Data != null && modelsResponse.Data.Any())
{
_logger.LogInformation("Found {Count} models:", modelsResponse.Data.Count);
foreach (var model in modelsResponse.Data.Take(10)) // Displaying first 10 for brevity
{
_logger.LogInformation("ID: {Id}, Name: {Name}, Context: {ContextLength} tokens",
model.Id, model.Name, model.ContextLength);
}
if (modelsResponse.Data.Count > 10)
{
_logger.LogInformation("...and {MoreCount} more models.", modelsResponse.Data.Count - 10);
}
}
else
{
_logger.LogWarning("No models found or error fetching models.");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error listing models");
}
}
}
```
--------------------------------
### Streaming Chat Completions with OpenRouter.NET C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/features/chat-completions.md
This example demonstrates how to receive chat completion responses in real-time chunks using `StreamChatCompletionAsync`. It shows how to handle each incoming `ChatCompletionChunk` to progressively display content and capture the full response, including usage information from the final chunk.
```C#
public async Task RunStreamingChatAsync()
{
_logger.LogInformation("--- Streaming Chat Example ---");
var request = new ChatCompletionRequest
{
Model = "mistralai/mistral-7b-instruct",
Messages = new List
{
new Message { Role = "user", Content = "Write a short poem about AI." }
},
MaxTokens = 100,
// Stream property defaults to true when using StreamChatCompletionAsync internally
};
var fullResponse = new System.Text.StringBuilder();
_logger.LogInformation("Streaming Response:");
try
{
await _chatService.StreamChatCompletionAsync(request, chunk =>
{
var content = chunk.Choices?.FirstOrDefault()?.Delta?.Content;
if (!string.IsNullOrEmpty(content))
{
Console.Write(content); // Write directly to console for immediate display
fullResponse.Append(content);
}
if (chunk.Choices?.FirstOrDefault()?.FinishReason != null)
{
_logger.LogInformation("\nStream finished. Finish Reason: {Reason}", chunk.Choices.First().FinishReason);
LogUsage(chunk.Usage); // Usage info usually comes with the last chunk
}
});
_logger.LogInformation("\n--- End of Stream ---");
_logger.LogInformation("Full assembled response: {FullResponse}", fullResponse.ToString());
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during streaming chat completion");
}
}
```
--------------------------------
### Managing Conversation History with OpenRouter.NET C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/features/chat-completions.md
This example illustrates how to maintain conversation context by passing a `List` as `Messages` in subsequent `ChatCompletionRequest` objects. It shows how to append both user input and assistant responses to the history to enable multi-turn conversations.
```C#
public async Task RunConversationAsync()
{
_logger.LogInformation("--- Conversation Example ---");
var conversationHistory = new List
{
new Message { Role = "system", Content = "You are a witty and slightly sarcastic assistant." }
};
await ProcessUserMessage("Hello there!", conversationHistory);
await ProcessUserMessage("What's your name?", conversationHistory);
await ProcessUserMessage("Can you tell me a fun fact?", conversationHistory);
}
private async Task ProcessUserMessage(string userInput, List history)
{
_logger.LogInformation("User: {Input}", userInput);
history.Add(new Message { Role = "user", Content = userInput });
var request = new ChatCompletionRequest
{
Model = "nousresearch/nous-hermes-2-mixtral-8x7b-dpo",
Messages = history, // Pass the updated history
MaxTokens = 150
};
try
{
var response = await _chatService.CreateChatCompletionAsync(request);
var assistantResponse = response.Choices?.FirstOrDefault()?.Message;
if (assistantResponse != null)
{
_logger.LogInformation("Assistant: {Content}", assistantResponse.Content);
history.Add(assistantResponse); // Add assistant's response to history
LogUsage(response.Usage);
}
else
{
_logger.LogWarning("No response from assistant.");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during conversation turn");
}
}
```
--------------------------------
### Client-Side Filtering of OpenRouter Models by Context Length (C#)
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/features/model-management.md
This C# example illustrates how to fetch all OpenRouter models and then apply client-side filtering to identify models that meet a minimum context length requirement. It sorts the filtered models by ID and logs their ID, name, and context length, demonstrating a common pattern for refining large datasets locally when server-side filtering is limited.
```C#
public async Task RunFilterModelsAsync(int minContextLength = 16000)
{
_logger.LogInformation("--- Filter Models Example (Min Context: {Length}) ---", minContextLength);
try
{
var modelsResponse = await _modelsService.GetModelsAsync();
var filteredModels = modelsResponse?.Data?
.Where(m => m.ContextLength >= minContextLength)
.OrderBy(m => m.Id)
.ToList();
if (filteredModels != null && filteredModels.Any())
{
_logger.LogInformation("Found {Count} models with at least {Length} tokens context window:",
filteredModels.Count, minContextLength);
foreach (var model in filteredModels)
{
_logger.LogInformation(" ID: {Id}, Name: {Name}, Context: {ContextLength}",
model.Id, model.Name, model.ContextLength);
}
}
else
{
_logger.LogWarning("No models found matching the criteria.");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error filtering models");
}
}
```
--------------------------------
### Binding OpenRouter Configuration from appsettings.json in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/features/authentication.md
This C# snippet illustrates how to bind the `OpenRouter` section from `appsettings.json` to the OpenRouter services during dependency injection. It uses `hostContext.Configuration.GetSection("OpenRouter")` to automatically map configuration values to `OpenRouterOptions`. An alternative manual mapping example is also provided for specific property assignment.
```C#
services.AddOpenRouter(hostContext.Configuration.GetSection("OpenRouter"));
// or manually map properties:
// services.AddOpenRouter(options =>
// {
// options.ApiKey = hostContext.Configuration["OpenRouter:ApiKey"];
// });
```
--------------------------------
### Retrieving Specific OpenRouter Model Details (C#)
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/features/model-management.md
This C# example demonstrates how to retrieve a list of all available OpenRouter models and then filter that list client-side to find details for a specific model by its ID. It logs various properties of the found model, such as name, description, context length, and pricing. This approach is used when a direct API endpoint for single model retrieval is not available or preferred.
```C#
public async Task RunModelDetailsAsync(string modelIdToFind = "openai/gpt-3.5-turbo")
{
_logger.LogInformation("--- Model Details Example for {ModelId} ---", modelIdToFind);
try
{
var modelsResponse = await _modelsService.GetModelsAsync();
var model = modelsResponse?.Data?.FirstOrDefault(m => m.Id == modelIdToFind);
if (model != null)
{
_logger.LogInformation("Details for Model ID: {Id}", model.Id);
_logger.LogInformation(" Name: {Name}", model.Name);
_logger.LogInformation(" Description: {Description}", model.Description);
_logger.LogInformation(" Context Length: {ContextLength} tokens", model.ContextLength);
_logger.LogInformation(" Pricing (Prompt): ${PromptPrice}/1M tokens", model.Pricing?.Prompt);
_logger.LogInformation(" Pricing (Completion): ${CompletionPrice}/1M tokens", model.Pricing?.Completion);
// Add more properties as needed, e.g., model.Architecture?.Tokenizer
}
else
{
_logger.LogWarning("Model with ID '{ModelId}' not found.", modelIdToFind);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting model details for {ModelId}", modelIdToFind);
}
}
```
--------------------------------
### Handling OpenRouter API Exceptions in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/features/error-handling.md
This C# example demonstrates how to catch and process `OpenRouterApiException` instances, extracting detailed error information such as status code, error type, message, and specific parameters. It also includes a `switch` statement for handling common HTTP status codes like 401 (Unauthorized), 429 (Too Many Requests), and 400 (Bad Request), along with general `HttpRequestException` and `OpenRouterSerializationException` handling.
```C#
using OpenRouter.Services.Chat;
using OpenRouter.Models.Requests;
using OpenRouter.Exceptions;
using Microsoft.Extensions.Logging;
using System.Net;
public class ErrorHandlingExample
{
private readonly IChatService _chatService;
private readonly ILogger _logger;
public ErrorHandlingExample(IChatService chatService, ILogger logger)
{
_chatService = chatService;
_logger = logger;
}
public async Task AttemptInvalidRequestAsync()
{
_logger.LogInformation("--- Error Handling Example ---");
var request = new ChatCompletionRequest
{
Model = "non_existent_model/fake-model-id", // Intentionally invalid model
Messages = new List
{ new OpenRouter.Models.Common.Message { Role = "user", Content = "Hello" } }
};
try
{
var response = await _chatService.CreateChatCompletionAsync(request);
_logger.LogInformation("Request succeeded (unexpectedly).");
}
catch (OpenRouterApiException apiEx)
{
_logger.LogError(apiEx, "OpenRouter API Error occurred.");
_logger.LogError("Status Code: {StatusCode}", apiEx.StatusCode);
_logger.LogError("Raw Content: {Content}", apiEx.Content);
if (apiEx.ErrorResponse?.Error != null)
{
_logger.LogError("API Error Type: {Type}", apiEx.ErrorResponse.Error.Type);
_logger.LogError("API Error Message: {Message}", apiEx.ErrorResponse.Error.Message);
if (!string.IsNullOrEmpty(apiEx.ErrorResponse.Error.Code))
{
_logger.LogError("API Error Code: {Code}", apiEx.ErrorResponse.Error.Code);
}
}
// Specific handling based on status code
switch (apiEx.StatusCode)
{
case HttpStatusCode.Unauthorized: // 401
_logger.LogError("Authentication failed. Check your API key.");
break;
case HttpStatusCode.TooManyRequests: // 429
_logger.LogError("Rate limit exceeded. Check response headers for retry information.");
// Example: apiEx.Headers?.RetryAfter?.Delta
break;
case HttpStatusCode.BadRequest: // 400
_logger.LogError("Bad request. Likely an issue with request parameters. Param: {Param}", apiEx.ErrorResponse?.Error?.Param);
break;
// Add more cases as needed
default:
_logger.LogError("Unhandled API error.");
break;
}
}
catch (HttpRequestException httpEx)
{
// Network issues, DNS problems, etc.
_logger.LogError(httpEx, "HTTP Request Error (network level)");
}
catch (OpenRouterSerializationException serializationEx)
{
// Errors during JSON serialization/deserialization
_logger.LogError(serializationEx, "Serialization/Deserialization Error");
_logger.LogError("Raw Content that failed to deserialize: {Content}", serializationEx.Content);
}
catch (Exception ex)
{
// Other unexpected errors
_logger.LogError(ex, "An unexpected error occurred.");
}
}
}
```
--------------------------------
### Using OpenRouter Client Services in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/core-concepts/services.md
This snippet demonstrates how to initialize and use the OpenRouter client to interact with different services. It shows accessing the Models service to list available models and the Chat service to create a chat completion, illustrating the typical workflow for API interactions.
```C#
public class MyLogic
{
private readonly IOpenRouterClient _openRouterClient;
public MyLogic(IOpenRouterClient openRouterClient)
{
_openRouterClient = openRouterClient;
}
public async Task ListModelsAndChat()
{
// Using the Models service
var modelsResponse = await _openRouterClient.Models.GetModelsAsync();
if (modelsResponse?.Data != null)
{
foreach (var model in modelsResponse.Data)
{
Console.WriteLine($"Model ID: {model.Id}, Name: {model.Name}");
}
}
// Using the Chat service
var chatRequest = new OpenRouter.Models.Requests.ChatCompletionRequest
{
Model = "openai/gpt-3.5-turbo",
Messages = new List
{
new OpenRouter.Models.Common.Message { Role = "user", Content = "Tell me a joke." }
}
};
var chatResponse = await _openRouterClient.Chat.CreateChatCompletionAsync(chatRequest);
Console.WriteLine($"Joke: {chatResponse.Choices?.FirstOrDefault()?.Message?.Content}");
}
}
```
--------------------------------
### Configuring OpenRouterOptions with AddOpenRouter in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/core-concepts/client-and-options.md
This C# snippet illustrates how to configure `OpenRouterOptions` when registering OpenRouter services using `services.AddOpenRouter`. It shows setting essential properties like `ApiKey`, `HttpReferer`, `XTitle`, and `DefaultHeaders` directly within the configuration lambda.
```C#
services.AddOpenRouter(options =>
{
options.ApiKey = "your_api_key";
options.HttpReferer = "https://my-app.com";
options.XTitle = "My App";
options.DefaultHeaders["User-Agent"] = "MyApp/1.0.0";
});
```
--------------------------------
### Building Chat Completion Requests with ChatRequestBuilder in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/features/chat-completions.md
This snippet demonstrates the use of the fluent `IChatRequestBuilder` to construct `ChatCompletionRequest` objects. It provides a more readable and structured way to set model, messages (system and user), max tokens, and temperature, simplifying request creation.
```C#
var request = _chatService.CreateChatCompletionRequestBuilder()
.WithModel("openai/gpt-4o")
.AddSystemMessage("You are a travel planner.")
.AddUserMessage("Suggest a 3-day itinerary for Paris.")
.WithMaxTokens(500)
.WithTemperature(0.7)
// .WithTools(myToolsList) // If using tools
.Build();
// var response = await _chatService.CreateChatCompletionAsync(request);
```
--------------------------------
### Validating OpenRouter API Key Configuration in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/features/authentication.md
This C# method, `ValidateConfiguration`, is designed to be called during application startup to ensure the OpenRouter API key is properly configured. It retrieves the `IOpenRouterClient` from the `IServiceProvider` and checks if `client.Options.ApiKey` is not null, empty, or the default placeholder value. This helps in catching configuration errors early in the application lifecycle.
```C#
// Simplified from Program.cs
private static bool ValidateConfiguration(IServiceProvider serviceProvider)
{
var client = serviceProvider.GetRequiredService();
var apiKey = client.Options.ApiKey;
if (string.IsNullOrWhiteSpace(apiKey) || apiKey == "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") // Example placeholder
{
// Log error, guide user
return false;
}
return true;
}
```
--------------------------------
### Creating Chat Completions with OpenRouter C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/core-concepts/services.md
The `ChatService` handles all chat completion interactions, supporting both standard and streaming responses. It allows sending messages to a model and receiving its response, and provides a fluent API for constructing chat completion requests.
```C#
CreateChatCompletionAsync(ChatCompletionRequest request, CancellationToken cancellationToken = default)
```
```C#
StreamChatCompletionAsync(ChatCompletionRequest request, Action chunkHandler, CancellationToken cancellationToken = default)
```
```C#
CreateChatCompletionRequestBuilder()
```
--------------------------------
### Integrating Custom DelegatingHandler and HttpClient Configuration in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/advanced/http-client.md
This C# code demonstrates how to integrate a custom `LoggingDelegatingHandler` and configure the `HttpClient` within the `ConfigureServices` method of a .NET application. It registers the handler with dependency injection, configures OpenRouter options, sets a custom HttpClient timeout, adds the logging handler to the pipeline, and shows how to configure the primary HttpMessageHandler for advanced settings like proxies.
```C#
// At the top of your file or within your namespace
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; // For ILogger
// ... other usings for OpenRouter types
// In your ConfigureServices method:
services.AddTransient(); // Register your handler with DI
services.AddOpenRouter(options =>
{
// Configure OpenRouterOptions as usual
options.ApiKey = Environment.GetEnvironmentVariable("OPENROUTER_API_KEY") ?? "your_fallback_api_key";
options.HttpReferer = "https://yourapp.com/example";
options.XTitle = "MyApplication";
options.DefaultHeaders["User-Agent"] = "MyApplication/1.0 OpenRouter.NET";
})
.ConfigureHttpClient((serviceProvider, client) => // Access IServiceProvider for more complex setups
{
// Direct HttpClient configuration (e.g., Timeout)
// This client is the one configured for OpenRouter by AddOpenRouter
client.Timeout = TimeSpan.FromSeconds(100); // Default is often 100s, adjust as needed
})
.AddHttpMessageHandler() // Add your custom handler to the pipeline
// You can chain other IHttpClientBuilder methods:
// .SetHandlerLifetime(TimeSpan.FromMinutes(5)); // Example: Configure handler lifetime
.ConfigurePrimaryHttpMessageHandler(serviceProvider => // Configure the innermost handler
{
// Example: Customizing HttpClientHandler settings
return new HttpClientHandler
{
AllowAutoRedirect = false,
UseProxy = true,
Proxy = new System.Net.WebProxy("http://localhost:8888") // Example proxy
// AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate
};
});
```
--------------------------------
### Configuring OpenRouter API Key in C# ConfigureServices
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/features/authentication.md
This C# snippet demonstrates how to configure the OpenRouter API key directly within the `ConfigureServices` method (e.g., in `Program.cs` or `Startup.cs`) using the `AddOpenRouter` extension method. It sets the `ApiKey` property of `OpenRouterOptions` to the provided API key string. This is a common way to set up services in ASP.NET Core applications.
```C#
services.AddOpenRouter(options =>
{
options.ApiKey = "sk-or-v1-your_actual_openrouter_api_key";
// ... other options
});
```
--------------------------------
### Building a ChatCompletionRequest in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/core-concepts/data-models.md
This snippet demonstrates how to instantiate and populate a `ChatCompletionRequest` object in C#. It sets the model, defines a list of messages for the conversation history, specifies the maximum number of tokens to generate, and configures the request for non-streaming. This request object is then ready to be passed to an `IChatService` method like `CreateChatCompletionAsync`.
```csharp
var chatRequest = new ChatCompletionRequest
{
Model = "mistralai/mistral-7b-instruct",
Messages = new List
{
new Message { Role = "user", Content = "What is the capital of France?" }
},
MaxTokens = 50,
Stream = false // For a non-streaming request
};
// Then pass to: await chatService.CreateChatCompletionAsync(chatRequest);
```
--------------------------------
### Reading OpenRouter API Key from Environment Variable in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/features/authentication.md
This C# snippet demonstrates how to retrieve the OpenRouter API key from an environment variable named `OPENROUTER_API_KEY`. It includes a fallback mechanism, using the `??` operator, to read the key from the `OpenRouter:ApiKey` configuration section if the environment variable is not set. The retrieved key is then used to configure the `OpenRouterOptions`.
```C#
var apiKey = Environment.GetEnvironmentVariable("OPENROUTER_API_KEY") ??
configuration["OpenRouter:ApiKey"]; // Fallback to config
services.AddOpenRouter(options => options.ApiKey = apiKey);
```
--------------------------------
### Retrieving Model Information with OpenRouter C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/core-concepts/services.md
The `ModelsService` provides functionality to fetch information about AI models available via OpenRouter. It can retrieve a list of all models or models updated after a specific generation, and can be accessed directly from the client instance.
```C#
GetModelsAsync(CancellationToken cancellationToken = default)
```
```C#
client.GetModelsAsync()
```
--------------------------------
### Configuring Additional HTTP Headers for OpenRouter in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/features/authentication.md
This C# snippet shows how to configure additional HTTP headers within `OpenRouterOptions` to provide more context about the application to the OpenRouter API. It sets `HttpReferer` and `XTitle` properties directly and adds a custom `User-Agent` string to the `DefaultHeaders` dictionary, which helps with API usage tracking and diagnostics.
```C#
options.HttpReferer = "https://myawesomeservice.com/integration";
options.XTitle = "My Awesome Service AI Integration";
options.DefaultHeaders["User-Agent"] = "MyAwesomeService/1.0.0 (OpenRouter.NET)";
```
--------------------------------
### Checking Account Credits with OpenRouter C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/core-concepts/services.md
The `CreditsService` allows users to check their remaining credits or usage status for their OpenRouter account. This functionality is available directly through the service or via a convenience method on the client.
```C#
GetCreditsAsync(CancellationToken cancellationToken = default)
```
```C#
client.GetCreditsAsync()
```
--------------------------------
### Defining OpenRouter API Key in appsettings.json
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/features/authentication.md
This JSON snippet shows the structure for storing the OpenRouter API key within an `appsettings.json` file. The `ApiKey` property is nested under the `OpenRouter` section, allowing for external configuration of the API key, which is recommended for security and environment-specific settings.
```JSON
{
"OpenRouter": {
"ApiKey": "sk-or-v1-your_actual_openrouter_api_key"
// ...
}
}
```
--------------------------------
### Defining a Custom Logging DelegatingHandler in C#
Source: https://github.com/xyoz-dev/logiq.openrouter.net/blob/master/docs/advanced/http-client.md
This C# class defines a custom DelegatingHandler named `LoggingDelegatingHandler`. It intercepts HTTP requests and responses to log information such as the outgoing request method and URI, and the incoming response status code. It depends on `ILogger` for logging capabilities. This handler can be used to monitor network traffic for debugging or auditing purposes.
```C#
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
public class LoggingDelegatingHandler : DelegatingHandler
{
private readonly ILogger _logger;
public LoggingDelegatingHandler(ILogger logger)
{
_logger = logger;
}
protected override async Task SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
_logger.LogInformation("Sending request to OpenRouter: {Method} {Uri}", request.Method, request.RequestUri);
// Add more detailed logging for headers or content if necessary,
// but be extremely careful with sensitive data like API keys in request content for other APIs.
// The Authorization header for OpenRouter is handled by the SDK.
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
_logger.LogInformation("Received response from OpenRouter: {StatusCode}", response.StatusCode);
// Log response headers or content if needed for debugging.
// For example, to see rate limit headers:
// if (response.Headers.TryGetValues("x-ratelimit-remaining", out var remaining))
// {
// _logger.LogInformation("Rate limit remaining: {Remaining}", string.Join(",", remaining));
// }
return response;
}
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.