### Install OpenRouter .NET Client via NuGet Source: https://github.com/kareemmagdy55/openrouterclient/blob/main/OpenRouterClient/OpenRouterClient/README.md Installs the OpenRouterClient package using the .NET CLI. Ensure you have the .NET SDK installed. ```bash dotnet add package OpenRouterClient --version 1.0.x ``` -------------------------------- ### Configure Temperature and Sampling in C# Source: https://context7.com/kareemmagdy55/openrouterclient/llms.txt Demonstrates how to control the randomness and creativity of model outputs by configuring temperature, top-p, top-k, and other sampling parameters. ```csharp // Configure sampling parameters for creative writing var creativeResponse = await client.Chat .WithModel("anthropic/claude-3-opus") .WithTemperature(1.2) // Higher temperature for more creative outputs (0-2) .WithTopP(0.95) // Nucleus sampling threshold (0-1) .WithTopK(50) // Consider top 50 tokens .WithMinP(0.05) // Minimum probability threshold .AddSystemMessage("You are a creative storyteller.") .AddUserMessage("Write a short story about a robot learning to paint.") .SendAsync(); // Configure for deterministic, focused outputs var deterministicResponse = await client.Chat .WithModel("openai/gpt-4o") .WithTemperature(0.1) // Low temperature for consistent outputs .WithSeed(42) // Set seed for reproducibility .AddUserMessage("List the first 5 prime numbers.") .SendAsync(); if (deterministicResponse != null) { Console.WriteLine(deterministicResponse.Choices[0].Message.Content); } ``` -------------------------------- ### Initialize and Execute Chat Request in .NET Source: https://context7.com/kareemmagdy55/openrouterclient/llms.txt Demonstrates how to initialize the OpenRouter client, configure a chat request using the fluent builder pattern, and handle the resulting response. It requires an API key stored in environment variables and provides fine-grained control over model parameters like temperature and max tokens. ```csharp using OpenRouterClient; using OpenRouterClient.DTO; class Program { static async Task Main(string[] args) { var client = new Client( apiUrl: "https://openrouter.ai/api/v1/chat/completions", apiToken: Environment.GetEnvironmentVariable("OPENROUTER_API_KEY") ?? throw new InvalidOperationException("API key not found") ); OpenRouterResponseDto? response = await client.Chat .WithModel("google/gemini-2.5-pro-exp-03-25:free") .WithTemperature(0.8) .WithMaxTokens(1000) .WithTopP(0.9) .WithFrequencyPenalty(0.2) .WithUser("demo-user-001") .AddSystemMessage("You are an expert software architect.") .AddUserMessage("How would you design a scalable microservices architecture for an e-commerce platform?") .SendAsync(); if (response != null && response.Choices?.Count > 0) { Console.WriteLine("=== OpenRouter Response ==="); Console.WriteLine($"ID: {response.Id}"); Console.WriteLine($"Response:\n{response.Choices[0].Message.Content}"); } else { Console.WriteLine("Failed to get response. Check API key and network connection."); } } } ``` -------------------------------- ### Configure Token Limits and Penalties in C# Source: https://context7.com/kareemmagdy55/openrouterclient/llms.txt Shows how to set token limits and apply penalties like frequency and presence penalties to control repetition and encourage topic diversity in generated text. ```csharp // Configure token limits and penalties var response = await client.Chat .WithModel("meta-llama/llama-3-70b-instruct") .WithMaxTokens(500) // Limit response to 500 tokens .WithFrequencyPenalty(0.5) // Reduce repetition of frequent tokens (-2 to 2) .WithPresencePenalty(0.3) // Encourage new topics (-2 to 2) .WithRepetitionPenalty(1.1) // General repetition penalty (0 to 2) .AddUserMessage("Explain the benefits of microservices architecture.") .SendAsync(); if (response != null) { Console.WriteLine(response.Choices[0].Message.Content); } ``` -------------------------------- ### Multi-Turn Conversations in C# Source: https://context7.com/kareemmagdy55/openrouterclient/llms.txt Illustrates how to build multi-turn conversations, including system prompts, user messages, and assistant responses, to enable context-aware interactions. ```csharp // Multi-turn conversation with system prompt var response = await client.Chat .WithModel("openai/gpt-4o") .AddSystemMessage("You are a helpful coding assistant specializing in C# and .NET.") .AddUserMessage("How do I read a JSON file in C#?") .AddAssistantMessage("You can use System.Text.Json to deserialize JSON files. Would you like a code example?") .AddUserMessage("Yes, please show me a complete example with error handling.") .SendAsync(); if (response != null) { Console.WriteLine(response.Choices[0].Message.Content); } ``` -------------------------------- ### Perform Synchronous Chat Completion Source: https://github.com/kareemmagdy55/openrouterclient/blob/main/README.md Demonstrates how to configure a model, add a user message, and send a request to the API to receive a response. ```csharp var response = client.Chat.WithModel("google/gemini-2.5-pro-exp-03-25:free").AddUserMessage("How would you build the tallest building ever?").SendAsync(); Console.WriteLine(response.Result?.Choices[0].Message); ``` -------------------------------- ### Reasoning Configuration Source: https://context7.com/kareemmagdy55/openrouterclient/llms.txt Enable and configure chain-of-thought reasoning tokens for supported models. ```APIDOC ## POST /chat/completions (Reasoning) ### Description Enable and configure reasoning/thinking tokens for models that support chain-of-thought reasoning. ### Method POST ### Endpoint /chat/completions ### Parameters #### Request Body - **reasoning_effort** (string) - Optional - "high", "medium", or "low". - **max_tokens** (integer) - Optional - Max tokens for reasoning. ### Request Example { "model": "anthropic/claude-3-opus", "reasoning_effort": "high", "max_tokens": 1000 } ### Response #### Success Response (200) - **choices** (array) - Contains the model response including reasoning if enabled. ``` -------------------------------- ### Implement Model Routing and Prompt Transforms Source: https://context7.com/kareemmagdy55/openrouterclient/llms.txt Utilize OpenRouter's model routing to specify fallback models in case the primary model is unavailable. Prompt transforms can also be applied to modify the input prompt before it's sent to the model. ```csharp var response = await client.Chat .WithModel("openrouter/auto") // Let OpenRouter choose optimal model .WithModelRouting( "anthropic/claude-3-opus", "openai/gpt-4o", "google/gemini-pro" ) .WithSortPreference("price") // Sort by price, throughput, etc. .WithTransforms("middle-out") // Apply prompt transforms .AddUserMessage("Summarize the key points of machine learning.") .SendAsync(); if (response != null) { Console.WriteLine($"Response ID: {response.Id}"); Console.WriteLine(response.Choices[0].Message.Content); } ``` -------------------------------- ### Basic Chat Completion Request in C# Source: https://context7.com/kareemmagdy55/openrouterclient/llms.txt Shows how to perform a simple chat completion request using the fluent builder API. It specifies the model and adds a user message. ```csharp // Simple chat completion request var response = await client.Chat .WithModel("google/gemini-2.5-pro-exp-03-25:free") .AddUserMessage("What is the capital of France?") .SendAsync(); // Access the response if (response != null) { string answer = response.Choices[0].Message.Content; Console.WriteLine($"Response: {answer}"); Console.WriteLine($"Response ID: {response.Id}"); } else { Console.WriteLine("Request failed - check console for error details"); } ``` -------------------------------- ### Initialize OpenRouter Client in C# Source: https://github.com/kareemmagdy55/openrouterclient/blob/main/OpenRouterClient/OpenRouterClient/README.md Initializes the OpenRouter client with the API URL and your personal API token. This client is used to make requests to the OpenRouter API. ```csharp Client client = new Client(apiUrl:"https://openrouter.ai/api/v1/chat/completions", apiToken: "sk-or-v1-xxxxx"); ``` -------------------------------- ### Model Routing and Transforms Source: https://context7.com/kareemmagdy55/openrouterclient/llms.txt Configure model routing for fallback scenarios and apply prompt transforms. ```APIDOC ## POST /chat/completions (Routing) ### Description Use OpenRouter-specific features like model routing (fallback models) and prompt transforms. ### Method POST ### Endpoint /chat/completions ### Parameters #### Request Body - **model** (string) - Required - The primary model name. - **models** (array) - Optional - List of fallback models. - **transforms** (array) - Optional - List of prompt transforms to apply. ### Request Example { "model": "openrouter/auto", "models": ["anthropic/claude-3-opus", "openai/gpt-4o"], "transforms": ["middle-out"] } ### Response #### Success Response (200) - **id** (string) - Unique response identifier. ``` -------------------------------- ### Configure Reasoning Tokens for Chain-of-Thought Source: https://context7.com/kareemmagdy55/openrouterclient/llms.txt Enable and configure reasoning tokens for models that support chain-of-thought processing. This feature allows the model to output its reasoning steps before providing the final answer, aiding in complex problem-solving. ```csharp var response = await client.Chat .WithModel("anthropic/claude-3-opus") .WithReasoning( effort: "high", // Reasoning effort: "high", "medium", "low" maxTokens: 1000, // Max tokens for reasoning (optional) exclude: false // Include reasoning in response ) .AddUserMessage("Solve this step by step: If a train travels 120km in 2 hours, then 90km in 1.5 hours, what is the average speed for the entire journey?") .SendAsync(); if (response != null) { Console.WriteLine(response.Choices[0].Message.Content); } ``` -------------------------------- ### Configure Logit Bias for Token Selection Source: https://context7.com/kareemmagdy55/openrouterclient/llms.txt Apply logit bias to specific tokens to influence their likelihood of appearing in the model's output. This allows for fine-grained control over token selection, useful for steering model behavior. ```csharp var logitBias = new Dictionary { { "12345", 5.0 }, // Strongly increase likelihood of token ID 12345 { "67890", -100.0 } // Effectively ban token ID 67890 }; var response = await client.Chat .WithModel("openai/gpt-4o") .WithLogitBias(logitBias) .WithTopLogprobs(5) // Return top 5 log probabilities .AddUserMessage("Describe the weather today.") .SendAsync(); if (response != null) { Console.WriteLine(response.Choices[0].Message.Content); } ``` -------------------------------- ### Perform Synchronous Chat Completion in C# Source: https://github.com/kareemmagdy55/openrouterclient/blob/main/OpenRouterClient/OpenRouterClient/README.md Sends a synchronous chat completion request to the OpenRouter API using a specified model and user message. It retrieves and prints the first message from the response. ```csharp var response = client.Chat. WithModel("google/gemini-2.5-pro-exp-03-25:free"). AddUserMessage("How would you build the tallest building ever?") .SendAsync(); Console.WriteLine(response.Result?.Choices[0].Message); ``` -------------------------------- ### Logit Bias Configuration Source: https://context7.com/kareemmagdy55/openrouterclient/llms.txt Configure token biases to influence model output behavior. ```APIDOC ## POST /chat/completions (Logit Bias) ### Description Apply biases to specific tokens to increase or decrease their likelihood of appearing in the output. ### Method POST ### Endpoint /chat/completions ### Parameters #### Request Body - **logit_bias** (object) - Optional - A map of token IDs to bias values. - **top_logprobs** (integer) - Optional - Number of log probabilities to return. ### Request Example { "model": "openai/gpt-4o", "logit_bias": { "12345": 5.0, "67890": -100.0 }, "top_logprobs": 5 } ### Response #### Success Response (200) - **choices** (array) - List of model completions. ``` -------------------------------- ### Implement User Tracking for Analytics Source: https://context7.com/kareemmagdy55/openrouterclient/llms.txt Set a unique user identifier for requests to enable monitoring, analytics, and per-user rate limiting on the OpenRouter platform. This helps in tracking usage patterns and managing API access. ```csharp var response = await client.Chat .WithModel("openai/gpt-4o-mini") .WithUser("user-12345-abc") // Unique identifier for your end-user .AddUserMessage("What time is it in Tokyo?") .SendAsync(); if (response != null) { Console.WriteLine(response.Choices[0].Message.Content); } ``` -------------------------------- ### User Tracking Source: https://context7.com/kareemmagdy55/openrouterclient/llms.txt Set a unique user identifier for analytics and rate limiting. ```APIDOC ## POST /chat/completions (User Tracking) ### Description Set a unique user identifier for monitoring and analytics purposes. ### Method POST ### Endpoint /chat/completions ### Parameters #### Request Body - **user** (string) - Optional - Unique identifier for the end-user. ### Request Example { "model": "openai/gpt-4o-mini", "user": "user-12345-abc" } ### Response #### Success Response (200) - **choices** (array) - Model completion response. ``` -------------------------------- ### Build Request Object Without Sending Source: https://context7.com/kareemmagdy55/openrouterclient/llms.txt Construct an AI request object without immediately sending it to the API. This is useful for inspecting the request details, logging, or integrating with custom HTTP handling workflows. ```csharp var request = client.Chat .WithModel("openai/gpt-4o") .WithTemperature(0.7) .WithMaxTokens(200) .AddSystemMessage("You are a helpful assistant.") .AddUserMessage("Hello!") .Build(); // Inspect the request object Console.WriteLine($"Model: {request.Model}"); Console.WriteLine($"Temperature: {request.Temperature}"); Console.WriteLine($"Max Tokens: {request.MaxTokens}"); Console.WriteLine($"Message Count: {request.Messages?.Count}"); foreach (var message in request.Messages ?? new List()) { Console.WriteLine($" [{message.Role}]: {message.Content}"); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.