Lab 002: Context as Infrastructure with Qdrant, RAG, and Hugging Face

Headline banner for Enterprise AI Architecture Labs Lab 002: Vector Retrieval featuring the series title, a blue background, and an illustrated sketch portrait of Ed Bednar.

Context is how enterprise information acquires meaning.
By Ed Bednar

Lab: 002

Technology: Claude Code, Python, Retrieval-Augmented Generation (RAG), Hugging Face, Qdrant

Prerequisites:
1. Lab 001: Encapsulating Enterprise Systems with Claude Code

Estimated Time: 40-50 minutes

1.0 Introduction

Large language models (LLMs) possess extensive general knowledge, but they have no inherent understanding of an organization’s data or the information that defines how the organization operates.

This enterprise content includes contracts, policies, engineering standards, operating procedures, regulatory guidance, technical documentation, and other information assets that govern business activities and decision making.

Within our simulated manufacturing enterprise, the AI system must determine whether a supplier satisfied a contractual service-level agreement, whether delivered components met the required quality standards, and whether an invoice complies with the negotiated payment terms.

These questions cannot be answered using general knowledge alone. They require access to the enterprise content that governs the supplier relationship.

This lab introduces AI infrastructure that makes enterprise content available through a shared services model.

We will build a retrieval pipeline that enables AI components to retrieve enterprise content based on semantic similarity, using contract data that defines the business rules governing the supplier relationship.

1.1 Enterprise Content

Enterprise content consists of the information that governs, explains, or provides context for business operations.

This information may exist as documents, structured records, business rules, master data, configuration, or other enterprise information assets.

Common examples of enterprise content include:

  • Contracts and service-level agreements
  • Corporate policies and operating procedures
  • Engineering specifications and technical standards
  • Regulatory guidance and compliance documentation
  • Product documentation and knowledge base articles
  • Architectural standards and design patterns

Consider a supplier invoice stored in an ERP system. The invoice records what was billed, when it was received, and the amount due.

Determining whether that invoice is valid, however, may require additional enterprise information such as the supplier agreement, negotiated payment terms, purchasing policies, or approval rules.

While an ERP system may record much of this, other enterprise content may be required to determine evaluative context.

This distinction is fundamental to enterprise AI.

For this lab, supplier contracts serve as the enterprise content. Later AI services will retrieve the relevant contract clauses before evaluating supplier performance, shipments, purchase orders, and invoices.

Although this lab focuses on contracts, the same retrieval architecture can support virtually any enterprise content, whether it originates from documents, enterprise applications, or other information repositories.

1.2 Embedding Models

Before enterprise content can be searched semantically, its textual representation must be converted into a numerical representation that captures its meaning.

An embedding model transforms text into high-dimensional vectors that place semantically related concepts near one another, even when, for instance, they use different wording. Rather than searching for exact keywords, vector search identifies content that expresses similar ideas.

For example, a query for delivery performance requirements should retrieve enterprise content describing a Delivery Service Level Agreement, even if those exact words do not appear in the query.

Embeddings allow AI systems to search by meaning rather than just by matching specific words, making semantic retrieval possible across a wide variety of enterprise information sources.

The Embedding Model

In this lab, embeddings are generated using the Hugging Face model sentence-transformers/all-MiniLM-L6-v2, which is hosted in the Hugging Face Model Hub.

The model produces compact, general-purpose sentence embeddings that are well suited for semantic search while remaining efficient enough for our exercise, which needs to run on a typical development workstation.

The Transformers Library

The implementation uses the Transformers library, Hugging Face’s open-source Python library for loading, executing, and interacting with pre-trained transformer models.

Rather than using a higher-level library that generates embeddings through a single function call, the Transformers library exposes the individual components involved in model inference.

This makes the implementation easier to understand while providing full visibility into the model and its dependencies.

Core Components

Two classes from the library perform the core work:

  1. AutoTokenizer converts raw text into the numerical tokens expected by the model. It breaks the text into recognized units, maps those units to integer identifiers, and organizes those identifiers into tensors. (A tensor is a multidimensional numerical array used by machine learning frameworks to represent and process data efficiently during model execution.)
  2. AutoModel loads the pre-trained transformer model and executes it on the tokenized input (i.e., it performs inference), producing contextual embeddings that capture the semantic meaning of the text.

Both Auto classes automatically load the correct tokenizer and model implementation based on the model identifier, allowing the same code to work with many different pre-trained models.

Embedding Pipeline

