Lernprogramm: Erstellen eines Dokumentzusammenfassers

Erstellen Sie eine Anwendung, die Textdateien liest und präzise Zusammenfassungen generiert – ganz auf Ihrem Gerät. Dies ist nützlich, wenn Sie den Inhalt von Dokumenten schnell verstehen müssen, ohne sie vollständig zu lesen, und wenn die Dokumente vertrauliche Informationen enthalten, die Ihren Computer nicht verlassen sollten.

In diesem Tutorial erfahren Sie, wie:

  • Einrichten eines Projekts und Installieren des Foundry Local SDK
  • Lesen eines Textdokuments aus dem Dateisystem
  • Laden eines Modells und Generieren einer Zusammenfassung
  • Steuern der Zusammenfassungsausgabe mit Systemaufforderungen
  • Verarbeiten mehrerer Dokumente in einem Batch
  • Bereinigen von Ressourcen

Voraussetzungen

  • Ein Windows, macOS oder Linux-Computer mit mindestens 8 GB RAM.

Beispielrepository

Den vollständigen Beispielcode für diesen Artikel finden Sie in den Foundry-Beispielen GitHub Repository. Um das Repository zu klonen und zum Beispielprojekt zu wechseln, verwenden Sie folgenden Befehl:

git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/csharp/foundry-local/tutorial-document-summarizer

Pakete installieren

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

Die C#-Beispiele im GitHub Repository sind vorkonfigurierte Projekte. Wenn Sie von Grund auf neu erstellen, sollten Sie die Referenz zum Foundry Local SDK lesen, um weitere Details zum Einrichten Ihres C#-Projekts mit Foundry Local zu erhalten.

Lesen eines Textdokuments

Bevor Sie etwas zusammenfassen, benötigen Sie ein Beispieldokument, mit dem Sie arbeiten können. Erstellen Sie eine Datei mit dem Namen document.txt in Ihrem Projektverzeichnis und fügen Sie den folgenden Inhalt hinzu.

Automated testing is a practice in software development where tests are written and executed
by specialized tools rather than performed manually. There are several categories of automated
tests, including unit tests, integration tests, and end-to-end tests. Unit tests verify that
individual functions or methods behave correctly in isolation. Integration tests check that
multiple components work together as expected. End-to-end tests simulate real user workflows
across the entire application.

Adopting automated testing brings measurable benefits to a development team. It catches
regressions early, before they reach production. It reduces the time spent on repetitive
manual verification after each code change. It serves as living documentation of expected
behavior, which helps new team members understand the codebase. Continuous integration
pipelines rely on automated tests to gate deployments and maintain release quality.

Effective test suites follow a few guiding principles. Tests should be deterministic, meaning
they produce the same result every time they run. Tests should be independent, so that one
failing test does not cascade into false failures elsewhere. Tests should run fast, because
slow tests discourage developers from running them frequently. Finally, tests should be
maintained alongside production code so they stay accurate as the application evolves.

Öffnen Sie nun Program.cs und fügen Sie den folgenden Code zum Lesen des Dokuments hinzu:

var target = args.Length > 0 ? args[0] : "document.txt";

Der Code akzeptiert einen optionalen Dateipfad als Befehlszeilenargument und fällt auf document.txt zurück, wenn keiner angegeben wird.

Generieren einer Zusammenfassung

Initialisieren Sie das Lokale SDK für Foundry, laden Sie ein Modell, und senden Sie den Dokumentinhalt zusammen mit einer Systemaufforderung, die das Modell zur Zusammenfassung anweist.

Ersetzen Sie den Inhalt von Program.cs durch den folgenden Code.

var systemPrompt =
    "Summarize the following document into concise bullet points. " +
    "Focus on the key points and main ideas.";

// <file_reading>
var target = args.Length > 0 ? args[0] : "document.txt";
// </file_reading>

if (Directory.Exists(target))
{
    await SummarizeDirectoryAsync(model, target, systemPrompt, ct);
}
else
{
    Console.WriteLine($"--- {Path.GetFileName(target)} ---");
    await SummarizeFileAsync(model, target, systemPrompt, ct);
}

Die Methode GetModelAsync akzeptiert einen Modellalias, bei dem es sich um einen kurzen Anzeigenamen handelt, der einem bestimmten Modell im Katalog zugeordnet ist. Die DownloadAsync Methode ruft die Modellgewichtung in Ihren lokalen Cache ab (und überspringt den Download, wenn sie bereits zwischengespeichert wurden), und LoadAsync macht das Modell zur Ableitung bereit. Die Systemaufforderung weist das Modell an, Aufzählungszeichenzusammenfassungen zu erstellen, die sich auf wichtige Ideen konzentrieren.

Kontrollieren der Zusammenfassungsausgabe

In verschiedenen Situationen sind unterschiedliche Zusammenfassungsstile erforderlich. Sie können die Systemaufforderung ändern, um zu steuern, wie das Modell seine Ausgabe strukturiert. Hier sind drei nützliche Varianten:

Aufzählungszeichen (Standardeinstellung aus dem vorherigen Schritt):

var systemPrompt =
    "Summarize the following document into concise bullet points. " +
    "Focus on the key points and main ideas.";

Zusammenfassung mit einem Absatz:

var systemPrompt =
    "Summarize the following document in a single, concise paragraph. " +
    "Capture the main argument and supporting points.";

Wesentliche Punkte:

var systemPrompt =
    "Extract the three most important takeaways from the following document. " +
    "Number each takeaway and keep each to one or two sentences.";

Wenn Sie einen anderen Stil ausprobieren möchten, ersetzen Sie den Content Wert in der Systemmeldung durch eine der Vorgaben. Das Modell folgt den Anweisungen in der Systemaufforderung, um das Format und die Tiefe der Zusammenfassung zu gestalten.

