Oktatóanyag: RAG-alkalmazás létrehozása

Hozzon létre egy lekéréssel bővített generálási (RAG) alkalmazást, amely teljes egészében az Ön eszközén lévő dokumentumok gyűjteményével kapcsolatos kérdésekre ad választ. A RAG kombinálja a beágyazási alapú keresést egy csevegési modellel, így a válaszok a saját adataiban vannak alapulva, nem pedig kizárólag a modell betanítási ismereteire támaszkodva.

Ebben az oktatóanyagban a következőket sajátíthatja el:

  • Projekt beállítása és az Foundry Helyi SDK telepítése
  • Tudásbázis létrehozása szöveges dokumentumokból
  • Beágyazások létrehozása a dokumentumokhoz
  • Releváns dokumentumok keresése hasonlóság alapján
  • A válaszok létrehozása a lekért környezet alapján
  • Erőforrások törlése

Előfeltételek

  • Legalább 8 GB RAM-mal rendelkező Windows, macOS vagy Linux rendszerű számítógép.
  • Python 3.11 vagy újabb verzió van telepítve.

Csomagok telepítése

Ha Windows fejleszt vagy szállít, válassza a Windows lapot. A Windows csomag integrálható a Windows ML futtatókörnyezettel – ugyanazt az API-felületet biztosítja a hardveres gyorsítás szélesebb körű használatával.

pip install foundry-local-sdk-winml openai

Tudásbázis létrehozása

A RAG-alkalmazásoknak dokumentumgyűjteményre van szükségük a kereséshez. Definiálja a tudásbázisként szolgáló szöveges sztringek listáját. Egy éles alkalmazásban a lista lehet fájlokból, adatbázisrekordokból vagy bármely más szövegforrásból származó bekezdés.

Hozzon létre egy hívott main.py fájlt, és adja hozzá a következő kódot:

import math
from foundry_local_sdk import Configuration, FoundryLocalManager

# Knowledge base — each string represents a document
documents = [
    "Foundry Local runs AI models directly on your device without cloud connectivity.",
    "The Foundry Local SDK supports Python, C#, JavaScript, and Rust.",
    "Embedding models convert text into numerical vectors for similarity search.",
    "Foundry Local uses ONNX Runtime for efficient model inference on CPUs and GPUs.",
    "The model catalog provides pre-optimized models that you can download and run locally.",
    "Retrieval-augmented generation grounds model responses in your own data.",
    "Vector similarity search finds documents that are semantically close to a query.",
    "Chat completions generate natural language responses from a prompt and context.",
]

Dokumentumbeágyazások létrehozása

Inicializálja az SDK-t, töltsön be egy beágyazási modellt, és konvertálja az egyes dokumentumokat numerikus vektorsá. Ezek a vektorok az egyes dokumentumok szemantikai jelentését jelölik, és lehetővé teszik a hasonlóság keresését.

Adja hozzá a következő kódot a következőhöz main.py:

def main():
    # Initialize the SDK
    config = Configuration(app_name="foundry_local_rag")
    FoundryLocalManager.initialize(config)
    manager = FoundryLocalManager.instance

    # Load the embedding model
    embedding_model = manager.catalog.get_model("qwen3-embedding-0.6b")
    embedding_model.download(
        lambda p: print(f"\rDownloading embedding model: {p:.1f}%", end="", flush=True)
    )
    print()
    embedding_model.load()
    embedding_client = embedding_model.get_embedding_client()

    # Embed all documents in a single batch call
    response = embedding_client.generate_embeddings(documents)
    doc_embeddings = [item.embedding for item in response.data]
    print(f"Indexed {len(doc_embeddings)} documents.")

A generate_embeddings metódus elfogadja a sztringek listáját, és bemenetenként egy vektort ad vissza. Minden vektor rögzíti a szöveg szemantikai jelentését, így a hasonló dokumentumok olyan vektorokat hoznak létre, amelyek közel vannak egymáshoz a beágyazási térben.

Releváns dokumentumok keresése

A lekérdezéshez kapcsolódó dokumentumok megkereséséhez hasonlítsa össze a lekérdezés beágyazását minden dokumentum beágyazásával, koszinusz hasonlóság használatával. A koszinusz hasonlósága azt méri, hogy a két vektor milyen közel van az irányban, a nagyságrendtől függetlenül. Az 1,0-hoz közeli értékek magas hasonlóságot jeleznek.

Helyezze el a következő segédfüggvényeket main() fölé a main.py fájlban:

def cosine_similarity(a, b):
    """Compute cosine similarity between two vectors."""
    dot = sum(x * y for x, y in zip(a, b))
    norm_a = math.sqrt(sum(x * x for x in a))
    norm_b = math.sqrt(sum(x * x for x in b))
    return dot / (norm_a * norm_b) if norm_a and norm_b else 0.0


def find_relevant(query_embedding, doc_embeddings, top_k=2):
    """Return the indices and scores of the top-k most similar documents."""
    scores = []
    for i, doc_emb in enumerate(doc_embeddings):
        score = cosine_similarity(query_embedding, doc_emb)
        scores.append((i, score))
    scores.sort(key=lambda x: x[1], reverse=True)
    return scores[:top_k]

A find_relevant függvény az összes dokumentumot hasonlóság alapján rangsorolja, és a legfontosabb találatokat adja vissza. Ez a megközelítés jól működik a kis gyűjtemények esetében. Nagyobb adathalmazok esetén fontolja meg egy dedikált vektoradatbázist.

Megalapozott válaszok létrehozása

Töltsön be egy csevegőmodellt, és egyesítse a beolvasott dokumentumokat a felhasználó kérdésével egy rendszerkérésben. A csevegőmodell a megadott kontextust használja a dokumentumokban alapozott válasz létrehozásához.

Adja hozzá a következő kódot a main() függvényhez a beágyazási szakasz után:

    # Load the chat model
    chat_model = manager.catalog.get_model("qwen2.5-0.5b")
    chat_model.download(
        lambda p: print(f"\rDownloading chat model: {p:.1f}%", end="", flush=True)
    )
    print()
    chat_model.load()
    chat_client = chat_model.get_chat_client()

    print("\nModels loaded. Ready for questions.")
    print("\nThe knowledge base contains information about:")
    print("  - Foundry Local features and architecture")
    print("  - Supported programming languages")
    print("  - Embedding models and vector search")
    print("  - ONNX Runtime inference")
    print("  - The model catalog")
    print("  - RAG and chat completions")
    print("\nExample questions:")
    print('  "What programming languages does the SDK support?"')
    print('  "How does Foundry Local run models?"')
    print('  "What is retrieval-augmented generation?"')
    print('\nType "quit" to exit.\n')

    # Interactive query loop
    while True:
        query = input("Question: ").strip()
        if not query or query.lower() == "quit":
            break

        # Embed the query
        query_response = embedding_client.generate_embedding(query)
        query_embedding = query_response.data[0].embedding

        # Retrieve the most relevant documents
        results = find_relevant(query_embedding, doc_embeddings, top_k=2)
        context = "\n".join(f"- {documents[i]}" for i, _ in results)

        # Build the prompt with retrieved context
        messages = [
            {
                "role": "system",
                "content": (
                    "Answer the user's question using only the provided context. "
                    "If the context doesn't contain enough information, say so.\n\n"
                    f"Context:\n{context}"
                ),
            },
            {"role": "user", "content": query},
        ]

        # Stream the response
        print("Answer: ", end="", flush=True)
        for chunk in chat_client.complete_streaming_chat(messages):
            content = chunk.choices[0].delta.content
            if content:
                print(content, end="", flush=True)
        print("\n")

    # Clean up
    embedding_model.unload()
    chat_model.unload()
    print("Models unloaded. Done!")


if __name__ == "__main__":
    main()

A rendszerkérés arra utasítja a modellt, hogy csak a lekért környezettel válaszoljon. A rendszerkérés megőrzi a dokumentumokban szereplő válaszokat, és csökkenti a helytelen válaszokat. A stream kimenete minden tokent megmutat, ahogy generálódik, ezáltal a válasz interaktív érzetet kelt.

Teljes kód

Itt található a teljes alkalmazás, amely egyesíti az összes lépést:

import math
from foundry_local_sdk import Configuration, FoundryLocalManager

# Knowledge base
documents = [
    "Foundry Local runs AI models directly on your device without cloud connectivity.",
    "The Foundry Local SDK supports Python, C#, JavaScript, and Rust.",
    "Embedding models convert text into numerical vectors for similarity search.",
    "Foundry Local uses ONNX Runtime for efficient model inference on CPUs and GPUs.",
    "The model catalog provides pre-optimized models that you can download and run locally.",
    "Retrieval-augmented generation grounds model responses in your own data.",
    "Vector similarity search finds documents that are semantically close to a query.",
    "Chat completions generate natural language responses from a prompt and context.",
]


