AI applications do not always need to use the model provided by their agent platform. An organization may already have an OpenAI deployment, a Microsoft Foundry model, an Anthropic subscription, or a locally hosted model running through Ollama. Developers may also have requirements related to data residency, model selection, cost management, or infrastructure ownership.
The GitHub Copilot SDK supports this approach through Bring Your Own Key (BYOK). It allows a C# application to use the Copilot agent runtime while routing model requests to a provider selected by the developer.
This separation is useful because the agent runtime and the language model perform different responsibilities. The runtime manages sessions, conversation state, tool execution, and agent orchestration. The configured model provider handles inference and generates responses.
For example, an enterprise application can use the Copilot SDK to manage an AI assistant while sending model requests to a deployment hosted in Microsoft Foundry. The application can also use an OpenAI-compatible endpoint or a locally hosted model, provided the provider and model support the required API capabilities.
In this article, we will configure a C# application to use its own AI model with the Copilot SDK. We will connect to an OpenAI-compatible provider, configure credentials securely, create a session, and send a prompt to the selected model.
Understanding BYOK in the Copilot SDK
BYOK stands for Bring Your Own Key. In the Copilot SDK, it means that the application supplies its own model provider connection and credentials rather than relying on the default Copilot inference provider.
The architecture separates the agent runtime from model inference:
C# Application
|
v
Microsoft Copilot SDK
|
v
Copilot Runtime
|
+---- Session Management
|
+---- Agent Orchestration
|
+---- Tool Execution
|
v
Configured Model Provider
|
+---- OpenAI
|
+---- Microsoft Foundry
|
+---- Anthropic
|
+---- Ollama
|
+---- OpenAI-Compatible API
The Copilot runtime continues to manage the agent workflow. The configured provider receives the model requests and returns inference results.
This means BYOK does not replace the Copilot runtime. It changes where the runtime sends model requests.
The current SDK documentation supports several provider types:
Provider | Configuration type | Typical use |
|---|
OpenAI | openai
| OpenAI API |
Microsoft Foundry | openai or azure
| Hosted enterprise models |
Anthropic | anthropic
| Claude models |
Ollama | openai
| Locally hosted models |
Microsoft Foundry Local | openai
| Local model inference |
vLLM or LiteLLM | openai
| Custom OpenAI-compatible endpoints |
The provider type must match the API interface exposed by the endpoint. For example, Microsoft Foundry's OpenAI-compatible /openai/v1/ endpoint uses the openai provider type, while a native Azure OpenAI endpoint uses the azure type.
Creating the C# Project
Start by creating a console application:
dotnet new console -n CopilotByokDemo
cd CopilotByokDemo
Install the Copilot SDK:
dotnet add package Microsoft.Copilot.SDK
The package provides the .NET client and session APIs required to communicate with the Copilot runtime.
You also need a compatible Copilot runtime. For local development, install the Copilot CLI and verify that it is available:
copilot --version
The runtime can be started by the SDK using its default connection configuration. You can also configure an explicit runtime connection when your application uses a separately hosted runtime.
For this example, we will use the SDK's default runtime connection and an external model provider.
Configuring the OpenAI Provider
Let's start with OpenAI because it provides a straightforward example of configuring a custom provider.
The application needs three important values:
Provider name: A name used to identify the configured connection.
Base URL: The API endpoint that receives model requests.
API key: The credential required by the provider.
Store the API key outside the source code.
For local development, use .NET User Secrets:
dotnet user-secrets init
dotnet user-secrets set "AI:ApiKey" "your-api-key"
Add the provider configuration to appsettings.json:
{
"AI": {
"Provider": "byok",
"Model": "gpt-4o",
"BaseUrl": "https://api.openai.com/v1"
}
}
The model identifier must be supported by the configured provider. The example uses gpt-4o, but you can select another model available to your account.
For a deployed application, use a managed secret store or an appropriately protected environment variable instead of User Secrets.
Creating a Copilot Session With Your Own Model
The important part of BYOK configuration is SessionInferenceOptions.
It defines the provider connection and tells the SDK which provider should handle inference.
Create Program.cs:
using Microsoft.Copilot;
using Microsoft.Extensions.Configuration;
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddUserSecrets<Program>(optional: true)
.AddEnvironmentVariables()
.Build();
var providerName =
configuration["AI:Provider"] ?? "byok";
var modelName =
configuration["AI:Model"]
?? throw new InvalidOperationException(
"AI model is not configured.");
var baseUrl =
configuration["AI:BaseUrl"]
?? throw new InvalidOperationException(
"AI provider URL is not configured.");
var apiKey =
configuration["AI:ApiKey"]
?? throw new InvalidOperationException(
"AI API key is not configured.");
await using var client = new CopilotClient(
new CopilotClientOptions
{
Mode = CopilotClientMode.Empty
});
await client.StartAsync();
#pragma warning disable MCPSDK001
await using var session =
await client.CreateSessionAsync(
new CreateSessionOptions
{
Model = modelName,
GitHub = new SessionGitHubOptions
{
Capi = new CapiSessionOptions
{
Enabled = false
}
},
Inference = new SessionInferenceOptions
{
DefaultProvider = providerName,
Providers =
[
new NamedProviderConfig
{
Name = providerName,
Type = "openai",
BaseUrl = baseUrl,
ApiKey = apiKey
}
]
}
});
#pragma warning restore MCPSDK001
var response = await session.SendAndWaitAsync(
new MessageOptions
{
Prompt = "Explain dependency injection in C#."
});
Console.WriteLine(response?.Data.Content);
Let's understand the important configuration properties.
CopilotClientMode.Empty starts the runtime without automatically enabling the broader coding-agent defaults. This is useful when the application wants to control which capabilities are available.
GitHub.Capi.Enabled = false disables Copilot inference through the GitHub Copilot API. This is important when using a custom provider as the default inference destination.
SessionInferenceOptions contains the provider configuration. DefaultProvider identifies the connection that should handle unqualified model selections. The Providers collection contains the actual connection details.
NamedProviderConfig describes the connection. Its Name must match the value assigned to DefaultProvider. The Type identifies the provider protocol, while BaseUrl and ApiKey configure the endpoint and authentication.
The Model property identifies the model used by the session. With a named provider, the model must be explicitly configured.
The MCPSDK001 warning suppression in this example is intentional. Named provider configuration is marked experimental in the current .NET SDK documentation. Review the package version and release notes before depending on this API in a production application.
Run the application:
dotnet run
The SDK starts the runtime, creates a session, and routes the model request to the configured OpenAI endpoint.
Connecting to Microsoft Foundry
Many enterprise applications use Microsoft Foundry or Azure OpenAI instead of calling a public model API directly.
The Copilot SDK supports both native Azure endpoints and OpenAI-compatible endpoints. The configuration depends on the endpoint format.
For a Microsoft Foundry deployment that exposes an OpenAI-compatible /openai/v1/ endpoint, use the openai provider type.
For example:
var provider = new NamedProviderConfig
{
Name = "foundry",
Type = "openai",
BaseUrl =
"https://your-resource.openai.azure.com/openai/v1/",
ApiKey = foundryApiKey,
WireApi = "responses"
};
The WireApi property specifies the API format used by the provider. The Responses API is appropriate for deployments that support it. Other compatible models may use the chat completions format.
For a native Azure OpenAI endpoint, use the Azure provider type:
var provider = new NamedProviderConfig
{
Name = "azure",
Type = "azure",
BaseUrl =
"https://your-resource.openai.azure.com",
ApiKey = azureApiKey,
Azure = new AzureProviderOptions
{
APIVersion = "2024-10-21"
}
};
Notice the difference between the two configurations.
The OpenAI-compatible endpoint includes /openai/v1/ and uses Type = "openai". The native Azure endpoint uses the resource host and Type = "azure".
Do not add /openai/v1/ to the native Azure endpoint configuration when using the Azure provider type. The runtime constructs the appropriate API path.
Also verify that the deployment supports the API format you select. A model deployment that supports chat completions does not automatically support the Responses API.
Using Ollama for Local Model Inference
One interesting use of BYOK is connecting the Copilot SDK to a locally hosted model.
Developers may want local inference for development, offline experimentation, or workloads where sending prompts to a public model endpoint is not appropriate.
Ollama provides an OpenAI-compatible API that can be used with the SDK.
First, install Ollama and download a model:
ollama pull llama3.1
Start the Ollama service:
ollama serve
The default API endpoint is:
http://localhost:11434/v1
Now configure the provider:
var provider = new NamedProviderConfig
{
Name = "local",
Type = "openai",
BaseUrl = "http://localhost:11434/v1"
};
Use it in the session configuration:
#pragma warning disable MCPSDK001
await using var session =
await client.CreateSessionAsync(
new CreateSessionOptions
{
Model = "llama3.1",
GitHub = new SessionGitHubOptions
{
Capi = new CapiSessionOptions
{
Enabled = false
}
},
Inference = new SessionInferenceOptions
{
DefaultProvider = "local",
Providers = [provider]
}
});
#pragma warning restore MCPSDK001
A local provider such as Ollama does not necessarily require an API key. However, the model name must match a model available in the local Ollama installation.
Local inference also has hardware requirements. Model size, available memory, GPU support, and context length can significantly affect response time.
Another important point is that a locally hosted model does not automatically provide every capability available with a hosted model. Tool calling, structured output, reasoning, and other features depend on the selected model and the compatibility of its API implementation.
Selecting Different Models for Different Sessions
An application may need more than one model.
For example, a developer assistant could use a smaller model for simple questions and a more capable model for complex code analysis. A reporting application could use one model for summarization and another for structured data generation.
The Copilot SDK supports independent sessions, allowing the application to select different models for different tasks.
For example:
#pragma warning disable MCPSDK001
var inference = new SessionInferenceOptions
{
DefaultProvider = "byok",
Providers =
[
new NamedProviderConfig
{
Name = "byok",
Type = "openai",
BaseUrl = "https://api.openai.com/v1",
ApiKey = apiKey
}
]
};
await using var simpleSession =
await client.CreateSessionAsync(
new CreateSessionOptions
{
Model = "gpt-4o-mini",
Inference = inference,
GitHub = new SessionGitHubOptions
{
Capi = new CapiSessionOptions
{
Enabled = false
}
}
});
await using var advancedSession =
await client.CreateSessionAsync(
new CreateSessionOptions
{
Model = "gpt-4o",
Inference = inference,
GitHub = new SessionGitHubOptions
{
Capi = new CapiSessionOptions
{
Enabled = false
}
}
});
#pragma warning restore MCPSDK001
Both sessions use the same provider connection but select different models.
This approach is useful when an application needs to control model selection without creating a separate runtime for every model.
For more advanced configurations, the SDK also supports named provider connections and model definitions. This makes it possible to separate the connection endpoint from the model identifier and provider-facing model name.
Understanding Model and API Compatibility
A common mistake when using a custom model is assuming that every model supported by an API-compatible endpoint will work with every Copilot SDK feature.
The endpoint may accept ordinary text requests but fail when the runtime attempts to use tool calling, structured output, or another capability.
Before selecting a model, verify the following:
The model identifier is accepted by the provider.
The endpoint supports the API format configured in WireApi.
The model supports the required context length.
Tool calling is supported if the application exposes custom tools.
Structured output is supported if the workflow depends on a specific response schema.
Token limits are appropriate for the model.
Pay particular attention to token limits when working with reasoning models. The maximum output-token budget may include both reasoning tokens and visible response tokens. A small limit can cause the model to consume its budget before producing a useful answer.
Do not assume that changing the model name is enough to make an incompatible provider work. Test the actual application workflow, including tool calls and error handling.
Securing Provider Credentials
Using your own provider means that the application is responsible for protecting the credentials used to access it.
Never place an API key directly in Program.cs, a committed JSON configuration file, or a public repository.
For local development, User Secrets is a convenient option:
dotnet user-secrets set "AI:ApiKey" "your-api-key"
For production, use a secure secret-management solution and grant access only to the application identity that needs the credential.
The SDK also supports provider authentication through bearer tokens and token-provider callbacks in supported configurations. This can be useful when credentials need to be refreshed instead of stored as a long-lived API key.
For example, an Azure-hosted application may obtain a token from an identity provider and supply it through a supported provider callback. Check the current SDK documentation for the exact authentication behavior of the package version being used.
Keep in mind that BYOK authentication and GitHub identity are separate concerns. Disabling Copilot inference does not mean the application cannot use GitHub identity for other supported GitHub services. Configure each authentication path according to the functionality your application actually needs.
When BYOK Makes Sense
BYOK is particularly useful when an organization already has an approved model provider or needs greater control over model deployment.
A company may want to use Microsoft Foundry because it already manages model deployments there. A development team may prefer Ollama for local experiments. Another application may use an OpenAI-compatible endpoint hosted behind an internal gateway.
The Copilot SDK allows these applications to retain the agent runtime while changing the model provider.
However, BYOK does not automatically guarantee lower cost, better privacy, or offline operation. Those benefits depend on the selected provider, its deployment configuration, network access, and the way the application handles prompts and responses.
For example, a cloud-hosted model still requires a network connection. A local model may reduce external data transfer, but the application must still secure local files, logs, model endpoints, and tool execution.
Conclusion
The Copilot SDK supports BYOK, allowing C# applications to use their own model providers while retaining the Copilot agent runtime.
With SessionInferenceOptions and NamedProviderConfig, developers can configure OpenAI, Microsoft Foundry, Azure OpenAI, Ollama, and other supported providers. The application can then create sessions, select models, and send prompts through the configured endpoint.
The most important part is understanding that model inference and agent orchestration are separate responsibilities. BYOK changes the inference provider, but the Copilot runtime continues to manage the agent workflow.
For production applications, choose a provider that supports the required API capabilities, protect credentials, configure model limits carefully, and test the complete workflow before deployment.
Join the conversation! Your thoughts help the community grow.