Generating an embedding consists of four steps:

  1. Tokenization converts the input text into the numerical token sequence expected by the model.
  2. Model Inference passes those tokens through the transformer network, producing contextual embeddings for every token in the sequence.
  3. Mean Pooling averages the embeddings produced for each token, creating a single fixed-length vector that represents the semantic meaning of the entire text.
  4. Vector Conversion converts the embedding into a standard Python list so it can be stored in the Qdrant vector database and used for semantic retrieval.

Implementation Transparency

Exposing each stage of the process and the underlying model dependency makes the embedding pipeline understandable and auditable.

This enables organizations to identify the exact model being used, review its metadata and licensing, and evaluate whether it satisfies their security, governance, and compliance requirements.

Enterprise Architecture Considerations

Organizations typically need to inventory the AI models incorporated into their solutions, understand how they are used, verify licensing, and evaluate whether they satisfy security, governance, and compliance requirements. Loading the model explicitly through the Transformers library keeps these implementation details visible and auditable.

In enterprise environments, this level of transparency should be established through architecture requirements, as discussed in the article Unstoppable Enterprise Architecture. 

1.3 Retrieval-Augmented Generation

Retrieval-Augmented Generation (RAG) is an architectural pattern that combines enterprise information retrieval with large language models.

Rather than expecting an AI model to answer questions solely from its pretrained knowledge, a RAG system first retrieves relevant enterprise content and supplies that information to the model as additional context.

This approach addresses one of the fundamental limitations of large language models: Although LLMs possess extensive general knowledge, they have no inherent understanding of an organization’s contracts, policies, engineering standards, or operational procedures.

Also, enterprise-specific information changes continuously so likely cannot be incorporated into a model through retraining alone. Instead, the required information is retrieved dynamically at runtime.

RAG Architecture

A RAG implementation consists of four primary components:

  1. Enterprise Content provides the source information used for semantic retrieval. In this lab, that content consists of supplier contracts.
  2. The Embedding Model converts both enterprise content and user queries into numerical vector representations that capture semantic meaning. In this lab, that role is performed by the Hugging Face model sentence-transformers/all-MiniLM-L6-v2.
  3. The Vector Database stores those embeddings and performs similarity searches to identify the document passages most relevant to a given query. In this lab, that role is performed by Qdrant.
  4. The Large Language Model receives the retrieved enterprise content as additional context before generating a response or evaluating a business event. This part will be introduced in subsequent implementation labs.

Retrieval Pipeline

The retrieval pipeline follows a sequence of processing steps:

  1. Enterprise content is divided into manageable chunks that preserve meaningful context.
  2. Each chunk is converted into an embedding and stored in the Qdrant vector database.
  3. A user query is converted into an embedding using the same embedding model.
  4. Qdrant performs a semantic similarity search and returns the document chunks whose embeddings are closest to the query vector.
  5. The retrieved content is supplied to the large language model as contextual information.
  6. The language model performs reasoning using both its pre-trained knowledge and the retrieved enterprise context before generating a response or making a decision.

Retrieval, Augmentation, and Generation

The term Retrieval-Augmented Generation reflects the three stages of the process:

  • Retrieval identifies the enterprise information relevant to the current task. 
  • Augmentation supplies that information to the language model as additional context. 
  • Generation refers to the model using both its pre-trained knowledge and the retrieved enterprise content to produce a response.

Manufacturing Example

Within our simulated manufacturing enterprise, this means an AI judgment service does not need to memorize supplier contracts.

Instead, when evaluating a shipment, purchase order, or invoice, it first retrieves the contract clauses governing delivery commitments, payment terms, quality standards, or service-level agreements.

The retrieved content provides the factual basis for the AI’s reasoning, ensuring that decisions are grounded in the organization’s own business rules and operational knowledge rather than relying solely on the model’s general knowledge.

Architectural Takeaway

By the end of this lab, the simulated enterprise will contain a reusable retrieval service that enables every subsequent AI component to access enterprise knowledge as part of its decision-making process.

Together, these steps establish a retrieval service that separates enterprise knowledge from AI reasoning.

Rather than embedding business rules directly into prompts or application code, enterprise content is retrieved at runtime to establish the contextual frame within which AI reasoning occurs.

2.0 Architecture Blueprint

Lab 001 established the operational systems that simulate a manufacturing enterprise, including purchasing, warehouse operations, ERP processing, and supplier contracts.

Those systems generate the operational data associated with business events.

