Zero Labs
Industry News / AI

Building an Enterprise RAG AI on OneLake Data in 50 Lines of Python

Source · Towards AI By Sandip Palit

From the publisher’s feed, collected in the ZeroLabs newsroom.

When we examine the modern enterprise AI landscape, we frequently encounter a common paradox: while generative AI promises to revolutionize customer support, internal search, and knowledge management, the underlying infrastructure required to deploy these solutions often grows prohibitively complex. Historically, building a production-grade Retrieval-Augmented Generation (RAG) pipeline meant provisioning specialized external vector databases, managing intricate data synchronization pipelines, and risking data sprawl across ungoverned cloud environments.We realized that for many enterprise workloads, this massive infrastructure overhead is entirely unnecessary. By leveraging Microsoft Fabric’s unified data estate, native Apache Spark engine, and Delta Lake storage format, we can build a fully operational, enterprise-grade RAG solution directly on top of our existing OneLake data. In this detailed operational guide, we share how we designed and deployed an end-to-end vector embedding and retrieval system using fewer than 50 lines of PySpark and Python code, connecting Azure OpenAI directly to our governed customer transcripts without moving a single byte outside our analytical perimeter.Architecture: OneLake → PySpark Vectorization → Azure OpenAIOur primary goal was to design an architecture that maximizes simplicity, security, and query execution performance while operating entirely within our governed workspace. Rather than exporting unstructured transcripts to a third-party vector database, we construct a unified pipeline where storage, compute, and AI inference coexist seamlessly.Our end-to-end RAG workflow follows a structured four-stage continuum:Governed Storage Layer (OneLake & Delta Parquet): Our raw and processed datasets, such as customer support logs, operational records, or internal knowledge bases reside directly within our Lakehouse as open Delta Parquet tables. This guarantees ACID compliance, version history, and zero-copy accessibility across analytical engines.Distributed Vectorization Engine (PySpark & Pandas UDFs): We harness Fabric’s native Apache Spark compute cluster to distribute the task of generating vector embeddings across millions of text records simultaneously. By employing PyArrow-accelerated Pandas UDFs, we batch API requests to Azure OpenAI efficiently.In-Lake Vector Persistence: Vector embeddings are stored natively as array columns inside a dedicated Gold Delta table (Gold_Lakehouse.SupportVectors). This eliminates external database licensing costs and guarantees that vector updates maintain strict transactional synchronization with our source tables.Distributed Vector Retrieval & Downstream Serving: We query our vectorized Delta tables directly using high-performance Spark mathematical expressions to extract relevant context segments, which are then passed alongside user prompts to Azure OpenAI or surfaced through interactive interfaces.Generating Embeddings: Distributed Processing with Pandas UDFsTo transform raw, unstructured text into dense vector representations, we must process large volumes of data efficiently. Calling an external embedding API row-by-row in a traditional loop introduces severe latency bottlenecks and exhausts network bandwidth. To resolve this, we leverage PySpark’s vectorized Pandas User Defined Functions (@pandas_udf).Pandas UDFs utilize Apache Arrow to transfer data seamlessly between Spark JVM memory and Python worker processes without the performance penalty of standard Python serialization. This allows us to process incoming text series in batched chunks, optimizing worker throughput and stabilizing API call patterns.Below is the exact implementation we designed to read customer support transcripts from OneLake, generate 1536-dimensional vector embeddings using Azure OpenAI, and persist the results back into our Gold Lakehouse layer:# PySpark Notebook in Fabric: Creating Vector Embeddings for OneLake Text Dataimport openaifrom pyspark.sql.functions import pandas_udf, colimport pandas as pd# Set Azure OpenAI Configopenai.api_type = "azure"openai.api_base = "https://your-resource.openai.azure.com/"openai.api_key = "YOUR_KEY"# Define a Pandas UDF for batch embedding generation@pandas_udf("array")def generate_embeddings(text_series: pd.Series) -> pd.Series: def get_embedding(text): response = openai.Embedding.create( input=text, engine="text-embedding-ada-002" ) return response['data'][0]['embedding'] return text_series.apply(get_embedding)'# Read customer support logs from OneLakedf_logs = spark.read.table("Gold_Lakehouse.CustomerSupportTranscripts")# Generate embeddings and save as a new Delta table for vector searchdf_vectorized = df_logs.withColumn("VectorEmbedding", generate_embeddings(col("TranscriptText")))df_vectorized.write.format("delta").mode("overwrite").saveAsTable("Gold_Lakehouse.SupportVectors")Deconstructing the Vectorization PipelineLet us examine the mechanical steps executed by this concise script:Environment Configuration: We initialize our Azure OpenAI credentials and endpoint configurations directly within our secure Fabric Notebook execution session.Vectorized UDF Definition: By decorating our function with @pandas_udf("array"), we instruct PySpark that the output column will be structured as an array of floating-point values. The inner function accepts a pandas.Series containing text fragments and dispatches API requests to the text-embedding-ada-002 model.Reading Governed Delta Tables: We invoke spark.read.table("Gold_Lakehouse.CustomerSupportTranscripts") to fetch our curated support transcripts natively from OneLake. Fabric abstracts away underlying ABFSS file paths and partition handling automatically.Distributed Transformation: When we execute withColumn("VectorEmbedding", generate_embeddings(...)), PySpark distributes the workload across the active Spark cluster nodes. Each executor node processes a slice of the dataset in parallel, sending batched requests to Azure OpenAI.Atomic Delta Lake Persistence: Finally, we persist the vectorized DataFrame back into OneLake using .write.format("delta").saveAsTable("Gold_Lakehouse.SupportVectors"). Because Delta Lake provides strict ACID transaction guarantees, our vectorized dataset remains resilient against partial failures during write operations.Vector Search: Querying Embeddings Using PySpark & Math FunctionsOnce our text embeddings are persisted in OneLake, we require a method to identify the most relevant customer transcripts when an incoming user query arrives. In traditional RAG setups, this step relies on dedicated vector databases using index structures like HNSW or IVF. However, for datasets containing hundreds of thousands to millions of rows, we can compute mathematical similarity directly within PySpark using vector geometry.Cosine similarity is the gold standard metric for measuring semantic closeness between high-dimensional text embeddings. Conceptually, it evaluates the angle between two vectors, such as an incoming user query and a stored document to determine how similar they are in context.Distributed Vector Lookup in PySparkWe can implement this similarity lookup natively by taking an incoming user prompt, generating its vector representation, and computing the dot product against our vector column stored in Gold_Lakehouse.SupportVectors:# PySpark Vector Retrieval Codeimport numpy as npfrom pyspark.sql.functions import udf, colfrom pyspark.sql.types import FloatType# 1. Generate query embedding for user promptuser_prompt = "How do I reset my customer portal password?"prompt_response = openai.Embedding.create(input=user_prompt, engine="text-embedding-ada-002")query_vector = prompt_response['data'][0]['embedding']# 2. Define a cosine similarity / dot product UDF@udf(returnType=FloatType())def compute_similarity(doc_vector): if doc_vector is None: return 0.0 return float(np.dot(query_vector, doc_vector))# 3. Query vectors from OneLake and retrieve top 5 matchesdf_vectors = spark.read.table("Gold_Lakehouse.SupportVectors")top_matches = ( df_vectors .withColumn("Similarity", compute_similarity(col("VectorEmbedding"))) .orderBy(col("Similarity").desc()) .limit(5))# Collect top context documentsretrieved_docs = [row['TranscriptText'] for row in top_matches.collect()]By executing this transformation across our Spark cluster, we perform candidate vector retrieval directly inside our analytical Lakehouse engine. The process retrieves the most contextually relevant transcript segments within milliseconds, perfectly preparing our pipeline for the generative synthesis stage.Serving and Orchestration: Synthesizing Context and DeploymentWith our vector retrieval engine operational, the final component of our enterprise RAG pipeline is prompt orchestration and response generation. We synthesize the retrieved transcript passages into a grounded context window and submit the instruction to Azure OpenAI Chat Completions.# Construct grounded context promptcontext_block = "\n---\n".join(retrieved_docs)system_instruction = ( "We are an AI assistant designed to answer customer support queries based strictly on historic logs. " "Use only the provided context to answer the prompt accurately.")# Call Azure OpenAI Chat Completioncompletion_response = openai.ChatCompletion.create( engine="gpt-4", messages=[ {"role": "system", "content": system_instruction}, {"role": "user", "content": f"Context:\n{context_block}\n\nQuestion: {user_prompt}"} ])final_answer = completion_response['choices'][0]['message']['content']print(final_answer)Deployment Patterns: Gradio and Copilot Studio IntegrationsTo bring this RAG solution into production and surface it to business stakeholders across our organization, we evaluate two highly effective serving patterns:Embedded Interactive Interfaces in Fabric: For internal prototyping, testing, or technical user interfaces, we can wrap our retrieval and synthesis functions into a lightweight Gradio interface running directly within a Fabric Notebook session. This allows analysts to test context retrieval, adjust hyper-parameters, and evaluate model grounding in real time.Copilot Studio & Semantic Link Orchestration: For enterprise-wide deployment, we can expose our PySpark RAG execution logic as an automated backend endpoint or register our Lakehouse tables within Power BI semantic models using Semantic Link (sempy). Copilot Studio can then query these semantic layers and invoke our underlying vectorized tables seamlessly, providing business users with an AI agent that converses with governed enterprise data in real time.Production Considerations: Performance, Cost, and GovernanceAs we transition our concise PySpark RAG pipeline into a continuous production environment, we incorporate several critical engineering practices to maintain operational efficiency and low compute cost:Storage Optimization with V-Order: When saving our vectorized Delta tables in OneLake, we ensure that Microsoft’s proprietary V-Order compression is enabled. V-Order reorganizes Parquet files at write time, dramatically improving memory layout and accelerating downstream read speeds when Spark or SQL engines scan vector arrays.Incremental Embeddings via Change Data Capture (CDC): Rather than re-generating embeddings for our entire dataset during every run, we implement incremental processing using Delta Lake transaction logs. By inspecting modified rows, we only vectorize newly inserted or updated customer transcripts, reducing OpenAI API overhead substantially.Unified Data Governance & Security: Because our embeddings reside within native OneLake Delta tables, they inherit Microsoft Purview governance policies, row-level security, and access controls automatically. Sensitive customer information remains fully safeguarded without requiring complex vector database role-based access configurations.ConclusionBy unifying our storage layer, distributed compute, vector geometry, and generative AI orchestration within Microsoft Fabric, we eliminate the friction of managing external infrastructure. In under 50 lines of Python code, we constructed a resilient, enterprise-grade RAG pipeline that operates entirely on top of open Delta Parquet tables in OneLake. This architecture keeps our enterprise data fully governed, minimizes total cost of ownership, and accelerates our time-to-value when deploying generative AI solutions. As we continue to advance our data engineering practices, solutions like this demonstrate that powerful enterprise AI does not require overly complex stacks, only the right unified foundation.Hey, I am Sandip Palit, from Kolkata, India. I love to explore what’s new in the Data Science space and share it with the community. I am a Fabric Super User, and in this Microsoft Fabric Playlist, I will share my learnings on Microsoft Fabric and the tips and tricks of using it effectively..Thank You for reading this article. Please feel free to share your thoughts in the comments section, and give this article a 🌟.Building an Enterprise RAG AI on OneLake Data in 50 Lines of Python was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.