<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Juan Ovalle on Medium]]></title>
        <description><![CDATA[Stories by Juan Ovalle on Medium]]></description>
        <link>https://medium.com/@juan.ovallevillamil?source=rss-e0686e203e91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zR8bBjbkENs7jxPTITluFQ.png</url>
            <title>Stories by Juan Ovalle on Medium</title>
            <link>https://medium.com/@juan.ovallevillamil?source=rss-e0686e203e91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:05:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@juan.ovallevillamil/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The King of Multi-Modal RAG: ColPali]]></title>
            <link>https://medium.com/@juan.ovallevillamil/the-king-of-multi-modal-rag-colpali-3a03b0db476c?source=rss-e0686e203e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a03b0db476c</guid>
            <category><![CDATA[colpali]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[multimodal]]></category>
            <dc:creator><![CDATA[Juan Ovalle]]></dc:creator>
            <pubDate>Thu, 05 Jun 2025 12:05:42 GMT</pubDate>
            <atom:updated>2025-06-05T12:05:57.366Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What exactly is ColPali in the document retrieval world?</strong></p><p>Traditional RAG systems have always struggled with complex documents — losing formatting, missing tables, and fumbling with figures. They treat documents as plain text, throwing away the visual richness that makes them meaningful.</p><p>Instead of extracting text and hoping for the best, <a href="https://arxiv.org/pdf/2407.01449">ColPali</a> treats documents as images, preserving every table, figure, and layout element. Like having a photographic memory for documents, it understands not just what’s written, but how it’s presented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uFzBWRazHqkTzyBk.png" /><figcaption>Taken from <a href="https://arxiv.org/pdf/2407.01449">ColPali: EFFICIENT DOCUMENT RETRIEVAL WITH VISION LANGUAGE MODELS</a></figcaption></figure><p>In this tutorial, <strong>we’ll create a web API that uses ColPali for visual document retrieval</strong>. Users can upload PDFs through REST endpoints, and the system will answer questions about those documents by understanding their visual layout — tables, figures, formatting and all.</p><p>ColPali represents a fundamental shift in how we approach document understanding. The original research introduced a clever technique: instead of extracting text from documents, they fed document images directly to a Vision-Language Model (PaliGemma-3B). The model splits each image into patches, processes them through a vision transformer, and generates contextualized embeddings in the language model space, essentially creating a visual understanding of the content.</p><p>Here’s what makes this approach powerful: during indexing, the vision transformer encodes document images by splitting them into patches, which become “soft” tokens for the language model. This produces high-quality contextualized patch embeddings that capture both textual content and spatial relationships. These embeddings are then projected to a lower dimension for efficient storage, creating what the researchers call “multi-vector document representations.”</p><p>The technique has evolved since the original paper. While ColPali established the methodology, newer implementations have experimented with different vision-language models as the backbone. The version we’re using in this tutorial (ColQwen 2.5) leverages Qwen2.5-VL, a more efficient vision-language model that maintains the same core approach while offering improved performance.</p><h3>Understanding the Core Components of a ColPali RAG System</h3><p>The backbone of a ColPali-based RAG application consists of five essential components that work together to create a visual document understanding pipeline:</p><ol><li><strong>PDF to Image Converter</strong>: Transforms PDF documents into high-quality images using pdf2image with optimized DPI settings. This preserves the document’s visual integrity — every table border, diagram annotation, and layout relationship that would be lost in traditional text extraction.</li><li><strong>Storage Service:</strong> Persists the converted images for retrieval during query processing. This component ensures document images remain accessible throughout the system’s lifetime.</li><li><strong>ColPali Model (ColQwen 2.5)</strong>: The visual understanding engine that generates embeddings directly from document images. Unlike traditional RAG models that process extracted text, ColQwen 2.5 captures spatial relationships, formatting context, and the interplay between text and visual elements.</li><li><strong>Vector Database (Qdrant)</strong>: Stores and indexes the visual embeddings for efficient similarity search. Qdrant’s multi-vector storage and cosine similarity support make it ideal for ColPali’s embedding structure, enabling precise page-level retrieval with metadata.</li><li><strong>Multimodal LLM (Claude Sonnet 3.7)</strong>: Interprets retrieved document images and generates responses. By working with actual images rather than extracted text, it can accurately reference tables, interpret figures, and maintain the document’s original visual context.</li></ol><h4>How Data Flows Through the System</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E4oIOtTY1DqC82Gg.png" /></figure><p><strong>Ingestion Pipeline:</strong> During document ingestion, PDFs are first converted into JPEG images which are then uploaded to the storage service. ColQwen 2.5 processes each page image to generate multi-vector embeddings that capture both textual content and spatial relationships. These embeddings are stored in Qdrant along with metadata including session ID, document name, and page number for efficient retrieval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yv_c5K2M2daSy4UX.png" /></figure><p><strong>Inference Pipeline</strong>: When processing user queries, the system converts the query text into an embedding using the same ColQwen 2.5 model to ensure compatibility. Qdrant performs a similarity search to find the most relevant document pages, then the storage service retrieves the actual page images for these matches. Finally, Claude Sonnet 3.7 receives both the original query and the retrieved images to generate a contextually accurate response.</p><blockquote>This architecture is provider-agnostic — you could substitute Qdrant with Weaviate, Supabase with S3, or Claude with GPT-4o. The key principle is maintaining the visual pipeline throughout, ensuring no visual information is lost in translation.</blockquote><p><strong>💻 Enough theory, let’s get into the implementation ↓</strong></p><h3>Service Providers</h3><p>You’re free to choose any providers for the five main components. In this tutorial, I use:</p><ul><li><strong>Document Processing</strong>: pdf2image for PDF conversion</li><li><strong>Object Storage</strong>: Supabase for image storage</li><li><strong>Visual Embeddings</strong>: ColQwen 2.5 (v0.2) from Hugging Face</li><li><strong>Vector Storage</strong>: Qdrant Cloud</li><li><strong>Response Generation</strong>: Claude Sonnet 3.7 from Anthropic</li></ul><p><em>Note: Why Supabase for storage? While you could use S3, Google Cloud Storage, or even local storage, Supabase offers a convenient free storage tier.</em></p><h4>Dependencies</h4><p>Before we start building our ColPali RAG application, let’s ensure we have all the necessary Python packages installed.</p><ul><li>pdf2image: Converts PDF documents into images</li><li>colpali-engine: Provides the ColPali models and processors</li><li>qdrant-client: Handles vector database operations and similarity search</li><li>supabase: Manages object storage for document images</li><li>fastapi[standard]: Powers our web API</li><li>instructor[anthropic]: Enables structured output parsing from Claude</li><li>pydantic-settings: Manages environment variables and configuration</li></ul><blockquote>Note: The <em>pdf2image</em> package requires Poppler. Check the <a href="https://pdf2image.readthedocs.io/en/latest/installation.html#installing-poppler">official documentation</a> and follow the appropriate instructions for your operating system.</blockquote><h3>Environment Variables</h3><p>To connect to these services, you’ll need API keys and configuration variables.</p><p><strong>Set up Anthropic:</strong> Create an an <a href="https://docs.anthropic.com/en/docs/get-started">Anthropic</a> ccount and generate an API key to use Claude Sonnet 3.7.</p><p><strong>Set up Qdrant:</strong> Create a <a href="https://qdrant.to/cloud">Qdrant Cloud</a> account and set up a free cluster for the vector store. This will provide both an API key and host URL. You’ll also need to choose a name for the collection that will be created in the next section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s1cvMPryIGw7tw6k.png" /></figure><p><strong>Set up Supabase:</strong> Create a <a href="https://supabase.com/dashboard">Supabase</a> account and project to get your project URL and API key. Then create a bucket in Supabase Storage and note the bucket name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tRWPw07JsJIx7Dfv.png" /></figure><p>Once you have all the keys, create a .env file that looks like this:</p><pre># Vector Database<br>QDRANT_URL=&lt;your-qdrant-url&gt;<br>QDRANT_API_KEY=&lt;your-qdrant-api-key&gt;<br>COLLECTION_NAME=&lt;your-collection-name&gt;</pre><pre># Storage<br>SUPABASE_URL=&lt;your-supabase-url&gt;<br>SUPABASE_KEY=&lt;your-supabase-key&gt;</pre><pre># AI Model<br>ANTHROPIC_API_KEY=&lt;your-anthropic-api-key&gt;</pre><p>💡<em> </em><strong><em>Note:</em></strong><em> Always add </em>.env<em> to your </em>.gitignore<em> to protect your credentials.<br></em>Now we&#39;ll use pydantic-settings to manage these securely:</p><pre>import os<br>from functools import lru_cache</pre><pre>from pydantic_settings import BaseSettings<br></pre><pre>class QdrantSettings(BaseSettings):<br>    collection_name: str = os.environ.get(&quot;QDRANT_COLLECTION_NAME&quot;, &quot;&quot;)<br>    qdrant_url: str = os.environ.get(&quot;QDRANT_URL&quot;, &quot;&quot;)<br>    qdrant_api_key: str = os.environ.get(&quot;QDRANT_API_KEY&quot;, &quot;&quot;)<br></pre><pre>class ColpaliSettings(BaseSettings):<br>    colpali_model_name: str = &quot;vidore/colqwen2.5-v0.2&quot;<br></pre><pre>class SupabaseSettings(BaseSettings):<br>    supabase_key: str = os.environ.get(&quot;SUPABASE_KEY&quot;, &quot;&quot;)<br>    supabase_url: str = os.environ.get(&quot;SUPABASE_URL&quot;, &quot;&quot;)<br>    bucket: str = &quot;colpali&quot;<br></pre><pre>class AnthropicSettings(BaseSettings):<br>    api_key: str = os.environ.get(&quot;ANTHROPIC_API_KEY&quot;, &quot;&quot;)<br></pre><pre>class Settings(BaseSettings):<br>    qdrant: QdrantSettings = QdrantSettings()<br>    colpali: ColpaliSettings = ColpaliSettings()<br>    supabase: SupabaseSettings = SupabaseSettings()<br>    anthropic: AnthropicSettings = AnthropicSettings()<br></pre><pre>@lru_cache<br>def get_settings() -&gt; Settings:<br>    return Settings()</pre><h3>Set up Qdrant Collection</h3><p>A collection in Qdrant serves as a container for vectors with the same dimensionality. In our ColPali system, it stores the multi-vector embeddings representing each document image.</p><p>You can create a collection through Qdrant Cloud’s UI or programmatically. Either way, the configuration follows <a href="https://arxiv.org/pdf/2407.01449">ColPali’s</a> specifications:</p><ul><li><strong>Embedding dimension</strong>: 128 (as specified in the ColPali paper)</li><li><strong>Distance metric</strong>: Cosine similarity for comparing embeddings</li><li><strong>Multi-vector comparison</strong>: Max similarity finds the best matching spots on each page for your query</li></ul><p>Here’s a simplified version of the programmatic approach:</p><pre># Full version available at https://github.com/jjovalle99/colpali-rag-app/blob/main/scripts/create_collection.py</pre><pre>qdrant_client.create_collection(<br>    collection_name=COLLECTION_NAME,<br>    vectors_config=models.VectorParams(<br>        size=128,<br>        distance=models.Distance.COSINE,<br>        multivector_config=models.MultiVectorConfig(<br>            comparator=models.MultiVectorComparator.MAX_SIM<br>        ),<br>    )<br>)</pre><h3>Loading the ColPali model</h3><p>If you’ve worked with Hugging Face models before, this step will feel familiar. The ColPali team provides a Python library that makes it straightforward to interact with their models. You can find their repository at <a href="https://github.com/illuin-tech/colpali">https://github.com/illuin-tech/colpali</a>.</p><p>When loading ColPali models, we need to consider a few key aspects:</p><ul><li><strong>Device Selection</strong>: The model can run on CUDA (NVIDIA GPUs), MPS (Apple Silicon), or CPU</li><li><strong>Precision</strong>: Using bfloat16 or float16 reduces memory usage while maintaining quality</li><li><strong>Attention Implementation</strong>: Flash Attention 2 significantly speeds up inference when available</li></ul><p>Here’s how to load the model and processor:</p><pre>import torch<br>from PIL import Image<br>from transformers.utils.import_utils import is_flash_attn_2_available</pre><pre>from colpali_engine.models import ColQwen2, ColQwen2Processor</pre><pre>model_name = &quot;vidore/colqwen2-v1.0&quot;</pre><pre>model = ColQwen2.from_pretrained(<br>    model_name,<br>    torch_dtype=torch.bfloat16,<br>    device_map=&quot;cuda:0&quot;,  # or &quot;mps&quot; if on Apple Silicon<br>    attn_implementation=&quot;flash_attention_2&quot; if is_flash_attn_2_available() else None,<br>).eval()</pre><pre>processor = ColQwen2Processor.from_pretrained(model_name)</pre><pre># Your inputs<br>images = [<br>    Image.new(&quot;RGB&quot;, (128, 128), color=&quot;white&quot;),<br>    Image.new(&quot;RGB&quot;, (64, 32), color=&quot;black&quot;),<br>]<br>queries = [<br>    &quot;What is the organizational structure for our R&amp;D department?&quot;,<br>    &quot;Can you provide a breakdown of last year’s financial performance?&quot;,<br>]</pre><pre># Process the inputs<br>batch_images = processor.process_images(images).to(model.device)<br>batch_queries = processor.process_queries(queries).to(model.device)</pre><pre># Forward pass<br>with torch.no_grad():<br>    image_embeddings = model(**batch_images)<br>    query_embeddings = model(**batch_queries)</pre><pre>scores = processor.score_multi_vector(query_embeddings, image_embeddings)</pre><p>To make our code more maintainable and avoid repeated initialization, let’s encapsulate the model loading logic into a dedicated class. This approach allows us to:</p><ul><li>Automatically detect the best available hardware (GPU, Apple Silicon, or CPU)</li><li>Select the optimal precision for your system</li><li>Handle the attention implementation gracefully</li></ul><pre>class ColQwen2_5Loader:<br>    def __init__(self, model_name: str):<br>        self.model_name = model_name<br>        self._device = (<br>            &quot;cuda&quot; if torch.cuda.is_available()<br>            else &quot;mps&quot; if torch.backends.mps.is_available()<br>            else &quot;cpu&quot;<br>        )<br>        self._dtype = (<br>            torch.bfloat16 if torch.cuda.is_bf16_supported() <br>            else torch.float16<br>        )</pre><pre>    def load(self):<br>        model = ColQwen2_5.from_pretrained(<br>            self.model_name,<br>            device_map=self._device,<br>            torch_dtype=self._dtype,<br>            attn_implementation=&quot;flash_attention_2&quot; if available else None<br>        ).eval()<br>        <br>        processor = ColQwen2_5_Processor.from_pretrained(self.model_name)<br>        <br>        return model, processor</pre><blockquote>Note: The <em>.eval()</em> call is crucial here as it ensures the model runs in evaluation mode, disabling dropout and other operations that would otherwise affect our embeddings&#39; consistency.</blockquote><p>This loader class provides a clean interface for initializing ColPali models throughout our application. We’ll use this in the next sections when building our ingestion pipeline and query functionality.</p><h3>Building the Document Ingestion Pipeline</h3><p>Now let’s build the document ingestion pipeline — the component that transforms PDFs into searchable visual embeddings.</p><p>If you look at traditional RAG pipelines, they typically extract text from PDFs, chunk it, and generate embeddings. But this approach loses crucial information — table structures, figure placements, and visual relationships that give documents their meaning. ColPali takes a fundamentally different approach.</p><p>Instead of text extraction, we’ll convert each PDF page into a high-resolution image and process it visually. This preserves everything — from complex tables to annotated diagrams.</p><pre>class PDFIngestController:<br>    def __init__(self, model, processor, uploader, qdrant_client, collection_name):<br>        self.model = model<br>        self.processor = processor<br>        self.uploader = uploader<br>        self.qdrant_client = qdrant_client<br>        self.collection_name = collection_name</pre><pre>    async def ingest(self, files: list[UploadFile], session_id: UUID4):<br>        results = []<br>        <br>        for file in files:<br>            # Convert PDF to high-resolution images<br>            pdf_bytes = await file.read()<br>            images = await run_in_threadpool(<br>                convert_from_bytes,<br>                pdf_file=pdf_bytes,<br>                dpi=300,  # High DPI for clear text<br>                thread_count=4,<br>                fmt=&quot;jpeg&quot;<br>            )<br>            <br>            # Process images with ColPali<br>            for page_num, image in enumerate(images, 1):<br>                with torch.inference_mode():<br>                    processed = self.processor.process_images([image])<br>                    embedding = self.model(**processed.to(self.model.device))<br>                <br>                # Store in vector database<br>                point = models.PointStruct(<br>                    id=str(uuid4()),<br>                    vector=embedding.cpu().float().numpy().tolist(),<br>                    payload={<br>                        &quot;session_id&quot;: session_id,<br>                        &quot;document&quot;: file.filename,<br>                        &quot;page&quot;: page_num<br>                    }<br>                )<br>                await self.qdrant_client.upsert(<br>                    collection_name=self.collection_name,<br>                    points=[point]<br>                )<br>                <br>                # Upload image to storage<br>                await self.uploader.upload_image(<br>                    session_id=session_id,<br>                    file_name=file.filename,<br>                    page=page_num,<br>                    image=image<br>                )</pre><p>In this code snippet, we:</p><ol><li>Receive the user file</li><li>Split each file into individual pages</li><li>Convert the pages into images</li><li>Persist the images</li><li>Generate the multi-vector embeddings using ColPali model</li><li>Store the vectors in the collection</li></ol><h3>Building the Inference Pipeline</h3><p>Traditional RAG systems search through text chunks and concatenate them for the LLM. But since we’re working with visual documents, our pipeline needs to handle images throughout the entire process. This means searching with visual embeddings, retrieving actual document images, and feeding them directly to a multimodal LLM.</p><pre>class QueryController:<br>    def __init__(self, model, processor, downloader, instructor_client, <br>                 qdrant_client, collection_name, prompts):<br>        self.model = model<br>        self.processor = processor<br>        self.downloader = downloader<br>        self.instructor_client = instructor_client<br>        self.qdrant_client = qdrant_client<br>        self.collection_name = collection_name<br>        self.prompts = prompts</pre><pre>    async def query(self, query: str, top_k: int, session_id: UUID4):<br>        # Generate query embedding<br>        with torch.inference_mode():<br>            processed_query = self.processor.process_queries([query])<br>            query_embedding = self.model(**processed_query.to(self.model.device))<br>        <br>        # Search for similar document pages<br>        search_results = await self.qdrant_client.query_points(<br>            collection_name=self.collection_name,<br>            query=query_embedding[0].cpu().float().tolist(),<br>            limit=top_k,<br>            query_filter=models.Filter(<br>                must=[models.FieldCondition(<br>                    key=&quot;session_id&quot;,<br>                    match=models.MatchValue(value=str(session_id))<br>                )]<br>            )<br>        )<br>        <br>        # Download retrieved images<br>        filenames = [<br>            f&quot;{point[&#39;session_id&#39;]}/{point[&#39;document&#39;]}/{point[&#39;page&#39;]}.jpeg&quot;<br>            for point in search_results.points<br>        ]<br>        images = await self.downloader.download_instructor_images(filenames)<br>        <br>        # Generate response with multimodal LLM<br>        prompt_content = [self.prompts[&quot;prompt1&quot;]]<br>        for filename, image in zip(filenames, images):<br>            prompt_content.extend([<br>                f&#39;&lt;image file=&quot;{filename}&quot;&gt;&#39;,<br>                image,<br>                &#39;&lt;/image&gt;&#39;<br>            ])<br>        prompt_content.append(self.prompts[&quot;prompt2&quot;])<br>        <br>        # Stream the response<br>        stream = self.instructor_client.completions.create_partial(<br>            model=&quot;claude-3-7-sonnet-latest&quot;,<br>            messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt_content}],<br>            context={&quot;query&quot;: query},<br>            temperature=0.0,<br>            max_tokens=8192<br>        )<br>        <br>        async for partial in stream:<br>            yield partial.model_dump_json() + &quot;\n&quot;</pre><p>Let’s break down what happens in this pipeline:</p><ol><li><strong>Query Embedding Generation</strong>: We convert the user’s question into a embedding using the same ColPali model. This ensures we’re searching in the same embedding space as our document images.</li><li><strong>Vector Similarity Search</strong>: Using Qdrant’s query capabilities, we find the most visually similar document pages. The multi-vector comparison (remember the MAX_SIM setting?) ensures we’re matching against the best regions within each page.</li><li><strong>Session Filtering</strong>: We filter results to only include documents from the current session, maintaining data isolation between users.</li><li><strong>Image Retrieval</strong>: Instead of retrieving text chunks, we download the actual document images from our storage service. This preserves the full visual context.</li><li><strong>Multimodal Response Generation</strong>: We construct a prompt that includes both the query and the retrieved images, then stream the response from Claude. The LLM can now reference specific tables, interpret figures, and understand the document’s visual layout.</li></ol><blockquote>Note: The streaming approach using <em>create_partial</em> from the <em>Instructor</em> library allows for real-time response generation while maintaining structured answer and reference formatting.</blockquote><p>This pipeline completes our visual RAG system. Unlike traditional approaches that would struggle with “find the revenue table on page 3,” our system understands both the semantic meaning and visual structure of documents, delivering accurate, contextual responses.</p><h3>Bringing It All Together: Building the API</h3><p>Now that we have our components ready, let’s bring everything together into a FastAPI application that can handle document ingestion and queries.</p><p>With our ColPali model, storage service, and vector database configured, we need to wire these components into a cohesive API. We’ll use FastAPI’s dependency injection system to manage our resources efficiently and ensure they’re properly initialized and cleaned up.</p><h3>Application Lifespan</h3><pre>from contextlib import asynccontextmanager<br>from fastapi import FastAPI</pre><pre>@asynccontextmanager<br>async def lifespan(app: FastAPI):<br>    settings = get_settings()<br>    <br>    # Initialize clients<br>    qdrant_client = create_qdrant_client(settings)<br>    anthropic_client = create_anthropic_client(settings)<br>    instructor_client = instructor.from_anthropic(anthropic_client)<br>    supabase_client = create_supabase_client(settings)<br>    <br>    # Initialize services<br>    supabase_uploader = SupabaseJPEGUploader(<br>        client=supabase_client, <br>        bucket_name=settings.supabase.bucket<br>    )<br>    supabase_downloader = SupabaseJPEGDownloader(<br>        client=supabase_client,<br>        bucket_name=settings.supabase.bucket<br>    )<br>    <br>    # Load ColPali model<br>    loader = ColQwen2_5Loader(model_name=&quot;vidore/colqwen2.5-v0.2&quot;)<br>    model, processor = loader.load()<br>    <br>    yield {<br>        &quot;model&quot;: model,<br>        &quot;processor&quot;: processor,<br>        &quot;supabase_uploader&quot;: supabase_uploader,<br>        &quot;supabase_downloader&quot;: supabase_downloader,<br>        &quot;instructor_client&quot;: instructor_client,<br>        &quot;qdrant_client&quot;: qdrant_client,<br>        &quot;collection_name&quot;: settings.qdrant.collection_name<br>    }<br>    <br>    # Cleanup<br>    await qdrant_client.close()<br>    await anthropic_client.close()</pre><p>In this lifespan handler, we:</p><ol><li><strong>Initialize all clients</strong>: Set up connections to Qdrant, Anthropic, and Supabase</li><li><strong>Load the ColPali model</strong>: This is the most resource-intensive step, loading the model into GPU memory</li><li><strong>Yield the resources</strong>: Make them available to our application through FastAPI’s state</li><li><strong>Clean up on shutdown</strong>: Properly close all connections to prevent resource leaks</li></ol><p>💡<em> </em><strong><em>Note:</em></strong><em> Loading the ColPali model can take 10–30 seconds depending on your hardware. The lifespan approach ensures this happens only once when your server starts.</em></p><h3>Setting Up the API Routes</h3><p>With our resources initialized, we need to create endpoints for document ingestion and querying. FastAPI’s dependency injection makes it elegant to access our shared resources in each endpoint.</p><p><strong>Document Ingestion Endpoint</strong> (/ingest-pdfs/):</p><ul><li>Accepts multiple PDF files and a session ID</li><li>Converts each PDF page to an image</li><li>Generates ColPali embeddings for each page</li><li>Stores the embeddings in Qdrant with metadata</li><li>Uploads the images to Supabase for later retrieval</li></ul><pre>@router.post(&quot;/ingest-pdfs/&quot;)<br>async def ingest_pdf(<br>    files: list[UploadFile],<br>    session_id: UUID4,<br>    model: Annotated[ColQwen2_5, Depends(get_colpali_model)],<br>    processor: Annotated[ColQwen2_5_Processor, Depends(get_colpali_processor)],<br>    uploader: Annotated[SupabaseJPEGUploader, Depends(get_supabase_uploader)],<br>    qdrant_client: Annotated[AsyncQdrantClient, Depends(get_qdrant_client)],<br>    collection_name: Annotated[str, Depends(get_collection_name)],<br>):<br>    controller = PDFIngestController(<br>        model=model,<br>        processor=processor,<br>        uploader=uploader,<br>        qdrant_client=qdrant_client,<br>        collection_name=collection_name,<br>    )<br>    return await controller.ingest(files=files, session_id=session_id)</pre><p>Let’s examine what each endpoint does:</p><p><strong>Query Endpoint</strong> (/query/):</p><ul><li>Takes a natural language query and session ID</li><li>Converts the query to a ColPali embedding</li><li>Searches for the most relevant document pages</li><li>Retrieves the actual page images</li><li>Streams the multimodal LLM’s response</li></ul><pre>@router.post(&quot;/query/&quot;)<br>async def query_endpoint(<br>    query: str,<br>    top_k: int,<br>    session_id: UUID4,<br>    model: Annotated[ColQwen2_5, Depends(get_colpali_model)],<br>    processor: Annotated[ColQwen2_5_Processor, Depends(get_colpali_processor)],<br>    downloader: Annotated[<br>        SupabaseJPEGDownloader, Depends(get_supabase_downloader)<br>    ],<br>    instructor_client: Annotated[<br>        AsyncInstructor, Depends(get_instructor_client)<br>    ],<br>    qdrant_client: Annotated[AsyncQdrantClient, Depends(get_qdrant_client)],<br>    collection_name: Annotated[str, Depends(get_collection_name)],<br>    prompts: Annotated[dict[str, str], Depends(get_prompts)],<br>):<br>    controller = QueryController(<br>        model=model,<br>        processor=processor,<br>        downloader=downloader,<br>        instructor_client=instructor_client,<br>        qdrant_client=qdrant_client,<br>        collection_name=collection_name,<br>        prompts=prompts,<br>    )<br>    return StreamingResponse(<br>        controller.query(query, top_k, session_id),<br>        media_type=&quot;text/event-stream&quot;,<br>    )</pre><p>The use of StreamingResponse in the query endpoint is crucial - it allows users to see results as they&#39;re generated rather than waiting for the complete response.</p><h3>Configuring the FastAPI Application</h3><p>Finally, we need to configure our FastAPI application with the necessary middleware and include our routers:</p><pre>from fastapi import FastAPI<br>from fastapi.middleware.cors import CORSMiddleware</pre><pre>app = FastAPI(lifespan=lifespan)</pre><pre>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;]<br>)</pre><pre>app.include_router(pdf_ingest.router)<br>app.include_router(query.router)</pre><h3>Testing the application</h3><p>With everything set up, let’s launch our ColPali RAG system:</p><pre>uvicorn server:app \<br>  --host 0.0.0.0 \<br>  --port 8000 \<br>  --reload</pre><p>Once your server is running, you can test the system through these steps:</p><ol><li><strong>Upload documents</strong>: Send PDFs to /ingest-pdfs/ with a session ID</li><li><strong>Query the system</strong>: Post queries to /query/ with the same session ID</li><li><strong>Stream responses</strong>: The system returns a stream of partial responses</li></ol><p>Programmatically, it would look something like this:</p><pre>import json<br>from pathlib import Path<br>from uuid import uuid4</pre><pre>import requests</pre><pre># Config<br>session_id = str(uuid4())<br>port = 8000<br>host = &quot;localhost&quot;</pre><pre># PDF Upload<br>url = f&quot;http://{host}:{port}/ingest-pdfs/?session_id={session_id}&quot;<br>pdf_path = Path(&quot;colpali.pdf&quot;)<br>headers = {<br>    &quot;accept&quot;: &quot;application/json&quot;,<br>}<br>with pdf_path.open(&quot;rb&quot;) as f:<br>    files = {&quot;files&quot;: (pdf_path.name, f, &quot;application/pdf&quot;)}<br>    response = requests.post(url, headers=headers, files=files)</pre><pre># Query<br>query = &quot;What are the advantages of Colpali? and what disadvantages does it have?&quot;<br>top_k = 5<br>url = f&quot;http://{host}:{port}/query/?query={query}&amp;top_k={top_k}&amp;session_id={session_id}&quot;</pre><pre>with requests.post(url, stream=True) as response:<br>    for chunk in response.iter_content(chunk_size=4096, decode_unicode=True):<br>        parsed_json = json.loads(chunk)<br>        formatted_json = json.dumps(parsed_json, indent=4)<br>        print(formatted_json)</pre><h3>Wrap-Up</h3><p>Congratulations! You now have a fully functional ColPali RAG system that can understand documents the way humans do — visually.</p><p>Throughout this tutorial, we’ve built a system that preserves the rich visual information in documents rather than discarding it. From converting PDFs to images, generating visual embeddings with ColPali, to having a multimodal LLM interpret the retrieved pages — every step maintains the visual pipeline.</p><p>To keep this tutorial focused and readable, I’ve shown you the core components and their interactions. However, a production system needs additional pieces like error handling, input validation, and proper logging.</p><blockquote>If you’re interested in the <strong>complete implementation</strong>, including all supporting code and best practices, I encourage you to check out the <a href="https://github.com/jjovalle99/colpali-rag-app"><strong>GitHub repository</strong></a>.</blockquote><h3>About the Author</h3><p>I’m <a href="https://www.linkedin.com/in/jjmov/"><strong>Juan Ovalle</strong></a>, an AI Engineer and Data Scientist passionate about building production-grade applications. My current work focuses on Generative AI applications, and I love exploring new technologies that make our lives as developers easier.</p><p>You can find more about my projects on <a href="https://github.com/jjovalle99"><strong>GitHub</strong></a> and <a href="http://www.linkedin.com/in/jjmov"><strong>LinkedIn</strong></a>.</p><h3>Images</h3><p>If not otherwise stated, all images are created by the author.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a03b0db476c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Your First Voice-to-Voice Application]]></title>
            <link>https://medium.com/@juan.ovallevillamil/building-your-first-voice-to-voice-application-b3b5248b4bdd?source=rss-e0686e203e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3b5248b4bdd</guid>
            <category><![CDATA[voice-assistant]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[pydantic-ai]]></category>
            <category><![CDATA[fastapi-tutorials]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Juan Ovalle]]></dc:creator>
            <pubDate>Sun, 19 Jan 2025 13:41:46 GMT</pubDate>
            <atom:updated>2025-01-25T09:37:09.877Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I had the chance to participate in a hackathon, and I decided to challenge myself by building a full voice-to-voice application. But what exactly is voice-to-voice? It’s an application that enables real-time voice communication between users over the internet — much like a phone call but integrated within your own app. Surprisingly, there’s limited information available on how to create such an application, and comprehensive guides are hard to find. You’ll need to understand WebSockets to handle real-time data transfer efficiently. In this article, I’ll guide you through building a simple voice-to-voice application.</p><h3>Understanding the Core Components of a Voice-to-Voice Application</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSIQfYCW00vV46UpW0LL5A.png" /></figure><p>The backbone of a voice-to-voice application consists of three essential components:</p><p><strong>1. Speech-to-Text (STT):</strong> This component transcribes spoken words into written text, allowing the application to understand user input. Popular solutions include OpenAI’s Whisper model and Amazon Transcribe. These tools convert audio into accurate text transcripts.</p><p><strong>2. Large Language Model (LLM):</strong> Serving as the brain of the application, an LLM generates meaningful responses based on the transcribed text. When choosing an LLM, consider one that can interact with external tools or APIs, as this capability enhances the application’s functionality by enabling more complex operations like retrieving real-time data or performing calculations.</p><p><strong>3. Text-to-Speech (TTS):</strong> This engine transforms the LLM’s textual responses back into spoken words, completing the conversational loop. Options include Amazon Polly and various open-source models. A good TTS engine produces natural-sounding speech, making interactions more engaging and accessible.</p><p><em>Note: You’re not limited to paid versions of these components. Open-source alternatives, such as models from Hugging Face, offer robust STT, LLM, and TTS capabilities. Utilizing open-source tools can reduce costs and provide greater customization for your application.</em></p><h3>Hands-On</h3><p>Now that we have a clear picture of what we want to build, let’s get right into coding. In this example, I’ll be using the <a href="https://docs.astral.sh/uv/#:~:text=uv%20executes%20and%20installs%20command,uvx%20pycowsay%20&#39;hello%20world!&#39;"><strong>uv</strong></a> to manage Python dependencies, but you can use your own environment manager of choice (Poetry, Conda, virtual environments, etc.)</p><p><em>Note: For detailed steps on how to scaffold and configure your project with uv, please consult the </em><a href="https://github.com/jjovalle99/Voice2Voice/tree/main?tab=readme-ov-file#project-setup-with-uv"><em>GitHub repository’s README.</em></a><em> This will give you all the commands and instructions for setting up the environment described in this tutorial.</em></p><p>Once your environment is ready, we’ll place our modules in the src/app folder and begin building the main application components.</p><h4>Component Providers</h4><p>You’re free to choose any providers you prefer for the three main components of this application. In this tutorial, I will use the following:</p><ul><li>STT: whisper-large-v3-turbo from Groq</li><li>LLM: llama-3.3–70b-versatile from Groq</li><li>TTS: tts-1 from OpenAI</li></ul><p><em>Note:</em> <em>These are examples, and you can replace them with models you have access to or prefer. Just ensure you have the necessary API keys or resources for these models.</em></p><h4>Environment Variables</h4><p>To communicate with the providers mentioned, we’ll need API keys. Additionally, we’ll need an API key to interact with the Weatherstack API. You can find instructions to obtain the keys at the following links:</p><ul><li><a href="https://console.groq.com/docs/quickstart"><em>Groq</em></a></li><li><a href="https://platform.openai.com/docs/quickstart"><em>OpenAI</em></a></li><li><a href="https://weatherstack.com/documentation"><em>Weatherstack</em></a></li></ul><p>Once you’ve collected the keys, we can create the .env file. It should look something like this:</p><pre>GROQ_API_KEY=&lt;your-key-here&gt;<br>OPENAI_API_KEY=&lt;your-key-here&gt;<br>WEATHERSTACK_API_KEY=&lt;your-key-here&gt;</pre><p><em>Note: Don’t forget to add your </em><em>.env file to your </em><em>.gitignore; you don&#39;t want your credentials to be available in a public repository.</em></p><p>Now, we’ll use pydantic-settings to access and validate our API keys. In our src/app folder, we&#39;ll create a new Python file called settings.py :</p><pre># src/app/settings.py<br>import os<br>from functools import lru_cache<br><br>from pydantic_settings import BaseSettings<br><br><br>class Settings(BaseSettings):<br>    groq_api_key: str = os.environ[&quot;GROQ_API_KEY&quot;]<br>    openai_api_key: str = os.environ[&quot;OPENAI_API_KEY&quot;]<br>    weatherstack_api_key: str = os.environ[&quot;WEATHERSTACK_API_KEY&quot;]<br><br><br>@lru_cache<br>def get_settings() -&gt; Settings:<br>    return Settings()</pre><p>We can now access our keys programmatically and securely. For example:</p><pre># Usage example<br>settings = get_settings()<br>print(settings.openai_api_key)</pre><h4>Building the Speech-to-Text (STT) Component</h4><p>Let’s start by building the Speech-to-Text (STT) component of our application.</p><p>If you refer to Groq <a href="https://console.groq.com/docs/speech-text">documentation</a> on implementing speech-to-text functionality, you’ll find an example like this:</p><pre>import os<br>from groq import Groq<br><br># Initialize the Groq client<br>client = Groq()<br><br># Specify the path to the audio file<br>filename = os.path.dirname(__file__) + &quot;/sample_audio.m4a&quot; # Replace with your audio file!<br><br># Open the audio file<br>with open(filename, &quot;rb&quot;) as file:<br>    # Create a transcription of the audio file<br>    transcription = client.audio.transcriptions.create(<br>      file=(filename, file.read()), # Required audio file<br>      model=&quot;whisper-large-v3-turbo&quot;, # Required model to use for transcription<br>      prompt=&quot;Specify context or spelling&quot;,  # Optional<br>      response_format=&quot;json&quot;,  # Optional<br>      language=&quot;en&quot;,  # Optional<br>      temperature=0.0  # Optional<br>    )<br>    # Print the transcription text<br>    print(transcription.text)</pre><p>Looking closely, you’ll notice that we simply need an audio file to send to the Groq client with the desired parameters, and we’ll receive the transcription in return. However, since we don’t want to store all the user inputs on disk — which can be inefficient and pose security concerns — we can utilize BytesIO to handle the audio data in memory, making the process more efficient:</p><pre># src/app/stt.py<br>from io import BytesIO<br><br>from groq import AsyncGroq<br><br><br>async def transcribe_audio_data(<br>    audio_data: bytes,<br>    api_client: AsyncGroq,<br>    model_name: str = &quot;whisper-large-v3-turbo&quot;,<br>    temperature: float = 0.0,<br>    language: str = &quot;en&quot;<br>) -&gt; str:<br>    with BytesIO(initial_bytes=audio_data) as audio_stream:<br>        audio_stream.name = &quot;audio.wav&quot;<br>        response = await api_client.audio.transcriptions.create(<br>            model=model_name,<br>            file=audio_stream,<br>            temperature=temperature,<br>            language=language,<br>        )<br>        text = response.text.strip()<br>        return text</pre><p>In this code snippet, we collect the audio bytes from the user, assign a filename to mimic an on-disk file, and send it directly to the Groq API to obtain the transcription.</p><h4>Building the Large Language Model (LLM) Component</h4><p>Now, let’s build the Large Language Model (LLM) component of our application.</p><p>For this component, I will use PydanticAI because it’s a lightweight framework that automates common operations when interacting with LLMs, such as handling messages, tools, and structured outputs. However, feel free to use your favorite framework or even pure Python to interact directly with the API clients. If you have the time, I highly recommend this approach, as it will give you a deeper understanding of LLM APIs.</p><p><strong>Setting Up Pydantic AI</strong></p><p>When using PydanticAI, we need to set up the following components:</p><ul><li><strong>Model</strong> (<em>Required</em>): Specify the LLM you plan to use. In our case, we’ll use llama-3.3–70b-versatile</li><li><strong>Dependencies</strong> (<em>Optional</em>): Think of dependencies as a way to inject external resources into the agent, similar to how FastAPI injects dependencies into route functions. For example, passing an HTTP client to the agent allows it to make API requests.</li><li><strong>System Prompt</strong> (<em>Optional</em>): This is the initial prompt that sets the behavior of the LLM, such as the classic “You are a helpful assistant.”</li><li><strong>Tools</strong> (<em>Optional</em>): Tools extend the capabilities of the LLM, allowing it to perform specific tasks or access external data.</li></ul><p><strong>Creating the Agent</strong></p><p>We’ll create a Python module that brings all these components together:</p><pre># src/app/llm.py<br>from dataclasses import dataclass<br>from typing import Literal<br><br>import aiohttp<br>from groq import AsyncGroq<br>from pydantic_ai import Agent, RunContext, Tool<br>from pydantic_ai.models.groq import GroqModel<br><br>from app.settings import Settings<br><br>type AvailableCities = Literal[&quot;Paris&quot;, &quot;Madrid&quot;, &quot;London&quot;]<br><br><br># 1. Dependencies: We can define a dataclass to hold the dependencies that our agent can use in its tools or prompts.<br>@dataclass<br>class Dependencies:<br>    settings: Settings<br>    session: aiohttp.ClientSession<br><br><br># 2. Tool: We can define functions that can be used by the agent to perform specific tasks.<br>async def get_weather(ctx: RunContext[Dependencies], city: AvailableCities) -&gt; str:<br>    url = &quot;http://api.weatherstack.com/current&quot;<br>    params = {<br>        &quot;access_key&quot;: ctx.deps.settings.weatherstack_api_key,<br>        &quot;query&quot;: city,<br>    }<br><br>    async with ctx.deps.session.get(url=url, params=params) as response:<br>        data = await response.json()<br>        observation_time = data.get(&quot;current&quot;).get(&quot;observation_time&quot;)<br>        temperature = data.get(&quot;current&quot;).get(&quot;temperature&quot;)<br>        weather_descriptions = data.get(&quot;current&quot;).get(&quot;weather_descriptions&quot;)<br>        return f&quot;At {observation_time}, the temperature in {city} is {temperature}°C. The weather is {weather_descriptions[0].lower()}&quot;<br><br><br># 3. Model<br>def create_groq_model(<br>    groq_client: AsyncGroq,<br>) -&gt; GroqModel:<br>    return GroqModel(<br>        model_name=&quot;llama-3.3-70b-versatile&quot;,<br>        groq_client=groq_client,<br>    )<br><br><br># 4. Agent<br>def create_groq_agent(<br>    groq_model: GroqModel,<br>    tools: list[Tool[Dependencies]],<br>    system_prompt: str,  # 5. System Prompt<br>) -&gt; Agent[Dependencies]:<br>    return Agent(<br>        model=groq_model,<br>        deps_type=Dependencies,<br>        system_prompt=system_prompt,<br>        tools=tools,<br>    )</pre><p>Some highlights:</p><ul><li><strong>Data Classes and Dependencies</strong>: We define a data class that specifies the objects stored in the agent’s context. In this case, we want the agent to have access to an HTTP client for making requests and an instance of the Settings class that contains our credentials. These dependencies are not provided to the LLM in the prompts but are used externally to support the agent&#39;s functionality.</li><li><strong>Tool Definition</strong>: In the tool definition, we expect the model to retrieve accurate information based on the city provided. The context is passed using the dependencies. In this example, we specify that the model can only fetch information for specific cities. This is just a sample implementation — you are free to code the tool function as you like.</li><li><strong>Model Initialization</strong>: When creating the model, we can initialize it directly with the API key instead of the client (PydanticAI handles the creation of the client internally). However, providing a client instance can avoid multiple initializations, making your code more efficient.</li></ul><p>If any of this is unclear, I highly recommend checking out the <a href="https://ai.pydantic.dev/#why-use-pydanticai">PydanticAI documentation</a>. It’s a valuable resource that can enhance your understanding and help you make the most of this framework in your applications.</p><h4>Building the Text-to-Speech (TTS) Component</h4><p>Finally, we will build what is probably the most challenging component: the Text-to-Speech (TTS) system.</p><p>If we aim for real-time interactions, we need to produce audio as soon as the LLM (Large Language Model) generates tokens. Otherwise, we’ll have to wait for the full chat completion before generating the audio. There’s nothing inherently wrong with the latter approach, but the user experience will be “near” real-time, meaning users will need to wait longer before hearing the response.</p><p><em>Note: OpenAI offers a </em><a href="https://platform.openai.com/docs/guides/realtime"><em>realtime API </em></a><em>that integrates both the LLM and TTS components of our application. You could use it to save some coding effort; however, only the </em><em>gpt-4o and </em><em>gpt-4o-mini models are available.</em></p><p>If we were willing to wait for the full generation, we could use something like this:</p><pre>from openai import OpenAI<br><br>client = OpenAI()<br><br>response = client.audio.speech.create(<br>    model=&quot;tts-1&quot;,<br>    voice=&quot;alloy&quot;,<br>    input=&quot;Hello world! This is a streaming test.&quot;,<br>)<br><br>response.stream_to_file(&quot;output.mp3&quot;)</pre><p>However, since we want to stream audio as soon as we receive tokens from the LLM, we need to take a different approach. We have to be very careful here because the streaming of tokens and the streaming of audio are interrelated, and we might end up with tightly coupled code. We want to avoid this, and one way to achieve that is by using a context manager.</p><pre># src/app/tts.py<br>class TextToSpeech:<br>    def __init__(<br>        self,<br>        client: AsyncOpenAI,<br>        model_name: str,<br>        voice: Voice = &quot;echo&quot;,<br>        response_format: ResponseFormat = &quot;aac&quot;,<br>        speed: float = 1.00,<br>        buffer_size: int = 64,<br>        sentence_endings: tuple[str, ...] = (<br>            &quot;.&quot;,<br>            &quot;?&quot;,<br>            &quot;!&quot;,<br>            &quot;;&quot;,<br>            &quot;:&quot;,<br>            &quot;\n&quot;,<br>        ),<br>        chunk_size: int = 1024 * 5,<br>    ) -&gt; None:<br>        self.client = client<br>        self.model_name = model_name<br>        self.voice: Voice = voice<br>        self.response_format: ResponseFormat = response_format<br>        self.speed = speed<br>        self.buffer_size = buffer_size<br>        self.sentence_endings = sentence_endings<br>        self.chunk_size = chunk_size<br>        self._buffer = &quot;&quot;<br><br>    async def __aenter__(self) -&gt; &quot;TextToSpeech&quot;:<br>        &quot;&quot;&quot;<br>        Enters the asynchronous context manager.<br><br>        Returns:<br>            The TextToSpeech instance.<br>        &quot;&quot;&quot;<br>        return self<br><br>    async def feed(self, text: str) -&gt; AsyncIterator[bytes]:<br>        &quot;&quot;&quot;<br>        Feeds text into the buffer and yields audio bytes if the buffer reaches the buffer size<br>        or ends with a sentence-ending character.<br><br>        Args:<br>            text: The text to add to the buffer.<br><br>        Yields:<br>            Audio bytes generated from the buffered text.<br>        &quot;&quot;&quot;<br>        self._buffer += text<br>        if len(self._buffer) &gt;= self.buffer_size or any(<br>            self._buffer.endswith(se) for se in self.sentence_endings<br>        ):<br>            async for chunk in self.flush():<br>                yield chunk<br><br>    async def flush(self) -&gt; AsyncIterator[bytes]:<br>        &quot;&quot;&quot;<br>        Flushes the buffered text and yields the resulting audio bytes.<br><br>        Yields:<br>            Audio bytes generated from the buffered text.<br>        &quot;&quot;&quot;<br>        if self._buffer:<br>            async for chunk in self._send_audio(self._buffer):<br>                yield chunk<br>            self._buffer = &quot;&quot;<br><br>    async def _send_audio(self, text: str) -&gt; AsyncIterator[bytes]:<br>        &quot;&quot;&quot;<br>        Sends text to the TTS API and yields audio chunks.<br><br>        Args:<br>            text: The text to convert to speech.<br><br>        Yields:<br>            Chunks of audio bytes generated from the input text.<br>        &quot;&quot;&quot;<br>        async with self.client.audio.speech.with_streaming_response.create(<br>            model=self.model_name,<br>            input=text,<br>            voice=self.voice,<br>            response_format=self.response_format,<br>            speed=self.speed,<br>        ) as audio_stream:<br>            async for audio_chunk in audio_stream.iter_bytes(<br>                chunk_size=self.chunk_size<br>            ):<br>                yield audio_chunk<br><br>    async def __aexit__(<br>        self,<br>        exc_type: type[BaseException] | None,<br>        exc_value: BaseException | None,<br>        exc_tb: TracebackType | None,<br>    ) -&gt; None:<br>        &quot;&quot;&quot;<br>        Exits the asynchronous context manager.<br>        &quot;&quot;&quot;<br>        pass</pre><p>The idea is to create a <strong>buffer</strong> that stores the tokens generated by the LLM until a certain point — either when the buffer is full or it ends with a specific character. Once we’ve accumulated enough tokens, the buffer is <strong>flushed</strong> and sent to the OpenAI Text-to-Speech client to produce audio bytes.</p><p>The great thing about this approach is that we haven’t coupled the text generation streaming process with the audio generation streaming process. As you can see, the TextToSpeech component doesn&#39;t need to know anything about the LLM; it just expects some strings, regardless of their source.</p><h4>Bringing It All Together: Building the API and Testing the Application</h4><p>Now that we have the code for our three components, our src/app folder should look something like this:</p><pre>src/app/<br>├── __init__.py<br>├── llm.py<br>├── settings.py<br>├── stt.py<br>└── tts.py</pre><p>With the components in place, we need to create our FastAPI-powered application.</p><p><strong>Application Lifespan</strong></p><p>Recall our earlier discussion about reusing the Groq client across the application. We’re going to extend that approach by reusing all the clients in our application. This strategy allows us to manage our resources efficiently and avoid creating multiple unnecessary connections.</p><p>FastAPI’s lifespan events enable us to execute certain operations at startup and shutdown, making them the ideal place to establish connections to our clients and close them appropriately. Here’s how we can implement this:</p><pre># src/app/lifespan.py<br>from contextlib import asynccontextmanager<br>from typing import AsyncIterator, TypedDict<br><br>import aiohttp<br>from fastapi import FastAPI<br>from groq import AsyncGroq<br>from loguru import logger<br>from openai import AsyncOpenAI<br>from pydantic_ai import Agent, Tool<br>from pydantic_ai.models.groq import GroqModel<br><br>from app.llm import Dependencies, create_groq_agent, get_weather<br>from app.settings import Settings, get_settings<br><br><br>def create_aiohttp_session() -&gt; aiohttp.ClientSession:<br>    return aiohttp.ClientSession()<br><br><br>def create_groq_client(<br>    settings: Settings,<br>) -&gt; AsyncGroq:<br>    return AsyncGroq(api_key=settings.groq_api_key)<br><br><br>def create_openai_client(<br>    settings: Settings,<br>) -&gt; AsyncOpenAI:<br>    return AsyncOpenAI(api_key=settings.openai_api_key)<br><br><br>def create_groq_model(<br>    groq_client: AsyncGroq,<br>) -&gt; GroqModel:<br>    return GroqModel(<br>        model_name=&quot;llama-3.3-70b-versatile&quot;,<br>        groq_client=groq_client,<br>    )<br><br><br>class State(TypedDict):<br>    aiohttp_session: aiohttp.ClientSession<br>    groq_client: AsyncGroq<br>    openai_client: AsyncOpenAI<br>    groq_agent: Agent[Dependencies]<br><br><br>@asynccontextmanager<br>async def app_lifespan(app: FastAPI) -&gt; AsyncIterator[State]:<br>    settings = get_settings()<br>    aiohttp_session = create_aiohttp_session()<br>    openai_client = create_openai_client(settings=settings)<br>    groq_client = create_groq_client(settings=settings)<br>    _groq_model = create_groq_model(groq_client=groq_client)<br>    groq_agent = create_groq_agent(<br>        groq_model=_groq_model,<br>        tools=[Tool(function=get_weather, takes_ctx=True)],<br>        system_prompt=(<br>            &quot;You are a helpful assistant. &quot;<br>            &quot;You interact with the user in a natural way. &quot;<br>            &quot;You should use `get_weather` ONLY to provide weather information.&quot;<br>        ),<br>    )<br><br>    yield {<br>        &quot;aiohttp_session&quot;: aiohttp_session,<br>        &quot;openai_client&quot;: openai_client,<br>        &quot;groq_client&quot;: groq_client,<br>        &quot;groq_agent&quot;: groq_agent,<br>    }<br><br>    logger.info(&quot;Closing aiohttp session&quot;)<br>    await aiohttp_session.close()<br><br>    logger.info(&quot;Closing OpenAI client&quot;)<br>    await openai_client.close()<br><br>    logger.info(&quot;Closing Groq client&quot;)<br>    await groq_client.close()<br></pre><p>In this setup, everything inside the app_lifespan function before the yield executes when we start the application. Conversely, everything after the yield runs when the application is shutting down. This approach allows us to reuse all the artifacts of our application—including settings and the agent—throughout its lifecycle. Additionally, by storing these artifacts in the lifespan state, we can access them anywhere within the app.</p><p><strong>FastAPI and WebSocket</strong></p><p>Next, we need to build the FastAPI application and the WebSocket to interact with the components we’ve created. We’ll put all this logic in a file called server.py at the root of the project.</p><pre># server.py<br>from fastapi import Depends, FastAPI, WebSocket<br>from groq import AsyncGroq<br>from pydantic_ai import Agent<br><br>from app.lifespan import app_lifespan as lifespan<br>from app.llm import Dependencies<br>from app.settings import get_settings<br>from app.stt import transcribe_audio_data<br>from app.tts import TextToSpeech<br><br>app = FastAPI(title=&quot;Voice to Voice Demo&quot;, lifespan=lifespan) # 1. Lifespan<br><br><br># ------------- 2. FastAPI Dependency Injection -------------<br>async def get_agent_dependencies(websocket: WebSocket) -&gt; Dependencies:<br>    return Dependencies(<br>        settings=get_settings(),<br>        session=websocket.state.aiohttp_session,<br>    )<br><br><br>async def get_groq_client(websocket: WebSocket) -&gt; AsyncGroq:<br>    return websocket.state.groq_client<br><br><br>async def get_agent(websocket: WebSocket) -&gt; Agent:<br>    return websocket.state.groq_agent<br><br><br>async def get_tts_handler(websocket: WebSocket) -&gt; TextToSpeech:<br>    return TextToSpeech(<br>        client=websocket.state.openai_client,<br>        model_name=&quot;tts-1&quot;,<br>        response_format=&quot;aac&quot;,<br>    )<br><br><br># ------------- 3. WebSocket -------------<br>@app.websocket(&quot;/voice_stream&quot;)<br>async def voice_to_voice(<br>    websocket: WebSocket,<br>    groq_client: AsyncGroq = Depends(get_groq_client),<br>    agent: Agent[Dependencies] = Depends(get_agent),<br>    agent_deps: Dependencies = Depends(get_agent_dependencies),<br>    tts_handler: TextToSpeech = Depends(get_tts_handler),<br>):<br>    &quot;&quot;&quot;<br>    WebSocket endpoint for voice-to-voice communication.<br><br>    - Receives audio bytes from the client<br>    - Transcribes the audio to text<br>    - generates a response using the language model agent<br>    - converts the response text to speech, and streams the audio bytes back to the client.<br><br>    Args:<br>        websocket: WebSocket connection.<br>        conversation_id: Unique identifier for the conversation (dependency).<br>        db_conn: Asynchronous database connection (dependency).<br>        groq_client: Groq API client for transcription (dependency).<br>        agent: Language model agent for generating responses (dependency).<br>        agent_deps: Dependencies for the agent (dependency).<br>        tts_handler: Text-to-Speech handler for converting text to audio (dependency).<br>    &quot;&quot;&quot;<br>    await websocket.accept()<br><br>    async for incoming_audio_bytes in websocket.iter_bytes():<br>        # Step 1: Transcribe the incoming audio<br>        transcription = await transcribe_audio_data(<br>            audio_data=incoming_audio_bytes,<br>            api_client=groq_client<br>        )<br><br>        # Step 2: Generate the agent&#39;s response<br>        generation = &quot;&quot;<br>        async with tts_handler:<br>            async with agent.run_stream(<br>                user_prompt=transcription,<br>                deps=agent_deps<br>            ) as result:<br>                async for message in result.stream_text(delta=True):<br>                    generation += message<br><br>                    # Stream the audio back to the client<br>                    async for audio_chunk in tts_handler.feed(text=message):<br>                        await websocket.send_bytes(data=audio_chunk)<br><br>            # Flush any remaining audio chunks<br>            async for audio_chunk in tts_handler.flush():<br>                await websocket.send_bytes(data=audio_chunk)</pre><p>The code above accomplishes the following:</p><p>Creating the FastAPI application and passing the lifespan that we created.</p><ul><li><strong>Creating the FastAPI Application:</strong> We initialize the FastAPI app and pass in the lifespan function we created.</li><li><strong>Defining Dependency Injection Functions: </strong>These functions allow us to access the objects stored in the lifespan state within the WebSocket.</li><li><strong>Implementing the WebSocket Endpoint: </strong>This WebSocket orchestrates all the components and performs the following steps:</li></ul><ol><li><strong>Receiving Audio Bytes: </strong>It receives audio bytes from the client.</li><li><strong>Transcribing Audio to Text: </strong>It uses the STT component to transcribe the audio.</li><li><strong>Generating a Response:</strong> It generates a response using the LLM Agent.</li><li><strong>Converting Text to Speech:</strong> It converts the response text to speech using the TTS component.</li><li><strong>Streaming Audio Back: </strong>It streams the audio bytes back to the client.</li></ol><p><strong>Testing the Application</strong></p><p>To test our WebSocket, we can build a simple user interface (UI) using HTML and JavaScript. I’m not a JavaScript developer, so I used ChatGPT to generate simple code for the UI (the code is available <a href="https://gist.github.com/jjovalle99/027b4c774e3856824ad238b1de015bef">here</a>). In real-world scenarios, this part might be handled by another team. I stored the code in an .html file at the root folder of the project</p><p><em>Note:</em> <em>You can also test the WebSocket using Python, but it may require additional setup with PyAudio.</em></p><p>To serve the HTML file, we can add a new endpoint to our FastAPI application that reads from the file and generates a simple UI:</p><pre># server.py<br>from pathlib import Path<br><br>from fastapi import Depends, FastAPI, WebSocket<br>from fastapi.responses import HTMLResponse<br>from groq import AsyncGroq<br>from pydantic_ai import Agent<br><br>from app.lifespan import app_lifespan as lifespan<br>from app.llm import Dependencies<br>from app.settings import get_settings<br>from app.stt import transcribe_audio_data<br>from app.tts import TextToSpeech<br><br>app = FastAPI(title=&quot;Voice to Voice Demo&quot;, lifespan=lifespan)  # 1. Lifespan<br><br><br>@app.get(&quot;/&quot;)<br>async def get():<br>    with Path(&quot;sample_ui.html&quot;).open(&quot;r&quot;) as file:<br>        return HTMLResponse(file.read()) # This will render the HTML<br><br>...</pre><p>With this setup, we’re ready to serve our application. As a final check, your project folder structure should look like this:</p><pre>├── README.md<br>├── pyproject.toml<br>├── sample_ui.html<br>├── server.py<br>├── src<br>│   └── app<br>│       ├── __init__.py<br>│       ├── lifespan.py<br>│       ├── llm.py<br>│       ├── settings.py<br>│       ├── stt.py<br>│       └── tts.py<br>└── uv.lock</pre><p>Finally, we need to launch the application and interact with it:</p><pre> uv run uvicorn server:app \<br>  --host 0.0.0.0 \<br>  --port 8000 \<br>  --reload</pre><p>If everything is working correctly, you’ll see the UI at <a href="http://localhost:8000/">http://localhost:8000</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_ZnzolmS0-Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_ZnzolmS0-Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_ZnzolmS0-Y%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/53098b51034dba0f41c2b722bf515581/href">https://medium.com/media/53098b51034dba0f41c2b722bf515581/href</a></iframe><h3>Wrap-Up</h3><p>Congratulations! You now have your own voice-to-voice application. However, this is a very lightweight implementation. As you may have noticed, there are several areas where this application can be improved, including but not limited to:</p><ul><li><strong>Better Separation of Concerns</strong>: Organizing each Python module for clarity and maintainability.</li><li><strong>Complete Docstrings</strong>: Adding comprehensive documentation to your code.</li><li><strong>Database Integration</strong>: Implementing a database to store data and allow for multi-turn conversations.</li><li><strong>Containerization</strong>: Using tools like Docker to containerize the application for easier deployment.</li><li><strong>Unit Tests</strong>: Writing tests to ensure your code functions as expected.</li><li><strong>Fine-Tuning Buffer Size:</strong> Adjusting the buffer size for more natural conversations.</li><li><strong>Prompt Optimization</strong>: Refining prompts for better LLM responses.</li><li><strong>Improved UI</strong>: Enhancing the user interface for a better user experience.</li></ul><p>If you’re interested in a more robust version of this application, I recommend visiting my GitHub repository, where I’ve implemented points 1, 2, 3, and 4.</p><p><a href="https://github.com/jjovalle99/Voice2Voice">GitHub - jjovalle99/Voice2Voice</a></p><p>This concludes our tutorial on building a simple voice-to-voice application. I hope this guide has been helpful, and I encourage you to explore and expand upon this foundation to create even more advanced applications.</p><h3>About the Author</h3><p>I’m Juan Ovalle, an AI Engineer and Data Scientist passionate about building production-grade applications. My current work focuses on Generative AI applications, and I love exploring new technologies that make our lives as developers easier. You can find more about my projects on <a href="https://github.com/jjovalle99">GitHub</a> and <a href="http://www.linkedin.com/in/jjmov">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3b5248b4bdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Expanding Horizons: Using SageMaker Pipelines with Non-Python Languages]]></title>
            <link>https://medium.com/@juan.ovallevillamil/expanding-horizons-using-sagemaker-pipelines-with-non-python-languages-23905a5a452e?source=rss-e0686e203e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/23905a5a452e</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[sagemaker-pipelines]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-sagemaker]]></category>
            <dc:creator><![CDATA[Juan Ovalle]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 18:13:41 GMT</pubDate>
            <atom:updated>2024-04-29T19:02:01.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*G4KClAQDRM5IsU_3.png" /></figure><h3>Motivation</h3><p>In the expansive world of machine learning, Python reigns as the go-to language, favored for its vast libraries and ease of use. However, not all companies are inclined to pivot from their established coding languages, whether due to existing infrastructure, specialized requirements, or simply preference. Languages like R remain widely used in fields such as statistics and actuarial sciences. This is where Amazon SageMaker Pipelines come into play, providing a flexible solution for managing MLOps pipelines, even when dealing with code written in “foreign” languages. By adhering to SageMaker’s requirements, teams can utilize the SageMaker SDK to define their pipelines without abandoning their language of expertise. This approach not only preserves a team’s programming proficiency but also sidesteps the disruption of migrating to a new language. At its core, implementing SageMaker Pipelines across diverse programming environments boils down to the same three essentials: a logical script, a suitable execution environment through containers, and robust AWS hardware to run it all.</p><h3>Introduction</h3><p>In the following sections, we will explore a practical example of a simple SageMaker Pipeline that operationalizes a model trained in R. I will cover some of the most common phases of apipeline: data preprocessing, model training, and batch inference, providing a comprehensive view of the process from start to finish.</p><h3>Folder Structure</h3><p>The diagram below shows (in a simplified way) how the project is organized. At the root, we have pipeline.ipynb, a Jupyter notebook that guides us through creating and managing the pipeline. In the scripts folder, we have process.R for data preprocessing, train.R for training the model, and in the inference subfolder, plumber.R and serve.R for setting up the server for model inference. This setup helps keep our code neatly organized and easy to manage.</p><pre>├── pipeline.ipynb<br>├── scripts<br>│   ├── inference<br>│   │   ├── plumber.R<br>│   │   └── serve.R<br>│   ├── process.R<br>│   └── train.R</pre><h3>Data Processing</h3><p>In this section, we focus on preparing our data for the SageMaker pipeline.</p><h4>Step 1: Processing logic</h4><p>We start with an R script that reads, processes, and splits the data into training and test sets. It begins by defining input and output paths, then reads the dataset and divides it based on specified features and the target column. After splitting the data according to a predetermined ratio, it saves the training and test datasets to their respective paths.</p><p>If you dont get the reason of the opt/ml/… paths, is just the structure that SageMaker expects inside the containers. You can read more about this at <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/processing-job.html">https://docs.aws.amazon.com/sagemaker/latest/dg/processing-job.html</a></p><pre>#!/usr/bin/env Rscript<br><br># I/O paths<br>input_data_path &lt;- &quot;/opt/ml/processing/input&quot;<br>processed_data_path &lt;- &quot;/opt/ml/processing/output&quot;<br>train_output_file_path &lt;- file.path(processed_data_path, &quot;train.csv&quot;)<br>test_output_file_path &lt;- file.path(processed_data_path, &quot;test.csv&quot;)<br><br># main function<br>main &lt;- function(train_test_split_ratio, target_column, features){<br>  # Read the dataset (assuming CSV format)<br>  dataset &lt;- read.csv(file.path(input_data_path, &quot;data.csv&quot;))<br>  <br>  # Split features and target column<br>  features_vector &lt;- unlist(strsplit(features, &quot;,&quot;))<br>  target &lt;- dataset[[target_column]]<br>  data_features &lt;- dataset[features_vector]<br>  <br>  # Create training and test datasets<br>  set.seed(1399) # for reproducibility<br>  train_indices &lt;- sample(1:nrow(dataset), size = floor(train_test_split_ratio * nrow(dataset)))<br>  train_set &lt;- data.frame(data_features[train_indices, ], target[train_indices])<br>  test_set &lt;- data.frame(data_features[-train_indices, ], target[-train_indices])<br>  <br>  # Save the datasets<br>  write.csv(train_set, file = train_output_file_path, row.names = FALSE)<br>  write.csv(test_set, file = test_output_file_path, row.names = FALSE)<br>}<br><br># script arguments<br>args &lt;- commandArgs(trailingOnly = TRUE)<br>main(train_test_split_ratio = as.numeric(args[1]),<br>  target_column = args[2],<br>  features = args[3])<br>)</pre><h4>Step 2: Dockerfile</h4><p>Next, we prepare a Docker container that will run our R script. This involves setting up a base image with R installed and adding necessary packages. The Dockerfile outlines the environment setup, ensuring that our R script will execute in a consistent, controlled setting. We finalize this step by building the Docker image, ready to be integrated into our SageMaker pipeline.</p><pre># container to execute your processing code<br>FROM r-base:4.3.3<br><br>RUN apt-get update &amp;&amp; \<br>    apt-get install -y --no-install-recommends libxml2-dev &amp;&amp; \<br>    rm -rf /var/lib/apt/lists/*<br><br>RUN R -e &quot;install.packages(&#39;remotes&#39;)&quot; &amp;&amp; \<br>    R -e &quot;remotes::install_version(&#39;dplyr&#39;, version = &#39;1.1.4&#39;)&quot;<br>    # Your packages here<br><br>ENTRYPOINT [&quot;Rscript&quot;]</pre><pre># build docker image<br>docker build -t processing:latest .<br></pre><p>After building the image you need to push it to AWS Elastic Container Registery (ECR) in order to use the image inside SageMaker. This is straightforward, you can follow this instructions <a href="https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html">https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html</a></p><h3>Train</h3><p>In this section, we focus on the model training component of our pipeline.</p><h4>Step 1: Train Logic</h4><p>We utilize an R script to handle the training process. The script starts by loading the necessary library, caret, which facilitates model training. It reads the training data, specifies the model formula with the target variable, and trains the model using linear regression. Finally, the trained model is saved for future use.</p><pre>#!/usr/bin/env Rscript<br><br># Load necessary libraries<br>library(caret) # for model training and processing<br><br>main &lt;- function(data_path, model_path) {<br>  # Load the training data<br>  train_data &lt;- read.csv(data_path)<br>  <br>  # Specify the model formula (assuming &#39;target&#39; as the dependent variable)<br>  formula &lt;- target ~ .  # Adjust &#39;target&#39; to your actual target column name<br><br>  # Train the model using linear regression<br>  model &lt;- train(formula, data=train_data, method=&quot;lm&quot;)<br><br>  # Save the trained model<br>  saveRDS(model, file=model_path)<br>}<br><br>main(<br>  data_path = file.path(Sys.getenv(&quot;SM_CHANNEL_TRAIN&quot;), &quot;train.csv&quot;),<br>  model_path = file.path(Sys.getenv(&quot;SM_MODEL_DIR&quot;), &quot;model.rds&quot;)<br>)</pre><h4>Step 2: Dockerfile</h4><p>For the Docker setup, we employ a multi-stage build process beginning with a Python environment. This is necessary to install sagemaker-training, which allows the integration of our R model training within the SageMaker environment. We then copy this setup into an R base image, ensuring that all Python and R dependencies are available within the same Docker image.</p><p>While the multi-stage structure is not strictly necessary, it facilitates the process of adapting the container to the structure SageMaker expects through the use of the sagemaker-training toolkit. You can read more about this at <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/amazon-sagemaker-toolkits.html">https://docs.aws.amazon.com/sagemaker/latest/dg/amazon-sagemaker-toolkits.html</a></p><pre>FROM python:3.11.6-slim as python-base<br>RUN apt-get update &amp;&amp; \<br>    apt-get install -y --no-install-recommends build-essential gcc python3-dev &amp;&amp; \<br>    rm -rf /var/lib/apt/lists/*<br>RUN pip install --no-cache-dir sagemaker-training<br><br>FROM r-base:4.3.3<br>COPY --from=python-base /usr/local /usr/local<br>RUN apt-get update &amp;&amp; \<br>    apt-get install -y --no-install-recommends libxml2-dev &amp;&amp; \<br>    rm -rf /var/lib/apt/lists/*<br>RUN R -e &quot;install.packages(&#39;remotes&#39;)&quot; &amp;&amp; \<br>    # Your packages here</pre><pre># build docker image<br>docker build -t training:latest .</pre><h3>Batch Transform</h3><p>In this section, we set up the batch transform stage, which handles the inference logic using SageMaker’s batch transform feature.</p><h4>Step 1: Inference logic</h4><p>Our setup includes an R script utilizing the plumber library to expose model predictions via a simple REST API. The script is divided into two main parts:</p><p>API Endpoints: We define two endpoints:</p><ul><li>/ping: A GET and POST endpoint for health checks, returning a message that the service is running, along with a timestamp and a status.</li><li>/invocations: A POST endpoint where the actual model inference takes place. It starts by loading the trained model and reading the incoming data. Predictions are then generated based on this data and returned in CSV format.</li></ul><p>Server Initialization: Another script handles starting the server. It sets up the environment where plumber operates, specifying the directory for the inference script and running the server on the designated host and port.</p><p>The structure I am describing above is not random; SageMaker expects this behavior inside the inference container. You can read more about this at <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-batch-code.html">https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-batch-code.html</a></p><pre>#!/usr/bin/env Rscript<br>#* @get /ping<br>#* @post /ping<br>function() {<br>  list(message = &quot;Service is running&quot;,<br>       timestamp = Sys.time(),<br>       status = &quot;OK&quot;)<br>}<br><br>#* @param req<br>#* @post /invocations<br>function(req) {<br>  # Load model<br>  prefix &lt;- &quot;/opt/ml&quot;<br>  model_path &lt;- file.path(prefix, &quot;model&quot;)<br>  model &lt;- readRDS(file.path(model_path, &quot;model.rds&quot;))<br><br><br><br>  # Read inference data<br>  con &lt;- textConnection(object = req$postBody, open = &quot;r&quot;)<br>  input_data &lt;- read.csv(file = con)<br>  close(con)<br><br>  # Make predictions<br>  predictions &lt;- predict(model, input_data)<br><br>  # Prepare predictions<br>  output &lt;- textConnection(object = &quot;outputCSV&quot;, open = &quot;w&quot;, local = TRUE)<br>  write.csv(x = predictions, file = output, row.names = FALSE)<br>  close(output)<br><br>  outputCSV<br>}</pre><pre>#!/usr/bin/env Rscript<br>library(plumber)<br><br>serve &lt;- function() {<br>  prefix &lt;- &quot;/opt/ml/model/code/inference&quot;<br>  app &lt;- plumb(file.path(prefix, &quot;plumber.R&quot;))<br>  app$run(host = &quot;0.0.0.0&quot;, port = 8080)<br>}<br><br>serve()</pre><h4>Step 2: Dockerfile</h4><pre>FROM rocker/r-ver:4.3.3<br><br>RUN apt-get update -qq &amp;&amp; apt-get install -y \<br>      libssl-dev \<br>      libcurl4-gnutls-dev<br><br>RUN R -e &quot;install.packages(&#39;plumber&#39;)&quot;<br><br>RUN echo &quot;#!/bin/bash&quot; &gt; /usr/local/bin/serve \<br>    &amp;&amp; echo &quot;Rscript /opt/ml/model/code/inference/serve.R&quot; &gt;&gt; /usr/local/bin/serve \<br>    &amp;&amp; chmod +x /usr/local/bin/serve</pre><pre># build docker image<br>docker build -t inference:latest .</pre><h3>SageMaker Pipeline Definition (Step 3)</h3><p>Now that we have all the Lego pieces, we just need the glue to paste all of them together. This is the job of SageMaker Pipelines.</p><h4>1. Libraries &amp; Setup</h4><p>We begin by importing necessary libraries from the SageMaker Python SDK, setting up the SageMaker session, and specifying resource URIs and parameters for processing, training, and batch transformation. This setup enables us to define the environment and prepare for the various steps of the pipeline.</p><pre>import sagemaker<br>from sagemaker.estimator import Estimator<br>from sagemaker.inputs import TrainingInput, TransformInput<br>from sagemaker.model import Model<br>from sagemaker.processing import ProcessingInput, ProcessingOutput, ScriptProcessor<br>from sagemaker.transformer import Transformer<br>from sagemaker.workflow.functions import Join<br>from sagemaker.workflow.model_step import ModelStep<br>from sagemaker.workflow.pipeline import Pipeline<br>from sagemaker.workflow.pipeline_context import PipelineSession<br>from sagemaker.workflow.steps import ProcessingStep, TransformStep</pre><pre># sagemaker details<br>sagemaker_session = sagemaker.Session()<br>region = sagemaker_session.boto_region_name<br>sagemaker_execution_role = sagemaker.get_execution_role()<br>pipeline_session = PipelineSession()<br><br># input data and ecr base<br>ecr_base = &quot;YOUR ECR REPOSITORY HERE&quot;<br>input_data = &quot;s3://foo/input/data.csv&quot;<br><br># processing params<br>processing_image_uri = f&quot;{ecr_base}/processing:latest&quot;<br>processing_output_destination = &quot;s3://foo/output/&quot;<br>processing_entrypoint = &quot;scripts/process.R&quot;<br><br>prep_train_test_split_pct = &quot;0.7&quot;<br>target = &quot;Y&quot;<br>columns = &quot;X1,X2,X3,X4&quot;<br><br># training params<br>train_image_uri = f&quot;{ecr_base}/training:latest&quot;<br>train_entrypoint = &quot;scripts/train.R&quot;<br><br># batch transform params<br>model_source_dir = &quot;scripts/inference&quot;<br>model_entrypoint = &quot;serve.R&quot;<br>inference_image_uri = f&quot;{ecr_base}/inference:latest&quot;<br>inference_input_data = &quot;s3://foo/output/train.csv&quot;<br>inference_output_data = &quot;s3://foo/predictions/&quot;</pre><h4>2. Processing</h4><p>A ScriptProcessor is defined to execute the R script for data processing. We specify the container image, the role, instance type, and the input-output configurations. The processed data is stored in S3, ready for the next stage.</p><pre># define script processor<br>script_processor = ScriptProcessor(<br>    command=[&quot;Rscript&quot;],<br>    image_uri=processing_image_uri,<br>    role=sagemaker_execution_role,<br>    instance_count=1,<br>    instance_type=&quot;ml.m5.xlarge&quot;,<br>    sagemaker_session=pipeline_session,<br>)<br><br># run script processor<br>processor_args = script_processor.run(<br>    code=processing_entrypoint,<br>    inputs=[ProcessingInput(source=input_data, destination=&quot;/opt/ml/processing/input&quot;)],<br>    outputs=[<br>        ProcessingOutput(<br>            output_name=&quot;splits&quot;, source=&quot;/opt/ml/processing/output&quot;, destination=processing_output_destination<br>        )<br>    ],<br>    arguments=[prep_train_test_split_pct, target, columns],<br>)<br><br># get arguments<br>step_prep = ProcessingStep(<br>    name=&quot;processing&quot;,<br>    step_args=processor_args,<br>)</pre><h4>3. Training</h4><p>The training phase uses an Estimator to manage the training of the model using another R script. We detail the Docker image to use, the instance specifications, and where to save the output. The model is trained on the processed data, which is fetched dynamically from the previous step.</p><pre># define train estimator<br>estimator = Estimator(<br>    entry_point=train_entrypoint,<br>    image_uri=train_image_uri,<br>    instance_type=&quot;ml.m5.xlarge&quot;,<br>    instance_count=1,<br>    output_path=train_output_data_uri,<br>    role=sagemaker_execution_role,<br>    sagemaker_session=pipeline_session,<br>)<br><br># run train estimator<br>train_file = Join(<br>    on=&quot;/&quot;, values=[step_prep.properties.ProcessingOutputConfig.Outputs[&quot;splits&quot;].S3Output.S3Uri, &quot;train.csv&quot;]<br>)<br><br># get train arguments<br>train_args = estimator.fit(inputs={&quot;train&quot;: TrainingInput(s3_data=train_file, content_type=&quot;text/csv&quot;)})</pre><h4>4. Batch Transform</h4><p>After training, a Model is created for deployment, using the trained artifacts and an inference script to set up endpoints for batch predictions. A Transformer object then handles the batch transformation job, specifying how the model processes input data and where it outputs predictions.</p><pre># create a SageMaker model that uses the previously trained model<br>model = Model(<br>    name=&quot;R-model&quot;,<br>    image_uri=inference_image_uri,<br>    model_data=step_train.properties.ModelArtifacts.S3ModelArtifacts,<br>    sagemaker_session=pipeline_session,<br>    role=sagemaker_execution_role,<br>    entry_point=model_entrypoint,<br>    source_dir=model_source_dir,<br>)<br><br># get model arguments<br>step_create_model = ModelStep(name=&quot;CreateModel&quot;)<br><br># create transformer ~ batch transform job<br>transformer = Transformer(<br>    model_name=step_create_model.properties.ModelName,<br>    instance_type=&quot;ml.m5.xlarge&quot;,<br>    instance_count=1,<br>    strategy=&quot;MultiRecord&quot;,<br>    assemble_with=&quot;Line&quot;,<br>    accept=&quot;text/csv&quot;,<br>    output_path=inference_output_data,<br>)<br><br># get batch transform arguments<br>step_transform = TransformStep(<br>    name=&quot;BatchTransform&quot;,<br>    transformer=transformer,<br>    inputs=TransformInput(<br>        data=inference_input_data,<br>        content_type=&quot;text/csv&quot;,<br>        split_type=&quot;Line&quot;,<br>    ),<br>)</pre><h4>5. Pipeline execution</h4><p>Finally, we define the entire pipeline, incorporating all the steps — processing, training, model creation, and batch transformation. This pipeline is then registered and executed within SageMaker, demonstrating a complete workflow from data preparation to obtaining predictions, all while leveraging diverse technologies and integrating R with SageMaker’s powerful capabilities.</p><pre><br># define the pipeline with the created steps<br>pipeline = Pipeline(<br>    name=&quot;r-pipeline&quot;,<br>    steps=[step_prep, step_train, step_create_model, step_transform],<br>    sagemaker_session=pipeline_session,<br>)<br>pipeline.upsert(role_arn=sagemaker_execution_role)<br><br># execute pipeline<br>execution = pipeline.start()</pre><h3>Conclusion</h3><p>In conclusion, Amazon SageMaker’s cloud-native and versatile platform demonstrates its capability to build robust, scalable, and flexible machine learning pipelines. The example we’ve explored showcases how SageMaker can seamlessly integrate with languages like R, and the principles can be applied to virtually any programming language, provided the code can be containerized. The ability to expand and enhance the pipeline with additional steps and parameters means that your workflows can evolve as your needs grow. Mastery of Docker plays a crucial role in this process; once you are proficient in container technology, you effectively unlock the potential to orchestrate complex ML operations on a global scale. This combination of flexibility, extensibility, and power positions SageMaker as a formidable tool in the arsenal of any data scientist.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23905a5a452e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS SageMaker Simplified: A Quick Guide to Data Preprocessing]]></title>
            <link>https://medium.com/@juan.ovallevillamil/aws-sagemaker-simplified-a-quick-guide-to-data-preprocessing-3b59852d950d?source=rss-e0686e203e91------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b59852d950d</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[sagemaker-studio]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <dc:creator><![CDATA[Juan Ovalle]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 01:29:07 GMT</pubDate>
            <atom:updated>2023-11-21T01:29:07.134Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*O3MLT-GFmDLIJ8RN.jpeg" /></figure><h3>Introduction</h3><p>SageMaker is packed with features and can seem overwhelming at first. It has lots of capabilities that might not be immediately clear. But, like anything new, it gets easier with practice. Having spent some time working in an AWS environment, I’ve picked up quite a few handy tips and tricks. In this post, I want to focus on making data preprocessing in SageMaker simpler for you. This is particularly useful for those occasions when SageMaker’s built-in solutions aren’t quite what you need.</p><h3>SageMaker and SageMaker Studio</h3><p>At first, I was a bit mixed up with all the different SageMaker options: SageMaker Studio, SageMaker Notebook Instances, and others. It clicked for me when I compared them to tools that are well-known in the ML and Data Science world. Here’s how I see it now:</p><ul><li><strong>SageMaker Notebook Instances</strong> are similar to your regular Jupyter Notebooks. Think of the traditional way of launching Jupyter Notebooks, like through Anaconda.</li><li><strong>SageMaker Studio</strong> is more like VSCode. Sure, you can work on notebooks in it, but that’s just one part of what it can do. It has many features suited for various tasks. The key difference is that while VSCode is used by a wide range of professionals (like web developers and software engineers), SageMaker Studio is like a specialized version of VSCode, tailored specifically for Machine Learning.</li></ul><h3>The Challenge</h3><p>When it comes to data preprocessing, there are three significant hurdles most people encounter. First, the need for suitable hardware to handle big data efficiently without overheating. Second, the challenge of setting up environments with various tools, as there’s no universal solution fitting every scenario. Finally, the crucial aspect of having an organized method to save and reuse your feature engineering processes. SageMaker addresses these challenges effectively. It provides a variety of instance types tailored for different needs, be it computing optimization, memory efficiency, or GPU capabilities. Additionally, SageMaker’s integration with Docker simplifies the creation of diverse environments, making it a flexible tool for a wide range of machine learning tasks and more.</p><h3>How to Leverage SageMaker for Data Preprocessing: A Quick Guide</h3><p>My scenario is relatively straightforward, but keep in mind that you can modify the steps as needed for your specific situation.</p><h3>Step 1: Environment Setup</h3><p>Our data was stored in an S3 bucket. For confidentiality reasons, let’s refer to it as s3://clientbucket. The dataset consisted of nearly 4 million records, each with 100 features, and was stored in a parquet file.</p><p>You might think that handling such a dataset requires a powerful instance. However, a simple ml.t3.medium instance suffices in this case. Why? Because you don&#39;t actually load your data into this instance. That&#39;s one of the neat things about how SageMaker is structured. You can reserve the more robust instances for the heavy lifting and use more cost-effective options for other tasks.</p><p>In terms of libraries, you really just need sagemaker and boto3. The majority of your main libraries will be used in the actual processing, not in this notebook, which is more about guiding the process. Fortunately, AWS SageMaker&#39;s base environments already have these installed, so you can get started right away.</p><pre># Libraries<br>import boto3<br>import sagemaker<br>from sagemaker.processing import ScriptProcessor, ProcessingInput, ProcessingOutput<br><br># Variables<br>bucket = &#39;clientbucket&#39;<br>role = sagemaker.get_execution_role()<br>seed = 1399</pre><h3>Step 2: Preprocessing Script</h3><p>Although not the primary focus of this post, here’s an overview of my preprocessing script. Rather than understanding my script, the main takeaway here is to demonstrate how you can define your own preprocessing logic for later use.</p><pre>%%writefile preprocess/preprocess.py<br><br># Libraries<br>import logging<br><br>import numpy as np<br>import pandas as pd<br>from sklearn.compose import make_column_transformer<br>from sklearn.model_selection import train_test_split<br>from sklearn.pipeline import make_pipeline<br>from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder<br><br>from src.col_definition import (BINARY, HIGH_CARDINALITY, LOW_CARDINALITY, NUMERIC,<br>                    SUPER_HIGH_CARDINALITY, WITH_CAT_LOW_FREQUENCY)<br><br># Logging configuration<br>logging.basicConfig(level=logging.INFO, format=&quot;%(asctime)s: %(levelname)s: %(message)s&quot;)<br><br># Variables<br>SEED = 1399<br>LABEL = &quot;nclaim&quot;<br><br># Pipeline definition<br>encoder1 = OneHotEncoder(drop=&quot;first&quot;, sparse_output=False, dtype=np.int8)<br>encoder2 = OneHotEncoder(drop=None, sparse_output=False, dtype=np.int8)<br>encoder3 = OneHotEncoder(drop=None, sparse_output=False, dtype=np.int8, handle_unknown=&quot;infrequent_if_exist&quot;, min_frequency=0.09)<br>encoder4 = OneHotEncoder(drop=None, sparse_output=False, dtype=np.int8, handle_unknown=&quot;infrequent_if_exist&quot;, min_frequency=0.01)<br>encoder5 = OrdinalEncoder(dtype=np.float16, handle_unknown=&quot;use_encoded_value&quot;, unknown_value=np.nan, min_frequency=0.01)<br><br>transformer = make_column_transformer(<br>    (encoder1, BINARY),<br>    (encoder2, LOW_CARDINALITY),<br>    (encoder3, WITH_CAT_LOW_FREQUENCY),<br>    (encoder4, HIGH_CARDINALITY),<br>    (encoder5, SUPER_HIGH_CARDINALITY),<br>    remainder=&quot;passthrough&quot;,<br>    verbose_feature_names_out=False,<br>    verbose=1, n_jobs=-1,<br>)<br>pipeline = make_pipeline(transformer, verbose=True)<br><br>if __name__ == &quot;__main__&quot;:<br><br>    # Read data and save variable names<br>    try:<br>        logging.info(&quot;Loading data ...&quot;)<br>        df = pd.read_parquet(&quot;/opt/ml/processing/input/db_rt_localizadores.parquet.gzip&quot;)<br>        df = df.astype({col: &#39;category&#39; for col in df.select_dtypes(&#39;object&#39;).columns})<br>        col_names = (BINARY + list(NUMERIC.keys()) + LOW_CARDINALITY + HIGH_CARDINALITY + WITH_CAT_LOW_FREQUENCY + SUPER_HIGH_CARDINALITY)<br>        col_names = [col for col in df.columns if col in col_names]<br>        logging.info(&quot;Data loaded !&quot;)<br>    except Exception as e:<br>        logging.error(f&quot;Something went wrong: {e}&quot;)<br>        raise e<br><br>    # Get train and test indexes<br>    try:<br>        logging.info(&quot;Getting indexes ...&quot;)<br>        train_idx, test_idx = train, test = train_test_split(df.index, test_size=0.2, random_state=SEED, stratify=df[LABEL])<br>        logging.info(&quot;Done !&quot;)<br>    except Exception as e:<br>        logging.error(f&quot;Something went wrong: {e}&quot;)<br>        raise e<br><br>    # Train pipeline<br>    try:<br>        logging.info(&quot;Training pipeline ...&quot;)<br>        pipeline.fit(df.loc[train_idx, col_names], df.loc[train_idx, LABEL])<br>        X_train = pipeline.transform(df.loc[train_idx, col_names])<br>        X_test = pipeline.transform(df.loc[test_idx, col_names])<br>        logging.info(&quot;Done !&quot;)<br>    except Exception as e:<br>        logging.error(f&quot;Something went wrong: {e}&quot;)<br>        raise e<br><br>    # Save feature names<br>    try:<br>        logging.info(&quot;Saving feature names ...&quot;)<br>        feature_columns_out = [str(name).replace(&quot;[&quot;, &quot;&quot;).replace(&quot;]&quot;, &quot;&quot;).replace(&quot;&lt;&quot;, &quot;&quot;).replace(&quot;infrequent_if_exist&quot;, &quot;otros&quot;)<br>            for name in pipeline.get_feature_names_out().tolist()]<br>        logging.info(&quot;Done !&quot;)<br>    except Exception as e:<br>        logging.error(f&quot;Something went wrong: {e}&quot;)<br>        raise e<br><br>    # Save preprocessed data<br>    try:<br>        logging.info(&quot;Saving data ...&quot;)<br>        pd.DataFrame(X_train, columns=feature_columns_out).to_parquet(&quot;/opt/ml/processing/output/train/X_train.parquet.gzip&quot;, compression=&quot;gzip&quot;)<br>        pd.DataFrame(X_test, columns=feature_columns_out).to_parquet(&quot;/opt/ml/processing/output/test/X_test.parquet.gzip&quot;, compression=&quot;gzip&quot;)<br>        logging.info(&quot;Data saved !&quot;)<br>    except Exception as e:<br>        logging.error(f&quot;Something went wrong: {e}&quot;)<br>        raise e</pre><h3>Step 3: Dockerfile and Custom Image</h3><p>Even though the SKLearnProcessor in SageMaker covers most scenarios, it&#39;s limited to specific versions of scikit-learn. In my project, I needed version 1.3.2, but the highest available was only 1.2.1. This situation led to the need for creating a custom image. Your requirements might be different, such as needing a specific version of another library or a framework that isn&#39;t yet supported in SageMaker. In these cases, you can follow a similar approach. Here&#39;s how I set up my Dockerfile to address this issue.</p><pre>%%writefile Dockerfile<br># Python version<br>FROM python:3.10.13-slim<br><br># Dependencies<br>RUN pip install --no-cache-dir \<br>  scikit-learn==1.3.2 \<br>  pandas==2.1.2 \<br>  numpy==1.26.1 \<br>  fastparquet==2023.10.1<br><br># Entrypoint<br>ENTRYPOINT [&quot;python&quot;]</pre><p>After creating your Dockerfile, the usual process involves building the image with Docker and then pushing it to an image registry, often Amazon ECR (Elastic Container Registry). However, SageMaker offers a more streamlined approach with sm-docker. This tool allows you to build and push your image using a single command line directly from SageMaker. The command looks something like this:</p><pre>sm-docker build . --repository &lt;your-awesome-repository&gt; --bucket clientbucket</pre><p>Executing this command will build your Docker image and then automatically push it to ECR using AWS CodeBuild. When this process is completed, you’ll receive the URI of your newly created image.</p><h3>Step 4: Executing the Preprocessing</h3><p>Once you have your URI, you can utilize the straightforward structure of the ScriptProcessor. This is where you select a powerful instance to handle the intensive tasks. In this case, I&#39;m using ml.c5.2xlarge because it&#39;s compute-efficient and provides the 16 GB of memory needed to prevent the kernel from crashing.</p><p>Here’s the setup:</p><pre>processing_repository_uri = &#39;URI-you-just-generated&#39;<br><br>script_processor = ScriptProcessor(<br>    role=role, <br>    image_uri=processing_repository_uri,<br>    instance_count=1,  # Number of instances for the job<br>    instance_type=&#39;ml.c5.2xlarge&#39;,  # Type of instance<br>    command=[&#39;python&#39;]<br>)<br><br># Running the processing job<br>script_processor.run(<br>    code=&#39;./preprocess/preprocess.py&#39;,<br>    inputs=[<br>        ProcessingInput(<br>            source=&#39;s3://clientbucket/data.parquet.gzip&#39;,<br>            destination=&#39;/opt/ml/processing/input&#39;<br>        ),<br>        ProcessingInput(<br>            source=&#39;preprocess/col_definition.py&#39;,<br>            destination=&#39;/opt/ml/processing/input/code/src/&#39;,<br>        )<br>    ],<br>    outputs=[<br>        ProcessingOutput(<br>            source=&#39;/opt/ml/processing/output/train&#39;,<br>            destination=&#39;s3://clientbucket/output/&#39;<br>        ),<br>        ProcessingOutput(<br>            source=&#39;/opt/ml/processing/output/test&#39;,<br>            destination=&#39;s3://clientbucket/output/&#39;<br>        )<br>    ]<br>)</pre><p>The ProcessingInput and ProcessingOutput in the script define where SageMaker pulls data from and where it saves the processed data. ProcessingInput specifies the source of your data in S3 and where it should be placed in the processing container. In our case, we have the dataset and an additional script as inputs. ProcessingOutput, on the other hand, defines where the results of your processing job (like the transformed train and test datasets) will be stored, directing them back to specified locations in your S3 bucket.</p><p>Now, it’s time to take your coffee break ☕! After running this script, your processed data will be safely stored in the specified S3 buckets.</p><h3>Conclusion</h3><p>In this guide, we explored how to create a custom script for data preprocessing that requires specific dependencies. SageMaker enables you to combine various powerful tools, making it possible to tackle even the most unique scenarios in data processing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b59852d950d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>