Verarbeiten mehrerer Dokumente

Erweitern Sie die Anwendung, um jede .txt Datei in einem Verzeichnis zusammenzufassen. Dies ist nützlich, wenn Sie über einen Ordner mit Dokumenten verfügen, die alle Zusammenfassungen benötigen.

Die folgende Methode durchläuft alle .txt Dateien in einem bestimmten Verzeichnis und fasst die einzelnen Dateien zusammen:

async Task SummarizeDirectoryAsync(
    dynamic chatClient,
    string directory,
    string systemPrompt,
    CancellationToken ct)
{
    var txtFiles = Directory.GetFiles(directory, "*.txt")
        .OrderBy(f => f)
        .ToArray();

    if (txtFiles.Length == 0)
    {
        Console.WriteLine($"No .txt files found in {directory}");
        return;
    }

    foreach (var txtFile in txtFiles)
    {
        var fileContent = await File.ReadAllTextAsync(txtFile, ct);
        var msgs = new List<ChatMessage>
        {
            new ChatMessage { Role = "system", Content = systemPrompt },
            new ChatMessage { Role = "user", Content = fileContent }
        };

        Console.WriteLine($"--- {Path.GetFileName(txtFile)} ---");
        var resp = await chatClient.CompleteChatAsync(msgs, ct);
        Console.WriteLine(resp.Choices[0].Message.Content);
        Console.WriteLine();
    }
}

Jede Datei wird gelesen, mit derselben Systemaufforderung gekoppelt und unabhängig an das Modell gesendet. Das Modell trägt keinen Kontext zwischen Dateien, sodass jede Zusammenfassung eigenständig ist.

Vollständiger Code

Ersetzen Sie den Inhalt von Program.cs durch den folgenden vollständigen Code:

// <imports>
using Microsoft.AI.Foundry.Local;
using Microsoft.Extensions.Logging;
// </imports>

// <init>
CancellationToken ct = CancellationToken.None;

var config = new Configuration
{
    AppName = "foundry_local_samples",
    LogLevel = Microsoft.AI.Foundry.Local.LogLevel.Information
};

using var loggerFactory = LoggerFactory.Create(builder =>
{
    builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information);
});
var logger = loggerFactory.CreateLogger<Program>();

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

// 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();

// Select and load a model from the catalog
var catalog = await mgr.GetCatalogAsync();
var model = await catalog.GetModelAsync("qwen2.5-0.5b")
    ?? throw new Exception("Model not found");

await model.DownloadAsync(progress =>
{
    Console.Write($"\rDownloading model: {progress:F2}%");
    if (progress >= 100f) Console.WriteLine();
});

await model.LoadAsync();
Console.WriteLine("Model loaded and ready.\n");

// </init>

// <summarization>
var systemPrompt =
    "Summarize the following document into concise bullet points. " +
    "Focus on the key points and main ideas.";

// <file_reading>
var target = args.Length > 0 ? args[0] : "document.txt";
// </file_reading>

if (Directory.Exists(target))
{
    await SummarizeDirectoryAsync(model, target, systemPrompt, ct);
}
else
{
    Console.WriteLine($"--- {Path.GetFileName(target)} ---");
    await SummarizeFileAsync(model, target, systemPrompt, ct);
}
// </summarization>

// Clean up
await model.UnloadAsync();
Console.WriteLine("\nModel unloaded. Done!");

async Task SummarizeFileAsync(
    IModel loadedModel,
    string filePath,
    string prompt,
    CancellationToken token)
{
    var fileContent = await File.ReadAllTextAsync(filePath, token);
    using var session = new ChatSession(loadedModel);
    using var request = new Request();
    request.AddItem(MessageItem.System(prompt));
    request.AddItem(MessageItem.User(fileContent));
    using var response = await session.ProcessRequestAsync(request, token);
    Console.WriteLine(string.Concat(
        response.OfType<MessageItem>()
            .SelectMany(message => message.Parts)
            .OfType<TextItem>()
            .Where(text => text.Type == TextItemType.Default)
            .Select(text => text.Text)));
}

async Task SummarizeDirectoryAsync(
    IModel loadedModel,
    string directory,
    string prompt,
    CancellationToken token)
{
    var txtFiles = Directory.GetFiles(directory, "*.txt")
        .OrderBy(f => f)
        .ToArray();

    if (txtFiles.Length == 0)
    {
        Console.WriteLine($"No .txt files found in {directory}");
        return;
    }

    foreach (var txtFile in txtFiles)
    {
        Console.WriteLine($"--- {Path.GetFileName(txtFile)} ---");
        await SummarizeFileAsync(loadedModel, txtFile, prompt, token);
        Console.WriteLine();
    }
}

Fassen Sie eine einzelne Datei zusammen:

dotnet run -- document.txt

Oder fassen Sie jede .txt Datei in einem Verzeichnis zusammen:

dotnet run -- ./docs

Es wird eine ähnliche Ausgabe angezeigt wie:

Downloading model: 100.00%
Model loaded and ready.

--- document.txt ---
- Automated testing uses specialized tools to execute tests instead of manual verification.
- Tests fall into three main categories: unit tests (individual functions), integration tests
  (component interactions), and end-to-end tests (full user workflows).
- Key benefits include catching regressions early, reducing manual effort, serving as living
  documentation, and gating deployments through continuous integration pipelines.
- Effective test suites should be deterministic, independent, fast, and maintained alongside
  production code.

Model unloaded. Done!

Beispielrepository

Der vollständige Beispielcode für diesen Artikel ist in den Gießereibeispielen GitHub Repository verfügbar. So klonen Sie das Repository, und navigieren Sie zur Beispielverwendung:

git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/javascript/foundry-local/tutorial-document-summarizer

Pakete installieren

npm install foundry-local-sdk openai

