Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This tutorial builds a simple WinUI 3 desktop app that uses the Phi Silica on-device language model. The finished app lets you type a prompt, choose a skill (chat, summarize, or rewrite), and see the response generated locally on your device — no cloud call, no API key.
Important
Phi Silica runs on Copilot+ PCs (on the NPU) and on non-Copilot+ Windows 11 devices with a supported GPU. See Supported hardware for the full list. If your device meets neither requirement, Foundry Local is an alternative that runs on any modern Windows PC.
Important
This tutorial uses Windows App SDK 2.6.4, which does not require a LanguageModel LAF token or unlock call. Apps using earlier SDK versions should retain their existing legacy unlock flow, or upgrade to Windows App SDK 2.6.4 or later. See Step 6 for legacy setup. See LAF compatibility.
Note
Phi Silica features are not available in China.
What you'll build
A WinUI 3 app with:
- A prompt input box
- A skill selector (Chat / Summarize / Rewrite)
- A response display area
- Status feedback while the model loads
Prerequisites
Copilot+ PC or a non-Copilot+ Windows 11 device with a supported GPU. See Phi Silica supported hardware. For Copilot+ PCs, also see the Copilot+ PCs developer guide.
Windows 11 build 26100 or later (24H2) — check with
winverfrom Windows Search.Developer Mode enabled — Windows Settings → System → For developers → Developer Mode.
Visual Studio 2022 with the Windows application development workload installed. See Start here.
Windows App SDK 2.6.4 NuGet package —
Microsoft.WindowsAppSDKversion2.6.4. You'll install this in the steps below.Legacy LAF setup, if you adapt the tutorial to an earlier SDK. Retain your existing legacy unlock flow, or upgrade to Windows App SDK 2.6.4 or later, which does not require this setup. See LAF compatibility.
Tip: Run the automated setup command in Windows Terminal to install Visual Studio and the Windows App SDK in one step:
winget configure https://raw.githubusercontent.com/microsoft/winget-dsc/refs/heads/main/samples/Configuration%20files/Learn%20tutorials/Windows%20AI/learn_wcr.winget
Step 1: Create the project
Open Visual Studio.
Select Create a new project, search for WinUI, and select Blank App, Packaged (WinUI 3 in Desktop).
Name the project
PhiSilicaChat, choose a location, and select Create.In Solution Explorer, right-click the project and select Manage NuGet Packages.
Search for
Microsoft.WindowsAppSDK, select version2.6.4, and click Install.Set the build configuration to ARM64 in the toolbar dropdown.
In the toolbar's launch profile dropdown (next to the play button), select PhiSilicaChat (Package) — not the unpackaged profile.
Important
The
LanguageModelAPI only works in a packaged MSIX app. If you accidentally run the unpackaged profile,GetReadyState()will fail with a COM error. Always use the MsixPackage launch profile.
Step 2: Configure the app manifest
The app needs the systemAIModels capability and a minimum OS version of 10.0.26100.0 to access Phi Silica.
In Solution Explorer, right-click
Package.appxmanifestand select View Code.Find the opening
<Packagetag and replace the entire<Package ...>opening tag with this version:<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" xmlns:systemai="http://schemas.microsoft.com/appx/manifest/systemai/windows10" IgnorableNamespaces="uap rescap systemai">Important
The
xmlns:systemaideclaration must appear in the<Package>opening tag. Adding<systemai:Capability>without the namespace declaration here causes an "undeclared prefix" parse error.Find the
<Dependencies>element and replace it entirely — raisingMinVersionto10.0.26100.0is required. If the minimum version is lower, Windows silently ignores thesystemai:CapabilityandGetReadyState()throws "Not declared by app":<Dependencies> <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.26100.0" MaxVersionTested="10.0.26300.0" /> <TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.26100.0" MaxVersionTested="10.0.26300.0" /> </Dependencies>Find the
<Capabilities>element and replace it entirely with:<Capabilities> <rescap:Capability Name="runFullTrust"/> <systemai:Capability Name="systemAIModels"/> </Capabilities>
Step 3: Configure the project file
Prevent Visual Studio from overriding the manifest version settings.
In Solution Explorer, right-click the project name (the top-level node with the C# icon, just below the solution) and select Edit Project File. This opens the
.csprojfile directly in the editor — it isn't shown as a file in Solution Explorer.Inside the
<PropertyGroup>element, add:<AppxOSMinVersionReplaceManifestVersion>false</AppxOSMinVersionReplaceManifestVersion> <AppxOSMaxVersionTestedReplaceManifestVersion>false</AppxOSMaxVersionTestedReplaceManifestVersion>
Step 4: Build the UI
Replace the contents of MainWindow.xaml with the following:
<Window
x:Class="PhiSilicaChat.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Phi Silica Chat">
<Grid Margin="24" RowSpacing="12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="Phi Silica Chat" Style="{StaticResource TitleTextBlockStyle}"/>
<TextBox Grid.Row="1"
x:Name="PromptBox"
PlaceholderText="Enter your prompt here..."
AcceptsReturn="True"
MinHeight="80"
TextWrapping="Wrap"/>
<StackPanel Grid.Row="2" Orientation="Horizontal" Spacing="12">
<ComboBox x:Name="SkillSelector" SelectedIndex="0" MinWidth="160">
<ComboBoxItem Content="Chat (no skill)"/>
<ComboBoxItem Content="Summarize"/>
<ComboBoxItem Content="Rewrite"/>
</ComboBox>
<Button x:Name="SendButton" Content="Generate" Click="OnSendClicked" Style="{StaticResource AccentButtonStyle}"/>
</StackPanel>
<ScrollViewer Grid.Row="3" VerticalScrollBarVisibility="Auto" Margin="0,8,0,0">
<TextBlock x:Name="ResponseText"
TextWrapping="Wrap"
IsTextSelectionEnabled="True"
FontSize="14"/>
</ScrollViewer>
<TextBlock Grid.Row="4" x:Name="StatusText" Opacity="0.6" FontSize="12"/>
</Grid>
</Window>
Step 5: Add the code-behind
Note
This tutorial uses prompt engineering for summarization and rewriting: it adds an instruction to the prompt text. For the dedicated text transformation APIs, see Text Intelligence Skills.
Replace the contents of MainWindow.xaml.cs with the following:
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.Windows.AI;
using Microsoft.Windows.AI.Text;
using System;
namespace PhiSilicaChat;
public sealed partial class MainWindow : Window
{
private LanguageModel? _languageModel;
public MainWindow()
{
InitializeComponent();
InitializeModelAsync();
}
private async void InitializeModelAsync()
{
SendButton.IsEnabled = false;
StatusText.Text = "Checking model availability...";
try
{
var readyState = LanguageModel.GetReadyState();
if (readyState == AIFeatureReadyState.NotReady)
{
StatusText.Text = "Model not ready — installing. This may take a few minutes...";
var ensureResult = await LanguageModel.EnsureReadyAsync();
if (ensureResult.ExtendedError != null)
{
StatusText.Text = $"Model installation failed: {ensureResult.ExtendedError.Message}";
return;
}
}
else if (readyState == AIFeatureReadyState.NotSupportedOnCurrentSystem)
{
StatusText.Text = "Phi Silica is not supported on this device.";
ResponseText.Text = "Phi Silica requires a Copilot+ PC (NPU) or a non-Copilot+ Windows 11 device with a supported GPU.\n\n" +
"For on-device AI on any Windows PC, see Foundry Local:\n" +
"https://learn.microsoft.com/windows/ai/foundry-local/get-started";
return;
}
_languageModel = await LanguageModel.CreateAsync();
StatusText.Text = "Model ready.";
SendButton.IsEnabled = true;
}
catch (Exception ex)
{
StatusText.Text = $"Model init failed: {ex.Message}";
}
}
private async void OnSendClicked(object sender, RoutedEventArgs e)
{
if (_languageModel is null) return;
string prompt = PromptBox.Text.Trim();
if (string.IsNullOrEmpty(prompt)) return;
SendButton.IsEnabled = false;
ResponseText.Text = string.Empty;
StatusText.Text = "Generating response...";
try
{
string fullPrompt;
int skillIndex = SkillSelector.SelectedIndex;
if (skillIndex == 1)
{
// Summarize: inject an instruction into the prompt
fullPrompt = $"Summarize the following text concisely:\n\n{prompt}";
}
else if (skillIndex == 2)
{
// Rewrite: inject an instruction into the prompt
fullPrompt = $"Rewrite the following text to be clearer and more professional:\n\n{prompt}";
}
else
{
// Plain chat
fullPrompt = prompt;
}
var result = await _languageModel.GenerateResponseAsync(fullPrompt);
ResponseText.Text = result.Text;
StatusText.Text = "Done.";
}
catch (Exception ex)
{
ResponseText.Text = $"Error: {ex.Message}";
StatusText.Text = "An error occurred.";
}
finally
{
SendButton.IsEnabled = true;
}
}
}
Step 6: Configure legacy LAF access, if required
Skip this step for Windows App SDK 2.6.4 or later, including this tutorial's package. Apps using earlier SDK versions should retain their existing legacy unlock flow before model calls, or upgrade to Windows App SDK 2.6.4 or later. The instructions below show legacy setup.
Note
What is a LAF token? A Limited Access Feature (LAF) token is how Microsoft gates pre-release or controlled-access Windows APIs. When you submit the request form, Microsoft emails you two values:
- A token — a short base64 string (e.g.
xK9mP2nQrL8vZw==) - An attestation string — a sentence in the form
"<id> has registered their use of <feature> with Microsoft and agrees to the terms of use."
Both values are specific to your app's Package Family Name — they won't work in a different app. Paste them into TryUnlockFeature() exactly as received.
For legacy LAF setup, obtain your token and attestation string before adding the unlock code.
Submit the LAF Access Token Request Form.
When you receive your token email, find your Package Family Name by deploying the app once (Build → Deploy Solution) then running in PowerShell:
Get-AppxPackage | Where-Object {$_.Name -like "*PhiSilicaChat*"} | Select-Object PackageFamilyNameTip
If your project
Identity Nameis a GUID (the default for new projects), search by that value instead:Get-AppxPackage | Where-Object {$_.Name -like "*YOUR-GUID*"}Reply to the token email with your Package Family Name. Microsoft will send you a token value and attestation string.
Add
using Windows.ApplicationModel;toMainWindow.xaml.cs. Insert the following code inInitializeModelAsync, before the readiness checks, and replace the placeholder values:var access = LimitedAccessFeatures.TryUnlockFeature( "com.microsoft.windows.ai.languagemodel", "YOUR_TOKEN_HERE", // ← replace with token from email "YOUR_ATTESTATION_HERE"); // ← replace with full attestation string from email if (access.Status != LimitedAccessFeatureStatus.Available && access.Status != LimitedAccessFeatureStatus.AvailableWithoutToken) { StatusText.Text = $"Feature access denied (LAF status: {access.Status}). Check your token."; return; }Important
The token is bound to your app's Package Family Name. Do not commit it to a public repository.
Step 7: Build and run
Confirm the build configuration is ARM64.
Press F5 to build and run.
Wait for the status bar to show "Model ready."
Type a prompt, select a skill, and click Generate.
Try these prompts to test each skill:
| Skill | Example prompt |
|---|---|
| Chat | What are the differences between WinUI 3 and WPF? |
| Summarize | Paste a long article or documentation section |
| Rewrite | make this formal: hey can u help me fix this bug |
Troubleshooting
Status shows "not supported on this device"
Your PC either isn't a Copilot+ PC or doesn't meet the minimum Windows version (build 26100+). Check winver and confirm your device has an NPU.
Build error: namespace not found
Confirm Microsoft.WindowsAppSDK version 2.6.4 is installed and the build is set to ARM64
(not x64 or AnyCPU).
API returns access denied / E_ACCESSDENIED
First verify package identity and the systemAIModels capability. Windows App SDK 2.6.4 or
later does not require a LanguageModel token; do not add one as a workaround for a missing
capability. Apps using earlier SDK versions should retain their existing legacy unlock flow,
or upgrade to Windows App SDK 2.6.4 or later. See
LAF compatibility and the optional setup in Step 6.
EnsureReadyAsync fails or hangs
Check Settings > Windows Update for the AI model download progress. The model download requires an internet connection and may take several minutes.