1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ASP.NET Core から OpenAI 互換 LLM Gateway を使って複数モデルを呼び出す方法

1
Posted at

この記事は nRouter の関係者が執筆しています。

LLM を使う ASP.NET Core アプリケーションを作る際、最初は特定の AI プロバイダーへ直接接続することが多いと思います。

しかし本番運用では、モデルの変更、複数プロバイダーの利用、利用料金の把握、障害時の対応、ガードレールの適用などを考える必要があります。

この記事では、OpenAI 互換 API を持つ LLM Gateway を利用し、ASP.NET Core からチャット補完を呼び出す基本構成を紹介します。例では nRouter を使用します。

構成

クライアント
    ↓
ASP.NET Core API
    ↓
nRouter API Gateway
    ↓
選択した LLM プロバイダー / モデル

アプリケーション側は 1 つの API エンドポイントに接続します。Gateway 側でモデルへのルーティング、利用状況の可視化、予算管理、ガードレールなどを一元管理できます。

前提条件

  • .NET 8 以降
  • ASP.NET Core Web API
  • nRouter の API キー
  • nRouter アカウントで利用可能なモデル ID

まずプロジェクトを作成します。

dotnet new webapi -n NRouterSample
cd NRouterSample

API キーを安全に設定する

API キーをソースコードや appsettings.json に直接書き込んではいけません。

ローカル開発では .NET User Secrets を使用します。

dotnet user-secrets init
dotnet user-secrets set "NROUTER_API_KEY" "your-nrouter-api-key"
dotnet user-secrets set "NROUTER_MODEL" "gpt-5.5"

gpt-5.5 は設定例です。実際には nRouter のモデルカタログで利用可能なモデル ID を確認してください。

Minimal API を実装する

Program.cs を次の内容に置き換えます。

using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpClient("nRouter", client =>
{
    client.BaseAddress = new Uri("https://api.nrouter.ai/");
    client.Timeout = TimeSpan.FromSeconds(60);
});

var app = builder.Build();

app.MapPost("/chat", async (
    ChatInput input,
    IHttpClientFactory httpClientFactory,
    IConfiguration configuration,
    CancellationToken cancellationToken) =>
{
    if (string.IsNullOrWhiteSpace(input.Prompt))
    {
        return Results.BadRequest(new
        {
            error = "prompt は必須です。"
        });
    }

    var apiKey = configuration["NROUTER_API_KEY"];
    var model = configuration["NROUTER_MODEL"];

    if (string.IsNullOrWhiteSpace(apiKey) ||
        string.IsNullOrWhiteSpace(model))
    {
        return Results.Problem(
            "NROUTER_API_KEY または NROUTER_MODEL が設定されていません。",
            statusCode: StatusCodes.Status500InternalServerError);
    }

    var requestBody = new
    {
        model,
        messages = new[]
        {
            new
            {
                role = "user",
                content = input.Prompt
            }
        }
    };

    var client = httpClientFactory.CreateClient("nRouter");

    using var request = new HttpRequestMessage(
        HttpMethod.Post,
        "v1/chat/completions");

    request.Headers.Authorization =
        new AuthenticationHeaderValue("Bearer", apiKey);

    request.Content = JsonContent.Create(requestBody);

    using var response = await client.SendAsync(
        request,
        cancellationToken);

    response.EnsureSuccessStatusCode();

    var completion = await response.Content
        .ReadFromJsonAsync<ChatCompletion>(
            cancellationToken: cancellationToken);

    var answer = completion?.Choices
        ?.FirstOrDefault()
        ?.Message
        ?.Content;

    return Results.Ok(new
    {
        answer = answer ?? "応答内容を取得できませんでした。"
    });
});

app.Run();

public sealed record ChatInput(string Prompt);

public sealed record ChatCompletion(
    [property: JsonPropertyName("choices")]
    List<ChatChoice> Choices);

public sealed record ChatChoice(
    [property: JsonPropertyName("message")]
    ChatMessage Message);

public sealed record ChatMessage(
    [property: JsonPropertyName("role")]
    string Role,

    [property: JsonPropertyName("content")]
    string Content);

この例では、https://api.nrouter.ai/v1/chat/completions に OpenAI 互換形式のリクエストを送信しています。

動作確認

アプリケーションを起動します。

dotnet run

次に、ローカル API へリクエストを送ります。

curl -X POST "https://localhost:5001/chat" \
  -H "Content-Type: application/json" \
  -d "{\"prompt\":\"ASP.NET Core の依存性注入を2文で説明してください。\"}"

成功すると、次のような JSON 応答が返ります。

{
  "answer": "..."
}

Gateway を間に置くメリット

アプリケーションから直接プロバイダーへ接続する場合、プロバイダーごとのキー、接続先、利用料金、モデル選定をアプリケーションごとに管理する必要があります。

Gateway を間に置くと、モデルの選択、リクエストのルーティング、利用状況の可視化、予算管理、ガードレールなどを一元化しやすくなります。

特に複数チームや複数サービスが LLM を利用する場合、利用量やコストを追跡できる構成は重要です。また、API キーをアプリケーション側で安全に扱い、プロバイダー固有の設定を減らすことにも役立ちます。

本番導入時のチェックポイント

  1. API キーをフロントエンドやモバイルアプリに露出させない
  2. API キーを環境変数またはシークレット管理サービスで管理する
  3. 利用するモデル ID を事前に確認する
  4. タイムアウトとキャンセル処理を実装する
  5. 個人情報や機密プロンプトをログに残さない
  6. テスト環境でエラー時の動作を確認する
  7. チームに必要な利用上限とアクセス権限を設定する

まとめ

ASP.NET Core アプリケーションから LLM を利用する際、Gateway を利用すると、アプリケーション側の実装をシンプルに保ちながら、モデル接続、ルーティング、利用状況の把握、運用上の制御をまとめて扱いやすくなります。

今回の例では、nRouter の OpenAI 互換 API を使って、ASP.NET Core Minimal API からチャット補完を呼び出しました。この構成は、ストリーミング応答、埋め込み生成、モデル切り替え、ログ連携などにも拡張できます。

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?