從 JavaScript 呼叫 Phi Silica(JS 繫結)

本指南說明如何直接從 Electron JavaScript 呼叫 Windows 應用程式 SDK Phi Silica 文字摘要 API,方法是使用產生的 JS 綁定。

先決條件

在開始本指南前,請確保你已經:

步驟一:加入 AI 功能

Phi Silica需要具備這項 systemAIModels 能力。 它位於其 自己的systemai 命名空間中——不是 rescap——因此請在 <Package> 上宣告該命名空間並將其標記為可忽略,然後新增該功能:

<Package
  xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
  xmlns:systemai="http://schemas.microsoft.com/appx/manifest/systemai/windows10"
  IgnorableNamespaces="rescap systemai">
  ...
  <Capabilities>
    <rescap:Capability Name="runFullTrust" />
    <systemai:Capability Name="systemAIModels" />
  </Capabilities>
</Package>

它還需要 TargetDeviceFamily/@MaxVersionTested 至少為 10.0.26226.0。

更改清單後,重新整理除錯身份:

npx winapp node add-electron-debug-identity

步驟二:從電子主製程呼叫 Phi Silica。

透過 #winapp/bindings 匯入產生的繫結,建立一個 TextSummarizer,並在 createWindow() 的最後呼叫它,以確認一切都正常運作:

需要 @microsoft/dynwinrt-codegen ≥ 0.1.0-preview.8 — 請參閱 開始使用 Electron,以了解舊版專案的替代方案。

// src/index.js (Electron main, CommonJS)
const {
  AIFeatureReadyState,
  LanguageModel,
  TextSummarizer,
} = require('#winapp/bindings');

const callPhiSilica = async () => {
  console.log('Summarizing with Phi Silica:');

  const readyState = LanguageModel.getReadyState();
  if (readyState !== AIFeatureReadyState.Ready && readyState !== AIFeatureReadyState.NotReady) {
    console.log('Summary: Model is not available');
    return;
  }
  if (readyState === AIFeatureReadyState.NotReady) {
    await LanguageModel.ensureReadyAsync();
  }

  const languageModel = await LanguageModel.createAsync();
  try {
    const summarizer = TextSummarizer.createInstance(languageModel);
    const result = await summarizer.summarizeParagraphAsync(
      "The Windows App Development CLI lets Electron apps call Windows-native APIs from JavaScript. Package identity enables features such as notifications and background tasks."
    );
    console.log('Summary:', result.text);
  } finally {
    languageModel.close();
  }
};

const createWindow = () => {
  // ... existing window creation code ...

  // Test the Phi Silica AI API
  callPhiSilica();
};

Note

getReadyState() 會回傳 Ready、NotReady、DisabledByUser 或 NotSupportedOnCurrentSystem 其中之一。 如果模型還沒準備好,呼叫 ensureReadyAsync() 會觸發系統下載/初始化。

步驟三:執行

npm start

檢查主控台輸出,你應該會看到列印出的 Phi Silica 摘要!

若該模型無法在裝置上取得,函數會記錄 "Summary: Model is not available"。 請確保你使用的是支援的硬體(Copilot+ PC),且清單中包含 systemAIModels。

接著,你可以隨心所欲地將摘要器整合到應用程式中——透過預載入腳本暴露給渲染器、接線到 IPC 處理器,或直接在主程序中呼叫。

後續步驟

祝賀! 你現在直接從 JavaScript 呼叫 Phi Silica——沒有 C# 插件,也沒有 node-gyp 建置步驟。 🎉

現在你準備好:

或者探索其他指南:

其他資源