Integración de SDK de inferencia con Foundry Local

Foundry Local se integra con sdk compatibles con OpenAI y clientes HTTP a través de un servidor REST local. En este artículo se muestra cómo conectar la aplicación a modelos de inteligencia artificial local mediante SDK populares.

Prerrequisitos

  • Python 3.11 o posterior instalado. Puede descargar Python desde el sitio web de official Python.

Repositorio de ejemplos

El código de ejemplo completo de este artículo está disponible en el repositorio foundry-samples GitHub. Cómo clonar el repositorio y acceder al directorio de ejemplo:

git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/python/foundry-local/web-server

Instalación de paquetes

Si está desarrollando o distribuyendo en Windows, seleccione la pestaña Windows. El paquete de Windows se integra con el entorno de ejecución Windows ML y ofrece la misma superficie de API con una gama más amplia de aceleración de hardware.

pip install foundry-local-sdk-winml openai

Sugerencia

Se recomienda usar un entorno virtual para evitar conflictos de paquetes. Puede crear un entorno virtual mediante venv o conda.

Uso del SDK de OpenAI con Foundry Local

Copie y pegue el código siguiente en un archivo de Python denominado app.py:

import openai
from foundry_local_sdk import Configuration, FoundryLocalManager


# Initialize the Foundry Local SDK
config = Configuration(app_name="foundry_local_samples")
FoundryLocalManager.initialize(config)
manager = FoundryLocalManager.instance

# Download and register all execution providers.
current_ep = ""


def _ep_progress(ep_name: str, percent: float):
    global current_ep
    if ep_name != current_ep:
        if current_ep:
            print()
        current_ep = ep_name
    print(f"\r  {ep_name:<30}  {percent:5.1f}%", end="", flush=True)


manager.download_and_register_eps(progress_callback=_ep_progress)
if current_ep:
    print()

# Load a model
model = manager.catalog.get_model("qwen2.5-0.5b")
model.download(
    lambda progress: print(
        f"\rDownloading model: {progress:.2f}%",
        end="",
        flush=True,
    )
)
print()
model.load()
print("Model loaded.")

# Start the web service to expose an OpenAI-compatible REST endpoint
manager.start_web_service()
base_url = f"{manager.urls[0]}/v1"

# Use the OpenAI SDK to connect to the local REST endpoint
client = openai.OpenAI(
    base_url=base_url,
    api_key="none",
)

# Make a chat completion request via the REST API
response = client.chat.completions.create(
    model=model.id,
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is the golden ratio?"},
    ],
    stream=True,
)

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

# Clean up
model.unload()
manager.stop_web_service()

Referencia: Referencia del SDK local de FoundryReferencia de la API REST local de Foundry

Ejecute el código con el siguiente comando:

python app.py

Debería ver una respuesta de streaming impresa en el terminal. En la primera ejecución, Foundry Local puede descargar proveedores de ejecución y el modelo, lo que puede tardar unos minutos.

Prerrequisitos

Repositorio de ejemplos

Puede encontrar el código de ejemplo completo de este artículo en el repositorio de ejemplos de Foundry GitHub. Para clonar el repositorio e ir al ejemplo, use:

git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/csharp/foundry-local/foundry-local-web-server

Instalación de paquetes

Si está desarrollando o distribuyendo en Windows, seleccione la pestaña Windows. El paquete de Windows se integra con el entorno de ejecución Windows ML y ofrece la misma superficie de API con una gama más amplia de aceleración de hardware.

dotnet add package Microsoft.AI.Foundry.Local.WinML
dotnet add package OpenAI

Los ejemplos de C# del repositorio de GitHub son proyectos preconfigurados. Si va a compilar desde cero, debe leer la referencia del SDK local de Foundry para obtener más detalles sobre cómo configurar el proyecto de C# con Foundry Local.

Uso del SDK de OpenAI con Foundry Local

Copie y pegue el código siguiente en un archivo de C# denominado Program.cs:

using Microsoft.AI.Foundry.Local;
using OpenAI;
using System.ClientModel;

var config = new Configuration
{
    AppName = "foundry_local_samples",
    LogLevel = Microsoft.AI.Foundry.Local.LogLevel.Information,
    Web = new Configuration.WebService
    {
        Urls = "http://127.0.0.1:52495"
    }
};


// Initialize the singleton instance.
await FoundryLocalManager.CreateAsync(config, Utils.GetAppLogger());
var mgr = FoundryLocalManager.Instance;