Lesen eines Textdokuments

Bevor Sie etwas zusammenfassen, benötigen Sie ein Beispieldokument, mit dem Sie arbeiten können. Erstellen Sie eine Datei mit dem Namen document.txt in Ihrem Projektverzeichnis und fügen Sie den folgenden Inhalt hinzu.

Automated testing is a practice in software development where tests are written and executed
by specialized tools rather than performed manually. There are several categories of automated
tests, including unit tests, integration tests, and end-to-end tests. Unit tests verify that
individual functions or methods behave correctly in isolation. Integration tests check that
multiple components work together as expected. End-to-end tests simulate real user workflows
across the entire application.

Adopting automated testing brings measurable benefits to a development team. It catches
regressions early, before they reach production. It reduces the time spent on repetitive
manual verification after each code change. It serves as living documentation of expected
behavior, which helps new team members understand the codebase. Continuous integration
pipelines rely on automated tests to gate deployments and maintain release quality.

Effective test suites follow a few guiding principles. Tests should be deterministic, meaning
they produce the same result every time they run. Tests should be independent, so that one
failing test does not cascade into false failures elsewhere. Tests should run fast, because
slow tests discourage developers from running them frequently. Finally, tests should be
maintained alongside production code so they stay accurate as the application evolves.

Erstellen Sie nun eine Datei namens, index.js und fügen Sie den folgenden Code zum Lesen des Dokuments hinzu:

const target = process.argv[2] || 'document.txt';

Das Skript akzeptiert einen optionalen Dateipfad als Befehlszeilenargument und fällt zurück, document.txt wenn keines angegeben wird.

Generieren einer Zusammenfassung

Initialisieren Sie das Lokale SDK für Foundry, laden Sie ein Modell, und senden Sie den Dokumentinhalt zusammen mit einer Systemaufforderung, die das Modell zur Zusammenfassung anweist.

Ersetzen Sie den Inhalt von index.js durch den folgenden Code.

const systemPrompt =
    'Summarize the following document into concise bullet points. ' +
    'Focus on the key points and main ideas.';

// <file_reading>
const target = process.argv[2] || 'document.txt';
// </file_reading>

try {
    const stats = statSync(target);
    if (stats.isDirectory()) {
        await summarizeDirectory(model, target, systemPrompt);
    } else {
        console.log(`--- ${basename(target)} ---`);
        const session = new ChatSession(model);
        await summarizeFile(session, target, systemPrompt);
        session.dispose();
    }
} catch {
    console.log(`--- ${basename(target)} ---`);
    const session = new ChatSession(model);
    await summarizeFile(session, target, systemPrompt);
    session.dispose();
}

Die Methode getModel akzeptiert einen Modellalias, bei dem es sich um einen kurzen Anzeigenamen handelt, der einem bestimmten Modell im Katalog zugeordnet ist. Die download Methode ruft die Modellgewichtung in Ihren lokalen Cache ab (und überspringt den Download, wenn sie bereits zwischengespeichert wurden), und load macht das Modell zur Ableitung bereit. Die Systemaufforderung weist das Modell an, Aufzählungszeichenzusammenfassungen zu erstellen, die sich auf wichtige Ideen konzentrieren.

Kontrollieren der Zusammenfassungsausgabe

In verschiedenen Situationen sind unterschiedliche Zusammenfassungsstile erforderlich. Sie können die Systemaufforderung ändern, um zu steuern, wie das Modell seine Ausgabe strukturiert. Hier sind drei nützliche Varianten:

Aufzählungszeichen (Standardeinstellung aus dem vorherigen Schritt):

const systemPrompt =
    'Summarize the following document into concise bullet points. ' +
    'Focus on the key points and main ideas.';

Zusammenfassung mit einem Absatz:

const systemPrompt =
    'Summarize the following document in a single, concise paragraph. ' +
    'Capture the main argument and supporting points.';

Wesentliche Punkte:

const systemPrompt =
    'Extract the three most important takeaways from the following document. ' +
    'Number each takeaway and keep each to one or two sentences.';

Wenn Sie einen anderen Stil ausprobieren möchten, ersetzen Sie den content Wert in der Systemmeldung durch eine der Vorgaben. Das Modell folgt den Anweisungen in der Systemaufforderung, um das Format und die Tiefe der Zusammenfassung zu gestalten.

Verarbeiten mehrerer Dokumente

Erweitern Sie die Anwendung, um jede .txt Datei in einem Verzeichnis zusammenzufassen. Dies ist nützlich, wenn Sie über einen Ordner mit Dokumenten verfügen, die alle Zusammenfassungen benötigen.

Die folgende Funktion durchläuft alle .txt Dateien in einem bestimmten Verzeichnis und fasst die einzelnen Dateien zusammen:

import { readdirSync } from 'fs';
import { join, basename } from 'path';

async function summarizeDirectory(chatClient, directory, systemPrompt) {
    const txtFiles = readdirSync(directory)
        .filter(f => f.endsWith('.txt'))
        .sort();

    if (txtFiles.length === 0) {
        console.log(`No .txt files found in ${directory}`);
        return;
    }

    for (const fileName of txtFiles) {
        const fileContent = readFileSync(join(directory, fileName), 'utf-8');
        const msgs = [
            { role: 'system', content: systemPrompt },
            { role: 'user', content: fileContent }
        ];

        console.log(`--- ${fileName} ---`);
        const resp = await chatClient.completeChat(msgs);
        console.log(resp.choices[0]?.message?.content);
        console.log();
    }
}

Jede Datei wird gelesen, mit derselben Systemaufforderung gekoppelt und unabhängig an das Modell gesendet. Das Modell trägt keinen Kontext zwischen Dateien, sodass jede Zusammenfassung eigenständig ist.

Vollständiger Code

