你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

Foundry Local SDK 参考

重要

  • Foundry Local 以预览版形式提供。 通过公共预览版,可以提前访问正处于开发状态的功能。
  • 正式发布 (GA) 之前,功能、方法和流程可能会发生更改或功能受限。

Foundry Local SDK 通过提供独立于数据平面推理代码的控制平面作,简化了本地环境中的 AI 模型管理。 本参考文档介绍了适用于 Python、JavaScript、C# 和 Rust 的 SDK 实现。

Python SDK 参考

安装

安装 Python 包:

pip install foundry-local-sdk

FoundryLocalManager 类

FoundryLocalManager 类提供用于管理模型、缓存和 Foundry Local 服务的方法。

初始化

from foundry_local import FoundryLocalManager

# Initialize and optionally bootstrap with a model
manager = FoundryLocalManager(alias_or_model_id=None, bootstrap=True)
  • alias_or_model_id:(可选)在启动时下载和加载的别名或模型 ID。
  • bootstrap:(默认值 True) 如果为 True,则启动服务(如果未运行),并在提供时加载模型。

有关别名的注释

此引用中概述的许多方法在签名中都有一个 alias_or_model_id 参数。 可以将 别名模型 ID 作为值传入方法。 使用别名将:

  • 选择适合可用硬件的最佳模型。 例如,如果 Nvidia CUDA GPU 可用,Foundry Local 将选择 CUDA 模型。 如果支持的 NPU 可用,Foundry Local 将选择 NPU 模型。
  • 允许使用较短的名称,而无需记住模型 ID。

小窍门

建议将alias_or_model_id别名传入参数,因为在部署应用程序时,Foundry Local 会在运行时为最终用户的计算机选择最佳模型。

服务管理

方法 签名 DESCRIPTION
is_service_running() () -> bool 检查 Foundry Local 服务是否正在运行。
start_service() () -> None 启动 Foundry Local 服务。
service_uri @property -> str 返回服务 URI。
endpoint @property -> str 返回服务终结点。
api_key @property -> str 返回 API 密钥(从 env 或默认值)。

目录管理

方法 签名 DESCRIPTION
list_catalog_models() () -> list[FoundryModelInfo] 列出目录中的所有可用模型。
refresh_catalog() () -> None 刷新模型目录。
get_model_info() (alias_or_model_id: str, raise_on_not_found=False) -> FoundryModelInfo or None 按别名或 ID 获取模型信息。

缓存管理

方法 签名 DESCRIPTION
get_cache_location() () -> str 返回模型缓存目录路径。
list_cached_models() () -> list[FoundryModelInfo] 列出下载到本地缓存的模型。

模型管理

方法 签名 DESCRIPTION
download_model() (alias_or_model_id: str, token: str = None, force: bool = False) -> FoundryModelInfo 将模型下载到本地缓存。
load_model() (alias_or_model_id: str, ttl: int = 600) -> FoundryModelInfo 将模型加载到推理服务器。
unload_model() (alias_or_model_id: str, force: bool = False) -> None 从推理服务器中卸载模型。
list_loaded_models() () -> list[FoundryModelInfo] 列出服务中当前加载的所有模型。

示例用法

以下代码演示如何使用 FoundryManager 类管理模型并与 Foundry Local 服务交互。

from foundry_local import FoundryLocalManager

# By using an alias, the most suitable model will be selected 
# to your end-user's device.
alias = "phi-3.5-mini"

# Create a FoundryLocalManager instance. This will start the Foundry.
manager = FoundryLocalManager()

# List available models in the catalog
catalog = manager.list_catalog_models()
print(f"Available models in the catalog: {catalog}")

# Download and load a model
model_info = manager.download_model(alias)
model_info = manager.load_model(alias)
print(f"Model info: {model_info}")

# List models in cache
local_models = manager.list_cached_models()
print(f"Models in cache: {local_models}")

# List loaded models
loaded = manager.list_loaded_models()
print(f"Models running in the service: {loaded}")

# Unload a model
manager.unload_model(alias)

