Foundry Local SDK には、テキストをデバイス上の数値ベクトルに変換する埋め込み API が用意されています。 これらのベクトルは、類似性検索、分類、クラスタリング、および取得拡張生成 (RAG) に使用します。
SDK では、専用の埋め込みクライアントを使用した単一入力とバッチ埋め込みの両方の生成がサポートされています。
前提 条件
- Python 3.11 以降がインストールされています。
サンプル リポジトリ
この記事の完全なサンプル コードは、foundry-samples GitHub リポジトリにあります。 リポジトリを複製し、サンプルに移動するには、次を使用します。
git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/python/foundry-local/embeddings
パッケージをインストールする
Windowsで開発または出荷する場合は、Windows タブを選択します。Windows パッケージは、Windows ML ランタイムと統合され、同じ API サーフェス領域に幅広いハードウェア アクセラレーションを提供します。
pip install foundry-local-sdk-winml openai
テキスト埋め込みを生成する
次のコードをコピーして、app.py という名前のPython ファイルに貼り付けます。
from foundry_local_sdk import Configuration, FoundryLocalManager
def main():
# Initialize the Foundry Local SDK
config = Configuration(app_name="foundry_local_samples")
FoundryLocalManager.initialize(config)
manager = FoundryLocalManager.instance
# Select and load an embedding model from the catalog
model = manager.catalog.get_model("qwen3-embedding-0.6b")
model.download(
lambda progress: print(
f"\rDownloading model: {progress:.2f}%",
end="",
flush=True,
)
)
print()
model.load()
print("Model loaded and ready.")
# Get an embedding client
client = model.get_embedding_client()
# Generate a single embedding
print("\n--- Single Embedding ---")
response = client.generate_embedding("The quick brown fox jumps over the lazy dog")
embedding = response.data[0].embedding
print(f"Dimensions: {len(embedding)}")
print(f"First 5 values: {embedding[:5]}")
# Generate embeddings for multiple inputs
print("\n--- Batch Embeddings ---")
batch_response = client.generate_embeddings(
[
"Machine learning is a subset of artificial intelligence",
"The capital of France is Paris",
"Rust is a systems programming language",
]
)
print(f"Number of embeddings: {len(batch_response.data)}")
for i, data in enumerate(batch_response.data):
print(f" [{i}] Dimensions: {len(data.embedding)}")
# Clean up
model.unload()
print("\nModel unloaded.")
if __name__ == "__main__":
main()
次のコマンドを使用してコードを実行します。
python app.py
トラブルシューティング
-
ModuleNotFoundError: No module named 'foundry_local_sdk':pip install foundry-local-sdkを実行して SDK をインストールします。 -
Model not found: オプションのモデル一覧スニペットを実行して、デバイスで使用可能なエイリアスを見つけ、get_modelに渡されたエイリアスを更新します。 - 最初の実行が遅い: モデルのダウンロードには、アプリを初めて実行するときに時間がかかる場合があります。
前提 条件
- .NET 8.0 SDK 以降がインストールされています。
サンプル リポジトリ
この記事の完全なサンプル コードは、Foundry サンプル GitHub リポジトリにあります。 リポジトリを複製し、サンプルに移動するには、次を使用します。
git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/csharp/foundry-local/embeddings
パッケージをインストールする
Windowsで開発または出荷する場合は、Windows タブを選択します。Windows パッケージは、Windows ML ランタイムと統合され、同じ API サーフェス領域に幅広いハードウェア アクセラレーションを提供します。
dotnet add package Microsoft.AI.Foundry.Local.WinML
dotnet add package OpenAI
GitHub リポジトリの C# サンプルは、事前構成済みのプロジェクトです。 最初からビルドする場合は、Foundry Local を使用して C# プロジェクトを設定する方法の詳細については、 Foundry Local SDK リファレンスを参照 してください。
テキスト埋め込みを生成する
次のコードをコピーして、 Program.csという名前の C# ファイルに貼り付けます。
using Microsoft.AI.Foundry.Local;
var config = new Configuration
{
AppName = "foundry_local_samples",
LogLevel = Microsoft.AI.Foundry.Local.LogLevel.Information
};
// Initialize the singleton instance.
await FoundryLocalManager.CreateAsync(config, Utils.GetAppLogger());
var mgr = FoundryLocalManager.Instance;
// Get the model catalog
var catalog = await mgr.GetCatalogAsync();
// Get an embedding model
var model = await catalog.GetModelAsync("qwen3-embedding-0.6b") ?? throw new Exception("Embedding model not found");
// Download the model (the method skips download if already cached)
await model.DownloadAsync(progress =>
{
Console.Write($"\rDownloading model: {progress:F2}%");
if (progress >= 100f)
{
Console.WriteLine();
}
});
// Load the model
Console.Write($"Loading model {model.Id}...");
await model.LoadAsync();
Console.WriteLine("done.");
// Get an embedding client
var embeddingClient = await model.GetEmbeddingClientAsync();
// Generate a single embedding
Console.WriteLine("\n--- Single Embedding ---");
var response = await embeddingClient.GenerateEmbeddingAsync("The quick brown fox jumps over the lazy dog");
var embedding = response.Data[0].Embedding;
Console.WriteLine($"Dimensions: {embedding.Count}");
Console.WriteLine($"First 5 values: [{string.Join(", ", embedding.Take(5).Select(v => v.ToString("F6")))}]");
// Generate embeddings for multiple inputs
Console.WriteLine("\n--- Batch Embeddings ---");
var batchResponse = await embeddingClient.GenerateEmbeddingsAsync([
"Machine learning is a subset of artificial intelligence",
"The capital of France is Paris",
"Rust is a systems programming language"
]);
Console.WriteLine($"Number of embeddings: {batchResponse.Data.Count}");
for (var i = 0; i < batchResponse.Data.Count; i++)
{
Console.WriteLine($" [{i}] Dimensions: {batchResponse.Data[i].Embedding.Count}");
}
// Tidy up - unload the model
await model.UnloadAsync();
Console.WriteLine("\nModel unloaded.");
次のコマンドを使用してコードを実行します。
dotnet run
トラブルシューティング
-
net8.0を参照するビルド エラー: .NET 8.0 SDK をインストールし、アプリをリビルドします。 -
Model not found: オプションのモデル一覧スニペットを実行して、デバイスで使用可能なエイリアスを見つけ、GetModelAsyncに渡されたエイリアスを更新します。 - 最初の実行が遅い: モデルのダウンロードには、アプリを初めて実行するときに時間がかかる場合があります。
前提 条件
- Node.js 20 以降がインストールされています。
サンプル リポジトリ
この記事の完全なサンプル コードは、foundry-samples GitHub リポジトリにあります。 リポジトリを複製し、サンプルに移動するには、次を使用します。
git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/javascript/foundry-local/embeddings
パッケージをインストールする
Windowsで開発または出荷する場合は、Windows タブを選択します。Windows パッケージは、Windows ML ランタイムと統合され、同じ API サーフェス領域に幅広いハードウェア アクセラレーションを提供します。
npm install foundry-local-sdk-winml openai
テキスト埋め込みを生成する
次のコードをコピーして、 app.jsという名前の JavaScript ファイルに貼り付けます。
import { FoundryLocalManager } from 'foundry-local-sdk';
// Initialize the Foundry Local SDK
console.log('Initializing Foundry Local SDK...');
const manager = FoundryLocalManager.create({
appName: 'foundry_local_samples',
logLevel: 'info'
});
console.log('✓ SDK initialized successfully');
// Get an embedding model
const modelAlias = 'qwen3-embedding-0.6b';
const model = await manager.catalog.getModel(modelAlias);
// Download the model
console.log(`\nDownloading model ${modelAlias}...`);
await model.download((progress) => {
process.stdout.write(`\rDownloading... ${progress.toFixed(2)}%`);
});
console.log('\n✓ Model downloaded');
// Load the model
console.log(`\nLoading model ${modelAlias}...`);
await model.load();
console.log('✓ Model loaded');
// Create embedding client
console.log('\nCreating embedding client...');
const embeddingClient = model.createEmbeddingClient();
console.log('✓ Embedding client created');
// Generate a single embedding
console.log('\n--- Single Embedding ---');
const response = await embeddingClient.generateEmbedding(
'The quick brown fox jumps over the lazy dog'
);
const embedding = response.data[0].embedding;
console.log(`Dimensions: ${embedding.length}`);
console.log(`First 5 values: [${embedding.slice(0, 5).map(v => v.toFixed(6)).join(', ')}]`);
// Generate embeddings for multiple inputs
console.log('\n--- Batch Embeddings ---');
const batchResponse = await embeddingClient.generateEmbeddings([
'Machine learning is a subset of artificial intelligence',
'The capital of France is Paris',
'Rust is a systems programming language'
]);
console.log(`Number of embeddings: ${batchResponse.data.length}`);
for (let i = 0; i < batchResponse.data.length; i++) {
console.log(` [${i}] Dimensions: ${batchResponse.data[i].embedding.length}`);
}
// Unload the model
console.log('\nUnloading model...');
await model.unload();
console.log('✓ Model unloaded');
次のコマンドを使用してコードを実行します。
node app.js
トラブルシューティング
-
Cannot find module 'foundry-local-sdk':npm install foundry-local-sdkを実行して SDK をインストールします。 -
Model not found: モデルのエイリアスが正しいことを確認します。manager.catalog.getModels()を使用して、使用可能なモデルを一覧表示します。 - 最初の実行が遅い: モデルのダウンロードには、アプリを初めて実行するときに時間がかかる場合があります。
前提 条件
- Rust と Cargo がインストールされている (Rust 1.70.0 以降)。
サンプル リポジトリ
この記事の完全なサンプル コードは、foundry-samples GitHub リポジトリにあります。 リポジトリを複製し、サンプルに移動するには、次を使用します。
git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/rust/foundry-local/embeddings
パッケージをインストールする
Windowsで開発または出荷する場合は、Windows タブを選択します。Windows パッケージは、Windows ML ランタイムと統合され、同じ API サーフェス領域に幅広いハードウェア アクセラレーションを提供します。
cargo add foundry-local-sdk --features winml
cargo add tokio --features full
cargo add tokio-stream anyhow
テキスト埋め込みを生成する
main.rsの内容を次のコードに置き換えます。
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
use foundry_local_sdk::{FoundryLocalConfig, FoundryLocalManager};
const ALIAS: &str = "qwen3-embedding-0.6b";
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Native Embeddings");
println!("=================\n");
// ── 1. Initialise the manager ────────────────────────────────────────
let manager = FoundryLocalManager::create(FoundryLocalConfig::new("foundry_local_samples"))?;
// ── 2. Pick a model and ensure it is downloaded ─────────────────────
let model = manager.catalog().get_model(ALIAS).await?;
println!("Model: {} (id: {})", model.alias(), model.id());
if !model.is_cached().await? {
println!("Downloading model...");
model
.download(Some(|progress: f64| {
print!("\r {progress:.1}%");
std::io::Write::flush(&mut std::io::stdout()).ok();
}))
.await?;
println!();
}
println!("Loading model...");
model.load().await?;
println!("✓ Model loaded\n");
// ── 3. Create an embedding client ───────────────────────────────────
let client = model.create_embedding_client();
// ── 4. Single embedding ─────────────────────────────────────────────
println!("--- Single Embedding ---");
let response = client
.generate_embedding("The quick brown fox jumps over the lazy dog")
.await?;
let embedding = &response.data[0].embedding;
println!("Dimensions: {}", embedding.len());
println!(
"First 5 values: {:?}",
&embedding[..5]
);
// ── 5. Batch embeddings ─────────────────────────────────────────────
println!("\n--- Batch Embeddings ---");
let batch_response = client
.generate_embeddings(&[
"Machine learning is a subset of artificial intelligence",
"The capital of France is Paris",
"Rust is a systems programming language",
])
.await?;
println!("Number of embeddings: {}", batch_response.data.len());
for (i, data) in batch_response.data.iter().enumerate() {
println!(" [{i}] Dimensions: {}", data.embedding.len());
}
// ── 6. Unload the model ─────────────────────────────────────────────
println!("\nUnloading model...");
model.unload().await?;
println!("Done.");
Ok(())
}
次のコマンドを使用してコードを実行します。
cargo run
トラブルシューティング
-
ビルド エラー: Rust 1.70.0 以降がインストールされていることを確認します。
rustup updateを実行して最新バージョンを取得します。 -
Model not found: モデルのエイリアスが正しいことを確認します。manager.catalog().get_models().await?を使用して、使用可能なモデルを一覧表示します。 - 最初の実行が遅い: モデルのダウンロードには、アプリを初めて実行するときに時間がかかる場合があります。