Erstellen Sie eine Datei mit dem Namen index.js , und fügen Sie den folgenden vollständigen Code hinzu:

// <imports>
import {
    ChatSession,
    FoundryLocalManager,
    Item,
    Request
} from 'foundry-local-sdk';
import { readFileSync, readdirSync, statSync } from 'fs';
import { join, basename } from 'path';
// </imports>

async function summarizeFile(chatSession, filePath, systemPrompt) {
    const content = readFileSync(filePath, 'utf-8');
    const request = new Request()
        .addItem(Item.systemMessage(systemPrompt))
        .addItem(Item.userMessage(content));
    const response = await chatSession.processRequest(request);
    const text = response.output
        .map((item) => item.type === 'message'
            ? item.content ?? item.parts?.map((part) => part.text ?? '').join('') ?? ''
            : item.type === 'text' ? item.text : '')
        .join('');
    console.log(text);
}

async function summarizeDirectory(model, directory, systemPrompt) {
    const txtFiles = readdirSync(directory)
        .filter(f => f.endsWith('.txt'))
        .sort();

    if (txtFiles.length === 0) {
        console.log(`No .txt files found in ${directory}`);
        return;
    }

    for (const fileName of txtFiles) {
        console.log(`--- ${fileName} ---`);
        const session = new ChatSession(model);
        await summarizeFile(session, join(directory, fileName), systemPrompt);
        session.dispose();
        console.log();
    }
}

// <init>
// Initialize the Foundry Local SDK
const manager = FoundryLocalManager.create({
    appName: 'foundry_local_samples',
    logLevel: 'info'
});

// 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');

// Select and load a model from the catalog
const model = await manager.catalog.getModel('qwen2.5-0.5b');

await model.download((progress) => {
    process.stdout.write(`\rDownloading model: ${progress.toFixed(2)}%`);
});
console.log('\nModel downloaded.');

await model.load();
console.log('Model loaded and ready.\n');

// </init>

// <summarization>
const systemPrompt =
    'Summarize the following document into concise bullet points. ' +
    'Focus on the key points and main ideas.';

// <file_reading>
const target = process.argv[2] || 'document.txt';
// </file_reading>

try {
    const stats = statSync(target);
    if (stats.isDirectory()) {
        await summarizeDirectory(model, target, systemPrompt);
    } else {
        console.log(`--- ${basename(target)} ---`);
        const session = new ChatSession(model);
        await summarizeFile(session, target, systemPrompt);
        session.dispose();
    }
} catch {
    console.log(`--- ${basename(target)} ---`);
    const session = new ChatSession(model);
    await summarizeFile(session, target, systemPrompt);
    session.dispose();
}
// </summarization>

// Clean up
await model.unload();
console.log('\nModel unloaded. Done!');

Fassen Sie eine einzelne Datei zusammen:

node index.js document.txt

Oder fassen Sie jede .txt Datei in einem Verzeichnis zusammen:

node index.js ./docs

Es wird eine ähnliche Ausgabe angezeigt wie:

Downloading model: 100.00%
Model downloaded.
Model loaded and ready.

--- document.txt ---
- Automated testing uses specialized tools to execute tests instead of manual verification.
- Tests fall into three main categories: unit tests (individual functions), integration tests
  (component interactions), and end-to-end tests (full user workflows).
- Key benefits include catching regressions early, reducing manual effort, serving as living
  documentation, and gating deployments through continuous integration pipelines.
- Effective test suites should be deterministic, independent, fast, and maintained alongside
  production code.

Model unloaded. Done!

Beispielrepository

Der vollständige Beispielcode für diesen Artikel ist in den Gießereibeispielen GitHub Repository verfügbar. So klonen Sie das Repository, und navigieren Sie zur Beispielverwendung:

git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/python/foundry-local/tutorial-document-summarizer

Pakete installieren

pip install foundry-local-sdk openai

Lesen eines Textdokuments

Bevor Sie etwas zusammenfassen, benötigen Sie ein Beispieldokument, mit dem Sie arbeiten können. Erstellen Sie eine Datei mit dem Namen document.txt in Ihrem Projektverzeichnis und fügen Sie den folgenden Inhalt hinzu.

Automated testing is a practice in software development where tests are written and executed
by specialized tools rather than performed manually. There are several categories of automated
tests, including unit tests, integration tests, and end-to-end tests. Unit tests verify that
individual functions or methods behave correctly in isolation. Integration tests check that
multiple components work together as expected. End-to-end tests simulate real user workflows
across the entire application.

Adopting automated testing brings measurable benefits to a development team. It catches
regressions early, before they reach production. It reduces the time spent on repetitive
manual verification after each code change. It serves as living documentation of expected
behavior, which helps new team members understand the codebase. Continuous integration
pipelines rely on automated tests to gate deployments and maintain release quality.

Effective test suites follow a few guiding principles. Tests should be deterministic, meaning
they produce the same result every time they run. Tests should be independent, so that one
failing test does not cascade into false failures elsewhere. Tests should run fast, because
slow tests discourage developers from running them frequently. Finally, tests should be
maintained alongside production code so they stay accurate as the application evolves.

Erstellen Sie nun eine Datei namens, main.py und fügen Sie den folgenden Code zum Lesen des Dokuments hinzu:

        target = sys.argv[1] if len(sys.argv) > 1 else "document.txt"
        target_path = Path(target)

Das Skript akzeptiert einen optionalen Dateipfad als Befehlszeilenargument und fällt zurück, document.txt wenn keines angegeben wird. Die Path.read_text Methode liest die gesamte Datei in eine Zeichenfolge.

Generieren einer Zusammenfassung

Initialisieren Sie das Lokale SDK für Foundry, laden Sie ein Modell, und senden Sie den Dokumentinhalt zusammen mit einer Systemaufforderung, die das Modell zur Zusammenfassung anweist.