This lab extends the architecture by introducing Enterprise AI Services, a shared set of capabilities that provide enterprise knowledge to applications, shown in Figure 2-1.

Enterprise content is converted into vector embeddings, stored in Qdrant, and made available through a retrieval service that can be accessed by applications throughout the enterprise.

Rather than embedding business rules directly into application logic, applications retrieve the enterprise content relevant to a business event before performing reasoning or making a decision.

This architectural separation decouples the operational systems that generate business events from the enterprise AI services that provide contextual knowledge, allowing each to evolve independently while ensuring applications operate from a consistent enterprise context.

Figure 2-1. Architecture blueprint illustrating the Enterprise AI Services, showing how enterprise content is ingested into a vector repository and retrieved by applications as enterprise context.

3.0 Artifacts Created

Claude Code will generate four artifacts that collectively implement the retrieval infrastructure introduced in this lab.

They ingest supplier contract content, generate semantic embeddings, store those embeddings in Qdrant, and expose a reusable retrieval service that subsequent AI components will consume.

These artifacts establish a reusable retrieval service that subsequent labs will invoke before performing AI-assisted reasoning.

3.1 rag/pipeline.py

Implements the retrieval pipeline by connecting to Qdrant, loading the Hugging Face embedding model, generating embeddings, ingesting supplier contract content, and performing semantic retrieval.

3.2 rag/ingest.py

Loads the supplier contract content from the simulated enterprise and ingests it into the Qdrant vector database, creating the searchable enterprise knowledge layer.

3.3 rag/model_card.py

Retrieves metadata for the Hugging Face embedding model, including the model name, license, and intended use, providing transparency into the AI model incorporated into the solution.

4.0 Generate the Retrieval Pipeline

In this section, you will use Claude Code to generate the retrieval infrastructure introduced in the previous sections.

4.1 Prompt Overview

The prompt instructs Claude Code to:

  • Create a rag package that implements the enterprise retrieval infrastructure.
  • Connect to a locally running Qdrant vector database.
  • Load the sentence-transformers/all-MiniLM-L6-v2 embedding model directly from Hugging Face using the Transformers library.
  • Generate embeddings through explicit tokenization, model execution (i.e., inference), and mean pooling.
  • Chunk supplier contract content into semantic retrieval units.
  • Create and populate the contracts collection in Qdrant.
  • Implement retrieval functions that return the enterprise content most relevant to a query.
  • Generate an ingestion utility that loads supplier contract content into the vector database.
  • Generate a utility that displays metadata about the embedding model.
  • Expose the retrieval pipeline for use by subsequent implementation labs.

4.2 Claude Code Prompt

Copy the following prompt into Claude Code exactly as shown.

Create a rag/ package for contract document retrieval.

rag/pipeline.py
Connect to Qdrant running at localhost:6333.
Load the embedding model sentence-transformers/all-MiniLM-L6-v2 from Hugging Face using
AutoTokenizer and AutoModel from the transformers library. Do NOT use the sentence-transformers
package. Load the model explicitly so the dependency is auditable.
Add a comment at the top of the file with the exact Docker command to start Qdrant:
  docker run -d --name qdrant -p 6333:6333 qdrant/qdrant

Implement a helper function embed(text: str) -> list[float] that tokenizes the input,
runs a forward pass through the model, and returns mean-pooled embeddings as a Python list.

Implement two public functions:

  ingest_contracts(documents: list[str])

    Create a Qdrant collection named 'contracts' with vector size 384
    (all-MiniLM output size).

    If the collection already exists, delete it and recreate it.

    Chunk each document into segments of approximately 200 tokens using
    simple sentence splitting.

    Generate embeddings for each chunk.

    Upsert all chunks as points into the collection, storing the chunk
    text as payload.

  retrieve_context(query: str, top_k: int = 3) -> list[str]

    Embed the query.

    Search the contracts collection.

    Return the top_k chunk texts as a list.

rag/ingest.py

Import contract_store from stubs and ingest_contracts from rag.pipeline.

Call ingest_contracts with the contract documents.

Print a confirmation message showing how many chunks were ingested.

rag/model_card.py

Use the huggingface_hub library's ModelCard class to load the card for
sentence-transformers/all-MiniLM-L6-v2.

Print three lines:

- Model name
- License
- Intended use

Handle the case where the card is unavailable gracefully.

rag/__init__.py

Import pipeline so it is accessible as rag.pipeline.

5.0 Verify the Implementation

5.1 Verify Contract Ingestion