与 OpenAI SDK 集成

安装 OpenAI 包:

pip install openai

以下代码演示如何使用 OpenAI SDK 集成 FoundryLocalManager 以与本地模型交互。

import openai
from foundry_local import FoundryLocalManager

# By using an alias, the most suitable model will be downloaded 
# to your end-user's device.
alias = "phi-3.5-mini"

# Create a FoundryLocalManager instance. This will start the Foundry 
# Local service if it is not already running and load the specified model.
manager = FoundryLocalManager(alias)

# The remaining code us es the OpenAI Python SDK to interact with the local model.

# Configure the client to use the local Foundry service
client = openai.OpenAI(
    base_url=manager.endpoint,
    api_key=manager.api_key  # API key is not required for local usage
)

# Set the model to use and generate a streaming response
stream = client.chat.completions.create(
    model=manager.get_model_info(alias).id,
    messages=[{"role": "user", "content": "Why is the sky blue?"}],
    stream=True
)

# Print the streaming response
for chunk in stream:
    if chunk.choices[0].delta.content is not None:
        print(chunk.choices[0].delta.content, end="", flush=True)

JavaScript SDK 参考文档

安装

请从 npm 安装该软件包:

npm install foundry-local-sdk

FoundryLocalManager 类

FoundryLocalManager 类允许你在浏览器和 Node.js 环境中管理模型、控制缓存以及与 Foundry Local 服务交互。

初始化

import { FoundryLocalManager } from "foundry-local-sdk";

const foundryLocalManager = new FoundryLocalManager()

可用选项:

  • serviceUrl:Foundry Local 服务的基 URL
  • fetch:(可选) 适用于 Node.js 等环境的自定义提取实现

有关别名的注释

此引用中概述的许多方法在签名中都有一个 aliasOrModelId 参数。 可以将 别名模型 ID 作为值传入方法。 使用别名将:

  • 选择适合可用硬件的最佳模型。 例如,如果 Nvidia CUDA GPU 可用,Foundry Local 将选择 CUDA 模型。 如果支持的 NPU 可用,Foundry Local 将选择 NPU 模型。
  • 允许使用较短的名称,而无需记住模型 ID。

小窍门

建议将aliasOrModelId别名传入参数,因为在部署应用程序时,Foundry Local 会在运行时为最终用户的计算机选择最佳模型。

服务管理

方法 签名 DESCRIPTION
init() (aliasOrModelId?: string) => Promise<void> 初始化 SDK 并选择性地加载模型。
isServiceRunning() () => Promise<boolean> 检查 Foundry Local 服务是否正在运行。
startService() () => Promise<void> 启动 Foundry Local 服务。
serviceUrl string Foundry Local 服务的基 URL。
endpoint string API 终结点(serviceUrl + /v1)。
apiKey string API 密钥(无)。

目录管理

方法 签名 DESCRIPTION
listCatalogModels() () => Promise<FoundryModelInfo[]> 列出目录中的所有可用模型。
refreshCatalog() () => Promise<void> 刷新模型目录。
getModelInfo() (aliasOrModelId: string, throwOnNotFound = false) => Promise<FoundryModelInfo \| null> 按别名或 ID 获取模型信息。

缓存管理

方法 签名 DESCRIPTION
getCacheLocation() () => Promise<string> 返回模型缓存目录路径。
listCachedModels() () => Promise<FoundryModelInfo[]> 列出下载到本地缓存的模型。

模型管理

方法 签名 DESCRIPTION
downloadModel() (aliasOrModelId: string, token?: string, force = false, onProgress?) => Promise<FoundryModelInfo> 将模型下载到本地缓存。
loadModel() (aliasOrModelId: string, ttl = 600) => Promise<FoundryModelInfo> 将模型加载到推理服务器。
unloadModel() (aliasOrModelId: string, force = false) => Promise<void> 从推理服务器中卸载模型。
listLoadedModels() () => Promise<FoundryModelInfo[]> 列出服务中当前加载的所有模型。

示例用法

以下代码演示如何使用 FoundryLocalManager 类管理模型并与 Foundry Local 服务交互。