Ersetzen Sie den Inhalt von main.py durch den folgenden Code.

        system_prompt = (
            "Summarize the following document into concise bullet points. "
            "Focus on the key points and main ideas."
        )

        # <file_reading>
        target = sys.argv[1] if len(sys.argv) > 1 else "document.txt"
        target_path = Path(target)
        # </file_reading>

        if target_path.is_dir():
            summarize_directory(model, target_path, system_prompt)
        else:
            print(f"--- {target_path.name} ---")
            summarize_file(model, target_path, system_prompt)

Die Methode get_model akzeptiert einen Modellalias, bei dem es sich um einen kurzen Anzeigenamen handelt, der einem bestimmten Modell im Katalog zugeordnet ist. Die download Methode ruft die Modellgewichtung in Ihren lokalen Cache ab (und überspringt den Download, wenn sie bereits zwischengespeichert wurden), und load macht das Modell zur Ableitung bereit. Die Systemaufforderung weist das Modell an, Aufzählungszeichenzusammenfassungen zu erstellen, die sich auf wichtige Ideen konzentrieren.

Kontrollieren der Zusammenfassungsausgabe

In verschiedenen Situationen sind unterschiedliche Zusammenfassungsstile erforderlich. Sie können die Systemaufforderung ändern, um zu steuern, wie das Modell seine Ausgabe strukturiert. Hier sind drei nützliche Varianten:

Aufzählungszeichen (Standardeinstellung aus dem vorherigen Schritt):

system_prompt = (
    "Summarize the following document into concise bullet points. "
    "Focus on the key points and main ideas."
)

Zusammenfassung mit einem Absatz:

system_prompt = (
    "Summarize the following document in a single, concise paragraph. "
    "Capture the main argument and supporting points."
)

Wesentliche Punkte:

system_prompt = (
    "Extract the three most important takeaways from the following document. "
    "Number each takeaway and keep each to one or two sentences."
)

Wenn Sie einen anderen Stil ausprobieren möchten, ersetzen Sie den "content" Wert in der Systemmeldung durch eine der Vorgaben. Das Modell folgt den Anweisungen in der Systemaufforderung, um das Format und die Tiefe der Zusammenfassung zu gestalten.

Verarbeiten mehrerer Dokumente

Erweitern Sie die Anwendung, um jede .txt Datei in einem Verzeichnis zusammenzufassen. Dies ist nützlich, wenn Sie über einen Ordner mit Dokumenten verfügen, die alle Zusammenfassungen benötigen.

Die folgende Funktion durchläuft alle .txt Dateien in einem bestimmten Verzeichnis und fasst die einzelnen Dateien zusammen:

async def summarize_directory(client, directory):
    txt_files = sorted(Path(directory).glob("*.txt"))

    if not txt_files:
        print(f"No .txt files found in {directory}")
        return

    for txt_file in txt_files:
        content = txt_file.read_text(encoding="utf-8")
        messages = [
            {
                "role": "system",
                "content": "Summarize the following document into concise bullet points. "
                           "Focus on the key points and main ideas."
            },
            {"role": "user", "content": content}
        ]

        print(f"--- {txt_file.name} ---")
        response = client.complete_chat(messages)
        print(response.choices[0].message.content)
        print()

Jede Datei wird gelesen, mit derselben Systemaufforderung gekoppelt und unabhängig an das Modell gesendet. Das Modell trägt keinen Kontext zwischen Dateien, sodass jede Zusammenfassung eigenständig ist.

Vollständiger Code

Erstellen Sie eine Datei mit dem Namen main.py , und fügen Sie den folgenden vollständigen Code hinzu:

# <imports>
import sys
from pathlib import Path

from foundry_local_sdk import (
    ChatSession,
    Configuration,
    FoundryLocalManager,
    MessageItem,
    Request,
    RequestOptions,
    SearchOptions,
    TextItem,
)

# </imports>


def get_text(response):
    parts = []
    for item in response:
        if isinstance(item, TextItem):
            parts.append(item.text)
        elif isinstance(item, MessageItem):
            parts.extend(part.text for part in item.parts if isinstance(part, TextItem))
    return "".join(parts)


def summarize_file(model, file_path, system_prompt):
    """Summarize a single file and print the result."""
    content = Path(file_path).read_text(encoding="utf-8")
    with ChatSession(model) as session:
        session.set_options(
            RequestOptions(
                search=SearchOptions(temperature=0.2, max_output_tokens=512)
            )
        )
        with (
            Request()
            .add_item(MessageItem.system(system_prompt))
            .add_item(MessageItem.user(content)) as request
        ):
            with session.process_request(request) as response:
                print(get_text(response))


def summarize_directory(model, directory, system_prompt):
    """Summarize all .txt files in a directory."""
    txt_files = sorted(Path(directory).glob("*.txt"))

    if not txt_files:
        print(f"No .txt files found in {directory}")
        return

    for txt_file in txt_files:
        print(f"--- {txt_file.name} ---")
        summarize_file(model, txt_file, system_prompt)
        print()


