<?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 Hikmah  Yousuph on Medium]]></title>
        <description><![CDATA[Stories by Hikmah  Yousuph on Medium]]></description>
        <link>https://medium.com/@hikmahx?source=rss-6e5c7fdb1b9f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*K_zWR385RuRRq5zv</url>
            <title>Stories by Hikmah  Yousuph on Medium</title>
            <link>https://medium.com/@hikmahx?source=rss-6e5c7fdb1b9f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:44:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hikmahx/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[Building a RAG Backend Pipeline (QuizMe Phase 1)]]></title>
            <link>https://medium.com/@hikmahx/building-a-rag-backend-pipeline-quizme-phase-1-6e317073a79e?source=rss-6e5c7fdb1b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e317073a79e</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Hikmah  Yousuph]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 07:06:59 GMT</pubDate>
            <atom:updated>2026-06-30T07:45:20.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bO-phB98wgAtdvhRXQyS1w.png" /></figure><p>QuizMe is a full-stack AI application I created that turns uploaded documents into an interactive learning experience. Users can generate summaries, ask questions across four intelligent modes, and take AI-generated quizzes to deepen their understanding. I used this project to properly build RAG pipelines, AI Agents, and to use FastAPI for the first time.</p><p>This is a beginner-friendly tutorial on building your first RAG pipeline using FastAPI, Supabase, and pgvector. If you’d like to take a simple deep dive on everything RAG-related, check out <a href="https://medium.com/@hikmahx/introduction-to-rag-29a02ed2fe9b">my article</a>.</p><p>Buckle up, because this is going to be a long one.</p><h3>Summary walkthrough</h3><p>Here is the breakdown of the RAG flow:</p><ol><li>User uploads document (.pdf, .docx, .md, .txt)</li><li>The backend decodes and extracts the raw text from the document</li><li>Text is broken down and split into small overlapping chunks</li><li>Each chunk is converted into a list of numbers (384‑dimensional vectors)</li><li>The numbers are then stored in Supabase (pgvector)</li><li>When the user requests a summary, all chunks are fetched</li><li>The Chunks are then sent to Groq’s LLM to generate the summary</li><li>The summary is finally sent to the frontend</li></ol><h3>Tech Stack</h3><ul><li><strong>Language:</strong> Python 3.11+</li><li><strong>Web Framework:</strong> FastAPI + Uvicorn</li><li><strong>Database:</strong> Supabase (PostgreSQL + pgvector)</li><li><strong>ORM:</strong> SQLAlchemy</li><li><strong>Embeddings:</strong> sentence-transformers (BAAI/bge-small-en-v1.5) — runs locally</li><li><strong>Text Splitting:</strong> langchain-text-splitters</li><li><strong>LLM:</strong> Groq (llama‑3.3‑70b‑versatile) — free API key</li><li><strong>Document Parsing:</strong> pdfplumber (PDF), python-docx (DOCX)</li><li><strong>Validation:</strong> Pydantic</li></ul><h3>Project Structure</h3><p>Based on how FastAPI files and folders are structured, the tree of this project should look like this:</p><pre>fastapi-backend/<br>├── app/<br>│   ├── main.py<br>│   ├── dependencies.py<br>│   ├── api/<br>│   │   ├── upload.py<br>│   │   └── summary.py<br>│   ├── core/<br>│   │   ├── config.py<br>│   │   └── database.py<br>│   ├── schemas/<br>│   │   └── summary.py<br>│   ├── rag/<br>│   │   ├── chunker.py<br>│   │   ├── embedder.py<br>│   │   ├── vectordb.py<br>│   │   └── retriever.py<br>│   ├── utils/<br>│   │   ├── pdf.py<br>│   │   └── docx.py<br>│   └── services/<br>│       ├── upload_service.py<br>│       └── summary_service.py<br>├── requirements.txt<br>└── .env</pre><p><strong>Side note:</strong> Remember to add __init__.py files inside every folder.</p><h3><strong>Set up</strong></h3><p>After creating your base folder and the files and folders in it, the next step is to set up a virtual environment. Virtual environments help avoid unnecessary errors caused by package version mismatches or upgrades.</p><pre>python -m venv venv<br>source venv/bin/activate      # Mac/Linux<br>venv\Scripts\activate         # Windows</pre><p>Next, install your dependencies. Create a requirements.txt in the root of your project and add this list:</p><pre>#requirements <br><br>fastapi==0.136.0<br>uvicorn==0.44.0<br>python-multipart==0.0.26<br>pydantic==2.10.4<br>pydantic-settings==2.7.0<br>sqlalchemy==2.0.36<br>pgvector==0.3.6<br>psycopg2-binary==2.9.10<br>sentence-transformers==5.4.1<br>langchain-text-splitters==0.3.2<br>torch==2.2.2<br>transformers==4.57.1<br>python-dotenv==1.2.2<br>groq==1.1.2<br>pdfplumber==0.11.9<br>python-docx==1.2.0<br>numpy==1.26.4</pre><p>FastAPI is the backend web framework. Uvicorn is the server for running asynchronous Python web frameworks. Python-multipart processes incoming file uploads and form submissions. Pydantic handles data validation, and pydantic-settings extends it to load configuration from environment variables.</p><p>SQLAlchemy streamlines communication between Python and relational databases. pgvector turns PostgreSQL into a vector database. psycopg2-binary connects Python to PostgreSQL without needing external development libraries.</p><p>sentence-transformers converts text into vector embeddings. langchain-text-splitters breaks large text into smaller, meaningful chunks.</p><p>Install all requirements:</p><pre>pip install -r requirements.txt</pre><h3><strong>Configuration</strong></h3><p>The config file in app/core/config.py holds all the configuration variables used throughout the application. Some have default values that don&#39;t change, while others are loaded from the .env file. If a variable has no default and no value in .env, the app will crash intentionally on startup.</p><p>For the .env, you need:</p><pre>DATABASE_URL=postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:5432/postgres<br>GROQ_API_KEY=your_groq_key_here<br>DEBUG=true</pre><p>Pydantic helps with types. Different variables have specific types enforced all through your app. If you use TypeScript, using Pydantic is very similar.</p><p>BaseSettings helps you manage configuration settings in a clean, efficient, and secure manner. It also reads values from your .env file automatically.</p><pre>from pydantic_settings import BaseSettings<br>from functools import lru_cache<br><br>class Settings(BaseSettings):<br>    APP_NAME: str = &quot;QuizMe API&quot;<br>    DEBUG: bool = False<br>    ALLOWED_ORIGINS: list[str] = [&quot;http://localhost:3000&quot;]<br>    DATABASE_URL: str<br>    GROQ_API_KEY: str<br>    GROQ_MODEL: str = &quot;llama-3.3-70b-versatile&quot;<br>    GROQ_MAX_TOKENS: int = 2048<br>    GROQ_TEMPERATURE: float = 0.3<br>    EMBEDDING_MODEL: str = &quot;BAAI/bge-small-en-v1.5&quot;<br>    EMBEDDING_DIMENSION: int = 384<br>    CHUNK_SIZE: int = 1000<br>    CHUNK_OVERLAP: int = 100<br>    RETRIEVAL_TOP_K: int = 5<br>    RETRIEVAL_TOP_K_BROAD: int = 15<br>    MAX_FILE_SIZE_MB: int = 20<br>    MAX_FILES_PER_SESSION: int = 10<br>    COLLECTION_TTL_DAYS: int = 1<br>    CLEANUP_INTERVAL_HOURS: int = 6<br>    ALLOWED_MIME_TYPES: list[str] = [<br>        &quot;application/pdf&quot;,<br>        &quot;application/vnd.openxmlformats-officedocument.wordprocessingml.document&quot;,<br>        &quot;text/plain&quot;,<br>        &quot;text/markdown&quot;,<br>    ]<br>    class Config:<br>        env_file = &quot;.env&quot;<br><br>@lru_cache<br>def get_settings() -&gt; Settings:<br>    return Settings()<br></pre><p>The variables with the GROQ_ prefix control the language model. GROQ_MODEL sets which model to use, GROQ_MAX_TOKENS caps how long the response can be, and GROQ_TEMPERATURE controls creativity (lower values give more consistent, factual answers).</p><p>EMBEDDING_MODEL is the local model that converts text into numbers. EMBEDDING_DIMENSION tells the database how many numbers each chunk produces. This must match the model exactly, since BAAI/bge-small-en-v1.5 always outputs 384 values.</p><p>CHUNK_SIZE is how many characters each text piece can be. CHUNK_OVERLAP is how many characters the next chunk shares with the previous one. This overlap prevents important context from being cut in half at a boundary.</p><p>RETRIEVAL_TOP_K is how many chunks to fetch when answering a specific question. RETRIEVAL_TOP_K_BROAD is a larger fetch used when you need a wider view of the document, like when generating a summary.</p><p>MAX_FILE_SIZE_MB and MAX_FILES_PER_SESSION are upload limits that prevent users from sending files that would overwhelm the server.</p><p>@lru_cache on get_settings() means the .env file is read only once, i.e., the first time the function is called. Every subsequent call returns the cached Settings object. This is like a singleton in JavaScript. Without it, the file would be re-read on every request.</p><p>I also implemented a collection cleanup. This part is <strong>completely optional</strong>. In essence, COLLECTION_TTL_DAYS and CLEANUP_INTERVAL_HOURS powers the background cleanup loop in main.py . Collections unused for 1 day are deleted every 6 hours.</p><h3>Database</h3><p>Here, we define how to connect to the database and what the tables look like.</p><pre>from contextlib import contextmanager<br>from sqlalchemy import Column, ForeignKey, Integer, String, Text, DateTime, Index, create_engine, text<br>from pgvector.sqlalchemy import Vector<br>from sqlalchemy.orm import sessionmaker, DeclarativeBase<br>from sqlalchemy.sql import func<br>from app.core.config import get_settings<br><br>settings = get_settings()<br>engine = create_engine(settings.DATABASE_URL, pool_pre_ping=True)<br>SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)<br><br>class Base(DeclarativeBase):<br>    pass<br><br>class DocumentCollection(Base):<br>    __tablename__ = &quot;document_collections&quot;<br>    id = Column(String(16), primary_key=True)<br>    file_fingerprint = Column(Text, nullable=False)<br>    created_at = Column(DateTime(timezone=True), server_default=func.now())<br>    last_accessed = Column(DateTime(timezone=True), server_default=func.now())<br><br>class DocumentChunk(Base):<br>    __tablename__ = &quot;document_chunks&quot;<br>    id = Column(Integer, primary_key=True, autoincrement=True)<br>    collection_id = Column(String(16), ForeignKey(&quot;document_collections.id&quot;, ondelete=&quot;CASCADE&quot;), nullable=False, index=True)<br>    doc_name = Column(Text, nullable=False)<br>    chunk_index = Column(Integer, nullable=False)<br>    content = Column(Text, nullable=False)<br>    embedding = Column(Vector(384))<br>    created_at = Column(DateTime(timezone=True), server_default=func.now())<br>    __table_args__ = (<br>        Index(&quot;document_chunks_embedding_idx&quot;, embedding, postgresql_using=&quot;ivfflat&quot;,<br>              postgresql_with={&quot;lists&quot;: 100}, postgresql_ops={&quot;embedding&quot;: &quot;vector_cosine_ops&quot;}),<br>    )<br><br>@contextmanager<br>def get_db():<br>    db = SessionLocal()<br>    try:<br>        yield db<br>        db.commit()<br>    except Exception:<br>        db.rollback()<br>        raise<br>    finally:<br>        db.close()<br><br>def get_db_dependency():<br>    db = SessionLocal()<br>    try:<br>        yield db<br>        db.commit()<br>    except Exception:<br>        db.rollback()<br>        raise<br>    finally:<br>        db.close()<br><br>def init_db():<br>    with engine.connect() as conn:<br>        conn.execute(text(&quot;CREATE EXTENSION IF NOT EXISTS vector;&quot;))<br>        conn.commit()<br>    Base.metadata.create_all(bind=engine)<br>    print(&quot;Database initialised&quot;)</pre><p>DocumentCollection tracks groups of uploaded files. Each group gets a unique 16-character ID (collection ID) generated by hashing the file names and sizes. If the same files are uploaded again later, they produce the same ID. The app recognizes them and skips re-processing entirely.</p><p>last_accessed records when the collection was last used. The background job checks this every 6 hours and deletes any collection that hasn&#39;t been touched in over a day.</p><p>DocumentChunk stores the actual text pieces and their vector embeddings. The ondelete=&quot;CASCADE&quot; on the foreign key means you never have to manually delete chunks. When a collection is removed, PostgreSQL automatically removes all its chunks too.</p><p>Vector(384) is a column type added by pgvector. It stores a list of 384 numbers per row. That number must match the embedding model, BAAI/bge-small-en-v1.5, which always produces exactly 384.</p><p>The ivfflat index at the bottom makes similarity search fast. Without it, every search would scan every row in the table. With it, PostgreSQL groups vectors into clusters and searches only the relevant ones, like a book index that lets you jump to the right page instead of reading everything.</p><p>get_db() is a context manager that opens a database session, runs your code, commits if everything went well, and rolls back if something went wrong. It is the Python equivalent of a try/catch/finally block around a database connection in JavaScript.</p><h3>App Entry Point</h3><p>app/main.py:</p><pre>import asyncio<br>from fastapi import FastAPI<br>from fastapi.middleware.cors import CORSMiddleware<br>from contextlib import asynccontextmanager<br>from app.core.config import get_settings<br>from app.core.database import init_db<br>from app.rag.vectordb import cleanup_stale_collections<br>from app.api import upload, summary<br><br>settings = get_settings()<br><br>async def _ttl_cleanup_loop():<br>    &quot;&quot;&quot;<br>    Background task: every CLEANUP_INTERVAL_HOURS (default 6) it deletes<br>    any document_collections row whose last_accessed is older than<br>    COLLECTION_TTL_DAYS (default 1 day).<br>    ON DELETE CASCADE removes the associated chunks automatically.<br>    &quot;&quot;&quot;<br>    interval_seconds = settings.CLEANUP_INTERVAL_HOURS * 3600<br>    while True:<br>        try:<br>            deleted = cleanup_stale_collections()<br>            if deleted:<br>                print(f&quot;TTL cleanup: removed {deleted} stale collection(s)&quot;)<br>            else:<br>                print(&quot;TTL cleanup: nothing to remove&quot;)<br>        except Exception as e:<br>            print(f&quot;TTL cleanup error: {e}&quot;)<br>        await asyncio.sleep(interval_seconds)<br><br>@asynccontextmanager<br>async def lifespan(app: FastAPI):<br>    print(f&quot;Starting {settings.APP_NAME}&quot;)<br>    init_db()<br>    # Run cleanup concurrently alongside request handling.<br>    # asyncio.create_task is like setInterval in JavaScript:<br>    # it fires every 6 hours in the background without blocking any requests.<br>    task = asyncio.create_task(_ttl_cleanup_loop())<br>    print(&quot;Server ready&quot;)<br>    yield<br>    # Graceful shutdown<br>    task.cancel()<br>    try:<br>        await task<br>    except asyncio.CancelledError:<br>        pass<br>    print(&quot;Server shutting down&quot;)<br><br>app = FastAPI(title=settings.APP_NAME, lifespan=lifespan)<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=settings.ALLOWED_ORIGINS,<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br>app.include_router(upload.router,  prefix=&quot;/api/upload&quot;,  tags=[&quot;Upload&quot;])<br>app.include_router(summary.router, prefix=&quot;/api/summary&quot;, tags=[&quot;Summary&quot;])<br><br>@app.get(&quot;/&quot;)<br>def health_check():<br>    return {&quot;status&quot;: &quot;ok&quot;, &quot;app&quot;: settings.APP_NAME}</pre><p>lifespan does two things. init_db() runs once at startup to enable pgvector and create tables. Then asyncio.create_task launches the TTL (Time To Live) cleanup loop concurrently, like setInterval in JavaScript, it fires every 6 hours in the background without blocking any requests. On shutdown, it is canceled cleanly.</p><h3>Text Extraction</h3><p>The frontend sends files as base64 data URLs (the same format localStorage uses to store them), a string like data:application/pdf;base64,JVBERi0x…. We decode this to bytes, then route to the right parser. The extraction lives in app/utils/pdf.py and app/utils/docx.py.</p><p>For PDFs (pdf.py):</p><pre>import base64, io, pdfplumber<br><br>def extract_text_from_pdf(data_url: str) -&gt; str:<br>    if &quot;,&quot; in data_url:<br>        base64_str = data_url.split(&quot;,&quot;, 1)[1]<br>    else:<br>        base64_str = data_url<br>    pdf_bytes = base64.b64decode(base64_str)<br>    extracted_pages = []<br>    with pdfplumber.open(io.BytesIO(pdf_bytes)) as pdf:<br>        for page in pdf.pages:<br>            text = page.extract_text()<br>            if text:<br>                extracted_pages.append(text)<br>    full_text = &quot;\n\n&quot;.join(extracted_pages)<br>    if not full_text.strip():<br>        raise ValueError(&quot;No text could be extracted. This PDF may be a scanned image.&quot;)<br>    return full_text</pre><p>For DOCX and TXT (docx.py):</p><pre>import base64, io<br>from docx import Document<br><br>def extract_text_from_docx(data_url: str) -&gt; str:<br>    if &quot;,&quot; in data_url:<br>        base64_str = data_url.split(&quot;,&quot;, 1)[1]<br>    else:<br>        base64_str = data_url<br>    docx_bytes = base64.b64decode(base64_str)<br>    document = Document(io.BytesIO(docx_bytes))<br>    paragraphs = [para.text for para in document.paragraphs if para.text.strip()]<br>    full_text = &quot;\n\n&quot;.join(paragraphs)<br>    if not full_text.strip():<br>        raise ValueError(&quot;No text could be extracted from this Word document.&quot;)<br>    return full_text<br><br>def extract_text_from_txt(data_url: str) -&gt; str:<br>    if &quot;,&quot; in data_url:<br>        base64_str = data_url.split(&quot;,&quot;, 1)[1]<br>    else:<br>        base64_str = data_url<br>    text_bytes = base64.b64decode(base64_str)<br>    return text_bytes.decode(&quot;utf-8&quot;, errors=&quot;replace&quot;)</pre><p>io.BytesIO wraps raw bytes in a file-like object. Both pdfplumber.open() and python-docx’s Document() normally accept a file path, but they also accept file-like objects. This way we never need to save anything to disk.</p><h3>Chunking</h3><p>In app/rag/chunker.py:</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from app.core.config import get_settings<br><br>settings = get_settings()<br><br>def chunk_text(text: str, doc_name: str) -&gt; list[dict]:<br>    splitter = RecursiveCharacterTextSplitter(<br>        chunk_size=settings.CHUNK_SIZE,<br>        chunk_overlap=settings.CHUNK_OVERLAP,<br>        length_function=len,<br>        separators=[&quot;\n\n&quot;, &quot;\n&quot;, &quot; &quot;, &quot;&quot;],<br>    )<br>    raw_chunks = splitter.split_text(text)<br>    return [{&quot;content&quot;: chunk, &quot;doc_name&quot;: doc_name, &quot;chunk_index&quot;: i} for i, chunk in enumerate(raw_chunks)]</pre><p>chunk_text uses RecursiveCharacterTextSplitter, which tries each separator in order: paragraph breaks first, then line breaks, then spaces, then individual characters as a last resort. This preserves natural text boundaries instead of cutting mid-sentence.</p><p>The function returns a list of dicts. Each dict has three keys: the chunk text, the source filename, and the chunk’s position within the document. Here is an example of what that looks like:</p><pre>[<br>  {&quot;content&quot;: &quot;RAG stands for Retrieval-Augmented Generation.&quot;, &quot;doc_name&quot;: &quot;notes.txt&quot;, &quot;chunk_index&quot;: 0},<br>  {&quot;content&quot;: &quot;It combines search with language model generation.&quot;, &quot;doc_name&quot;: &quot;notes.txt&quot;, &quot;chunk_index&quot;: 1},<br>]</pre><h3>Embeddings</h3><p>In app/rag/embedder.py:</p><pre>from sentence_transformers import SentenceTransformer<br>from app.core.config import get_settings<br><br>settings = get_settings()<br>model = SentenceTransformer(settings.EMBEDDING_MODEL)<br><br>def get_embedding(text: str) -&gt; list[float]:<br>    return model.encode(text).tolist()<br><br>def embed_chunks(chunks: list[dict]) -&gt; list[dict]:<br>    texts = [c[&quot;content&quot;] for c in chunks]<br>    embeddings = model.encode(texts, batch_size=32)<br>    return [{**c, &quot;embedding&quot;: emb.tolist()} for c, emb in zip(chunks, embeddings)]</pre><p>get_embedding takes a single string and returns its vector (a list of 384 floats). This is used at query time to convert a user&#39;s question into the same number space as the stored chunks.</p><p>embed_chunks takes the full list of chunk dicts from the chunker and adds an &quot;embedding&quot; key to each one. It processes all chunks in batches of 32, which is far faster than encoding one at a time. The {**c, &quot;embedding&quot;: emb.tolist()} syntax copies the existing dict and adds the new key, equivalent to { ...chunk, embedding: emb } in JavaScript.</p><p>The model loads into memory once when this module is first imported. All later calls are fast because the model is already ready.</p><h3>Vector Database</h3><p>app/rag/vectordb.py:</p><pre>import hashlib<br>from datetime import datetime, timedelta, timezone<br>from sqlalchemy.exc import IntegrityError<br>from app.core.config import get_settings<br>from app.core.database import SessionLocal, DocumentCollection, DocumentChunk<br><br>settings = get_settings()<br><br>def make_collection_id(files: list[dict]) -&gt; str:<br>    raw = &quot;&quot;.join(f[&quot;name&quot;] + str(len(f[&quot;dataUrl&quot;])) for f in files)<br>    return hashlib.md5(raw.encode()).hexdigest()[:16]<br><br>def collection_exists(collection_id: str) -&gt; bool:<br>    db = SessionLocal()<br>    try:<br>        return db.get(DocumentCollection, collection_id) is not None<br>    finally:<br>        db.close()<br><br>def register_collection(collection_id: str, file_fingerprint: str):<br>    db = SessionLocal()<br>    try:<br>        db.add(DocumentCollection(id=collection_id, file_fingerprint=file_fingerprint))<br>        db.commit()<br>    except IntegrityError:<br>        db.rollback()<br>    finally:<br>        db.close()<br><br>def touch_collection(collection_id: str):<br>    db = SessionLocal()<br>    try:<br>        row = db.get(DocumentCollection, collection_id)<br>        if row:<br>            row.last_accessed = datetime.now(timezone.utc)<br>            db.commit()<br>    finally:<br>        db.close()<br><br>def store_chunks(collection_id: str, chunks: list[dict]):<br>    db = SessionLocal()<br>    try:<br>        records = [DocumentChunk(collection_id=collection_id, doc_name=c[&quot;doc_name&quot;],<br>                                 chunk_index=c[&quot;chunk_index&quot;], content=c[&quot;content&quot;],<br>                                 embedding=c[&quot;embedding&quot;]) for c in chunks]<br>        db.add_all(records)<br>        db.commit()<br>    finally:<br>        db.close()<br><br>def cleanup_stale_collections() -&gt; int:<br>    &quot;&quot;&quot;<br>    Delete collections that haven&#39;t been accessed within COLLECTION_TTL_DAYS.<br>    Returns the number of collections deleted.<br>    ON DELETE CASCADE handles the associated chunks automatically.<br>    &quot;&quot;&quot;<br>    db = SessionLocal()<br>    try:<br>        cutoff = datetime.now(timezone.utc) - timedelta(days=settings.COLLECTION_TTL_DAYS)<br>        stale = (<br>            db.query(DocumentCollection)<br>            .filter(DocumentCollection.last_accessed &lt; cutoff)<br>            .all()<br>        )<br>        for row in stale:<br>            db.delete(row)<br>        db.commit()<br>        return len(stale)<br>    finally:<br>        db.close()</pre><p>make_collection_id hashes the file names and sizes together into a 16-character ID. The same files always produce the same ID, while different files produce different ones. This is how the caching works.</p><p>collection_exists checks whether a collection with that ID is already in the database. If it is, we skip all the expensive processing.</p><p>register_collection saves a new collection row. It catches IntegrityError in case two requests race to create the same collection at the same instant. The second one silently does nothing because the data is already there.</p><p>touch_collection updates last_accessed to now, resetting the 1-day TTL timer. This is called every time a collection is used so it doesn&#39;t expire while still active.</p><p>store_chunks saves all chunk records in one batch using db.add_all(), which is significantly faster than adding them one at a time.</p><p>cleanup_stale_collections is called by the background scheduler every 6 hours. It calculates the cutoff timestamp, finds all collections older than that, deletes them, and returns the count. Because of ON DELETE CASCADE, deleting a collection automatically removes all its chunks — no extra query needed.</p><h3>Retriever</h3><p>app/rag/retriever.py:</p><pre>from app.core.database import SessionLocal, DocumentChunk<br>from app.rag.embedder import get_embedding<br>from app.core.config import get_settings<br><br>settings = get_settings()<br><br>def retrieve_chunks(collection_id: str, query: str, top_k: int = None) -&gt; list[dict]:<br>    if top_k is None:<br>        top_k = settings.RETRIEVAL_TOP_K<br>    query_vec = get_embedding(query)<br>    db = SessionLocal()<br>    try:<br>        rows = (db.query(DocumentChunk).filter(DocumentChunk.collection_id == collection_id)<br>                .order_by(DocumentChunk.embedding.cosine_distance(query_vec)).limit(top_k).all())<br>        return [{&quot;content&quot;: r.content, &quot;doc_name&quot;: r.doc_name, &quot;chunk_index&quot;: r.chunk_index} for r in rows]<br>    finally:<br>        db.close()<br><br>def retrieve_all_chunks(collection_id: str) -&gt; list[dict]:<br>    db = SessionLocal()<br>    try:<br>        rows = (db.query(DocumentChunk).filter(DocumentChunk.collection_id == collection_id)<br>                .order_by(DocumentChunk.doc_name, DocumentChunk.chunk_index).all())<br>        return [{&quot;content&quot;: r.content, &quot;doc_name&quot;: r.doc_name, &quot;chunk_index&quot;: r.chunk_index} for r in rows]<br>    finally:<br>        db.close()</pre><p>retrieve_chunks is the core of RAG search. It converts the query into an embedding using the same model that stores the chunks. This is essential because the similarity search only works if both sides live in the same number space. It then asks PostgreSQL to find the most similar chunks using cosine distance and returns the top results.</p><p>retrieve_all_chunks skips the similarity search entirely and returns every chunk in document order. This is used for summary generation, where you want the complete document rather than just the parts most relevant to a specific question.</p><h3>Schemas</h3><p>Schemas define the shape of data coming in and going out of each endpoint. Pydantic validates every field automatically, wrong types or missing required fields return a clear error before your code even runs.</p><p>app/schemas/summary.py:</p><pre>from pydantic import BaseModel, field_validator<br>from typing import Literal<br><br>class FilePayload(BaseModel):<br>    name: str<br>    type: str<br>    dataUrl: str<br>    @field_validator(&quot;dataUrl&quot;)<br>    @classmethod<br>    def must_have_data(cls, v: str) -&gt; str:<br>        if not v or not v.strip():<br>            raise ValueError(&quot;dataUrl appears to be empty or invalid&quot;)<br>        payload = v.split(&quot;,&quot;, 1)[1] if &quot;,&quot; in v else v<br>        if len(payload) &lt; 4:<br>            raise ValueError(&quot;dataUrl appears to be empty or invalid&quot;)<br>        return v<br><br>class UploadRequest(BaseModel):<br>    files: list[FilePayload]<br><br>class UploadResponse(BaseModel):<br>    collection_id: str<br>    files_indexed: int<br>    total_chunks: int<br>    message: str<br><br>class SummaryRequest(BaseModel):<br>    files: list[FilePayload]<br>    length: Literal[&quot;short&quot;, &quot;medium&quot;, &quot;long&quot;] = &quot;medium&quot;<br>    style: Literal[&quot;default&quot;, &quot;combined&quot;, &quot;doc-by-doc&quot;] = &quot;default&quot;<br><br>class SingleSummary(BaseModel):<br>    doc_name: str<br>    summary: str<br><br>class SummaryResponse(BaseModel):<br>    collection_id: str<br>    style: str<br>    summaries: list[SingleSummary]<br>    fallback: bool = False</pre><p>FilePayload represents a single uploaded file. The @field_validator on dataUrl checks that the base64 payload has actual content and isn&#39;t just an empty string.</p><p>UploadRequest and SummaryRequest are what the frontend sends. UploadResponse and SummaryResponse are what the backend returns.</p><p>Literal[&quot;short&quot;, &quot;medium&quot;, &quot;long&quot;] means only those exact strings are accepted for length. Anything else is rejected automatically, no manual validation needed.</p><h3>Upload Service</h3><p>The service layer contains the business logic. The API routes should handle only HTTP concerns: parsing requests, returning responses, and handling HTTP errors. The actual work lives here.</p><p>app/services/upload_service.py:</p><pre>from app.schemas.summary import FilePayload<br>from app.utils.pdf import extract_text_from_pdf<br>from app.utils.docx import extract_text_from_docx, extract_text_from_txt<br>from app.rag.chunker import chunk_text<br>from app.rag.embedder import embed_chunks<br>from app.rag.vectordb import make_collection_id, collection_exists, touch_collection, register_collection, store_chunks<br>from app.core.config import get_settings<br><br>settings = get_settings()<br><br>def extract_text(file: FilePayload) -&gt; str:<br>    mime = file.type.lower()<br>    if mime == &quot;application/pdf&quot;:<br>        return extract_text_from_pdf(file.dataUrl)<br>    elif mime == &quot;application/vnd.openxmlformats-officedocument.wordprocessingml.document&quot;:<br>        return extract_text_from_docx(file.dataUrl)<br>    elif mime in (&quot;text/plain&quot;, &quot;text/markdown&quot;):<br>        return extract_text_from_txt(file.dataUrl)<br>    else:<br>        raise ValueError(f&quot;Unsupported file type: {mime}&quot;)<br><br>def index_files(files: list[FilePayload]) -&gt; dict:<br>    collection_id = make_collection_id([{&quot;name&quot;: f.name, &quot;dataUrl&quot;: f.dataUrl} for f in files])<br>    if collection_exists(collection_id):<br>        touch_collection(collection_id)<br>        return {&quot;collection_id&quot;: collection_id, &quot;files_indexed&quot;: len(files), &quot;total_chunks&quot;: 0, &quot;cached&quot;: True}<br>    all_chunks = []<br>    for file in files:<br>        text = extract_text(file)<br>        chunks = chunk_text(text, doc_name=file.name)<br>        all_chunks.extend(chunks)<br>    embedded = embed_chunks(all_chunks)<br>    register_collection(collection_id, file_fingerprint=str(len(files)))<br>    store_chunks(collection_id, embedded)<br>    return {&quot;collection_id&quot;: collection_id, &quot;files_indexed&quot;: len(files), &quot;total_chunks&quot;: len(all_chunks), &quot;cached&quot;: False}</pre><p>extract_text routes each file to the right parser based on its MIME type and returns the raw text string.</p><p>index_files is the main pipeline. It generates the collection ID, checks whether those files have already been processed, and, if so, resets the TTL and returns immediately, no re-embedding. If the files are new, it extracts text from each one, splits into chunks, embeds them all in a single batch, saves everything to the database, and returns the result. The early return on cached files is a significant performance gain since embedding is the slow step.</p><h3>Upload API</h3><p>In app/api/upload.py:</p><pre>from fastapi import APIRouter, HTTPException<br>from app.schemas.summary import UploadRequest, UploadResponse<br>from app.services.upload_service import index_files<br>from app.core.config import get_settings<br><br>settings = get_settings()<br>router = APIRouter()<br><br>@router.post(&quot;/&quot;, response_model=UploadResponse)<br>def upload_documents(body: UploadRequest):<br>    if not body.files:<br>        raise HTTPException(400, detail=&quot;No files provided&quot;)<br>    if len(body.files) &gt; settings.MAX_FILES_PER_SESSION:<br>        raise HTTPException(400, detail=f&quot;Maximum {settings.MAX_FILES_PER_SESSION} files per session&quot;)<br>    for file in body.files:<br>        if file.type not in settings.ALLOWED_MIME_TYPES:<br>            raise HTTPException(415, detail=f&quot;Unsupported type: {file.type}&quot;)<br>        approx_mb = len(file.dataUrl) * 0.75 / (1024 * 1024)<br>        if approx_mb &gt; settings.MAX_FILE_SIZE_MB:<br>            raise HTTPException(413, detail=f&quot;File too large: {approx_mb:.1f}MB&quot;)<br>    try:<br>        result = index_files(body.files)<br>    except ValueError as e:<br>        raise HTTPException(422, detail=str(e))<br>    except Exception as e:<br>        raise HTTPException(500, detail=f&quot;Indexing failed: {str(e)}&quot;)<br>    return UploadResponse(<br>        collection_id=result[&quot;collection_id&quot;],<br>        files_indexed=result[&quot;files_indexed&quot;],<br>        total_chunks=result[&quot;total_chunks&quot;],<br>        message=&quot;Files indexed successfully&quot; if not result[&quot;cached&quot;] else &quot;Already indexed&quot;<br>    )</pre><p>upload_documents validates the request before doing any work, checking file count, MIME types, and file sizes. The size check uses len(file.dataUrl) * 0.75 because base64 encoding inflates binary data by roughly 33%, so multiplying by 0.75 converts back to the approximate original file size. A ValueError from the service means bad input (422); anything else is an unexpected server error (500).</p><h3>Summary Service</h3><p>In app/services/summary_service.py:</p><pre>from groq import Groq<br>from app.rag.retriever import retrieve_all_chunks<br>from app.rag.vectordb import make_collection_id, collection_exists, touch_collection<br>from app.services.upload_service import index_files<br>from app.schemas.summary import FilePayload, SingleSummary<br>from app.core.config import get_settings<br><br>settings = get_settings()<br>groq_client = Groq(api_key=settings.GROQ_API_KEY)<br>LENGTH_INSTRUCTIONS = {<br>    &quot;short&quot;: &quot;Write a concise summary in 3-5 sentences (80-120 words).&quot;,<br>    &quot;medium&quot;: &quot;Write a clear summary in 2-3 short paragraphs (200-300 words).&quot;,<br>    &quot;long&quot;: &quot;Write a detailed summary in 4-6 paragraphs (400-600 words).&quot;<br>}<br><br>def _get_collection_id(files: list[FilePayload]) -&gt; str:<br>    collection_id = make_collection_id([{&quot;name&quot;: f.name, &quot;dataUrl&quot;: f.dataUrl} for f in files])<br>    if not collection_exists(collection_id):<br>        index_files(files)<br>    else:<br>        touch_collection(collection_id)<br>    return collection_id<br><br>def _summarise_single_doc(chunks: list[dict], length: str, doc_name: str) -&gt; str:<br>    context = &quot;\n\n---\n\n&quot;.join(chunk[&quot;content&quot;] for chunk in chunks)<br>    length_instruction = LENGTH_INSTRUCTIONS.get(length, LENGTH_INSTRUCTIONS[&quot;medium&quot;])<br>    prompt = f&quot;&quot;&quot;\<br>        You are a document summarisation assistant.<br>        Below is the full text of a document called &quot;{doc_name}&quot;.<br>        {length_instruction}<br>        Focus on the main ideas, key points, and important conclusions.<br>        Do not add information that is not in the document.<br>        DOCUMENT:<br>        {context}<br>        SUMMARY:&quot;&quot;&quot;<br>    try:<br>        response = groq_client.chat.completions.create(<br>            model=settings.GROQ_MODEL,<br>            messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>            max_tokens=settings.GROQ_MAX_TOKENS,<br>            temperature=settings.GROQ_TEMPERATURE,<br>        )<br>    except Exception as e:<br>        print(f&quot;Groq error for {doc_name}: {e}&quot;)<br>        raise<br>    return response.choices[0].message.content.strip()<br><br>def _summarise_combined(all_chunks: list[dict], length: str) -&gt; tuple[str, bool]:<br>    docs_context: dict[str, list[str]] = {}<br>    for chunk in all_chunks:<br>        name = chunk[&quot;doc_name&quot;]<br>        if name not in docs_context:<br>            docs_context[name] = []<br>        docs_context[name].append(chunk[&quot;content&quot;])<br>    context_parts = []<br>    for doc_name, chunks in docs_context.items():<br>        doc_text = &quot;\n\n&quot;.join(chunks)<br>        context_parts.append(f&quot;=== Document: {doc_name} ===\n\n{doc_text}&quot;)<br>    context = &quot;\n\n&quot;.join(context_parts)<br>    length_instruction = LENGTH_INSTRUCTIONS.get(length, LENGTH_INSTRUCTIONS[&quot;medium&quot;])<br>    prompt = f&quot;&quot;&quot;\<br>        You are summarising multiple documents together.<br>        {length_instruction}<br>        If the documents are clearly unrelated topics, respond with exactly:<br>        UNRELATED_DOCUMENTS<br>        Otherwise, write a unified summary covering all documents.<br>        DOCUMENTS:<br>        {context}<br>        SUMMARY:&quot;&quot;&quot;<br>    try:<br>        response = groq_client.chat.completions.create(<br>            model=settings.GROQ_MODEL,<br>            messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>            max_tokens=settings.GROQ_MAX_TOKENS,<br>            temperature=settings.GROQ_TEMPERATURE,<br>        )<br>    except Exception as e:<br>        print(f&quot;Groq error for combined summary: {e}&quot;)<br>        raise<br>    result = response.choices[0].message.content.strip()<br>    if &quot;UNRELATED_DOCUMENTS&quot; in result:<br>        return &quot;&quot;, True<br>    return result, False<br><br>def generate_summary(files: list[FilePayload], length: str, style: str) -&gt; dict:<br>    collection_id = _get_collection_id(files)<br>    all_chunks = retrieve_all_chunks(collection_id)<br>    if not all_chunks:<br>        raise ValueError(&quot;No content found. Please re-upload your files.&quot;)<br>    fell_back_from_combined = False<br>    if style == &quot;combined&quot; and len(files) &gt; 1:<br>        summary_text, fallback = _summarise_combined(all_chunks, length)<br>        if fallback:<br>            style = &quot;doc-by-doc&quot;<br>            fell_back_from_combined = True<br>        else:<br>            return {<br>                &quot;collection_id&quot;: collection_id,<br>                &quot;style&quot;: &quot;combined&quot;,<br>                &quot;summaries&quot;: [SingleSummary(doc_name=&quot;Combined Summary&quot;, summary=summary_text)],<br>                &quot;fallback&quot;: False,<br>            }<br>    if style in (&quot;doc-by-doc&quot;, &quot;default&quot;) or len(files) == 1:<br>        summaries = []<br>        chunks_by_doc: dict[str, list[dict]] = {}<br>        for chunk in all_chunks:<br>            name = chunk[&quot;doc_name&quot;]<br>            if name not in chunks_by_doc:<br>                chunks_by_doc[name] = []<br>            chunks_by_doc[name].append(chunk)<br>        summaries = []<br>        for doc_name, doc_chunks in chunks_by_doc.items():<br>            summary_text = _summarise_single_doc(doc_chunks, length, doc_name)<br>            summaries.append(SingleSummary(doc_name=doc_name, summary=summary_text))<br>        return {<br>            &quot;collection_id&quot;: collection_id,<br>            &quot;style&quot;: &quot;doc-by-doc&quot; if len(files) &gt; 1 else &quot;default&quot;,<br>            &quot;summaries&quot;: summaries,<br>            &quot;fallback&quot;: fell_back_from_combined,<br>        }<br>    raise ValueError(f&quot;Unknown summary style: {style}&quot;)</pre><p>_get_collection_id is a safety net. The upload endpoint should always be called before summary, but if someone calls summary directly or the database was wiped, this function re-indexes the files automatically rather than crashing.</p><p>_summarise_single_doc joins all chunks from one document into a single context string, builds a length-specific prompt, and sends it to Groq. The LENGTH_INSTRUCTIONS dict at the top controls how long the output should be, the right instruction is injected into the prompt based on what the user selected.</p><p>_summarise_combined does the same but for multiple documents at once. The prompt tells the LLM to respond with the exact string UNRELATED_DOCUMENTS if the documents are too different to combine. We check for that string in the response and fall back to doc-by-doc mode if it appears. Getting a boolean decision from an LLM by instructing it to output a specific sentinel word like this is a simple and reliable pattern.</p><p>generate_summary is the entry point. It retrieves or creates the collection, fetches all chunks, and then routes to the appropriate summary function based on style. If combined mode falls back to doc-by-doc, it sets fell_back_from_combined = True so the frontend can show the user a notice explaining what happened.</p><h3>Summary API</h3><p>In app/api/summary.py:</p><pre>from fastapi import APIRouter, HTTPException<br>from app.schemas.summary import SummaryRequest, SummaryResponse<br>from app.services.summary_service import generate_summary<br><br>router = APIRouter()<br><br>@router.post(&quot;/&quot;, response_model=SummaryResponse)<br>def summarise_documents(body: SummaryRequest):<br>    if not body.files:<br>        raise HTTPException(400, detail=&quot;No files provided&quot;)<br>    try:<br>        result = generate_summary(body.files, body.length, body.style)<br>    except ValueError as e:<br>        raise HTTPException(422, detail=str(e))<br>    except Exception as e:<br>        raise HTTPException(500, detail=f&quot;Summary failed: {str(e)}&quot;)<br>    return SummaryResponse(**result)</pre><p>summarise_documents is a thin wrapper that validates that files were provided, calls the service, handles errors, and returns the result. SummaryResponse(**result) unpacks the dict from the service directly into the response model. It works because the dict keys exactly match the field names in SummaryResponse.</p><h3>Supabase Setup</h3><p>Create a free project at <a href="https://supabase.com/">supabase.com</a>. In SQL Editor, run:</p><pre>CREATE EXTENSION IF NOT EXISTS vector;<br><br>CREATE TABLE IF NOT EXISTS document_collections (<br>    id VARCHAR(16) PRIMARY KEY,<br>    file_fingerprint TEXT NOT NULL,<br>    created_at TIMESTAMPTZ DEFAULT NOW(),<br>    last_accessed TIMESTAMPTZ DEFAULT NOW()<br>);<br><br>CREATE TABLE IF NOT EXISTS document_chunks (<br>    id SERIAL PRIMARY KEY,<br>    collection_id VARCHAR(16) NOT NULL REFERENCES document_collections(id) ON DELETE CASCADE,<br>    doc_name TEXT NOT NULL,<br>    chunk_index INTEGER NOT NULL,<br>    content TEXT NOT NULL,<br>    embedding vector(384),<br>    created_at TIMESTAMPTZ DEFAULT NOW()<br>);<br><br>CREATE INDEX IF NOT EXISTS document_chunks_collection_idx ON document_chunks(collection_id);<br><br>CREATE INDEX IF NOT EXISTS document_chunks_embedding_idx ON document_chunks USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);<br></pre><p>Go to <strong>Project Settings → Database → Connection string (Session mode)</strong>. Copy the URI and paste into your .env as DATABASE_URL.</p><h3>Running and Testing</h3><p>Start the server (from the fastapi-backend folder):</p><pre>uvicorn app.main:app --reload --port 8000</pre><p>Visit http://localhost:8000/docs to see the interactive API documentation.</p><p><strong>Test upload:</strong></p><pre>curl -X POST http://localhost:8000/api/upload/ \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;files&quot;:[{&quot;name&quot;:&quot;test.txt&quot;,&quot;type&quot;:&quot;text/plain&quot;,&quot;dataUrl&quot;:&quot;data:text/plain;base64,UkFHIHN0YW5kcyBmb3IgUmV0cmlldmFsLUF1Z21lbnRlZCBHZW5lcmF0aW9uLg==&quot;}]}&#39;</pre><p>Expected response:</p><pre>{<br>  &quot;collection_id&quot;: &quot;a1b2c3d4e5f6g7h8&quot;,<br>  &quot;files_indexed&quot;: 1,<br>  &quot;total_chunks&quot;: 1,<br>  &quot;message&quot;: &quot;Files indexed successfully&quot;<br>}</pre><p><strong>Test summary:</strong></p><pre>curl -X POST http://localhost:8000/api/summary/ \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;files&quot;:[{&quot;name&quot;:&quot;test.txt&quot;,&quot;type&quot;:&quot;text/plain&quot;,&quot;dataUrl&quot;:&quot;data:text/plain;base64,UkFHIHN0YW5kcyBmb3IgUmV0cmlldmFsLUF1Z21lbnRlZCBHZW5lcmF0aW9uLg==&quot;}],&quot;length&quot;:&quot;short&quot;,&quot;style&quot;:&quot;default&quot;}&#39;</pre><p>Call upload with the same file again. The response should be instant and show &quot;message&quot;: &quot;Already indexed&quot;. That&#39;s the caching working.</p><blockquote><strong><em>Note:</em></strong><em> The first server start downloads the embedding model (~130MB). Allow a few minutes before testing upload.</em></blockquote><h3>Conclusion</h3><p>In this article, we covered how to build a RAG pipeline that automatically removes data from its vector database when the collection is unused for over 24 hours. We also looked at uploading, summary generation, and automatic caching for cases where some files are re-uploaded (to prevent reprocessing these files).</p><p>Phase 1 is complete and ready. In the next article, Phase 2, we will look into the <strong>Voice RAG pipeline </strong>that speaks questions, allows the user to speak their answers, and returns spoken responses grounded in your documents.</p><p>Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e317073a79e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to RAG]]></title>
            <link>https://medium.com/@hikmahx/introduction-to-rag-29a02ed2fe9b?source=rss-6e5c7fdb1b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/29a02ed2fe9b</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Hikmah  Yousuph]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 13:08:28 GMT</pubDate>
            <atom:updated>2026-06-17T13:08:28.782Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g7GS6RqPAGGzIJGnrnF7nw.png" /></figure><p>You ask your chatbot a generic question. It answers correctly. You ask it a more specific question relating to more private details, and it answers. But this time, the answer is hallucinated. Rather than its LLM saying it doesn’t know, it confidently gives you wrong answers to a question it knows little about.</p><p>And that’s why it needs RAG.</p><h3>What is RAG?</h3><p>RAG (Retrieval Augmented Generation) can be defined as an AI framework or architecture that gives LLM access to additional external information. Chatbots, search engines, etc, use RAG behind the scenes to provide users with more accurate and fresh information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_EDXTqlPlEnVsYW4gig2eg.png" /><figcaption>RAG summary</figcaption></figure><p>Without RAG, the LLM more often than not gives guessed responses as it doesn’t have the correct information. This is called <strong>hallucination</strong>. This happens because the LLM doesn’t have access to certain information, such as company data, private files, and so on. To prevent an LLM from hallucinating, it requires access to the right data at query time. This external data can be in any form: documents, images, videos, text, etc.</p><p>In summary, RAG is made up of:</p><ul><li><strong>Retrieval:</strong> Converting the query into a vector and extracting the top-matching data from the vector database.</li><li><strong>Augmentation:</strong> Adding the extracted data into the prompt to give the LLM the correct, up-to-date context it needs.</li><li><strong>Generation:</strong> Producing a response based on the combination of its learned knowledge and the fresh facts it has just retrieved.</li></ul><h3>RAG vs Finetuning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8qsCcYebGFeMZrKh4SRhAg.png" /><figcaption>RAG vs Fine-tuning</figcaption></figure><p>Fine-tuning is the process of adjusting a pre-trained AI model on a smaller, more specific dataset to improve its performance on a particular task. It is useful when:</p><ul><li>The LLM needs a specific tone or persona, like a professional editor, a lawyer, or a medical expert.</li><li>The LLM needs to respond to shorter, faster prompts without much context.</li><li>The LLM needs stricter output formatting.</li></ul><p>RAG and fine-tuning are both used to optimize an LLM for specific tasks, but they solve different problems. RAG gives the model access to external knowledge without changing it. Fine-tuning changes the model itself to <strong>alter its tone, behavior, or output format</strong>. Because RAG grounds answers in retrieved facts, hallucination tends to be lower compared to fine-tuning alone.</p><p>In some cases, both are used together. Fine-tune the model for tone and behavior, use RAG for the facts. This is called the hybrid approach.</p><h3>RAG Use Cases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RbwxTgAEiFC7a1yRMncdQ.png" /><figcaption>Different RAG use cases</figcaption></figure><p>In real-life scenarios, RAG can be used for:</p><ul><li><strong>Chatbots:</strong> Customer support assistants on websites or mobile apps have access to relevant company information, so they can answer accurately and remain responsive whenever something changes.</li><li><strong>Summary generation:</strong> Long documents, reports, logs, etc., can be summarized separately or in a single concise summary based on what they contain, not what the LLM hallucinates.</li><li><strong>Quiz generation and grading: </strong>Generating questions from external files and grading answers from these questions is possible using RAG, fine-tuning, and accurate prompt engineering.</li><li><strong>Document analysis: </strong>Extracting insights, flagging clauses, or answering questions about contracts, research papers, or internal reports.</li><li><strong>Key point extraction: </strong>Retrieving important facts, passages, and keywords from documents without having to read the whole file, especially for large documents.</li></ul><h3>RAG Benefits</h3><p>Some of the main benefits of using RAG include:</p><ul><li><strong>Lesser hallucinations:</strong> Because the model answers from retrieved content rather than memory, it has less room to invent facts.</li><li><strong>Up-to-date information: </strong>The vector database can be constantly updated with the latest information from companies and websites. So the models never need to worry about giving outdated responses.</li><li><strong>Cost efficiency:</strong> Updating a knowledge base is significantly cheaper than retraining or fine-tuning a model every time information changes.</li><li><strong>Source traceability:</strong> A well-built RAG system can point to the exact document chunk that produced an answer, which matters greatly in regulated or high-stakes contexts.</li></ul><h3>Vector database</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XOKYgtXDjaEldi29fJHmjA.png" /><figcaption>Vector database</figcaption></figure><p>A <strong>vector</strong> is a list of numbers that represents the meaning of a piece of text. When you convert a sentence or a document chunk into a vector, similar pieces of text end up with similar numbers. This allows you to search by meaning, not just by keyword.</p><p>In a standard database, data is stored as rows and columns that you can query with exact matches. A <strong>vector database</strong>, on the other hand, stores these numerical representations and lets you search them by similarity. When a user asks a question, that question is also converted into a vector, and the database finds the chunks whose vectors are closest to it. This is <strong>similarity search</strong>.</p><p>The most common way to measure this similarity is <strong>cosine similarity</strong>. Instead of measuring the straight-line distance between two vectors, cosine similarity measures the <strong>angle</strong> between them. Vectors pointing in roughly the same direction are considered similar, regardless of their physical size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pj0lgNRcteMh3tp-jgNwSQ.png" /></figure><p>This approach is great for text processing because both a short sentence and a long paragraph can convey the same meaning. Scoring is straightforward:</p><ul><li><strong>1:</strong> Indicates the vectors share the same direction</li><li><strong>0:</strong> Indicates the vectors are orthogonal (no meaningful similarity)</li><li><strong>-1</strong>: Indicates the vectors point in opposite directions</li></ul><p>Because it successfully matches content based on meaning rather than length, most Retrieval-Augmented Generation (RAG) systems use cosine similarity as their default metric.</p><p>Vector databases are important to RAG because they allow fast, semantically accurate retrieval. Without them, you’d have no efficient way to find the most relevant chunks from thousands of documents at query time.</p><p>Examples of popular vector databases include Pinecone, Weaviate, Qdrant, and pgvector.</p><h3>Stages of RAG</h3><p>Every RAG pipeline follows the same five stages:</p><ol><li><strong>Ingesting</strong> (Preparing your documents)</li><li><strong>Indexing</strong> (Converting to numbers)</li><li><strong>Retrieval</strong> (Finding the right information)</li><li><strong>Augmentation</strong> (Injecting context into the prompt)</li><li><strong>Generation</strong> (Answering with context)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9E8Ml2oaRGK819USGqe3w.png" /><figcaption>stages of RAG</figcaption></figure><h4>Ingesting (Preparing your documents)</h4><p>Here, the relevant files and documents, i.e., webpages, images, pdf, docs, logs, etc, are gathered, prepared, and split into <strong>chunks</strong>. Chunking is essential because of LLMs’ context limit and smaller chunks (about 300–600 tokens) are better for retrieving, though the ideal size varies by use case. An <strong>overlap</strong> is usually placed between chunks so that context is not lost during retrieval.</p><h4>Indexing (Convert to numbers)</h4><p>Each chunk is passed through an <strong>embedding model</strong>, which converts it into a vector. These vectors are then stored in a vector database. This step only happens <strong>once per document</strong> (or when the document changes), and it’s what makes fast semantic retrieval possible at query time.</p><h4>Retrieval (Finding the right information)</h4><p>When a user asks a question, the question is also converted into a vector using the same embedding model. The vector database then finds the chunks whose vectors are most similar to the question vector. These top-matching chunks are the context the LLM will use to answer.</p><h4>Augmentation (Injecting context into the prompt)</h4><p>The retrieved chunks are inserted into the prompt alongside the user’s question. The LLM doesn’t search for anything at this point. It simply reads the context it was given and uses it to reason through an answer. This is the ‘augmented’ part of Retrieval Augmented Generation.</p><h4>Generation (Answering with context)</h4><p>The LLM generates a response using the retrieved content. Because it now has the right information in its context window, it can answer accurately. The quality of this step depends heavily on <strong>how well retrieval and augmentation went </strong>before it.</p><h3>How RAG Works</h3><p>Putting it all together, here’s the full flow:</p><ol><li>Prepare the documents and split them into chunks.</li><li>Convert each chunk into a vector and store it in a vector database.</li><li>At query time, convert the user’s question into a vector.</li><li>Find the most similar chunks in the vector database.</li><li>Pass those chunks and the question to the LLM.</li><li>The LLM generates a grounded answer.</li></ol><h3>Types of RAG</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ViQYQlfbcz2m0MQUv6Xztw.png" /><figcaption>Types of RAG</figcaption></figure><p>Here are the types of RAG you’ll find, from simplest to most advanced:</p><ul><li><strong>Naive RAG:</strong> This is the simplest, most basic version of RAG. It takes a query, searches for matching vectors, and delivers them to the LLM to generate an answer.</li><li><strong>Advanced RAG:</strong> This upgraded RAG type rephrases the query to get better results and uses re-ranking to pick only the best chunks before delivering them to the LLM.</li><li><strong>Modular RAG: </strong>Instead of a rigid search-and-answer loop, it breaks the pipeline down into independent modules that can be plugged in or swapped out depending on what the system needs.</li><li><strong>Agentic RAG: </strong>AI Agent + RAG. Rather than just retrieving and generating a response, it features an autonomous agent that evaluates results, conducts deeper research, and self-corrects.</li><li><strong>GraphRAG: </strong>This connects the dots between ideas. It converts unstructured data into a knowledge graph to capture complex relationships and entities across documents.</li><li><strong>Hybrid RAG: </strong>Combines traditional keyword search (exact word matching) with vector search (semantic similarity search) at the same time to maximize accuracy.</li><li><strong>Multimodal RAG: </strong>Processes all kinds of data types (text, images, audio, video, etc.). It allows the system to search, examine, and understand diverse formats beyond just plain text.</li></ul><h3>Simple RAG Walkthrough</h3><p>Let’s use a project example: <a href="https://quizme-hikmahx.vercel.app/">QuizMe</a>’s summary generation. QuizMe:</p><ol><li>Loads one or more uploaded documents.</li><li>Splits documents into around 500-character chunks with a 50-character overlap between chunks.</li><li>Converts each chunk into a vector using an embedding model and stores it in Supabase with pgvector.</li><li>Converts the user’s summary specification ( ‘give me a long summary based on the combination of these two files’) into a vector.</li><li>Finds 5 most similar chunks</li><li>Injects chunks into a prompt along with the user’s specification, and the LLM generates a summary based on the uploaded documents.</li></ol><h3>Summary</h3><p>In this article, we looked at:</p><ul><li>What RAG is and why LLMs need it.</li><li>How RAG differs from fine-tuning, and when to use each.</li><li>Real-world use cases and benefits of RAG.</li><li>What vector databases are and why they matter.</li><li>The five stages of a RAG pipeline: Ingesting, Indexing, Retrieval, Augmentation, and Generation.</li><li>How the full flow comes together.</li><li>An introduction to more advanced RAG patterns like Agentic RAG and GraphRAG.</li><li>A concrete walkthrough of RAG in <a href="https://quizme-hikmahx.vercel.app/">QuizMe</a>.</li></ul><h3>Conclusion</h3><p>RAG is very important in AI engineering, especially with user-related data that LLMs aren’t trained on or don’t have access to. Understanding how the pipeline works and how to properly implement it in code is essential for retrieving and generating the right data.</p><p>In my next article, I’ll be giving a step-by-step tutorial on how to build a simple RAG pipeline using FastAPI, pgvector, and Supabase to implement <a href="https://quizme-hikmahx.vercel.app/">QuizMe</a>’s very own summary generation.</p><p>Till next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29a02ed2fe9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Terms & Terminologies to Know in AI Engineering]]></title>
            <link>https://medium.com/@hikmahx/basic-terms-terminologies-to-know-in-ai-engineering-7e90fb630259?source=rss-6e5c7fdb1b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e90fb630259</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <dc:creator><![CDATA[Hikmah  Yousuph]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 18:44:10 GMT</pubDate>
            <atom:updated>2026-06-09T18:44:10.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a00vI1vMIWuxN_a2d6OAjg.png" /></figure><p>When I first started getting into AI engineering, I kept running into terms I didn’t fully understand: LLM, RAG, embeddings, agents, MCP. As a beginner in a new field, it can get confusing, especially when you don’t have your footing yet.</p><p>So I’m writing this article to help with that. Here, I’ll walk you through the key terms and terminologies you’ll encounter as you get started in AI engineering, grouped under the 4 core concepts that tie everything together.</p><p><strong>Table of Contents</strong></p><ul><li><a href="#91ac">4 Top Concepts to Be Familiar With</a></li><li><a href="#8aed">LLM (Large Language Model)</a></li><li><a href="#6dac">RAG (Retrieval Augmented Generation)</a></li><li><a href="#833a">AI Agent</a></li><li><a href="#70be">Model Context Protocol (MCP)</a></li><li><a href="#5c15">Conclusion</a></li></ul><h3>4 Top Concepts to Be Familiar With</h3><p>To begin in AI engineering, you must at least be familiar with the meaning of these 4 concepts:</p><ul><li>LLM (Large Language Model)</li><li>RAG (Retrieval Augmented Generation)</li><li>AI Agent</li><li>MCP (Model Context Protocol)</li></ul><p>Let’s break down each concept, with related terms you can find under each one.</p><h3>LLM (Large Language Model)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9WbQuhIzTxD3gqmGh8_IqQ.png" /></figure><p>Claude, DeepSeek, GPT, Gemini, Llama, and so on, are all known as Large Language Models.</p><p>A model is a software program that learns from data and uses it to perform tasks. These tasks can be as simple as predicting the next word in a sentence, classifying images, translating language, or generating content.</p><h4>SLM vs LLM</h4><p>Depending on the amount of data used to train the model, it can be classified into two broad categories: small language models (SLMs) and large language models (LLMs).</p><p>Small language models are trained on limited datasets for focused, specific tasks. LLMs, on the other hand, are trained on an enormous amount of data/text to understand and generate human language. They can perform the simple tasks that SLMs can, and much more, which is why they’ve become the foundation of most AI engineering work today.</p><h4>Different LLM Concepts</h4><p><strong>LLM Framework:</strong> Software libraries that bridge the gap between LLMs and application code. Instead of talking to the LLM directly through raw API calls, frameworks give you cleaner, reusable building blocks. Examples include LangChain, LlamaIndex, LiteLLM, etc.</p><p><strong>Token:</strong> LLMs can’t read words the way humans do. Texts are broken down into small pieces called tokens. The process of breaking down these texts is called tokenization. This matters because everything you send to an LLM (your question, documents, chat history) gets counted in tokens.</p><p><strong>Context Window:</strong> Maximum amount of tokens an LLM can process at a time. This is like the LLM’s short-term memory, and exceeding the limit can make the LLM forget previous information. It differs from LLM to LLM, and it’s why long documents need to be handled carefully.</p><p><strong>Temperature:</strong> A setting used to control the randomness and creativity of an LLM response. At low temperature (0.0 to 0.3), the response is more factual, strict, and rigid. At high temperature (0.7 to 1.5), it is more creative. For something like data extraction, you want low temperature. For brainstorming, higher works better.</p><p><strong>Top-K and Top-P:</strong> Parameters used to control the predictability and creativity of the AI’s responses. Top-K is a metric used to identify or filter the top choices, while Top-P (nucleus sampling) is for a percentage-based pool of choices. Both give you finer control over how the model generates text.</p><p><strong>Hallucinations:</strong> When an LLM confidently gives a false answer. The tricky part is that it doesn’t signal uncertainty, it just sounds sure. This is one of the most important problems to handle when building reliable AI systems.</p><p><strong>Fine-Tuning:</strong> Adjusting a pre-trained LLM on a new dataset for better, task-specific performance. Unlike RAG, fine-tuning changes the model itself rather than just fetching external information at runtime. You’d use it when you need the model to behave differently, not just know more.</p><p><strong>Transformers:</strong> A design that processes all tokens in an input at once and uses attention to focus on the most relevant parts when predicting the next word. It is the foundation of modern LLMs, and nearly every major model today is built on this architecture.</p><p><strong>Prompt Engineering:</strong> A way of controlling how LLMs respond through how your request (e.g., task, question, instruction) is phrased. Small changes in wording can lead to very different outputs, which is why this is a skill worth developing early.</p><p><strong>Chain-of-Thought:</strong> Prompting that asks the LLM to show step-by-step reasoning before answering. This helps increase accuracy dramatically on hard tasks. Instead of jumping to an answer, the model thinks it through first.</p><h3>RAG (Retrieval Augmented Generation)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*21qAxQHbQV5YNyLS07--vA.png" /></figure><p>LLMs give answers based on the data they were trained on. The problem is that training data has a cutoff date, and the LLM has no access to your private files, real-time data, or anything specific to your use case.</p><p>RAG is the process of allowing a model to retrieve relevant information from external sources (documents, databases, files, etc.) and use that retrieved information to generate a more accurate, grounded response. Instead of the LLM guessing from memory, you hand it the right information at the moment it needs it.</p><p>RAG pipeline involves:</p><ul><li><strong>Retrieval:</strong> Getting and extracting the data from a source, e.g., a memory or database.</li><li><strong>Augmentation:</strong> Enhancing the text generation process with the retrieved information.</li><li><strong>Generation:</strong> Creating a response for the user based on that context.</li></ul><h4>Different RAG Concepts</h4><p><strong>RAG process involves:</strong> user query → embed the query → search vector DB → retrieve chunks → pass to LLM → generate response.</p><p><strong>Chunking:</strong> Breaking down/splitting external information into smaller pieces before storage. Documents can be large, and if not chunked, they’d be stored as one giant embedding that’s too broad to be useful. Chunking makes retrieval precise.</p><p><strong>Embeddings:</strong> The process of converting chunks into vectors. Vectors are lists of numbers that represent the meaning of the text. This is what makes it possible to search by meaning rather than just exact keywords. Similar text gets similar numbers, so they’re easier to find together.</p><p><strong>Vector Database:</strong> A special kind of database built for storing and searching vector embeddings. The metadata and original content of documents are stored alongside the embeddings. Examples include pgvector, ChromaDB, Pinecone, Qdrant, etc.</p><p><strong>Similarity Search:</strong> Finds documents whose meaning is closest to your query, not just matching exact words. Cosine similarity and dot product are the methods used to find the closest match. This is what makes RAG feel “smart,” as it understands intent, not just keywords.</p><p><strong>Hybrid Search:</strong> Combines keyword search (matching exact words) with semantic search (matching meaning) to retrieve the most relevant information. Useful when you need both precision and understanding.</p><p><strong>Reranking:</strong> An optional step where the retrieved chunks are reordered so the most relevant ones are at the top before being fed to the LLM. It adds a bit of latency but can noticeably improve response quality.</p><p><strong>Metadata Filtering:</strong> Filtering through vector databases using structured attributes like date, source, or category, for higher precision and less hallucination. Instead of searching everything, you narrow the search space first.</p><p><strong>Latency:</strong> Total time from request to response. In RAG, this includes the time used for embedding, vector search, reranking, and LLM generation. Each step adds up, so optimizing latency is an ongoing concern in production RAG systems.</p><p><strong>Agentic RAG:</strong> Advanced RAG pipelines used with AI Agents. Instead of a fixed retrieval step, the AI Agent decides when to retrieve, what to search for, and whether the results are good enough, looping back if they’re not.</p><h3>AI Agent</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PC7xOhz4vi-SWnXdxPPOFw.png" /></figure><p>AI Agents are systems built on top of LLMs that can plan, act, observe, learn, and achieve goals using tools, memory, and reasoning without human assistance.</p><p>The LLM is the brain that processes input and generates responses. RAG feeds the LLM specific, up-to-date data. An AI Agent takes both and adds autonomy. It decides what to do, takes action, checks the result, and keeps going until the job is done.</p><p>Popular AI Agent frameworks include CrewAI, LangChain, LangGraph, LlamaIndex, and n8n.</p><h4>Different AI Agent Concepts</h4><p><strong>Multi-agent system:</strong> Having several AI Agents working towards a common goal, each with a specific role. For example, one agent generates a quiz, another grades the user’s answers. Splitting responsibilities like this tends to produce better results than loading one agent with everything.</p><p><strong>Guardrails:</strong> Rules/constraints that prevent agents from going off track, overusing APIs, and producing low-quality outputs. Without them, agents can loop endlessly, hallucinate, or call tools they shouldn’t.</p><p><strong>ReAct (Reason + Act):</strong> An AI Agent pattern loop that thinks about what to do, acts on a decision, observes the result, then thinks again and answers. Most agent frameworks use this pattern under the hood.</p><p><strong>Memory:</strong> Allows agents to remember past information, create cohesive responses, and improve over time. Without memory, the AI Agent starts afresh each time and loses context from previous interactions. Short-term memory holds the current session; long-term memory persists across sessions.</p><p><strong>Tools:</strong> Functions agents invoke to perform an action: search the web, calculate math, call an API, send an email, etc. Tools are what give an agent the ability to actually do things, not just talk about them.</p><p><strong>Tasks:</strong> A goal given to an AI Agent. The agent figures out how to accomplish it, sometimes by breaking complex ones into subtasks. Without a task, the AI Agent wouldn’t know what to do.</p><p><strong>Human-in-the-loop:</strong> A setup where humans are part of the decision-making for AI Agents, to guide them or intervene when they make mistakes. Especially important in high-stakes workflows where you can’t afford an unchecked error.</p><p><strong>Feedback loop:</strong> A cycle where the agent collects outcomes, observes effects, and adjusts actions. The agent learns from what just happened and uses that to make better decisions next time.</p><h3>Model Context Protocol (MCP)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gc3wljWVQU-IJnIt8oO_EA.png" /></figure><p>MCP is a standard way of connecting an AI application to external data sources, applications, and developer tools. It is an open, universal standard that allows AI applications to interact with other applications and tools. It was designed for AI Agents to avoid having multiple tools to juggle.</p><p>Breaking down the name helps:</p><ul><li><strong>Model:</strong> The LLM, the AI client app that consumes context and calls tools.</li><li><strong>Context:</strong> The knowledge and tools the model uses, including resources, tools, and prompts.</li><li><strong>Protocol:</strong> The rules of communication that let any AI app talk to any tool.</li></ul><p>Without MCP, the LLM only knows what it was trained on. With MCP, the LLM can call your code, read your files, query your database, and more.</p><p>MCP and APIs are, in a way, very similar. Both are used to communicate between software. But while APIs are built for applications, MCP is built for AI. An API is rigid; MCP is flexible. The AI can change its mind, ask follow-up questions, and pull in extra information as it goes.</p><p>In summary, MCP is like an API that lets LLMs talk to tools in a flexible, bidirectional way. It’s important because it lets AI connect to many external tools through a single, universal system, rather than building a custom integration for every combination.</p><h4>Different MCP Concepts</h4><p><strong>Host:</strong> A chat app like ChatGPT, Claude Desktop, or an AI-enhanced IDE like Cursor. It initializes the connection between the MCP and the system when in use.</p><p><strong>Client:</strong> A component built inside the host that handles communication with the server. The host creates one client per server it connects to, and the client handles the back-and-forth between them.</p><p><strong>Server:</strong> The bridge/translator sitting between the AI application and other software that gets things done. It’s an external service that does the actual work: it can be a database, a file system, a web search API, etc.</p><p><strong>API Wrapper:</strong> An interpreter that translates an app’s strict technical language into a flexible format the AI can easily use. It takes a regular, rigid app API and makes it readable for an AI.</p><p><strong>Tools:</strong> Functions/actions that the AI can call on. Instead of just reading information, tools let the AI send an email, create a file, or update a Notion ticket. You always control which tools the AI is allowed to trigger.</p><p><strong>Resources:</strong> Read-only data like files, APIs, and databases.</p><h3>Conclusion</h3><p>You don’t need to know everything at once. When I started out, I barely knew anything about AI Agents and MCP. As I’ve progressed, they’ve become simpler for me.</p><p>Try to learn the terms here to give yourself simple definitions of AI engineering concepts, so you don’t feel overwhelmed when going further into AI engineering.</p><p>In my next article, I’ll do a deeper dive into RAG.</p><p>Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e90fb630259" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transitioning into AI Engineering as a Full-Stack Developer]]></title>
            <link>https://medium.com/@hikmahx/transitioning-into-ai-engineering-as-a-full-stack-developer-ff4c7ed92449?source=rss-6e5c7fdb1b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff4c7ed92449</guid>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Hikmah  Yousuph]]></dc:creator>
            <pubDate>Sun, 31 May 2026 21:18:55 GMT</pubDate>
            <atom:updated>2026-05-31T21:18:55.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUItEaqbXt8Wq4_deF-AFA.png" /></figure><p>By now, you must have seen it as well: everyone wants in on AI. Companies, developers, designers… everyone. It almost feels like you are falling behind if you don’t move with it, because let’s be honest, with tech jobs disappearing faster than free tier limits, the best thing you can do is adapt.</p><p>As someone who genuinely enjoys learning and advancing my skills, I found that transitioning into AI engineering felt like the natural next step. But knowing where to start was a different story.</p><h3>Where It Began</h3><p>I had built a simple model during my time as a frontend developer at GitRoll, but it barely scratched the surface. I still had massive gaps in my AI/ML knowledge, and every resource I found either assumed too much or explained too little to beginners.</p><p>When <a href="https://www.frontendmentor.io/">Frontend Mentor</a> hosted their first hackathon, I went through the projects, reading code and studying implementations. One thing I noticed was how easily developers were integrating AI into simple frontend apps. The project that caught my fancy the most was an AI chat assistant built with Groq. It looked complex from the outside but was surprisingly easy.</p><p>At the time, I was working on a content writer project (blog page, experience page, resume generator, contact page). The AI chat assistant fit right in here. I built it, connected it to the small-scale database, and the assistant accurately answered questions about the client’s experience, posts, socials, and anything stored in the database.</p><figure><img alt="chat assistant of content writer website" src="https://cdn-images-1.medium.com/max/1024/1*rkMMi_j6SIfAssrj5wna5Q.png" /><figcaption>content writer website</figcaption></figure><p>This was the first time I added AI into a full-stack application.</p><h3>MLH GHW AI/ML: The Turning Point</h3><figure><img alt="global hack week ai/ml" src="https://cdn-images-1.medium.com/max/1024/1*Ec8aspA4E9Ra8LQOdfspOg.jpeg" /><figcaption>Global Hack Week AI/ML</figcaption></figure><p>I attended <a href="https://ghw.mlh.com/">MLH Global Hack Week </a>AI/ML in December 2025 at the perfect time, when I was actively trying to figure out how to break into AI engineering, jumping between articles and YouTube videos and feeling a little lost.</p><p>GHW simplified a lot of concepts and topics I had been struggling with and introduced me to ideas I hadn’t even come across yet. I didn’t complete any challenge, but that wasn’t the goal either. The point is, it gave me clarity and the exposure I needed. And most importantly, it gave me a list of ideas for how to bring AI/ML into my full-stack projects.</p><p>That week helped straighten things out for me, and the videos are still available on YouTube. MLH also has a community on <a href="https://discord.mlh.io/?_gl=1*rc85jx*_ga*MTQ4Njc0NjQxNS4xNzc5NDU4NDI2*_ga_E5KT6TC4TK*czE3ODAyNjExMTEkbzIkZzAkdDE3ODAyNjExMTEkajYwJGwwJGgw">Discord</a> where you can get input on other tech areas as well.</p><h3>Social Media (YouTube, LinkedIn) and Finding the Right Project</h3><p>The deeper I dived, the faster it came towards me.</p><p>I wanted to build something that checked all the boxes: RAG, AI Agents, all of it. After GHW, I started seeing more relevant content from creators like <a href="https://www.youtube.com/@maddyzhang">Maddy Zhang</a> and <a href="https://www.youtube.com/@MarinaWyssAI">Marina Wyss</a>, whose videos pointed toward solid AI projects worth building. Around the same time, I was learning Vue.js for a new full-stack application, <a href="https://github.com/Hikmahx/vue-job-listings">JobList</a>, and wanted to weave AI concepts into it.</p><figure><img alt="job list hero section" src="https://cdn-images-1.medium.com/max/1024/1*IYioCGFkrcU0KUSPcI5Rrw.png" /><figcaption>JobList hero section</figcaption></figure><p>I decided to implement a RAG pipeline into the search filter. The idea was for it to search every detail of a job listing (the company, the people, everything) and return results that matched the user’s query semantically, not just by keyword. I chose MongoDB as the vector database, using what I’d learned from GHW. I was also creating almost all the pages and components from scratch on Figma.</p><figure><img alt="job list filter" src="https://cdn-images-1.medium.com/max/787/1*T31gyPb0bGgvjEvyRPFKyA.png" /><figcaption>JobList filter</figcaption></figure><p>And then came the problems.</p><p>I kept hitting walls. Too many features. Too much Vue.js to learn. Too much UI to design.</p><p>All of this overshadowed what I really wanted to focus on: the AI concepts. I was building a good project with strong visuals, completed most of the designs, and learned Vue.js well, but I didn’t learn what I set out to learn. With the project buried under too many things pulling my focus, I had to admit that JobList wasn’t giving me what I needed: a deep, hands-on understanding of AI implementation.</p><p>So I put it on pause and started looking for a new project. Back to researching, articles, more YouTube, more LinkedIn, until I finally stumbled on the right thing.</p><h3>Finding the Right Material</h3><p><a href="https://drive.google.com/file/d/1_s2UaD7tEPECjgC5YMOa1LIOB9HUWFO-/view"><em>AI Engineering Guidebook</em></a> was exactly what I needed. Direct, visual, simplified, and most importantly, tailored specifically for software developers wanting to break into AI engineering.</p><figure><img alt="AI Engineering Guidebook by Avi Chawla and Akshay Pachaar" src="https://cdn-images-1.medium.com/max/564/1*qIynudCqvhVlFhuP-kZLvw.png" /><figcaption>AI Engineering Guidebook by Avi Chawla and Akshay Pachaar</figcaption></figure><p>I also came across articles by <a href="https://amanxai.com/">Amanxai</a> with practical tutorials on AI engineering. Reading through them sparked a new project idea, one that felt more focused and more mine.</p><p>I didn’t want to pour more energy into JobList. It had too many features, too much UI work, and not enough AI. I needed a clean slate.</p><h3>Enter QuizMe</h3><p>I browsed Frontend Mentor’s challenges for a UI I could use as a base without spending a lot of time on design. The <a href="https://www.frontendmentor.io/challenges/frontend-quiz-app-BE7xkzXQnU">Quiz App</a> challenge stood out immediately, partly because I love EdTech, and partly because the layout was clean, two-column, and easy to adapt. I could adjust certain things without reinventing anything.</p><figure><img alt="QuizMe’s UI based on Frontend Mentor’s Quiz App" src="https://cdn-images-1.medium.com/max/1024/1*gUJ5SAVqRRZP-DWlPlBDGQ.png" /><figcaption>QuizMe’s UI based on Frontend Mentor’s Quiz App</figcaption></figure><p>I brainstormed names and landed on <strong>QuizMe</strong>, an AI-powered learning platform where users upload documents and use them to generate summaries, take quizzes, and chat through a multi-mode Q&amp;A interface.</p><p>I listed out different features, mapped out pages, and condensed everything into a Version 1 scope:</p><ul><li><strong>View Summary</strong> — generate short, medium, or long summaries from uploaded documents</li><li><strong>Ask Questions</strong> — a multi-mode Q&amp;A chat (default, resume, compare, glossary)</li><li><strong>Quiz Time!</strong> — AI-generated MCQ and theory quizzes, including an oral mode</li></ul><p>Simple. Focused. AI-forward.</p><p>I also consulted multiple LLMs (Claude, ChatGPT, and DeepSeek) to confirm that I could incorporate RAG, AI Agents, and MCP into a single project, and yes, it was possible.</p><p>After coming across the <em>AI Engineering Guidebook</em>, I soon discovered two other books by the same author: <a href="https://drive.google.com/file/d/1Th8mN_IF7Ttc8bI_OLtUuQ7Mjx3aJ6Hi/view"><em>AI Agents Guidebook</em></a> and <a href="https://www.dailydoseofds.com/what-is-mcp"><em>MCP Guidebook</em></a>. These were more focused and had a lot more follow-along projects (with code) than the first.</p><figure><img alt="ai agent and mcp guidebook cover by Avi Chawla &amp; Akshay Pachaar" src="https://cdn-images-1.medium.com/max/1024/1*AphNjEbDJ_PvUw_te9dghA.png" /><figcaption>ai agent and mcp guidebook by Avi Chawla &amp; Akshay Pachaar</figcaption></figure><p>At this point, the ideas, UI, tech stack, features, workflow, and project structure were all finalized. I then created the project’s main README to keep track of everything.</p><h3>Building the Backend</h3><p>For the backend, I initially planned to use Django. But FastAPI kept showing up in everything I was reading, and for good reason. It’s fast, lightweight, and well-suited for AI workloads. So I learned it and made the switch.</p><p>Before writing a single line of code, I used the <a href="https://drive.google.com/file/d/1_s2UaD7tEPECjgC5YMOa1LIOB9HUWFO-/view"><em>AI Engineering Guidebook</em></a> and the <a href="https://drive.google.com/file/d/1Th8mN_IF7Ttc8bI_OLtUuQ7Mjx3aJ6Hi/view"><em>AI Agents Guidebook</em></a> to map out every AI implementation the project would need. Then I consulted LLMs to break down the tech stack, workflow, and file structure for each feature. This gave me a clear picture of what to build and in what order.</p><p>I divided the backend work into phases. Phase 1 covered:</p><ul><li>FastAPI setup</li><li>Upload API</li><li>Text extraction</li><li>Chunking</li><li>Vector database</li><li>Summary API</li></ul><p>Since I planned to fully deploy the backend with ease, I used Supabase for the database and vector database (switching from ChromaDB to pgvector).</p><p>For the RAG pipeline, I also implemented a TTL-based cache: embeddings older than 1 day are automatically deleted, unless they’re accessed regularly, in which case the timer resets. It keeps things clean without surprising users.</p><p>Once the RAG pipeline was working, I immediately tested it with the summary generation feature. It worked. From there, I kept building, voice RAG pipeline, AI Agents for quiz generation, multi-mode Q&amp;A chat, phase by phase. More articles on each of these later.</p><h3>Challenges (and There Were Many)</h3><p><a href="https://quizme-hikmahx.vercel.app/">QuizMe</a> is live and running, but it didn’t get there cleanly.</p><p>I fixed bugs around data leaking, mode mismatches, and vector retrieval issues caused by similar file names. I also made UX improvements along the way (text pasting for uploads, default option selection, file preview), things you only notice need fixing once you actually use the product.</p><p>Because of cost constraints, I built an LLM fallback system: Groq runs first, and if it hits its limit, it falls back to Cerebras, Gemini, and Mistral. This wasn’t the perfect solution, but a practical one.</p><p>Summary and quiz generation are still a bit slow, something I’m actively looking into through LLM optimization, reducing token usage, and refining prompts. I implemented RAG and AI Agents successfully, but not MCP. I haven’t decided yet whether it belongs in this project or a future one.</p><h3>What I’d Tell Anyone Starting This Journey</h3><p>A few things I genuinely believe after going through this:</p><p><strong>Use multiple LLMs:</strong> ChatGPT, Claude, and DeepSeek often give different perspectives on the same problem. Use that to your advantage.</p><p><strong>Try to stand out:</strong> There’s a lot of generic AI content out there. You don’t need a completely original idea. Even one distinct feature, well implemented and explained clearly, can set you apart.</p><p><strong>Stay active on social media:</strong> Medium, LinkedIn, and Twitter are great places to find the right resources and to be found by the right people. Document and share your progress consistently.</p><p><strong>Read, read, and read:</strong> The right knowledge saves you time and energy. The <em>AI Engineering Guidebook</em> helped change my trajectory. The right resource at the right time is worth more than hours of scattered YouTube videos.</p><p><strong>Always push forward:</strong> Tech is unpredictable right now. Growth is still possible, but it requires staying consistent, even when it doesn’t feel like it’s working.</p><p><strong>Have fun!:</strong> Seriously. Coding and learning don’t always have to feel overwhelming. Create personal projects or features that you like and would actually want to use in real life.</p><h3>What’s Next</h3><p>QuizMe is live. You can upload a document, generate a summary, take a quiz, and chat with it through the Q&amp;A interface.</p><p>In future articles, I’ll be doing a step-by-step breakdown of how I implemented RAG, AI Agents, and more, using QuizMe’s actual code as the example. If you’re a developer trying to break into AI engineering, that’s exactly what these next articles are for.</p><p>Till next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff4c7ed92449" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Accessibility: Making the Internet Inclusive for Everyone]]></title>
            <link>https://medium.com/@hikmahx/web-accessibility-making-the-internet-inclusive-for-everyone-1b1cee53e4a?source=rss-6e5c7fdb1b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b1cee53e4a</guid>
            <category><![CDATA[a11y]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[web-accessibility]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[inclusion]]></category>
            <dc:creator><![CDATA[Hikmah  Yousuph]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 07:20:12 GMT</pubDate>
            <atom:updated>2023-09-27T07:20:12.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*faMhkIjcuakbgx4UMO3YLw.jpeg" /></figure><p>In order to create a user-friendly website, it is essential to consider the needs of all individuals. Disabled users — people with low vision, auditory impairment, physical disabilities, the elderly population, neurological conditions, etc. — can encounter issues when using websites in their everyday lives, and unfortunately, most websites don’t fully consider all users. This is why web accessibility is important for the improvement of websites.</p><p>In this article, we will explore the importance of web accessibility, covering what it is, who it’s for, why it’s crucial, and how to incorporate accessibility.</p><h3>Outline</h3><ul><li><a href="#96c5">What is web accessibility?</a></li><li><a href="#31bf">Who is Web Accessibility for?</a></li><li><a href="#873c">Why is Web Accessibility Important?</a></li><li><a href="#8a5d">How to Include Accessibility</a></li><li><a href="#d50b">Tools to check web accessibility</a></li><li><a href="#5c5a">Conclusion</a></li></ul><h3>What is web accessibility?</h3><p>Web accessibility, commonly abbreviated as a11y (11 referring to the letters between ‘a’ and ‘y’), is about making websites and applications available to everyone. This involves designing and developing these technologies while considering people with all sorts of disabilities. According to a 2011 report by the WHO, 15% of the global population has disabilities, which is roughly about 1 billion people.</p><p>The primary goal of web accessibility is to remove any barriers faced by these billion people and make their web experience as easy as any regular user, ensuring inclusion and equity among users.</p><h3><strong>Who is Web Accessibility for?</strong></h3><p>Web accessibility is for a diverse range of individuals and groups which can be classified into the following:</p><p><strong>People with Disabilities</strong>: Web accessibility primarily targets individuals with disabilities. These disabilities include:</p><ul><li><strong>Visual</strong>: blindness, low vision, color blindness, visual impairment.</li><li><strong>Auditory</strong>: deafness, hearing impairment.</li><li><strong>Cognitive</strong>: learning disabilities(ADHD, dyslexia), developmental disabilities.</li><li><strong>Motor and Mobility</strong>: difficulties with hand movement, loss or slowness of muscle control (stroke, cerebral palsy, Parkinson&#39;s disease).</li><li><strong>Neurological: </strong>seizure.</li></ul><p><strong>Situational Disabilities</strong>: In these cases, users have difficulty using technology due to their surroundings, e.g., using a phone in a bright environment or a noisy place, or in an unfamiliar language.</p><p><strong>Temporary Disabilities</strong>: Temporary conditions like a broken arm, temporary blindness, temporary hearing loss, etc.</p><p><strong>Aging Population</strong>: Changes in abilities due to aging can lead to challenges in accessing technology, and web accessibility ensures no difficulties.</p><p><strong>Location</strong>: Rural areas and developing countries, where limited resources and infrastructure may affect accessibility.</p><h3><strong>Why is Web Accessibility Important?</strong></h3><ul><li><strong>Inclusivity and Equality: </strong>The primary reason for web accessibility is to include everyone, considering their abilities and disabilities to ensure equal access to technology.</li><li><strong>Enhance User Experience: </strong>Web accessibility improves the experience for all users, not just disabled users, by ensuring a user-friendly design with clear navigation, benefiting all users.</li><li><strong>Expand User Audience: </strong>By implementing web accessibility, you increase the number of site users. The more accessible the site, the more users it attracts.</li><li><strong>Improve SEO: </strong>Accessible websites rank higher in search results, boosting Search Engine Optimization (SEO).</li><li><strong>Legal Requirement: </strong>Certain laws protect the rights of disabled people in different countries, making web accessibility a legal requirement. Failure to implement it can lead to legal action.</li></ul><h3>How to Include Accessibility</h3><p>According to the WCAG (Web Content Accessibility Guidelines), four core principles should be considered to make a site accessible, following the POUR principle: Perceivable, Operable, Understandable, and Robust. We can categorize how to include accessibility practices according to the POUR principle:</p><h4><strong>Perceivable</strong>:</h4><p>Users should easily obtain information based on how it is presented. Perceivability is mostly related to sight but can also involve all sensory perception.</p><ol><li><strong>Alternative Text for Images</strong>: All images should have alternative text that perfectly describes them, making visual content accessible to those using screen readers.</li><li><strong>Multimedia Accessibility</strong>: In cases of auditory disabilities, provide transcripts for audio and video content, along with captions and subtitles for videos. Additionally, adding sign language interpretations should also be considered.</li><li><strong>Color Contrast</strong>: Maintain consistent color and font choices to enhance readability and ensure that text is distinguishable from the background for users with visual impairments.</li></ol><h4>Operable:</h4><p>This refers to any form of navigation on the website or application, e.g., mouse, keyboard, or an assistive device.</p><ol><li><strong>Structure Heading Hierarchy</strong>: Each page should have a single, short, and unique title header (h1 tag) to describe the page’s content. Use sectioning paragraphs and other headers (h2-h6) in an orderly fashion to outline the content for easy navigation.</li><li><strong>Decipherable Link Text</strong>: Clear and descriptive link text helps users understand the purpose of the link, hence creating easy navigation.</li><li><strong>Clear Navigation</strong>: Use menu bars, search forms, headers, footers, etc., for clear navigation.</li><li><strong>Interactive Elements</strong>: Ensure that interactive elements like buttons and forms are operable using various input methods, including keyboard navigation.</li><li><strong>Spacing</strong>: Maintain appropriate spacing between elements to prevent content from appearing cluttered and enhance usability.</li><li><strong>Readable Text</strong>: Use legible fonts and adjustable text sizes to ensure content remains easily readable for all users.</li></ol><h4>Understandable:</h4><p>This principle ensures content can be comprehended by all users, making it understandable, readable, and predictable.</p><ol><li><strong>Semantic HTML</strong>: Use semantic HTML elements to create a meaningful and well-structured page layout, enhancing comprehension.</li><li><strong>Form Accessibility</strong>: Enhance form accessibility by adding labels, providing error handling, and indicating required fields (e.g., with asterisks).</li><li><strong>Language change</strong>: The use of language change can help users across different parts of the globe have universal access to any website without worrying about language barriers.</li></ol><h4>Robust:</h4><p>This simply takes into consideration that the website maximizes compatibility across all browsers, assistive technologies, and devices.</p><ol><li><strong>ARIA Roles and Attributes</strong>: Implement Accessible Rich Internet Applications (ARIA) roles and attributes to improve the accessibility of dynamic content and interactive elements.</li><li><strong>Responsive Web Design</strong>: Create websites that can adapt to different screen sizes and devices, making sure the content remains accessible regardless of the user’s platform.</li><li><strong>Avoid Flashing, Blinking Content</strong>: Eliminate or provide warnings of content that flashes or blinks excessively, as this can trigger seizures or discomfort in some users.</li></ol><p>By incorporating these practices, you can make your website perceivable, operable, understandable, and robust, thereby enhancing its accessibility and ensuring that it caters to all users, including those with disabilities.</p><h3>Tools to check web accessibility</h3><ul><li><a href="http://wave.webaim.org/">WAVE</a>: Provides visual feedback about the accessibility of your web content. It scans web pages and highlights any accessibility issues found.</li><li><a href="https://developer.chrome.com/docs/lighthouse/overview/">Google Lighthouse</a>: An open-source tool that analyses websites and recommends improvement.</li><li><a href="https://www.deque.com/axe/">aXE</a>: Designed to help developers perform tests on web pages and create a list of errors found on websites and applications, along with solutions.</li><li><a href="https://achecks.org/checker/">AChecker</a>: Allows users to check accessibility and provides reports on problems detected through the provided URL or uploaded HTML documents.</li></ul><h3>Conclusion</h3><p>Web accessibility is an important consideration for both designers and developers when creating and designing a website. It is essential to understand how necessary it is to create an inclusive environment for all users. Make it a habit to consistently include accessibility to ensure an easy user experience for everyone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b1cee53e4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Permissions in Python and JavaScript: A Django and Node.js Express Comparison]]></title>
            <link>https://medium.com/shecodeafrica/permissions-in-python-and-javascript-a-django-and-node-js-express-comparison-1a8fcd7a4c33?source=rss-6e5c7fdb1b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a8fcd7a4c33</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Hikmah  Yousuph]]></dc:creator>
            <pubDate>Thu, 14 Sep 2023 09:01:53 GMT</pubDate>
            <atom:updated>2023-10-04T04:34:56.748Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comparing Permission Handling in Django and Express.js for Web Applications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3DWe6-olGc_jexdoEUCjA.png" /></figure><p>A while back, I had a task where I was required to create an API for a ride-sharing application. I initially built it using Node.js, Express.js, MongoDB, and TypeScript but later decided to create the same backend on another branch using Django. During this process, I encountered a crucial aspect: <strong>managing permissions</strong>. In this article, I will compare how Django and Express.js handle permissions differently.</p><h3>Introduction</h3><p>Permission is essential for the building of the backend and APIs of an application, ensuring security and integrity. Permissions are checked before the code they manifest in is authorized to run.</p><p>In Django, permissions are created through the use of the permission class while in Express.js, it is done mostly through middleware or simple functions.</p><h3>Permissions in Django</h3><p>Django, the framework for perfectionists, has a lot of built-in classes assigned to views that take the load off developers, making web development easier and faster. Permissions in Django Rest Framework come in two ways: built-in and custom.</p><h3>Built-in Permissions:</h3><ul><li>IsAuthenticated: Only authenticated users (logged-in users) have access.</li><li>IsAdminUser: Only admin or superusers are allowed access.</li><li>IsAuthenticatedOrReadOnly: Grants read-only access to unauthenticated users, while authenticated users can modify data.</li></ul><p>Here’s an example of how IsAuthenticated is used:</p><pre>from rest_framework import permissions, generics</pre><pre>class GetAllRidesAPI (generics.ListAPIView):<br>    queryset = DriverRide.objects.all()<br>    serializer_class = DriverRideSerializer<br>    permission_classes = [permissions.IsAuthenticated,]</pre><p>In the code above, users can get all the rides available as long as they are authenticated. In cases where they are not, an error message will instead be returned, depicting what the user should do.</p><h3>Custom Permissions:</h3><p>In cases where the built-in permissions don’t meet your specific requirements, Django allows you to create custom permissions. custom permission gives the flexibility to create permissions the way you want.</p><p>To create a custom permission in Django Rest Framework, you need to create a permissions.py file:</p><pre>from rest_framework import permissions<br>from vehicle.models import Vehicle</pre><pre>class HasVehicle(permissions.BasePermission):<br>    &quot;&quot;&quot;<br>    Check if the driver has a vehicle<br>    &quot;&quot;&quot;</pre><pre>    def has_permission(self, request, view):<br>        try:<br>            vehicle = Vehicle.objects.get(driver=request.user)<br>            return True<br>        except Vehicle.DoesNotExist:<br>            self.message = &quot;Driver need a vehicle before creating a ride.&quot;<br>            return False</pre><p>The HasVehicle permission class above checks if the user (the driver) has a vehicle in the database before allowing them to create a ride. This custom permission can be used in conjunction with built-in permissions.</p><p>This can be seen in the view for creating a new ride:</p><pre>from rest_framework import generics, permissions<br>from ..models import DriverRide<br>from .serializers import DriverRideSerializer<br>from .permissions import HasVehicle</pre><pre>class CreateRideAPI (generics.CreateAPIView):<br>    queryset = DriverRide.objects.all()<br>    serializer_class = DriverRideSerializer<br>    permission_classes = [permissions.IsAuthenticated, HasVehicle,]</pre><h3>Permissions in Express.js</h3><p>Unlike Django’s ready-made solutions, Express.js provides flexibility and requires developers to implement permissions using middlewares.</p><h3>Middleware</h3><p>Middleware functions in Express.js have access to the request and response objects and act as middlemen between incoming HTTP requests and outgoing responses.</p><p>For instance, let’s create a middleware to check if a driver has a vehicle before creating a ride:</p><pre>const isDriver = (req, res, next) =&gt; {<br>const driverVehicle = await Vehicle.findOne({ driver: req.user?.id });</pre><pre>  if (!driverVehicle) {<br>    return res<br>      .status(404)<br>      .json({ message: &quot;Driver need a vehicle before creating a ride&quot; });<br>  }</pre><pre>  next();<br>};</pre><p>The middleware is placed in the route like this:</p><pre>import { createRide } from &quot;../controllers/driverRideController&quot;;<br>import { verifyToken } from &quot;../middlewares/authMiddleware&quot;;</pre><pre>...<br>app.post(&quot;/create-ride&quot;, isDriver, createRide);</pre><p>Express.js allows you to use multiple middlewares for a route, either by listing them directly in the route definition or by nesting one middleware within another.</p><h3>Pros and Cons</h3><p>Let’s briefly explore the advantages and disadvantages of each framework:</p><h3>Django:</h3><p><strong>Pros:</strong></p><ul><li>Django’s built-in functionalities reduce the workload for developers.</li><li>It has a great security system already set up.</li><li>Enables fast and scalable applications.</li><li>The documentation is excellently detailed and easy to understand.</li><li>It has great community support.</li></ul><p><strong>Cons:</strong></p><ul><li>Can be seen as rigid due to all the built-in functionalities.</li><li>It is more convenient for large and complex applications than small-scale projects.</li><li>It is very vast and can be cumbersome for new developers.</li></ul><h3>Express.js:</h3><p><strong>Pros:</strong></p><ul><li>Easy to learn and use.</li><li>Provides flexibility and control over applications.</li><li>Lightweight and fast.</li><li>Great community support.</li><li>Allows easy integration of libraries.</li></ul><p><strong>Cons:</strong></p><ul><li>Lack of built-in features</li><li>May require more structure for larger projects.</li><li>Primarily suited for small to medium-sized applications.</li></ul><h3>Conclusion</h3><p>Django and Express.js are both powerful frameworks for creating APIs. Choosing between them depends on your project’s needs and your development preferences.</p><p>Managing permissions effectively is crucial in web development in order to enhance security, protect sensitive data, and provide a seamless user experience. Whether you prefer Django’s built-in approach or Express.js’s flexibility, both frameworks offer robust solutions for handling permissions in your web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a8fcd7a4c33" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shecodeafrica/permissions-in-python-and-javascript-a-django-and-node-js-express-comparison-1a8fcd7a4c33">Permissions in Python and JavaScript: A Django and Node.js Express Comparison</a> was originally published in <a href="https://medium.com/shecodeafrica">Nur: The She Code Africa Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Backend Engineering: A Beginner’s Guide]]></title>
            <link>https://medium.com/shecodeafrica/getting-started-with-backend-engineering-a-beginners-guide-2426759238ea?source=rss-6e5c7fdb1b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2426759238ea</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <dc:creator><![CDATA[Hikmah  Yousuph]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 17:01:44 GMT</pubDate>
            <atom:updated>2023-09-12T17:01:44.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkLbFTOS9Wc7GRWTchkdOw.png" /></figure><p>When I first started coding, I was just so excited to begin the journey. I had no idea about frontend, backend, or full-stack. I started with Python, and then Django. As I decided to progress further to make my website more responsive, that’s when I realized just how little I knew to be an actual developer. That’s when I realized what I had initially learned was the backend.</p><p>The backend refers to the server side of a web application, as opposed to the frontend, which focuses on the look and feel of the website — what you see when you visit a website. The backend runs in the background of a website, serving as the backbone where the logic is processed. It involves creating APIs, data storage and retrieval, user authentication, among many other functions.</p><p>There are many paths to choose from when starting out, some being more popular than others. I’m writing this guide to help people who are just starting out find their bearings in backend development.</p><h3>Steps to become a backend developer</h3><h3>1 — Learn a Programming languages</h3><p>The very first step in becoming a backend developer is to learn a programming language. Some of the popular languages include:</p><ul><li><a href="https://www.python.org/"><strong>Python</strong></a>: In terms of simplicity and readability, Python is a great language to start your coding journey with. According to the 2022 Octoverse report, it is the second most used language, and apart from being used as a backend language, it can be used in machine learning, data analysis, automated tasks, etc.</li><li><a href="https://nodejs.org/en"><strong>JavaScript</strong></a>: According to a study by Statista, this is the most widely used programming language and a great choice if you want to transition easily to being a full-stack developer, working on both the frontend and backend. Node.js allows developers to use JavaScript on the server side.</li><li><a href="https://www.java.com/en/"><strong>Java</strong></a>: A high-level, robust language also used in creating mobile apps, games, and desktop applications. It is fast, reliable, and secure.</li><li><a href="https://www.php.net/"><strong>PHP</strong></a>: PHP stands for Hypertext Preprocessor. It is a general-purpose language that can be embedded in HTML. It is popularly known in the production of popular content management systems (CMS) like WordPress.</li><li><a href="https://www.ruby-lang.org/en/"><strong>Ruby</strong></a>: An open-source language with elegant syntax with a focus on simplicity and productivity. It’s a gem to work with.</li></ul><p>Other backend languages include C#, Go, Kotlin, Swift, Elixir, Scala, Rust, Haskell, and Perl.</p><h3>2 — Learn its Framework</h3><p>Once you are comfortable with the language of your choice and can write and debug challenges with it, it is time to learn a framework. Why learn a framework? Because it’s for best practice. Frameworks save time and provide faster solutions to your problems. Some frameworks handle most of the bulk of the complexity, making it so much easier when simply using the language.</p><p>Below are languages with their framework:</p><ul><li>Python: Django, Flask, FastAPI, Pyramid</li><li>JavaScript (Node.js): Express.js, Nest.js, Koa.js</li><li>Java: Spring Boot, Play Framework, Micronaut</li><li>Ruby: Ruby on Rails, Sinatra, Hanami</li><li>PHP: Laravel, Symfony, Yii, CodeIgniter</li><li>C#: <a href="http://asp.net/">ASP.NET</a> Core, Nancy</li><li>Go: Gin, Echo, Revel</li><li>Kotlin: Ktor, Spring Boot (with Kotlin)</li><li>Swift: Vapor</li><li>Elixir: Phoenix</li><li>Scala: Play Framework, Akka HTTP</li><li>Rust: Rocket, Actix</li><li>Haskell: Yesod, Scotty, Servant</li><li>Perl: Dancer2, Mojolicious</li></ul><h3>3- Learn a database</h3><p>A database is an organized collection of data stored and managed in a way that allows for efficient retrieval, modification, and analysis of the data. Every time you visit a website and request something like your user information, products in an online store, or available drivers in your area, it’s the database that queries and fetches the data to be returned.</p><p>The best database to learn as a beginner should be either a relational or non-relational database. Relational databases are stored in the form of a table, like spreadsheets, with information organized in a structured manner of rows and columns. Non-relational database is non-tabular, and more flexible in storing data. The difference between these two types is how they store data.</p><p>With that in mind, let’s look at some examples of each database:</p><h4>Relational Databases:</h4><ol><li><strong>SQLite</strong> — A lightweight, serverless relational database that’s great for small-scale applications. It’s commonly used with frameworks like Django, and Flask and is ideal for learning purposes.</li><li><strong>MySQL</strong> — A widely-used open-source relational database management system. It’s often paired with frameworks like Node.js, Django, Laravel, and Ruby on Rails.</li><li><strong>PostgreSQL</strong> — Another popular open-source relational database known for its advanced features. It can be integrated with backend frameworks like Django, and Ruby on Rails.</li></ol><h4>Non-Relational Databases:</h4><ol><li><strong>MongoDB</strong> — A document-based NoSQL database. It works well with frameworks like Express.js due to its JSON-like document format.</li><li><strong>Redis</strong> — A high-performance, in-memory key-value store, often used for caching and real-time applications. It can be integrated into frameworks like Ruby on Rails, and Spring Boot.</li><li><strong>Cassandra</strong> — A highly scalable, largely distributed data used with frameworks like Spring Boot.</li><li><strong>Neo4j</strong> — A graph database that’s excellent for representing and querying relationships in data. It pairs well with frameworks like Express.js or Django.</li></ol><h3>4 — Learn basic HTML and CSS</h3><p>While HTML and CSS are mostly associated with frontend development as it is the building block of a website, you need to know and understand at least the basics of HTML and CSS even as a backend developer. HTML, HyperText Markup Language, is the structure of a web page. It allows the creation of elements such as headers, paragraphs, links, and sections within an application. CSS is for styling this content.</p><h3>5 — Learn about APIs</h3><p>Application programming interfaces (APIs) take a request from URLs, process it, and send back responses formatted as JSON. APIs come in different types, like the RESTful API, which follows a set of rules for making requests using simple URLs, similar to typing a web address in your browser.</p><p>When learning about APIs, it is crucial to learn about different HTTP requests: GET, POST, PUT, DELETE, etc. for CRUD (Create, Read, Update, Delete) functionalities to different endpoints — the URLs accessed to perform certain actions.</p><h3>6 — Learn about Version Control System</h3><p>Version control is the best way to keep track of your project and store it online for others to view. You can clone projects from others, collaborate with them, and track changes made to projects over time. <a href="https://git-scm.com/">Git</a> is the most popular Version Control System used by developers. Git has an online platform called GitHub, which is used for managing Git repositories.</p><p>As a beginner, Git may seem cumbersome to understand, but once you get the hang of it, it’s easy to use. There are many free tutorials online to learn how to use it.</p><h3>Conclusion</h3><p>After deciding to become a backend engineer, research, pick a language, a framework, and a database compatible with it. Create an API, and commit your code to GitHub. And Congrats! You’re already a developer.</p><p>Becoming a developer takes time, patience, and a passion for challenges. To be seen as reliable in your skills, you need to create impressive projects to prove yourself on your resume. While this is simply a comprehensive guide, remember that there is more than one way to go about this roadmap.</p><p>Research is the best way to learn more about your chosen path. In my experience, YouTube is a great starting point. YouTube videos are free and accessible to all levels, offering project-based learning to navigate the learning curve. Additionally, reading articles and staying updated on trends through social media can further enhance your skills.</p><p>With that said, I wish you the best of luck in your journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2426759238ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shecodeafrica/getting-started-with-backend-engineering-a-beginners-guide-2426759238ea">Getting Started with Backend Engineering: A Beginner’s Guide</a> was originally published in <a href="https://medium.com/shecodeafrica">Nur: The She Code Africa Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating customized graphs with Chart.js in React Applications]]></title>
            <link>https://medium.com/@hikmahx/creating-customized-graphs-with-chart-js-in-react-be72bb2ffd0?source=rss-6e5c7fdb1b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/be72bb2ffd0</guid>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[chartjs]]></category>
            <dc:creator><![CDATA[Hikmah  Yousuph]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 01:51:09 GMT</pubDate>
            <atom:updated>2023-08-24T02:08:41.093Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4a5vyJM00Rq6mbyFxJnIQ.png" /></figure><h3>Outline</h3><ul><li>Introduction</li><li>What is Chart.js?</li><li>Set up</li><li>Creating Graph Components</li><li>Line Graph</li><li>Bar Graph</li><li>Customizing Line Graphs</li><li>Chart.js Properties</li><li>Conclusions</li></ul><h3>Introduction</h3><p>Data representation is essential for conveying information effectively, often achieved through graphs or charts. One of the most popular tools for creating interactive and visually appealing charts and graphs in web applications is Chart.js. In this article, we’ll explore how to leverage Chart.js within a React application to create and customize various types of graphs.</p><h3>What is Chart.js?</h3><p>Chart.js is a JavaScript library designed for data visualization on the frontend using the HTML &lt;canvas&gt; element. It is direct, user-friendly, and responsive on all screen sizes. Chart.js supports 8 different chart types: bar, line, pie, scatter, bubble, area, radar, and polar. <br>Whether you’re working with complex frontend frameworks or building simple websites with plain HTML, Chart.js is easily integrable and comprehensible. Our focus in this article will be on harnessing the capabilities of Chart.js to create and tailor bar and line graphs within a React application.</p><h3>Set up</h3><p><strong>Installation</strong>:</p><ol><li>Create your React application: Run the command npx create-react-app react-graph.</li><li>Installing Dependencies: Use npm to install both Chart.js and the react-chartjs-2 wrapper. This wrapper allows the easy integration of Chart.js into React components. Run:</li></ol><pre>npm install chart.js react-chartjs-2</pre><h3><strong>Create your component:</strong></h3><p>As we venture forward, let’s explore the implementation of line and bar graphs using Chart.js within React.</p><h4><strong>Line graph</strong></h4><figure><img alt="line graph using chart.js and react" src="https://cdn-images-1.medium.com/max/1024/1*_mBEOiNFa0nOFjLFaLg2oQ.png" /></figure><p>The code below is for the LineGraph component:</p><pre>import React from &quot;react&quot;;<br>import { Line } from &quot;react-chartjs-2&quot;;<br>import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler } from &quot;chart.js&quot;;<br><br>ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler);<br><br>const LineGraph = () =&gt; {<br>  const sampleData = [43, 40, 50, 40, 70, 40, 45, 33, 40, 60, 40, 50, 36];<br><br>  const canvasData = {<br>    datasets: [<br>      {<br>        label: &quot;Home&quot;,<br>        borderColor: &quot;navy&quot;,<br>        pointRadius: 0,<br>        fill: true,<br>        backgroundColor: &#39;yellow&#39;,<br>        lineTension: 0.4,<br>        data: sampleData,<br>        borderWidth: 1,<br>      },<br>    ],<br>  };<br><br>  const options = {<br>    scales: {<br>      x: {<br>        grid: {<br>          display: false,<br>        },<br>        labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],<br>        ticks: {<br>          color: &quot;red&quot;,<br>          font: {<br>            family: &quot;Nunito&quot;,<br>            size: 12,<br>          },<br>        },<br>      },<br>      y: {<br>        grid: {<br>          display: false,<br>        },<br>        border: {<br>          display: false,<br>        },<br>        min: 0,<br>        max: 80,<br>        ticks: {<br>          stepSize: 10,<br>          color: &quot;green&quot;,<br>          font: {<br>            family: &quot;Nunito&quot;,<br>            size: 12,<br>          },<br>        },<br>      },<br>    },<br>    maintainAspectRatio: false,<br>    responsive: true,<br>    plugins: {<br>      legend: {<br>        display: false,<br>      },<br>      title: {<br>        display: false,<br>      },<br>    },<br>  };<br><br>  const graphStyle = {<br>    minHeight: &quot;10rem&quot;,<br>    maxWidth: &quot;540px&quot;,<br>    width: &quot;100%&quot;,<br>    border: &quot;1px solid #C4C4C4&quot;,<br>    borderRadius: &quot;0.375rem&quot;,<br>    padding: &quot;0.5rem&quot;,<br>  };<br><br>  return (<br>    &lt;div style={graphStyle}&gt;<br>      &lt;Line id=&quot;home&quot; options={options} data={canvasData} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default LineGraph;</pre><p>In the LineGraph component:</p><ul><li>We import the necessary components and register them using ChartJS.register(…).</li><li>sampleData represents the data points for the line graph.</li><li>canvasData configures the dataset for the line graph.</li><li>options provides various customization options for the graph’s appearance and behavior.</li><li>The Line component from react-chartjs-2 is used to render the actual line graph on the canvas.</li></ul><h4><strong>Bar Chart</strong></h4><figure><img alt="bar chart using chart.js and react" src="https://cdn-images-1.medium.com/max/1024/1*qG8MAv_TBY9J7o17iiu2Ng.png" /></figure><p>This is the code for the BarChart component:</p><pre>import ReactDOM from &#39;react-dom&#39;<br>import React from &#39;react&#39;<br>import {Bar} from &#39;react-chartjs-2&#39;<br>import {Chart, registerables} from &#39;chart.js&#39;<br>import {Chart as ChartJS} from &#39;chart.js&#39;<br><br>Chart.register(...registerables)<br><br>export const options = {<br>  responsive: true,<br>  plugins: {<br>    legend: {<br>      display: false,<br>    },<br>    title: {<br>      display: false,<br>    },<br>    colors: {<br>      enabled: true,<br>    },<br><br>    tooltip: {<br>      callbacks: {<br>        title: (tooltipItems) =&gt; {<br>          return &#39;&#39;<br>        },<br>        label: function (context) {<br>          let label = context.dataset.label || &#39;&#39;<br><br>          if (label) {<br>            label += &#39;Participant signup&#39;<br>          }<br>          if (context.parsed.y !== null) {<br>            label += `${context.parsed.y} signups`<br>          }<br>          return label<br>        },<br>        afterLabel: (tooltipItem) =&gt; {<br>          return tooltipItem.label<br>        },<br>        labelColor() {<br>          return {<br>            borderColor: &#39;transparent&#39;,<br>            backgroundColor: &#39;transparent&#39;,<br>            borderWidth: 3,<br>          }<br>        },<br>        labelTextColor: function (context) {<br>          return &#39;#050305&#39;<br>        },<br>        afterLabelTextColor: function (context) {<br>          return &#39;#495434&#39;<br>        },<br>      },<br><br>      backgroundColor: &#39;#fff&#39;,<br>      borderColor: &#39;#frfrfr&#39;,<br>      usePointStyle: false,<br>      showShadow: true,<br>    },<br>  },<br>  scales: {<br>    x: {<br>      display: false,<br>    },<br>    y: {<br>      grid: {<br>        display: true,<br>      },<br>      border: {<br>        display: false,<br>      },<br>      ticks: {<br>        display: false,<br>      },<br>    },<br>  },<br>}<br><br>const graphData = Array.from({length: 40}, () =&gt;<br>  Math.floor(Math.random() * 100),<br>)<br><br>const months = [<br>  &#39;January&#39;,<br>  &#39;February&#39;,<br>  &#39;March&#39;,<br>  &#39;April&#39;,<br>  &#39;May&#39;,<br>  &#39;June&#39;,<br>  &#39;July&#39;,<br>  &#39;August&#39;,<br>  &#39;September&#39;,<br>  &#39;October&#39;,<br>  &#39;November&#39;,<br>  &#39;December&#39;,<br>]<br>const labels = graphData.map((_, index) =&gt; months[index % 12])<br>export const data = {<br>  labels,<br>  datasets: [<br>    {<br>      backgroundColor: &#39;#5052ff&#39;,<br>      data: graphData,<br>      barPercentage: 1,<br>      borderRadius: 100,<br>      borderSkipped: false,<br>    },<br>  ],<br>}<br><br>const BarGraph = () =&gt; {<br>  const graphStyle = {<br>    minHeight: &#39;10rem&#39;,<br>    maxWidth: &#39;540px&#39;,<br>    width: &#39;100%&#39;,<br>    border: &#39;1px solid #C4C4C4&#39;,<br>    borderRadius: &#39;0.375rem&#39;,<br>    padding: &#39;1rem&#39;,<br>  }<br><br>  return (<br>    &lt;div style={graphStyle}&gt;<br>      &lt;Bar data={data} options={options} /&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default BarGraph;</pre><p>In the BarGraph component:</p><ul><li>graphData represents random data points for the bar chart.</li><li>months is used to label the x-axis ticks.</li><li>data configures the dataset for the bar chart.</li><li>options provides customization options for the graph’s appearance, tooltips, and more.</li></ul><h3>Chart.js Properties</h3><p>Let’s talk about the two properties in a chart js built-in component from the react chart.js library. These properties are the data and options properties, and we need these in order to customize a graph with Chart.js.</p><p><strong>Data Property:</strong></p><p>The data property contains the dataset information for your graph. Each dataset represents a set of data points on the graph, defining the appearance and behavior of the lines, bars, or other elements.</p><p>In the provided examples, the datasets array within the data object are hardcoded but you can fetch the data through an API to display it in a graph form.</p><p><strong>Options Property:</strong></p><p>The options property empowers you to customize every part of your graph, from its visual styling to its interactive behavior. By modifying the options object, you can tailor grid lines, tooltips, legends, and more.</p><h3>Conclusions</h3><p>We’ve covered the setup steps, creating both bar and line graph components, and customizing them. By providing these two different graph types, you can see how to customize your graphs easily and also play around with the data and options properties. Keep in mind, Chart.js offers even more customization possibilities. Your journey into crafting compelling data visualizations has just begun!</p><p>For more information about Chart.js’s capabilities, I encourage you to visit the <a href="https://www.chartjs.org/docs/">Chart.js documentation</a> to learn more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be72bb2ffd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding how useEffect works: A comprehensive guide]]></title>
            <link>https://medium.com/shecodeafrica/understanding-how-useeffect-works-a-comprehensive-guide-3b8b1781454c?source=rss-6e5c7fdb1b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b8b1781454c</guid>
            <category><![CDATA[components]]></category>
            <category><![CDATA[useeffect]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Hikmah  Yousuph]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 18:27:34 GMT</pubDate>
            <atom:updated>2023-06-09T18:27:34.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTnpjA90ilBE0x1Zllp8bg.png" /></figure><h3>Outline</h3><p>· <a href="#3d09">Introduction</a><br> ∘ <a href="#e89f">What is useEffect?</a><br> ∘ <a href="#7ce0">React lifecycle and useEffect</a><br>· <a href="#3737">How useEffect works</a><br> ∘ <a href="#089d">Code Structure</a><br>· <a href="#e7c3">When to use useEffect</a><br> ∘ <a href="#99c1">When performing side effects</a><br> ∘ <a href="#a962">When updating state</a><br> ∘ <a href="#174f">When cleaning up after component</a><br> ∘ <a href="#102c">When controlling the component rendering</a><br>· <a href="#f5b9">Conclusion</a></p><p>Hooks are important in React functional components and can come in handy when building React applications. There are a number of hooks in React but one of the most popular hooks that is used in many React applications is the useEffect hook. In this article, we’ll look at how the useEffect hook works.</p><h3>Introduction</h3><h4>What is useEffect?</h4><p>useEffect is a hook in React functional components that allows you to perform side effect functions. Side effect functions are actions that affect the states or behaviour of the component or outside the scope of the component, like when fetching data from an API, using event handlers, and modifying the DOM among others.</p><h4>React lifecycle and useEffect</h4><p>If you’re transitioning from class-based components to function-based components in React, you can think of useEffect as an equivalent to ComponentDidMount, ComponentDidUpdate, and ComponentWillUnmount methods.</p><p>In useEffect, there are three phases in React lifecycle, from initiation to destruction:</p><p>i. <strong>Mounting</strong>: When a component loads for the first time or is reloaded, it is said to have mounted. The component is initialized and inserted into the DOM and its state is set. This phase is similar to the ComponentDidMount method in class-based components.</p><p>ii. <strong>Updating</strong>: This is the next phase in the lifecycle, equivalent to ComponentDidUpdate. The component updates when there is a change in the state or props.</p><p>iii. <strong>Unmounting:</strong> In this final phase, the component’s state is destroyed through a cleanup function. A cleanup function is used to remove the component from the DOM, similar to ComponentWillUnmount in class-based components.</p><h3>How useEffect works</h3><h4>Code Structure</h4><p>Below this the structure of a typical useEffect function:</p><pre>import React, { useEffect } from &#39;react&#39;;<br><br>function Component() {<br>  useEffect(() =&gt; {<br>    // Side effect code here<br>    // This code will run after every render<br>    // Optional cleanup function<br>    return () =&gt; {<br>      // Code to clean up after the effect<br>      // This code will run before the next effect runs<br>    };<br>  }, [/* dependency array */]);<br>  // Component code here<br>  // This code will run after the side effect code<br>  return (<br>    // JSX to render the component<br>  );<br>}</pre><p>Usually, useEffect takes two arguments: a function and an array.</p><p>The first argument is a callback function that runs after the component renders. This function runs every time the component re-renders, depending on the second argument, the array. The cleanup function is optional and is only needed if the useEffect function is unmounting and requires cleanup.</p><p>The second argument, the dependencies array, controls the re-rendering of the component. You can add states and props to this array to control the component’s rendering. If you leave the array as an empty array, the component will only render once. Not including at least an empty array can cause the component to mount infinitely, which is bad. If you include one or more dependencies in the array, useEffect will only run if any of the dependencies change.</p><h3>When to use useEffect</h3><h4>When performing side effects</h4><p>Side effect functions that affect the component or the outside world state or behaviour are done in useEffect functions. These functions such as fetching data from an API, setting a timer, manipulating the DOM, etc, can only happen after the component is rendered.</p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>function Component() {<br>  const [data, setData] = useState([]);<br>  useEffect(() =&gt; {<br>    fetch(&#39;&lt;https://api.apiwebsitename.com/&gt;&#39;)<br>      .then(response =&gt; response.json())<br>      .then(data =&gt; setData(data))<br>      .catch(error =&gt; console.error(error));<br>  }, []);<br>  return (<br>    &lt;div&gt;<br>      {data.map(item =&gt; (<br>        &lt;div key={item.id}&gt;{item.name}&lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>This code snippet shows data being fetched from an API only once due to the empty dependency array. Initially, the data state was an empty array, but after the side effect function in the useEffect, the state gets updated.</p><h4>When updating state</h4><p>A change in a state can be used to trigger the update of another state with the help of useEffect.</p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>function Component() {<br>  const [count, setCount] = useState(0);<br>  useEffect(() =&gt; {<br>    document.title = `Count is currently at ${count}`;<br>  }, [count]);<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In the above example, the document title gets updated with every click event, incrementing the count state and triggering the useEffect with each change in the count state.</p><h4>When cleaning up after component</h4><p>For example, when setting a timer or an interval, removing an event listener, or canceling a subscription, cleaning up with useEffect is important to prevent memory leaks that can cause issues in the application.</p><pre>import { useEffect } from &#39;react&#39;;<br><br>function Component() {<br>  useEffect(() =&gt; {<br>    const timer = setTimeout(() =&gt; {<br>      console.log(&#39;Timeout completed.&#39;);<br>    }, 3000);<br>    return () =&gt; {<br>      clearTimeout(timer);<br>      console.log(&#39;Timeout cleared.&#39;);<br>    };<br>  }, []);<br>...</pre><p>In the provided example, the timeout function is called after 3 seconds, after which it is cleared out of the memory when the component unmounts.</p><h4>When controlling the component rendering</h4><p>Unlike when a state is updated, this, that is when controlling the component state, determines whether or not the component should be rendered at all. States used return boolean value while the states used when updating ranges from strings to objects.</p><pre>import React, { useState, useEffect } from &quot;react&quot;;<br><br>function Component(props) {<br>  const [isLoading, setIsLoading] = useState(true);<br>  const [data, setData] = useState(null);<br>  useEffect(() =&gt; {<br>    const fetchData = async () =&gt; {<br>      const result = await fetch(&quot;&lt;https://api.apiwebsitename.com/&gt;&quot;);<br>      const json = await result.json();<br>      setData(json);<br>      setIsLoading(false);<br>    }<br>    fetchData();<br>  }, [props.userId]);<br>  return (<br>    &lt;div&gt;<br>      {isLoading ? (<br>        &lt;div&gt;Loading...&lt;/div&gt;<br>      ) : (<br>        &lt;&gt;<br>          &lt;h1&gt;{data.name}&lt;/h1&gt;<br>          &lt;p&gt;Your email is {data.email}.&lt;/p&gt;<br>        &lt;/&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>A common example of this is when a user profile is being fetched. If there is a userId or the userId exists, the component displays, if not, the component doesn’t.</p><h3>Conclusion</h3><p>Although useEffect can be challenging for beginners, but with practice, it becomes easier to understand and use. By understanding how useEffect works, you can effectively execute your React application, enhancing its behaviour and function.</p><p>Overall, useEffect is an important hook and should be harnessed to optimise the functionality and performance of your React components.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b8b1781454c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shecodeafrica/understanding-how-useeffect-works-a-comprehensive-guide-3b8b1781454c">Understanding how useEffect works: A comprehensive guide</a> was originally published in <a href="https://medium.com/shecodeafrica">Nur: The She Code Africa Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Print PDF Files with React (Using react-to-print & Tailwind)]]></title>
            <link>https://medium.com/@hikmahx/how-to-print-pdf-files-with-react-using-react-to-print-tailwind-884c46750c35?source=rss-6e5c7fdb1b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/884c46750c35</guid>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[react-to-print]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Hikmah  Yousuph]]></dc:creator>
            <pubDate>Wed, 31 May 2023 18:20:58 GMT</pubDate>
            <atom:updated>2023-05-31T18:20:58.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nsVitH5jTEz45Bfe1z91lg.png" /></figure><p>Perhaps you have an invoice, report, or payslip that you want to generate from your website for safekeeping or proof. You want to easily obtain the file on your computer with a simple click of a button. This article will show you an easy way to accomplish that. In this article, I’ll demonstrate a beginner-friendly approach to printing a PDF file from a React component.</p><h3>Glossary</h3><ul><li><a href="https://react.dev/">React</a>: A frontend component-based library for building web applications.</li><li><a href="https://tailwindcss.com/">Tailwind</a>: a utility-first CSS framework for building websites.</li><li><a href="https://www.npmjs.com/package/react-to-print">react-to-print</a>: an npm package for printing out the content of a component.</li></ul><h3>Step by Step</h3><h4>Step 1- Installation:</h4><ol><li>Create your React application: Run the command npx create-react-app print-my-component.</li><li>Install Tailwind into your application: Refer to the <a href="https://tailwindcss.com/docs/guides/create-react-app">Tailwind documentation</a> for this step.</li><li>Install react-to-print: Run the command npm i react-to-print.</li><li>Run npm start.</li></ol><h4>Step 2- Create your component:</h4><p>Here, we will create a simple component for an employee, which includes their name, email, position, earnings, deductions, etc.</p><ol><li>In the src folder, create a components folder. Inside it, create a file named Employee.js. Add the following code to the Employee.js component:</li></ol><pre>import React, { useRef } from &quot;react&quot;;<br>import { useReactToPrint } from &quot;react-to-print&quot;;<br><br>const Employee = ({ employee }) =&gt; {<br>  let componentRef = useRef(null);<br><br>  const handlePrint = useReactToPrint({<br>    content: () =&gt; componentRef.current,<br>    documentTitle: `${employee.name.replace(/\s/g, &quot;-&quot;)<br>      }-Payslip`,<br>    onPrintError: () =&gt; alert(&quot;there is an error when printing&quot;),<br>  });<br><br>  return (<br>    &lt;section className=&quot;min-h-[85vh] p-4 lg:p-8 max-w-4xl mx-auto&quot; ref={componentRef}&gt;<br>      &lt;div<br>        key={employee.id}<br>        className=&quot;bg-white rounded-md p-3 lg:p-8 relative print:mt-12&quot;<br>      &gt;<br>        &lt;h1 className=&quot;font-bold mb-8 mt-12 lg:mt-0 print:text-3xl&quot;&gt;<br>          Employee Details<br>        &lt;/h1&gt;<br><br>        &lt;div className=&quot;info p-4 border border-zinc-200 rounded-md&quot;&gt;<br>          &lt;p className=&quot;mb-4&quot;&gt;<br>            &lt;span className=&quot;font-bold&quot;&gt;Name:&lt;/span&gt;{&quot; &quot;}<br>            &lt;span className=&quot;text-zinc-500 text-sm capitalize&quot;&gt;<br>              {employee.name}<br>            &lt;/span&gt;<br>          &lt;/p&gt;<br>          &lt;p className=&quot;mb-4&quot;&gt;<br>            &lt;span className=&quot;font-bold&quot;&gt;Email:&lt;/span&gt;{&quot; &quot;}<br>            &lt;span className=&quot;text-zinc-500 text-sm break-words&quot;&gt;<br>              {employee.email}<br>            &lt;/span&gt;<br>          &lt;/p&gt;<br>          &lt;p className=&quot;mb-4&quot;&gt;<br>            &lt;span className=&quot;font-bold&quot;&gt;Cadre Level:&lt;/span&gt;{&quot; &quot;}<br>            &lt;span className=&quot;text-zinc-500 text-sm capitalize&quot;&gt;<br>              {employee.cadreLevel}<br>            &lt;/span&gt;<br>          &lt;/p&gt;<br>          &lt;p className=&quot;mb-4&quot;&gt;<br>            &lt;span className=&quot;font-bold&quot;&gt;Position:&lt;/span&gt;{&quot; &quot;}<br>            &lt;span className=&quot;text-zinc-500 text-sm capitalize&quot;&gt;<br>              {employee.position}<br>            &lt;/span&gt;<br>          &lt;/p&gt;<br>        &lt;/div&gt;<br>        &lt;div className=&quot;flex flex-col lg:flex-row gap-5 my-6&quot;&gt;<br>          &lt;div className=&quot;flex-1 p-4 border border-zinc-200 rounded-md flex flex-col justify-between&quot;&gt;<br>            &lt;div className=&quot;&quot;&gt;<br>              &lt;h2 className=&quot;font-bold mb-6  text-lg lg:text-xl&quot;&gt;Earnings&lt;/h2&gt;<br><br>              &lt;div className=&quot;mb-4&quot;&gt;<br>                &lt;span className=&quot;font-bold&quot;&gt;Basic:&lt;/span&gt;{&quot; &quot;}<br>                &lt;span className=&quot;text-zinc-500 text-sm&quot;&gt;<br>                  {employee.earnings.basic}<br>                &lt;/span&gt;<br>              &lt;/div&gt;<br>              &lt;div className=&quot;mb-4&quot;&gt;<br>                &lt;span className=&quot;font-bold&quot;&gt;Transport:&lt;/span&gt;{&quot; &quot;}<br>                &lt;span className=&quot;text-zinc-500 text-sm&quot;&gt;<br>                  {employee.earnings.transport}<br>                &lt;/span&gt;<br>              &lt;/div&gt;<br>              &lt;div className=&quot;mb-4&quot;&gt;<br>                &lt;span className=&quot;font-bold&quot;&gt;Overtime:&lt;/span&gt;{&quot; &quot;}<br>                &lt;span className=&quot;text-zinc-500 text-sm&quot;&gt;<br>                  {employee.earnings.overtime}<br>                &lt;/span&gt;<br>              &lt;/div&gt;<br>              &lt;div className=&quot;mb-4&quot;&gt;<br>                &lt;span className=&quot;font-bold&quot;&gt;Housing:&lt;/span&gt;{&quot; &quot;}<br>                &lt;span className=&quot;text-zinc-500 text-sm&quot;&gt;<br>                  {employee.earnings.housing}<br>                &lt;/span&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;&quot;&gt;<br>              &lt;h2 className=&quot;text-lg&quot;&gt;<br>                &lt;span className=&quot;font-bold&quot;&gt;Total:&lt;/span&gt;{&quot; &quot;}<br>                &lt;span className=&quot;&quot;&gt; ₦ 7,070.00&lt;/span&gt;<br>              &lt;/h2&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;{&quot; &quot;}<br>          &lt;div className=&quot;flex-1 p-4 border border-zinc-200 rounded-md flex flex-col justify-between&quot;&gt;<br>            &lt;div className=&quot;&quot;&gt;<br>              &lt;h2 className=&quot;font-bold mb-6 text-lg lg:text-xl&quot;&gt;Deductions&lt;/h2&gt;<br>              &lt;div className=&quot;mb-4&quot;&gt;<br>                &lt;span className=&quot;font-bold&quot;&gt;Tax:&lt;/span&gt;{&quot; &quot;}<br>                &lt;span className=&quot;text-zinc-500 text-sm&quot;&gt;<br>                  {employee.deductions?.tax}<br>                &lt;/span&gt;<br>              &lt;/div&gt;<br>              &lt;div className=&quot;mb-4&quot;&gt;<br>                &lt;span className=&quot;font-bold&quot;&gt;Pension:&lt;/span&gt;{&quot; &quot;}<br>                &lt;span className=&quot;text-zinc-500 text-sm&quot;&gt;<br>                  {employee.deductions?.pension}<br>                &lt;/span&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;&quot;&gt;<br>              &lt;h2 className=&quot;text-lg&quot;&gt;<br>                &lt;span className=&quot;font-bold&quot;&gt;Total:&lt;/span&gt;{&quot; &quot;}<br>                &lt;span className=&quot;&quot;&gt;₦ 700.00&lt;/span&gt;<br>              &lt;/h2&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div className=&quot;info p-4 border border-zinc-200 rounded-md&quot;&gt;<br>          &lt;h2 className=&quot;text-lg&quot;&gt;<br>            &lt;span className=&quot;font-bold&quot;&gt;Overall Total:&lt;/span&gt;{&quot; &quot;}<br>            &lt;span className=&quot;&quot;&gt;₦ 6,370.00&lt;/span&gt;<br>          &lt;/h2&gt;<br>        &lt;/div&gt;<br>        &lt;div className=&quot;print:hidden&quot;&gt;<br>          &lt;button<br>            onClick={handlePrint}<br>            className=&quot;bg-cyan-500 px-6 py-2 text-white border border-cyan-500 font-bold rounded-md mb-3 w-full lg:w-fit my-6 max-w-sm&quot;<br>          &gt;<br>            Print Payslip<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/section&gt;<br>  );<br>};<br><br>export default Employee;</pre><p>2. Clear the contents of your App.js file and replace it with the following code:</p><pre>import React, { useState } from &quot;react&quot;;<br>import Employee from &#39;./components/Employee&#39;;<br><br>function App() {<br>  const [employee, setEmployee] = useState({<br>    id: 1685328248504,<br>    name: &quot;John Doe&quot;,<br>    email: &quot;johndoe@gmail.com&quot;,<br>    position: &quot;accountant&quot;,<br>    cadreLevel: &quot;Consultant&quot;,<br>    isAdmin: false,<br>    earnings: {<br>      basic: 5000,<br>      transport: 1000,<br>      overtime: 370,<br>      housing: 700,<br>    },<br>    deductions: {<br>      tax: 500,<br>      pension: 200,<br>    },<br>  });<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;main className=&quot;min-h-screen bg-gray-200 w-full&quot;&gt;<br>        &lt;Employee employee={employee} /&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Your website should now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPiJfiF7jZr_dlWNqN-bew.png" /></figure><p>If you click on the “Print Payslip” button, this is what will be displayed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_uCZd4myeftG54DMUHKIIg.png" /></figure><h3>Code explanation</h3><p>In the App.js file, we use the useState hook to create an employee state, which we pass as a destructured prop to the Employee.js component.</p><pre>const Employee = ({ employee }) =&gt; {<br>...</pre><p>To print a component, we use the useRef hook to create a reference to a DOM element. This reference captures the component&#39;s HTML content when printing. We place the useRef hook on the section tag that represents the part of the document we want to print.</p><pre>import React, { useRef } from &quot;react&quot;;<br>import { useReactToPrint } from &quot;react-to-print&quot;;<br><br>const Employee = ({ employee }) =&gt; {<br>  let componentRef = useRef(null);<br><br>  const handlePrint = useReactToPrint({<br>    content: () =&gt; componentRef.current,<br>    documentTitle: `${employee.name.replace(/\s/g, &quot;-&quot;)<br>      }-Payslip`,<br>    onPrintError: () =&gt; alert(&quot;there is an error when printing&quot;),<br>  });<br><br>  return (<br><br>    &lt;section className=&quot;min-h-[85vh] p-4 lg:p-8 max-w-4xl mx-auto&quot; ref={componentRef}&gt;<br>       ...<br></pre><p>When the “Print Payslip” button is clicked, it triggers the handlePrint function, which, in turn, triggers the useReactToPrint hook. This hook handles the printing functionality seamlessly.</p><p>The useReactToPrint hook receives an object with different properties as props. In this tutorial, we use the following properties:</p><ul><li>content: A function that returns the DOM element to be printed. In this case, it returns the current value of componentRef using componentRef.current.</li><li>documentTitle: The title to be displayed for the printed document. It is set to the employee&#39;s name with spaces replaced by hyphens and appended with &quot;-Payslip&quot;.</li><li>onPrintError: A callback function that executes if there is an error during printing. In this case, it displays an alert message.</li></ul><p>Please note that you can visit the <a href="https://www.npmjs.com/package/react-to-print">react-to-print</a> documentation to view other props that you can use in your applications.</p><p>Lastly, I used Tailwind CSS to add the print class prefix. In the provided code, you&#39;ll notice the print:hidden class on the &quot;Print Payslip&quot; button, which hides the button from being printed in the PDF document. Additionally, you can apply additional styling based on your desired document appearance. For example, adding print:text-purple-700 would display the text with a purple color when ready to be printed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VxMZxK9PyrFzufp8qaubg.png" /></figure><p>And that’s how easy it is to print out a document with React!</p><h3>Conclusion</h3><p>See how easy it was to implement printing in your application? We were able to generate PDF files and customize them effortlessly with Tailwind CSS.</p><p>This article serves as an easy-to-follow guide for anyone looking to add printing functionality to their website for the first time. Make sure to visit the mentioned documentation for a more advanced understanding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=884c46750c35" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>