Run the ingestion script to create the contracts collection in Qdrant and populate it with embedded contract chunks.

Command

python3.11 -m rag.ingest

Example Output

Loading weights: 100%
Ingested 35 chunks from 5 contract documents.

Verify That

  • The ingestion process completes without errors.
  • The Hugging Face embedding model loads successfully.
  • Contract documents are chunked and embedded.
  • The `contracts` collection is created or refreshed in Qdrant.
  • The reported number of chunks is greater than zero.
  • If a Hugging Face authentication warning appears during the initial download of the model, it can be safely ignored when using public models.

5.2 Verify Semantic Retrieval

Execute a semantic search against the vector database to confirm that relevant contract clauses are returned for a representative business query.

Command

python3.11 -c "from rag.pipeline import retrieve_context; results = retrieve_context('steel components delivery penalty clause'); print(results[0][:200])"

Example Output

SUPPLY AND PURCHASE AGREEMENT
Contract Number: CTR-1001
Product Category: Steel Components
This Supply and Purchase Agreement ("Agreement") is entered into by...

Verify That

  • The command executes successfully.
  • At least one contract passage is returned.
  • The returned text is relevant to the query.
  • The retrieved clause references contractual language related to delivery obligations, penalties, or steel components.
  • Keep in mind that results are returned through semantic similarity rather than exact keyword matching.

5.3 Verify Model Metadata

Display the Hugging Face model card to verify that the embedding model metadata can be retrieved successfully.

Command

python3.11 -m rag.model_card

Example Output

Model name: sentence-transformers/all-MiniLM-L6-v2
License: apache-2.0
Intended use: General-purpose sentence and semantic embeddings.

Verify That

  • The model card loads successfully.
  • The reported model name matches the model configured in rag/pipeline.py.
  • The license is displayed correctly.
  • The intended-use information is displayed, or the utility gracefully handles an unavailable model card.

5.4 Verify the Retrieval Pipeline

Confirm that the individual components function together as a complete retrieval pipeline capable of supporting downstream AI reasoning.

Command

python3.11 -c "from rag.pipeline import retrieve_context; results = retrieve_context('delivery service level agreement for steel components'); print(results[0])"

Example Output

2. DELIVERY SERVICE LEVEL AGREEMENT

Vendor shall confirm receipt of each purchase order within two (2)
business days and shall ship confirmed quantities within 14 calendar
days of order acceptance...

Verify That

  • The retrieval command completes successfully without errors.
  • One or more contract passages are returned from the contracts collection.
  • The returned passage is semantically relevant to the query rather than requiring an exact keyword match.
  • The returned text contains contractual language related to the requested topic, such as delivery service levels, shipping requirements, quality standards, or pricing terms.
  • The retrieved passage originates from one of the supplier contracts that was ingested into Qdrant.
  • The returned text may include neighboring contract sections in addition to the requested topic. This is expected behavior because documents were ingested as chunks of approximately 200 tokens, preserving surrounding context for downstream AI reasoning.

6.0 Lab Summary

This lab introduced a retrieval infrastructure that enables AI services to access enterprise content as contextual input for reasoning.

This separation of responsibilities is a fundamental architectural pattern. Operational systems remain the systems of record for enterprise operations, while the retrieval infrastructure provides a standardized mechanism for retrieving enterprise content as contextual input for AI reasoning.

By decoupling enterprise content from the applications and AI services that consume it, both can evolve independently while maintaining a consistent contextual foundation across the enterprise.

The remaining labs will build on this foundation.

6.1 What You Built

During this lab, you:

  • Created a reusable rag package that implements semantic retrieval of enterprise content.
  • Loaded the sentence-transformers/all-MiniLM-L6-v2 embedding model using the Hugging Face Transformers library.
  • Generated semantic embeddings for supplier contract content.
  • Stored supplier contract content as searchable vector embeddings in a Qdrant contracts collection.
  • Implemented retrieval functions that return enterprise content using semantic similarity rather than just keyword matching.
  • Verified the retrieval pipeline by ingesting enterprise content, retrieving relevant results, and validating the embedding model metadata.

Retrieval-Augmented Generation is an architectural capability for integrating enterprise content into AI reasoning. While it is often introduced through chatbot examples, the same architectural pattern applies to any AI system that must reason from enterprise information.

The next lab, Lab 003: Judgment as a Service with Anthropic Claude and Pydantic, builds on this foundation by introducing AI judgment services that combine operational data with enterprise content to evaluate business events.