import { FoundryLocalManager } from "foundry-local-sdk";

// By using an alias, the most suitable model will be downloaded 
// to your end-user's device.
// TIP: You can find a list of available models by running the 
// following command in your terminal: `foundry model list`.
const alias = "phi-3.5-mini";

const manager = new FoundryLocalManager()

// Initialize the SDK and optionally load a model
const modelInfo = await manager.init(alias)
console.log("Model Info:", modelInfo)

// Check if the service is running
const isRunning = await manager.isServiceRunning()
console.log(`Service running: ${isRunning}`)

// List available models in the catalog
const catalog = await manager.listCatalogModels()

// Download and load a model
await manager.downloadModel(alias)
await manager.loadModel(alias)

// List models in cache
const localModels = await manager.listCachedModels()

// List loaded models
const loaded = await manager.listLoadedModels()

// Unload a model
await manager.unloadModel(alias)

与 OpenAI 客户端集成

安装 OpenAI 包:

npm install openai

以下代码演示如何将 FoundryLocalManager 与 OpenAI 客户端集成,以便与本地模型进行交互。

import { OpenAI } from "openai";
import { FoundryLocalManager } from "foundry-local-sdk";

// By using an alias, the most suitable model will be downloaded 
// to your end-user's device.
// TIP: You can find a list of available models by running the 
// following command in your terminal: `foundry model list`.
const alias = "phi-3.5-mini";

// Create a FoundryLocalManager instance. This will start the Foundry 
// Local service if it is not already running.
const foundryLocalManager = new FoundryLocalManager()

// Initialize the manager with a model. This will download the model 
// if it is not already present on the user's device.
const modelInfo = await foundryLocalManager.init(alias)
console.log("Model Info:", modelInfo)

const openai = new OpenAI({
  baseURL: foundryLocalManager.endpoint,
  apiKey: foundryLocalManager.apiKey,
});

async function streamCompletion() {
    const stream = await openai.chat.completions.create({
      model: modelInfo.id,
      messages: [{ role: "user", content: "What is the golden ratio?" }],
      stream: true,
    });
  
    for await (const chunk of stream) {
      if (chunk.choices[0]?.delta?.content) {
        process.stdout.write(chunk.choices[0].delta.content);
      }
    }
}
  
streamCompletion();

浏览器使用情况

SDK 包含与浏览器兼容的版本,必须在其中手动指定服务 URL:

import { FoundryLocalManager } from "foundry-local-sdk/browser"

// Specify the service URL
// Run the Foundry Local service using the CLI: `foundry service start`
// and use the URL from the CLI output
const endpoint = "ENDPOINT"

const manager = new FoundryLocalManager({serviceUrl: endpoint})

// Note: The `init`, `isServiceRunning`, and `startService` methods 
// are not available in the browser version

注释

浏览器版本不支持initisServiceRunningstartService方法。 在浏览器环境中使用 SDK 之前,必须确保 Foundry Local 服务正在运行。 可以使用 Foundry Local CLI 启动服务: foundry service start。 可以从 CLI 输出中收集服务 URL。

示例用法

import { FoundryLocalManager } from "foundry-local-sdk/browser"

// Specify the service URL
// Run the Foundry Local service using the CLI: `foundry service start`
// and use the URL from the CLI output
const endpoint = "ENDPOINT"

const manager = new FoundryLocalManager({serviceUrl: endpoint})

const alias = 'phi-3.5-mini'

// Get all available models
const catalog = await manager.listCatalogModels()
console.log("Available models in catalog:", catalog)

// Download and load a specific model
await manager.downloadModel(alias)
await manager.loadModel(alias)

// View models in your local cache
const localModels = await manager.listLocalModels()
console.log("Cached models:", catalog)

// Check which models are currently loaded
const loaded = await manager.listLoadedModels()
console.log("Loaded models in inference service:", loaded)

// Unload a model when finished
await manager.unloadModel(alias)

C# SDK 参考

安装

若要使用 Foundry 本地 C# SDK,需要安装 NuGet 包:

dotnet add package Microsoft.AI.Foundry.Local

有关别名的注释

此引用中概述的许多方法在签名中都有一个 aliasOrModelId 参数。 可以将 别名模型 ID 作为值传入方法。 使用别名将:

  • 选择适合可用硬件的最佳模型。 例如,如果 Nvidia CUDA GPU 可用,Foundry Local 将选择 CUDA 模型。 如果支持的 NPU 可用,Foundry Local 将选择 NPU 模型。
  • 允许使用较短的名称,而无需记住模型 ID。

小窍门

建议将aliasOrModelId别名传入参数,因为在部署应用程序时,Foundry Local 会在运行时为最终用户的计算机选择最佳模型。

枚举

DeviceType

表示用于模型执行的设备的类型。

价值 DESCRIPTION
中央处理器 CPU 设备
图形处理器 (GPU) GPU 设备
NPU (神经处理单元) NPU 设备
无效 无效/未知

ExecutionProvider

表示模型推理的执行提供程序。

价值 DESCRIPTION
无效 提供程序无效
CPUExecutionProvider CPU 执行
WebGpuExecutionProvider WebGPU 执行
CUDAExecutionProvider CUDA GPU 执行
QNNExecutionProvider Qualcomm NPU 执行

FoundryLocalManager

管理模型、缓存和 Foundry 本地服务的主要入口点。

建筑

var manager = new FoundryLocalManager();

性能

资产 类型 DESCRIPTION
ServiceUri Uri Foundry Local 服务的基 URI。
端点 Uri API 终结点 (ServiceUri + /v1)。
ApiKey(应用程序密钥) string API 密钥(默认值: "OPENAI_API_KEY") 。
IsServiceRunning bool 指示服务是否正在运行。

服务管理

启动服务
await manager.StartServiceAsync(CancellationToken.None);

启动 Foundry Local 服务(如果尚未运行)。

停止服务
await manager.StopServiceAsync(CancellationToken.None);

停止 Foundry Local 服务。

启动和加载模型(静态帮助程序)
var manager = await FoundryLocalManager.StartModelAsync("aliasOrModelId");

启动服务并加载指定的模型。

目录管理

列出所有目录模型
List<ModelInfo> models = await manager.ListCatalogModelsAsync();

返回目录中的所有可用模型。

刷新目录
manager.RefreshCatalog();

清除缓存的目录,以便在下次访问时重新加载它。

按别名或 ID 获取模型信息
ModelInfo? info = await manager.GetModelInfoAsync("aliasOrModelId");

返回模型信息或 null (如果找不到)。

缓存管理

获取缓存位置
string cachePath = await manager.GetCacheLocationAsync();

返回缓存模型的目录路径。

列出缓存的模型
List<ModelInfo> cached = await manager.ListCachedModelsAsync();

返回下载到本地缓存的模型。

模型管理

下载模型
ModelInfo? model = await manager.DownloadModelAsync("aliasOrModelId");

将模型下载到本地缓存。

下载带有进度指示的模型
await foreach (var progress in manager.DownloadModelWithProgressAsync("aliasOrModelId"))
{
    // progress.Percentage, progress.Status, etc.
}

流式传输下载进度更新。

加载模型
ModelInfo loaded = await manager.LoadModelAsync("aliasOrModelId");

将模型加载到推理服务器。

列出加载的模型
List<ModelInfo> loaded = await manager.ListLoadedModelsAsync();

列出服务中当前加载的所有模型。

卸载模型
await manager.UnloadModelAsync("aliasOrModelId");

从推理服务器中卸载模型。

处理

同时实现 IDisposableIAsyncDisposable 以正确进行清理。

manager.Dispose();
// or
await manager.DisposeAsync();

模型类型

本页记录 Foundry Local C# SDK 用于描述模型、下载和运行时信息的关键数据类型。

PromptTemplate

表示模型的提示模板。

资产 类型 DESCRIPTION
助手 字符串 助手的提示模板。
提示 字符串 用户提示模板。

Runtime

