From 941894761a7a1fbce7f5750bef1b2efb7ee5b1fe Mon Sep 17 00:00:00 2001 From: Tomi Eckert Date: Thu, 5 Mar 2026 11:52:08 +0100 Subject: [PATCH] feat: Implement OpenRouter API client for managing headers and retrieving model pricing. --- OpenRouter/OpenRouterHeaders.cs | 19 +++++++++++++++++++ OpenRouter/PricingProvider.cs | 5 +++++ Program.cs | 6 +++++- 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 OpenRouter/OpenRouterHeaders.cs diff --git a/OpenRouter/OpenRouterHeaders.cs b/OpenRouter/OpenRouterHeaders.cs new file mode 100644 index 0000000..eccea25 --- /dev/null +++ b/OpenRouter/OpenRouterHeaders.cs @@ -0,0 +1,19 @@ +using System.Net.Http; + +namespace AnchorCli.OpenRouter; + +/// +/// Provides extension methods for adding OpenRouter-specific HTTP headers. +/// +public static class OpenRouterHeaders +{ + /// + /// Applies the required OpenRouter headers to the specified HttpClient. + /// + public static void ApplyTo(HttpClient httpClient) + { + httpClient.DefaultRequestHeaders.TryAddWithoutValidation("HTTP-Referer", "https://git.technopunk.space/tomi/AnchorCli"); + httpClient.DefaultRequestHeaders.TryAddWithoutValidation("X-OpenRouter-Title", "Anchor CLI"); + httpClient.DefaultRequestHeaders.TryAddWithoutValidation("X-OpenRouter-Categories", "cli-agent"); + } +} diff --git a/OpenRouter/PricingProvider.cs b/OpenRouter/PricingProvider.cs index 3a28f16..a17a7c1 100644 --- a/OpenRouter/PricingProvider.cs +++ b/OpenRouter/PricingProvider.cs @@ -14,6 +14,11 @@ internal sealed class PricingProvider private static readonly HttpClient Http = new(); private Dictionary? _models; + static PricingProvider() + { + OpenRouterHeaders.ApplyTo(Http); + } + /// /// Fetches the full model list from OpenRouter (cached after first call). /// diff --git a/Program.cs b/Program.cs index e16067b..5f1b23a 100644 --- a/Program.cs +++ b/Program.cs @@ -88,9 +88,13 @@ AnsiConsole.Write(infoTable); AnsiConsole.WriteLine(); // ── Build the chat client with tool-calling support ───────────────────── +var httpClient = new HttpClient(); +OpenRouterHeaders.ApplyTo(httpClient); + var openAiClient = new OpenAIClient(new ApiKeyCredential(apiKey), new OpenAIClientOptions { - Endpoint = new Uri(endpoint) + Endpoint = new Uri(endpoint), + Transport = new System.ClientModel.Primitives.HttpClientPipelineTransport(httpClient) }); IChatClient innerClient = openAiClient.GetChatClient(model).AsIChatClient();