def main():
    # <init>
    # Initialize the Foundry Local SDK
    config = Configuration(app_name="foundry_local_samples")
    FoundryLocalManager.initialize(config)
    manager = FoundryLocalManager.instance

    # Discover and register execution providers that are not already available.
    missing_eps = [ep.name for ep in manager.discover_eps() if not ep.is_registered]
    if missing_eps:
        manager.download_and_register_eps(missing_eps)

    # Select and load a model from the catalog.
    model = manager.catalog.get_model("qwen2.5-0.5b")
    if model is None:
        raise RuntimeError("Model 'qwen2.5-0.5b' was not found in the catalog.")
    if not model.is_cached:
        model.download(
            lambda progress: print(
                f"\rDownloading model: {progress:.2f}%", end="", flush=True
            )
        )
        print()
    model.load()
    print("Model loaded and ready.\n")
    # </init>

    try:
        # <summarization>
        system_prompt = (
            "Summarize the following document into concise bullet points. "
            "Focus on the key points and main ideas."
        )

        # <file_reading>
        target = sys.argv[1] if len(sys.argv) > 1 else "document.txt"
        target_path = Path(target)
        # </file_reading>

        if target_path.is_dir():
            summarize_directory(model, target_path, system_prompt)
        else:
            print(f"--- {target_path.name} ---")
            summarize_file(model, target_path, system_prompt)
    # </summarization>
    finally:
        # Clean up
        if model.is_loaded:
            model.unload()
        manager.close()
        print("\nModel unloaded. Done!")


if __name__ == "__main__":
    main()

Fassen Sie eine einzelne Datei zusammen:

python main.py document.txt

Oder fassen Sie jede .txt Datei in einem Verzeichnis zusammen:

python main.py ./docs

Es wird eine ähnliche Ausgabe angezeigt wie:

Downloading model: 100.00%
Model loaded and ready.

--- document.txt ---
- Automated testing uses specialized tools to execute tests instead of manual verification.
- Tests fall into three main categories: unit tests (individual functions), integration tests
  (component interactions), and end-to-end tests (full user workflows).
- Key benefits include catching regressions early, reducing manual effort, serving as living
  documentation, and gating deployments through continuous integration pipelines.
- Effective test suites should be deterministic, independent, fast, and maintained alongside
  production code.

Model unloaded. Done!

Beispielrepository

Der vollständige Beispielcode für diesen Artikel ist in den Gießereibeispielen GitHub Repository verfügbar. So klonen Sie das Repository, und navigieren Sie zur Beispielverwendung:

git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/rust/foundry-local/tutorial-document-summarizer

Pakete installieren

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

Lesen eines Textdokuments

Bevor Sie etwas zusammenfassen, benötigen Sie ein Beispieldokument, mit dem Sie arbeiten können. Erstellen Sie eine Datei mit dem Namen document.txt in Ihrem Projektverzeichnis und fügen Sie den folgenden Inhalt hinzu.

Automated testing is a practice in software development where tests are written and executed
by specialized tools rather than performed manually. There are several categories of automated
tests, including unit tests, integration tests, and end-to-end tests. Unit tests verify that
individual functions or methods behave correctly in isolation. Integration tests check that
multiple components work together as expected. End-to-end tests simulate real user workflows
across the entire application.

Adopting automated testing brings measurable benefits to a development team. It catches
regressions early, before they reach production. It reduces the time spent on repetitive
manual verification after each code change. It serves as living documentation of expected
behavior, which helps new team members understand the codebase. Continuous integration
pipelines rely on automated tests to gate deployments and maintain release quality.

Effective test suites follow a few guiding principles. Tests should be deterministic, meaning
they produce the same result every time they run. Tests should be independent, so that one
failing test does not cascade into false failures elsewhere. Tests should run fast, because
slow tests discourage developers from running them frequently. Finally, tests should be
maintained alongside production code so they stay accurate as the application evolves.

Öffnen Sie nun src/main.rs und fügen Sie den folgenden Code zum Lesen des Dokuments hinzu:

    let target = env::args()
        .nth(1)
        .unwrap_or_else(|| "document.txt".to_string());
    let target_path = Path::new(&target);

Der Code akzeptiert einen optionalen Dateipfad als Befehlszeilenargument und fällt auf document.txt zurück, wenn keiner angegeben wird.

Generieren einer Zusammenfassung

Initialisieren Sie das Lokale SDK für Foundry, laden Sie ein Modell, und senden Sie den Dokumentinhalt zusammen mit einer Systemaufforderung, die das Modell zur Zusammenfassung anweist.

Ersetzen Sie den Inhalt von src/main.rs durch den folgenden Code.

    let system_prompt = "Summarize the following document into concise bullet points. Focus on \
                         the key points and main ideas.";

    // <file_reading>
    let target = env::args()
        .nth(1)
        .unwrap_or_else(|| "document.txt".to_string());
    let target_path = Path::new(&target);
    // </file_reading>

    if target_path.is_dir() {
        summarize_directory(&model, target_path, system_prompt).await?;
    } else {
        let file_name = target_path
            .file_name()
            .map(|name| name.to_string_lossy().to_string())
            .unwrap_or_else(|| target.clone());
        println!("--- {file_name} ---");
        summarize_file(&model, target_path, system_prompt).await?;
    }

Die Methode get_model akzeptiert einen Modellalias, bei dem es sich um einen kurzen Anzeigenamen handelt, der einem bestimmten Modell im Katalog zugeordnet ist. Die download Methode ruft die Modellgewichtung in Ihren lokalen Cache ab (und überspringt den Download, wenn sie bereits zwischengespeichert wurden), und load macht das Modell zur Ableitung bereit. Die Systemaufforderung weist das Modell an, Aufzählungszeichenzusammenfassungen zu erstellen, die sich auf wichtige Ideen konzentrieren.

Kontrollieren der Zusammenfassungsausgabe

In verschiedenen Situationen sind unterschiedliche Zusammenfassungsstile erforderlich. Sie können die Systemaufforderung ändern, um zu steuern, wie das Modell seine Ausgabe strukturiert. Hier sind drei nützliche Varianten:

Aufzählungszeichen (Standardeinstellung aus dem vorherigen Schritt):

let system_prompt =
    "Summarize the following document into concise bullet points. \
     Focus on the key points and main ideas.";

Zusammenfassung mit einem Absatz:

let system_prompt =
    "Summarize the following document in a single, concise paragraph. \
     Capture the main argument and supporting points.";