描述模型的运行时环境。

资产 类型 DESCRIPTION
设备类型 DeviceType 设备类型(CPU、GPU 等)。
ExecutionProvider ExecutionProvider 执行提供程序(CUDA、CPU 等)。

ModelSettings

表示特定于模型的参数。

资产 类型 DESCRIPTION
参数 列出<JsonElement> 模型参数集合

ModelInfo

介绍 Foundry Local 目录或缓存中的模型。

资产 类型 DESCRIPTION
ModelId 字符串 唯一模型标识符。
DisplayName 字符串 人类可读的模型名称。
提供者类型 字符串 提供程序类型(例如,“CUDA”、“CPU”)。
Uri 字符串 下载模型的 URI。
版本 字符串 模型版本。
模型类型 字符串 模型类型(例如“llm”、“embedding”)。
PromptTemplate PromptTemplate 模型的提示模板。
发布者 字符串 模型的发布者。
任务 字符串 任务类型(例如“聊天”、“完成”)。
运行时 运行时 运行时环境信息。
文件大小 (Mb) 长整型 模型文件大小(以 MB 为单位)。
ModelSettings ModelSettings 特定于模型的设置。
别名 字符串 模型的别名。
SupportsToolCalling 布尔 是否支持工具调用。
许可证 字符串 许可证标识符。
许可证描述 字符串 许可证说明。
ParentModelUri 字符串 父模型的 URI(如果有)。

ModelDownloadProgress

表示模型下载作业的进度。

资产 类型 DESCRIPTION
百分比 双精度 下载完成百分比(0-100)。
已完成 布尔 下载是否已完成。
ModelInfo ModelInfo? 下载已完成时的模型信息。
错误消息 字符串? 如果下载失败,则显示错误消息。

静态方法:

  • Progress(double percentage):创建进度更新。
  • Completed(ModelInfo modelInfo):生成已完成的进度结果。
  • Error(string errorMessage):创建错误结果。

示例用法

using Microsoft.AI.Foundry.Local;

var manager = new FoundryLocalManager();
await manager.StartServiceAsync();

var models = await manager.ListCatalogModelsAsync();
var alias = "phi-3.5-mini";

await manager.DownloadModelAsync(alias);
await manager.LoadModelAsync(alias);

var loaded = await manager.ListLoadedModelsAsync();

await manager.UnloadModelAsync(alias);

manager.Dispose();

Rust SDK 参考

Rust SDK for Foundry Local 提供了一种管理模型、控制缓存以及与 Foundry Local 服务交互的方法。

安装

若要使用 Foundry Local Rust SDK,请将以下内容添加到你的 Cargo.toml位置:

[dependencies]
foundry-local-sdk = "0.1"

或者,可以使用 cargo 添加 Foundry Local Crate:

cargo add foundry-local

FoundryLocalManager

面向 Foundry Local SDK 操作的管理器。

领域

  • service_uri: Option<String> — Foundry 服务的 URI。
  • client: Option<HttpClient> — API 请求的 HTTP 客户端。
  • catalog_list: Option<Vec<FoundryModelInfo>> — 目录模型的缓存列表。
  • catalog_dict: Option<HashMap<String, FoundryModelInfo>> - 目录模型的缓存字典。
  • timeout: Option<u64> - 可选的 HTTP 客户端超时。