def cosine_similarity(a, b):
    """Compute cosine similarity between two vectors."""
    dot = sum(x * y for x, y in zip(a, b))
    norm_a = math.sqrt(sum(x * x for x in a))
    norm_b = math.sqrt(sum(x * x for x in b))
    return dot / (norm_a * norm_b) if norm_a and norm_b else 0.0


def find_relevant(query_embedding, doc_embeddings, top_k=2):
    """Return the indices and scores of the top-k most similar documents."""
    scores = []
    for i, doc_emb in enumerate(doc_embeddings):
        score = cosine_similarity(query_embedding, doc_emb)
        scores.append((i, score))
    scores.sort(key=lambda x: x[1], reverse=True)
    return scores[:top_k]


def main():
    # Initialize the SDK
    config = Configuration(app_name="foundry_local_rag")
    FoundryLocalManager.initialize(config)
    manager = FoundryLocalManager.instance

    # Load the embedding model
    embedding_model = manager.catalog.get_model("qwen3-embedding-0.6b")
    embedding_model.download(
        lambda p: print(f"\rDownloading embedding model: {p:.1f}%", end="", flush=True)
    )
    print()
    embedding_model.load()
    embedding_client = embedding_model.get_embedding_client()

    # Embed all documents
    response = embedding_client.generate_embeddings(documents)
    doc_embeddings = [item.embedding for item in response.data]
    print(f"Indexed {len(doc_embeddings)} documents.")

    # Load the chat model
    chat_model = manager.catalog.get_model("qwen2.5-0.5b")
    chat_model.download(
        lambda p: print(f"\rDownloading chat model: {p:.1f}%", end="", flush=True)
    )
    print()
    chat_model.load()
    chat_client = chat_model.get_chat_client()

    print("\nModels loaded. Ready for questions.")
    print("\nThe knowledge base contains information about:")
    print("  - Foundry Local features and architecture")
    print("  - Supported programming languages")
    print("  - Embedding models and vector search")
    print("  - ONNX Runtime inference")
    print("  - The model catalog")
    print("  - RAG and chat completions")
    print("\nExample questions:")
    print('  "What programming languages does the SDK support?"')
    print('  "How does Foundry Local run models?"')
    print('  "What is retrieval-augmented generation?"')
    print('\nType "quit" to exit.\n')

    # Interactive query loop
    while True:
        query = input("Question: ").strip()
        if not query or query.lower() == "quit":
            break

        # Embed the query
        query_response = embedding_client.generate_embedding(query)
        query_embedding = query_response.data[0].embedding

        # Retrieve the most relevant documents
        results = find_relevant(query_embedding, doc_embeddings, top_k=2)
        context = "\n".join(f"- {documents[i]}" for i, _ in results)

        # Build the prompt with retrieved context
        messages = [
            {
                "role": "system",
                "content": (
                    "Answer the user's question using only the provided context. "
                    "If the context doesn't contain enough information, say so.\n\n"
                    f"Context:\n{context}"
                ),
            },
            {"role": "user", "content": query},
        ]

        # Stream the response
        print("Answer: ", end="", flush=True)
        for chunk in chat_client.complete_streaming_chat(messages):
            content = chunk.choices[0].delta.content
            if content:
                print(content, end="", flush=True)
        print("\n")

    # Clean up
    embedding_model.unload()
    chat_model.unload()
    print("Models unloaded. Done!")


if __name__ == "__main__":
    main()

Futtassa az alkalmazást:

python main.py

A következőhöz hasonló kimenet jelenik meg:

Downloading embedding model: 100.0%
Indexed 8 documents.
Downloading chat model: 100.0%

Models loaded. Ready for questions.

The knowledge base contains information about:
  - Foundry Local features and architecture
  - Supported programming languages
  - Embedding models and vector search
  - ONNX Runtime inference
  - The model catalog
  - RAG and chat completions

Example questions:
  "What programming languages does the SDK support?"
  "How does Foundry Local run models?"
  "What is retrieval-augmented generation?"

Type "quit" to exit.

Question: What programming languages does the SDK support?
Answer: The Foundry Local SDK supports Python, C#, JavaScript, and Rust.

Question: quit
Models unloaded. Done!

Erőforrások törlése

A modell súlyai a modell kiürítése után is a helyi gyorsítótárban maradnak. Az alkalmazás következő futtatásakor a rendszer kihagyja a letöltési lépést, és a modellek gyorsabban töltődnek be. Nincs szükség további törlésre, ha vissza szeretné igényelni a lemezterületet.