OpenRouterClientLite 1.0.4

dotnet add package OpenRouterClientLite --version 1.0.4
                    
NuGet\Install-Package OpenRouterClientLite -Version 1.0.4
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="OpenRouterClientLite" Version="1.0.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="OpenRouterClientLite" Version="1.0.4" />
                    
Directory.Packages.props
<PackageReference Include="OpenRouterClientLite" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add OpenRouterClientLite --version 1.0.4
                    
#r "nuget: OpenRouterClientLite, 1.0.4"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package OpenRouterClientLite@1.0.4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=OpenRouterClientLite&version=1.0.4
                    
Install as a Cake Addin
#tool nuget:?package=OpenRouterClientLite&version=1.0.4
                    
Install as a Cake Tool

OpenRouterClientLite

NuGet Static Badge

Легковесный .NET клиент для интеграции с OpenRouter API. Поддерживает все основные функции API, включая получение списка моделей и генерацию текста.

DOC

Особенности

  • Получение информации о доступных моделях с ценами
  • Генерация текстовых ответов через чат-интерфейс
  • Поддержка параметров генерации (температура, макс. токены)
  • Автоматическая сериализация/десериализация запросов
  • Поддержка отмены операций (CancellationToken)
  • Правильная обработка HTTP-заголовков (аутентификация, реферер)
  • Полная типизация моделей данных.

Установка

Добавьте пакет через NuGet:

bash Install-Package OpenRouterClientLite Или через .NET CLI:

bash dotnet add package OpenRouterClientLite

Быстрый старт

Инициализация клиента

using OpenRouterClientLite;

var apiKey = "your_api_key_here";
var client = new OpenRouterClient(
    apiKey: apiKey,
    appName: "MyAwesomeApp",    // Необязательно
    siteUrl: "https://myapp.com" // Необязательно
);

Получение списка моделей

try
{
    var models = await client.GetModelsAsync();
    foreach (var model in models)
    {
        Console.WriteLine($"ID: {model.Id}");
        Console.WriteLine($"Name: {model.Name}");
        Console.WriteLine($"Description: {model.Description}");
        Console.WriteLine($"Pricing: {model.Pricing.Prompt} (prompt) / {model.Pricing.Completion} (completion)");
        Console.WriteLine();
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}

Генерация текста

try
{
    var response = await client.GenerateResponseAsync(
        model: "openai/gpt-3.5-turbo",
        prompt: "Расскажи интересный факт о космосе",
        temperature: 0.7,
        maxTokens: 150
    );

    var message = response.ChatCompletionChoice[0].GeneratedMessage.Content;
    var usage = response.UsageTokens;
    
    Console.WriteLine($"Response: {message}");
    Console.WriteLine($"Tokens used: {usage.PromptTokens} (prompt) + {usage.CompletionTokens} (completion) = {usage.TotalTokens}");
}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}

Модели данных

Запрос генерации (ChatRequest) |Параметр| Тип| Описание| |---|-----|-------| |Model |string| Идентификатор модели| |Messages |GeneratedMessage[] |Массив сообщений| |Temperature| double?| Креативность (0-1)| |MaxTokens| int? |Макс. количество токенов в ответе|

Ответ (ChatResponse)

public record ChatResponse(
    ChatCompletionChoice[] Choices,
    UsageTokens Usage);

public record ChatCompletionChoice(
    GeneratedMessage Message,
    string FinishReason);

public record UsageTokens(
    int PromptTokens,
    int CompletionTokens,
    int TotalTokens);

Сообщение (GeneratedMessage)

public record GeneratedMessage(
    string Role,   // "user", "assistant", "system"
    string Content);

Рекомендации

API Keys: Получите ключ на OpenRouter Dashboard

Модели: Актуальный список моделей доступен через GetModelsAsync()

Обработка ошибок: Все методы выбрасывают исключения при HTTP-ошибках

Освобождение ресурсов: Клиент реализует IDisposable

using (var client = new OpenRouterClient(apiKey))
{
    // работа с клиентом
}
Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net9.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.4 226 6/6/2025
1.0.1 170 6/6/2025
1.0.0 187 6/6/2025