方法

  • pub fn builder() -> FoundryLocalManagerBuilder
    FoundryLocalManager 创建新的生成器。

  • pub fn service_uri(&self) -> Result<&str>
    获取服务 URI 地址。
    返回:Foundry 服务的 URI。

  • fn client(&self) -> Result<&HttpClient>
    获取 HTTP 客户端实例。
    返回:HTTP 客户端。

  • pub fn endpoint(&self) -> Result<String>
    获取服务的终结点。
    返回:终结点 URL。

  • pub fn api_key(&self) -> String
    获取用于身份验证的 API 密钥。
    返回: API 密钥。

  • pub fn is_service_running(&mut self) -> bool
    检查服务是否正在运行,并设置服务 URI(如果找到)。
    返回:true(如果运行),否则返回 false

  • pub fn start_service(&mut self) -> Result<()>
    启动 Foundry 本地服务。

  • pub async fn list_catalog_models(&mut self) -> Result<&Vec<FoundryModelInfo>>
    获取目录中可用模型的列表。

  • pub fn refresh_catalog(&mut self)
    刷新目录缓存。

  • pub async fn get_model_info(&mut self, alias_or_model_id: &str, raise_on_not_found: bool) -> Result<FoundryModelInfo>
    按别名或 ID 获取模型信息。
    参数:

    • alias_or_model_id:别名或模型 ID。
    • raise_on_not_found:如果为 true,则为错误(如果找不到)。
  • pub async fn get_cache_location(&self) -> Result<String>
    以字符串的形式获取缓存位置。

  • pub async fn list_cached_models(&mut self) -> Result<Vec<FoundryModelInfo>>
    列出缓存的模型。

  • pub async fn download_model(&mut self, alias_or_model_id: &str, token: Option<&str>, force: bool) -> Result<FoundryModelInfo>
    下载模型。
    参数:

    • alias_or_model_id:别名或模型 ID。
    • token:可选身份验证令牌。
    • force:如果缓存了,则强制重新下载。
  • pub async fn load_model(&mut self, alias_or_model_id: &str, ttl: Option<i32>) -> Result<FoundryModelInfo>
    加载用于推理的模型。
    参数:

    • alias_or_model_id:别名或模型 ID。
    • ttl:可选的生存时间(以秒为单位)。
  • pub async fn unload_model(&mut self, alias_or_model_id: &str, force: bool) -> Result<()>
    卸载模型。
    参数:

    • alias_or_model_id:别名或模型 ID。
    • force:强制卸载(即使正在使用)。
  • pub async fn list_loaded_models(&mut self) -> Result<Vec<FoundryModelInfo>>
    列出加载的模型。

FoundryLocalManagerBuilder

用于创建实例的 FoundryLocalManager 生成器。

领域

  • alias_or_model_id: Option<String> - 要下载和加载的别名或模型 ID。
  • bootstrap: bool — 是否在未运行的情况下启动服务。
  • timeout_secs: Option<u64> — HTTP 客户端超时(以秒为单位)。

方法

  • pub fn new() -> Self
    创建新的生成器实例。

  • pub fn alias_or_model_id(mut self, alias_or_model_id: impl Into<String>) -> Self
    设置要下载和加载的别名或模型 ID。

  • pub fn bootstrap(mut self, bootstrap: bool) -> Self
    设置是否在未运行时启动服务。

  • pub fn timeout_secs(mut self, timeout_secs: u64) -> Self
    设置 HTTP 客户端超时(以秒为单位)。

  • pub async fn build(self) -> Result<FoundryLocalManager>
    生成 FoundryLocalManager 实例。

FoundryModelInfo

表示有关模型的信息。

领域

  • alias: String — 模型别名。
  • id: String — 模型 ID。
  • version: String — 模型版本。
  • runtime: ExecutionProvider — 执行提供程序(CPU、CUDA 等)。
  • uri: String — 模型 URI。
  • file_size_mb: i32 — 模型文件大小(以 MB 为单位)。
  • prompt_template: serde_json::Value —— 模型的提示模板。
  • provider: String - 提供程序名称。
  • publisher: String — 发布者名称。
  • license: String — 许可证类型。
  • task: String — 模型任务(例如文本生成)。

方法

  • from_list_response(response: &FoundryListResponseModel) -> Self
    根据目录响应创建 FoundryModelInfo

  • to_download_body(&self) -> serde_json::Value
    将模型信息转换为用于下载请求的 JSON 正文。

ExecutionProvider

支持的执行提供程序的枚举。

  • CPU
  • WebGPU
  • CUDA
  • QNN
方法
  • get_alias(&self) -> String
    返回执行提供程序的字符串别名。

ModelRuntime

描述模型的运行时环境。

  • device_type: DeviceType
  • execution_provider: ExecutionProvider