从 JavaScript 调用 Phi Silica(JS 绑定)

本指南介绍如何使用生成的 JS 绑定直接从电子 JavaScript 调用 Windows 应用 SDK Phi 二氧化二次文本摘要 API。

先决条件

在开始本指南之前,请确保具备:

步骤 1:添加 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

步骤 2:从电子主过程调用 Phi 硅

通过 #winapp/bindings导入生成的绑定,创建一个 TextSummarizer并在末尾 createWindow() 调用它,以验证一切是否正常工作:

Important

需要 @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();
};

注释

getReadyState() 返回 Ready、NotReady、DisabledByUser 或 NotSupportedOnCurrentSystem 中的一个。 调用 ensureReadyAsync() 会触发系统下载/初始化模型(如果尚未准备就绪)。

步骤 3:运行

npm start

检查控制台输出 - 你应该看到打印的 Phi Silica 摘要!

如果模型无法在设备上运行,则函数会记录 "Summary: Model is not available"。 如果模型受支持但尚未准备就绪,则函数将调用 ensureReadyAsync() 下载或初始化模型。 检查当前 Phi Silica 要求,了解支持的 NPU 或 GPU 硬件、Windows 和 Windows 应用 SDK 版本以及 GPU 驱动程序。 此外,请确保清单包含 systemAIModels ,并且该模型未被用户禁用。

在这里,你可以按自己喜欢的任何方式将摘要生成器集成到应用中——无论是通过预加载脚本将其暴露给渲染进程,将其接入 IPC 处理程序,还是直接在主进程中调用它。

后续步骤

恭喜! 现在,你可以直接在 JavaScript 中调用 Phi Silica——无需 C# 扩展程序,也无需 node-gyp 构建步骤。 🎉

现在,你已准备好:

或者浏览其他指南:

其他资源