// Ensure that any Execution Provider (EP) downloads run and are completed.
// Download and register all execution providers.
var currentEp = "";
await mgr.DownloadAndRegisterEpsAsync((epName, percent) =>
{
    if (epName != currentEp)
    {
        if (currentEp != "") Console.WriteLine();
        currentEp = epName;
    }
    Console.Write($"\r  {epName.PadRight(30)}  {percent,6:F1}%");
});
if (currentEp != "") Console.WriteLine();


// Get the model catalog
var catalog = await mgr.GetCatalogAsync();


// Get a model using an alias
var model = await catalog.GetModelAsync("qwen2.5-0.5b") ?? throw new Exception("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.");


// Start the web service
Console.Write($"Starting web service on {config.Web.Urls}...");
await mgr.StartWebServiceAsync();
Console.WriteLine("done.");

// <<<<<< OPEN AI SDK USAGE >>>>>>
// Use the OpenAI SDK to call the local Foundry web service

ApiKeyCredential key = new ApiKeyCredential("notneeded");
OpenAIClient client = new OpenAIClient(key, new OpenAIClientOptions
{
    Endpoint = new Uri(config.Web.Urls + "/v1"),
});

var chatClient = client.GetChatClient(model.Id);
var completionUpdates = chatClient.CompleteChatStreaming("Why is the sky blue?");

Console.Write($"[ASSISTANT]: ");
foreach (var completionUpdate in completionUpdates)
{
    if (completionUpdate.ContentUpdate.Count > 0)
    {
        Console.Write(completionUpdate.ContentUpdate[0].Text);
    }
}
Console.WriteLine();
// <<<<<< END OPEN AI SDK USAGE >>>>>>

// Tidy up
// Stop the web service and unload model
await mgr.StopWebServiceAsync();
await model.UnloadAsync();

Referencia: Referencia del SDK local de FoundryReferencia de la API REST local de Foundry

dotnet run

Prerrequisitos

  • Node.js versión 20 o posterior instalada.

Repositorio de ejemplos

El código de ejemplo completo de este artículo está disponible en el repositorio foundry-samples GitHub. Cómo clonar el repositorio y acceder al directorio de ejemplo:

git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/javascript/foundry-local/web-server-example

Instalación de paquetes

Si está desarrollando o distribuyendo en Windows, seleccione la pestaña Windows. El paquete de Windows se integra con el entorno de ejecución Windows ML y ofrece la misma superficie de API con una gama más amplia de aceleración de hardware.

npm install foundry-local-sdk-winml openai

Uso del SDK de OpenAI con Foundry Local

Copie y pegue el código siguiente en un archivo JavaScript denominado app.js:

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

// Initialize the Foundry Local SDK
console.log('Initializing Foundry Local SDK...');

const endpointUrl = 'http://localhost:5764';

const manager = FoundryLocalManager.create({
    appName: 'foundry_local_samples',
    logLevel: 'info',
    webServiceUrls: endpointUrl
});
console.log('✓ SDK initialized successfully');

// Download and register all execution providers.
let currentEp = '';
await manager.downloadAndRegisterEps((epName, percent) => {
    if (epName !== currentEp) {
        if (currentEp !== '') process.stdout.write('\n');
        currentEp = epName;
    }
    process.stdout.write(`\r  ${epName.padEnd(30)}  ${percent.toFixed(1).padStart(5)}%`);
});
if (currentEp !== '') process.stdout.write('\n');

// Get the model object
const modelAlias = 'qwen2.5-0.5b'; // Using an available model from the list above
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');

// Start the web service
console.log('\nStarting web service...');
manager.startWebService();
console.log('✓ Web service started');

const openai = new OpenAI({
    baseURL: endpointUrl + '/v1',
    apiKey: 'notneeded',
});

// Example chat completion
console.log('\nTesting chat completion with OpenAI client...');
const response = await openai.chat.completions.create({
    model: model.id,
    messages: [
    {
        role: "user",
        content: "What is the golden ratio?",
    },
    ],
});

console.log(response.choices[0].message.content);

// Tidy up
console.log('Unloading model and stopping web service...');
await model.unload();
manager.stopWebService();
console.log(`✓ Model unloaded and web service stopped`);

Referencia: Referencia del SDK local de FoundryReferencia de la API REST local de Foundry

Ejecute el código con el siguiente comando:

node app.js

Debería ver una respuesta de texto impresa en el terminal. En la primera ejecución, Foundry Local puede descargar proveedores de ejecución y el modelo, lo que puede tardar unos minutos.

Sugerencia