Wesentliche Punkte:

let system_prompt =
    "Extract the three most important takeaways from the following document. \
     Number each takeaway and keep each to one or two sentences.";

Um einen anderen Stil auszuprobieren, ersetzen Sie die Systemnachricht durch eine der Aufforderungen. Das Modell folgt den Anweisungen in der Systemaufforderung, um das Format und die Tiefe der Zusammenfassung zu gestalten.

Verarbeiten mehrerer Dokumente

Erweitern Sie die Anwendung, um jede .txt Datei in einem Verzeichnis zusammenzufassen. Dies ist nützlich, wenn Sie über einen Ordner mit Dokumenten verfügen, die alle Zusammenfassungen benötigen.

Die folgende Funktion durchläuft alle .txt Dateien in einem bestimmten Verzeichnis und fasst die einzelnen Dateien zusammen:

use std::path::Path;

async fn summarize_directory(
    client: &foundry_local_sdk::ChatClient,
    directory: &Path,
    system_prompt: &str,
) -> anyhow::Result<()> {
    let mut txt_files: Vec<_> = fs::read_dir(directory)?
        .filter_map(|entry| entry.ok())
        .filter(|entry| {
            entry.path().extension()
                .map(|ext| ext == "txt")
                .unwrap_or(false)
        })
        .collect();

    txt_files.sort_by_key(|e| e.path());

    if txt_files.is_empty() {
        println!("No .txt files found in {}", directory.display());
        return Ok(());
    }

    for entry in &txt_files {
        let file_content = fs::read_to_string(entry.path())?;
        let messages: Vec<ChatCompletionRequestMessage> = vec![
            ChatCompletionRequestSystemMessage::new(system_prompt).into(),
            ChatCompletionRequestUserMessage::new(&file_content).into(),
        ];

        let file_name = entry.file_name();
        println!("--- {} ---", file_name.to_string_lossy());
        let resp = client.complete_chat(&messages, None).await?;
        let text = resp.choices[0]
            .message
            .content
            .as_deref()
            .unwrap_or("");
        println!("{}\n", text);
    }

    Ok(())
}

Jede Datei wird gelesen, mit derselben Systemaufforderung gekoppelt und unabhängig an das Modell gesendet. Das Modell trägt keinen Kontext zwischen Dateien, sodass jede Zusammenfassung eigenständig ist.

Vollständiger Code

Ersetzen Sie den Inhalt von src/main.rs durch den folgenden vollständigen Code:

// <imports>
use foundry_local_sdk::{
    ChatSession, FoundryLocalConfig, FoundryLocalManager, Item, Model, Request, RequestOptions,
    SearchOptions,
};
use std::io::{self, Write};
use std::path::Path;
use std::{env, fs};
// </imports>

async fn summarize_file(
    model: &Model,
    file_path: &Path,
    system_prompt: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let content = fs::read_to_string(file_path)?;
    let session = ChatSession::new(model).await?;
    session
        .set_options(RequestOptions {
            search: SearchOptions {
                temperature: Some(0.7),
                max_output_tokens: Some(512),
                ..Default::default()
            },
            ..Default::default()
        })
        .await?;

    let response = session
        .process_request(Request::from_items(vec![
            Item::system_message(vec![Item::text(system_prompt)]),
            Item::user_message(vec![Item::text(content)]),
        ]))
        .await?;

    for item in &response.items {
        if let Some(message) = item.as_message() {
            print!("{}", message.text());
        } else if let Some(text) = item.as_text() {
            print!("{text}");
        }
    }
    println!();
    drop(session);
    Ok(())
}

async fn summarize_directory(
    model: &Model,
    directory: &Path,
    system_prompt: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut txt_files: Vec<_> = fs::read_dir(directory)?
        .filter_map(Result::ok)
        .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "txt"))
        .collect();

    txt_files.sort_by_key(|entry| entry.path());

    if txt_files.is_empty() {
        println!("No .txt files found in {}", directory.display());
        return Ok(());
    }

    for entry in &txt_files {
        println!("--- {} ---", entry.file_name().to_string_lossy());
        summarize_file(model, &entry.path(), system_prompt).await?;
        println!();
    }

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // <init>
    // Initialize the Foundry Local SDK
    let manager = FoundryLocalManager::create(FoundryLocalConfig::new("foundry_local_samples"))?;

    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  {ep_name:<30}  {percent:5.1}%");
                io::stdout().flush().ok();
            }
        })
        .await?;
    println!();

    let model = manager.catalog().get_model("qwen2.5-0.5b").await?;
    if !model.is_cached().await? {
        println!("Downloading model...");
        model
            .download(Some(|progress: f64| {
                print!("\r  {progress:.1}%");
                io::stdout().flush().ok();
            }))
            .await?;
        println!();
    }

    model.load().await?;
    println!("Model loaded and ready.\n");
    // </init>

    // <summarization>
    let system_prompt = "Summarize the following document into concise bullet points. Focus on \
                         the key points and main ideas.";

    // <file_reading>
    let target = env::args()
        .nth(1)
        .unwrap_or_else(|| "document.txt".to_string());
    let target_path = Path::new(&target);
    // </file_reading>

    if target_path.is_dir() {
        summarize_directory(&model, target_path, system_prompt).await?;
    } else {
        let file_name = target_path
            .file_name()
            .map(|name| name.to_string_lossy().to_string())
            .unwrap_or_else(|| target.clone());
        println!("--- {file_name} ---");
        summarize_file(&model, target_path, system_prompt).await?;
    }
    // </summarization>

    model.unload().await?;
    println!("\nModel unloaded. Done!");

    Ok(())
}

Fassen Sie eine einzelne Datei zusammen:

cargo run -- document.txt

Oder fassen Sie jede .txt Datei in einem Verzeichnis zusammen:

cargo run -- ./docs

Es wird eine ähnliche Ausgabe angezeigt wie:

Downloading model: 100.00%
Model loaded and ready.

--- document.txt ---
- Automated testing uses specialized tools to execute tests instead of manual verification.
- Tests fall into three main categories: unit tests (individual functions), integration tests
  (component interactions), and end-to-end tests (full user workflows).
- Key benefits include catching regressions early, reducing manual effort, serving as living
  documentation, and gating deployments through continuous integration pipelines.
- Effective test suites should be deterministic, independent, fast, and maintained alongside
  production code.

Model unloaded. Done!

Beispielrepository

Klonen Sie das GitHub-Repository der Foundry-Beispiele und wechseln Sie zum C++-Beispiel:

git clone https://github.com/microsoft-foundry/foundry-samples.git
cd foundry-samples/samples/cpp/foundry-local/tutorial-document-summarizer

Pakete installieren

Für die C++-Beispiele ist Folgendes erforderlich:

  • CMake 3.20 oder höher.
  • Ein C++20-Compiler.
  • Die NuGet-CLI auf Ihrem PATH.

Konfigurieren und erstellen Sie das Beispiel:

cmake -S . -B build
cmake --build build --config Release

Während der Konfiguration stellt das Beispiel die Version 2.2.1 des Microsoft.AI.Foundry.Local.Runtime NuGet-Pakets in build/_packages wieder her. Das Paket enthält die C++-Header und systemeigene Bibliotheken für Windows, Linux und macOS. Sie benötigen kein separates WinML-Paket.

Die CMake-Konfiguration wählt die Laufzeitressourcen für Ihr Betriebssystem und die Architektur aus und kopiert die erforderlichen nativen Bibliotheken neben der ausführbaren Datei. Führen Sie unter macOS und Linux die ausführbare Datei von build aus. Führen Sie unter Windows die .exe-Datei aus build aus.

Lesen eines Textdokuments

Eine Textdatei aus einem Befehlszeilenpfad lesen:

    const std::string path = argc > 1 ? argv[1] : "document.txt";
    std::ifstream input(path);
    if (!input) {
      throw std::runtime_error("Could not open document: " + path);
    }
    const std::string document{
        std::istreambuf_iterator<char>(input),
        std::istreambuf_iterator<char>(),
    };
    if (document.empty()) {
      throw std::runtime_error("The document is empty.");
    }

Generieren einer Zusammenfassung

Laden Sie ein Chatmodell, und fordern Sie es auf, das Dokument zusammenzufassen:

    {
      ChatSession session(*model);
      Request request{
          SystemMessage(
              "Summarize the supplied document using a short overview and three bullet points."),
          UserMessage(document),
      };
      request.SetOptions({
          .search = {.temperature = 0.2F, .max_output_tokens = 512, .seed = 42},
      });
      std::cout << ResponseText(session.ProcessRequest(request)) << "\n";
    }

Vollständiger Code

#include <foundry_local/foundry_local_cpp.h>

#include <fstream>
#include <iostream>
#include <iterator>
#include <string>

using namespace foundry_local;

std::string ResponseText(const Response& response) {
  std::string text;
  for (const Item& item : response.GetItems()) {
    if (item.GetType() != FOUNDRY_LOCAL_ITEM_MESSAGE) {
      continue;
    }
    for (const Item& part : item.GetMessage().parts) {
      if (part.GetType() == FOUNDRY_LOCAL_ITEM_TEXT) {
        text.append(part.GetText().text);
      }
    }
  }
  return text;
}

int main(int argc, char* argv[]) {
  try {
    Configuration config("foundry_local_cpp_document_summarizer");
    Manager manager(std::move(config));
    auto model = manager.GetCatalog().GetModel("qwen2.5-0.5b");
    if (!model) {
      throw std::runtime_error("Model 'qwen2.5-0.5b' was not found in the catalog.");
    }
    if (!model->IsCached()) {
      model->Download([](float progress) {
        std::cout << "\rDownloading model: " << static_cast<int>(progress) << "%" << std::flush;
        return 0;
      });
      std::cout << "\n";
    }
    model->Load();

    // <file_reading>
    const std::string path = argc > 1 ? argv[1] : "document.txt";
    std::ifstream input(path);
    if (!input) {
      throw std::runtime_error("Could not open document: " + path);
    }
    const std::string document{
        std::istreambuf_iterator<char>(input),
        std::istreambuf_iterator<char>(),
    };
    if (document.empty()) {
      throw std::runtime_error("The document is empty.");
    }
    // </file_reading>

    // <summarization>
    {
      ChatSession session(*model);
      Request request{
          SystemMessage(
              "Summarize the supplied document using a short overview and three bullet points."),
          UserMessage(document),
      };
      request.SetOptions({
          .search = {.temperature = 0.2F, .max_output_tokens = 512, .seed = 42},
      });
      std::cout << ResponseText(session.ProcessRequest(request)) << "\n";
    }
    // </summarization>

    model->Unload();
    manager.Shutdown();
  } catch (const Error& error) {
    std::cerr << "Foundry Local error [" << error.Code() << "]: " << error.what() << "\n";
    return 1;
  } catch (const std::exception& error) {
    std::cerr << "Error: " << error.what() << "\n";
    return 1;
  }

  return 0;
}

Datei zusammenfassen:

./build/tutorial-document-summarizer document.txt

Bereinigen von Ressourcen

Die Gewichtungen des Modells verbleiben im lokalen Cache, nachdem Sie ein Modell entladen haben. Dies bedeutet, dass beim nächsten Ausführen der Anwendung der Downloadschritt übersprungen wird und das Modell schneller geladen wird. Es ist keine zusätzliche Bereinigung erforderlich, es sei denn, Sie möchten Speicherplatz freigeben.