Para obtener un ejemplo de trabajo completo que combina la transcripción de audio y chat, consulte el ejemplo de Chat + Audio en GitHub.

Prerrequisitos

Repositorio de ejemplos

El código de ejemplo completo de este artículo está disponible en el repositorio foundry-samples GitHub. Cómo clonar el repositorio y acceder al directorio de ejemplo:

git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/rust/foundry-local/foundry-local-webserver

Instalación de paquetes

Si está desarrollando o distribuyendo en Windows, seleccione la pestaña Windows. El paquete de Windows se integra con el entorno de ejecución Windows ML y ofrece la misma superficie de API con una gama más amplia de aceleración de hardware.

cargo add foundry-local-sdk --features winml
cargo add tokio --features full
cargo add tokio-stream anyhow

Actualizar el main.rs archivo

Copie y pegue el código siguiente en el archivo rust denominado main.rs:

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

//! Foundry Local Web Server example.
//!
//! Demonstrates how to start a local OpenAI-compatible web server using the
//! Foundry Local SDK, then call it with a standard HTTP client. This is useful
//! when you want to use the OpenAI REST API directly or integrate with tools
//! that expect an OpenAI-compatible endpoint.

use std::io::{self, Write};

use serde_json::json;

use foundry_local_sdk::{FoundryLocalConfig, FoundryLocalManager};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // ── 1. Initialise the SDK ────────────────────────────────────────────
    println!("Initializing Foundry Local SDK...");
    let manager = FoundryLocalManager::create(FoundryLocalConfig::new("foundry_local_samples"))?;
    println!("✓ SDK initialized");

    // Download and register all execution providers.
    manager
        .download_and_register_eps_with_progress(None, {
            let mut current_ep = String::new();
            move |ep_name: &str, percent: f64| {
                if ep_name != current_ep {
                    if !current_ep.is_empty() {
                        println!();
                    }
                    current_ep = ep_name.to_string();
                }
                print!("\r  {:<30}  {:5.1}%", ep_name, percent);
                io::stdout().flush().ok();
            }
        })
        .await?;
    println!();

    // ── 2. Download and load a model ─────────────────────────────────────
    let model_alias = "qwen2.5-0.5b";
    let model = manager.catalog().get_model(model_alias).await?;

    if !model.is_cached().await? {
        print!("Downloading model {model_alias}...");
        model
            .download(Some(move |progress: f64| {
                print!("\rDownloading model... {progress:.1}%");
                io::stdout().flush().ok();
            }))
            .await?;
        println!();
    }

    print!("Loading model {model_alias}...");
    model.load().await?;
    println!("done.");

    // ── 3. Start the web service─────────────────────────────────────────
    print!("Starting web service...");
    manager.start_web_service().await?;
    println!("done.");

    let urls = manager.urls()?;
    let endpoint = urls
        .first()
        .expect("Web service did not return an endpoint");
    println!("Web service listening on: {endpoint}");

    // ── 4. Use the OpenAI-compatible REST API with streaming ────────────
    // Any HTTP client (or OpenAI SDK) can now talk to this endpoint.
    let client = reqwest::Client::new();
    let base_url = endpoint.trim_end_matches('/');

    let mut response = client
        .post(format!("{base_url}/v1/chat/completions"))
        .json(&json!({
            "model": model.id(),
            "messages": [
                { "role": "user", "content": "Why is the sky blue?" }
            ],
            "stream": true
        }))
        .send()
        .await?;

    print!("[ASSISTANT]: ");
    while let Some(chunk) = response.chunk().await? {
        let text = String::from_utf8_lossy(&chunk);
        for line in text.lines() {
            let line = line.trim();
            if let Some(data) = line.strip_prefix("data: ") {
                if data == "[DONE]" {
                    break;
                }
                if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(data) {
                    if let Some(content) = parsed
                        .pointer("/choices/0/delta/content")
                        .and_then(|v| v.as_str())
                    {
                        print!("{content}");
                        io::stdout().flush().ok();
                    }
                }
            }
        }
    }
    println!();

    // ── 5. Clean up ──────────────────────────────────────────────────────
    println!("\nStopping web service...");
    manager.stop_web_service().await?;

    println!("Unloading model...");
    model.unload().await?;

    println!("✓ Done.");
    Ok(())
}

Referencia: Referencia del SDK local de FoundryReferencia de la API REST local de Foundry

Ejecute el código con el siguiente comando:

cargo run

Debería ver una respuesta de streaming impresa en el terminal. En la primera ejecución, Foundry Local puede descargar proveedores de ejecución y el modelo, lo que puede tardar unos minutos.