<?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 Nikos on Medium]]></title>
        <description><![CDATA[Stories by Nikos on Medium]]></description>
        <link>https://medium.com/@nikos.ka?source=rss-793000d01214------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A-wh6kMHH18FF7ZV1vz4wQ.png</url>
            <title>Stories by Nikos on Medium</title>
            <link>https://medium.com/@nikos.ka?source=rss-793000d01214------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:27:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikos.ka/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[Creating a Fraud Detection MCP Server Prototype in Python]]></title>
            <link>https://medium.com/@nikos.ka/creating-a-fraud-detection-mcp-server-prototype-in-python-d16a7c52737e?source=rss-793000d01214------2</link>
            <guid isPermaLink="false">https://medium.com/p/d16a7c52737e</guid>
            <dc:creator><![CDATA[Nikos]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 05:22:31 GMT</pubDate>
            <atom:updated>2025-08-28T05:22:31.658Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QCGuNKy8CYqQZuAf709_A.png" /></figure><p>Fraud detection is a critical function in the modern financial industry, safeguarding billions of dollars from illicit activities. It’s also a fantastic use case for showcasing the power of modern data-processing systems and APIs. In this article, we’ll walk through a simple prototype of a Fraud Detection server using Python and the Model Context Protocol (MCP).</p><h3>What is MCP?</h3><p>Before we dive into the code, let’s briefly touch on what MCP is. Think of MCP as a universal language for how different software components can talk to each other, especially when one of them is an AI agent or a “model.”</p><p>In simple terms, MCP defines a standard way for a server (like our fraud detector) to expose its capabilities — what it knows and what it can do — to a client. It specifies how to:</p><ul><li>Expose “tools”: These are actions the server can perform, like our check_fraud function that we will see next.</li><li>Expose “resources”: This is data the server can provide, like our list of fraud://rules we will see next.</li></ul><p>By using a standard protocol like MCP, we make it easier for different systems to work together without needing to write custom integrations every time.</p><h3>Why fraud detection is a great use case</h3><p>Fraud detection systems are excellent examples for a few key reasons:</p><ul><li>Structured data: Transactions are almost always well-structured, containing fields like amount, location, user ID, and device information. This makes them easy to process programmatically.</li><li>Real-time queries: Detecting fraud requires immediate analysis. Systems must be able to receive a transaction, process it against a set of rules or models, and return a verdict in milliseconds.</li><li>High impact: The financial and reputational costs of fraud are enormous. Even simple, effective fraud detection can provide immense value.</li></ul><h3>A Prototype</h3><p>It’s important to clarify that we are building a prototype designed to illustrate the concepts. It uses mock data and a few simple, hard-coded rules. A production-grade fraud detection engine would be far more complex, likely involving:</p><ul><li>Real-time data streams from multiple sources.</li><li>Machine learning models trained on vast datasets.</li><li>A highly scalable and resilient infrastructure.</li><li>Complex rule engines that can be updated dynamically.</li></ul><p>Our goal is to show the basic structure of such a service, not to build a production-ready tool.</p><h3>Building the Fraud Detection MCP Server, step by step</h3><p>Let’s build our fraud detection server piece by piece. This will make it easier to understand the role of each part.</p><h3>1. The core logic: detecting fraud</h3><p>First, we need a function that contains our business logic. This function will take a transaction and check it against our rules. It’s a standard Python function, with no MCP-specific code.</p><pre>def detect_fraud(transaction: dict):<br>    flags = []<br>    if transaction.get(&#39;amount&#39;, 0) &gt; 10000:<br>        flags.append(&#39;High-value transaction&#39;)<br>    if transaction.get(&#39;location&#39;) == &#39;foreign&#39; and transaction.get(&#39;new_device&#39;):<br>        flags.append(&#39;Foreign + new device&#39;)<br>    if transaction.get(&#39;failed_logins&#39;, 0) &gt; 3:<br>        flags.append(&#39;Too many failed login attempts&#39;)<br>    return flags </pre><p>This function, detect_fraud, takes a dictionary representing a transaction and returns a list of strings, or “flags.” Each flag is a human-readable description of a suspicious pattern. If no patterns are found, it returns an empty list.</p><h3>2. Creating the server and adding a tool</h3><p>Next, we’ll create an MCP server and expose our fraud detection logic as a “tool.” A tool is an action that the server can perform on behalf of a client.</p><p>We’ll use FastMCP, a lightweight framework for creating MCP-compliant servers.</p><pre>from mcp.server.fastmcp import FastMCP<br><br># Initialize the server<br>server = FastMCP(&#39;fraud-detection&#39;)<br><br># The core logic from step 1<br>def detect_fraud(transaction):<br>    # ... (code from above)<br><br>@server.tool(&#39;check_fraud&#39;)<br>def check_fraud(transaction: dict) -&gt; dict:<br>    flags = detect_fraud(transaction)<br>    return {<br>        &#39;transaction&#39;: transaction,<br>        &#39;fraud_flags&#39;: flags,<br>        &#39;is_suspicious&#39;: len(flags) &gt; 0,<br>    } </pre><p>Here’s what’s new:</p><ul><li>We import FastMCP and create a server instance named fraud-detection.</li><li>We define a new function, check_fraud, which acts as a wrapper around our core detect_fraud logic.</li><li>The @server.tool(‘check_fraud’) decorator is the magic part. It registers our check_fraud function as a tool that clients can call. It packages the results in a structured dictionary, indicating whether the transaction is suspicious.</li></ul><h3>3. Exposing the rules as a Resource</h3><p>Good APIs are self-documenting. It would be helpful for a client to be able to ask our server what rules it uses for fraud detection. MCP allows us to expose this kind of information as a “resource.” A resource is a file-like data that a client can query.</p><pre>@server.resource(&#39;fraud://rules&#39;)<br>def fraud_rules():<br>    return {<br>        &#39;rules&#39;: [<br>            &#39;Transaction &gt; 10,000 flagged&#39;,<br>            &#39;Foreign + new device flagged&#39;,<br>            &#39;More than 3 failed logins flagged&#39;,<br>        ]<br>    } </pre><p>The @server.resource(‘fraud://rules’) decorator exposes our list of rules. The string fraud://rules is a unique identifier for this resource, similar to a URL. Now, a client can query this URI to get a list of the server’s current fraud-detection rules. This is great for transparency and debugging.</p><h3>4. Putting it all together and running the server</h3><p>Now let’s assemble all the pieces into a single, runnable script. The final step is to add the standard Python entry point to start the server.</p><pre># server.py<br>from mcp.server.fastmcp import FastMCP<br><br>server = FastMCP(&#39;fraud-detection&#39;)<br><br><br>def detect_fraud(transaction):<br>    flags = []<br>    if transaction.get(&#39;amount&#39;, 0) &gt; 10000:<br>        flags.append(&#39;High-value transaction&#39;)<br>    if transaction.get(&#39;location&#39;) == &#39;foreign&#39; and transaction.get(&#39;new_device&#39;):<br>        flags.append(&#39;Foreign + new device&#39;)<br>    if transaction.get(&#39;failed_logins&#39;, 0) &gt; 3:<br>        flags.append(&#39;Too many failed login attempts&#39;)<br>    return flags<br><br><br>@server.tool(&#39;check_fraud&#39;)<br>def check_fraud(transaction: dict) -&gt; dict:<br>    flags = detect_fraud(transaction)<br>    return {<br>        &#39;transaction&#39;: transaction,<br>        &#39;fraud_flags&#39;: flags,<br>        &#39;is_suspicious&#39;: len(flags) &gt; 0,<br>    }<br><br><br>@server.resource(&#39;fraud://rules&#39;)<br>def fraud_rules():<br>    return {<br>        &#39;rules&#39;: [<br>            &#39;Transaction &gt; 10,000 flagged&#39;,<br>            &#39;Foreign + new device flagged&#39;,<br>            &#39;More than 3 failed logins flagged&#39;,<br>        ]<br>    }<br><br><br>if __name__ == &#39;__main__&#39;:<br>    server.run(transport=&#39;stdio&#39;) </pre><p>The if __name__ == ‘__main__’ block ensures that server.run() is called only when the script is executed directly. The transport=’stdio’ argument tells the server to communicate over standard input and output, which is a common way for MCP servers to interact with their clients.</p><h3>How to run and test the server</h3><p>Now that we have our server script, let’s run it. To start the server with the MCP Inspector (a web-based tool for testing MCP servers), run the following command in your terminal, just after you pip install ‘mcp[cli]’:</p><pre># Run the MCP server with the MCP Inspector<br>$ mcp dev server.py </pre><p>This command will start the server and provide a URL to the MCP Inspector, which you can open in your web browser.</p><h3>Using the MCP Inspector</h3><p>Once you open the MCP Inspector in your browser:</p><ol><li>The Inspector will connect to your running fraud-detection server.</li><li>It will help you discover the check_fraud tool and the fraud://rules resource.</li><li>To test the tool, select check_fraud and provide the transaction argument.</li><li>Paste in a sample transaction. For example: { “amount”: 12000, “location”: “foreign”, “new_device”: true, “failed_logins”: 1 }</li><li>Execute the tool. The Inspector will show you the JSON response from the server. For the data above, you should see: { “transaction”: { “amount”: 12000, “location”: “foreign”, “new_device”: true, “failed_logins”: 1 }, “fraud_flags”: [ “High-value transaction”, “Foreign + new device” ], “is_suspicious”: true }</li></ol><p>As you can see, the server correctly identified two suspicious flags and marked the transaction as suspicious. You can also use the Inspector to query the fraud://rules resource to see the list of rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDykcjqi6FWHifwCCzFYtg.png" /><figcaption>MCP Inspector with a list of tools exposed by our prototype MCP server</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHnpBYBh4c2QptTdmXMMlQ.png" /><figcaption>Run a transaction check with MCP Inspector</figcaption></figure><h3>How to use fraud detector in Claude</h3><p>One of the powerful features of MCP is the ability to make your tools available to AI models like Claude. If you have the Claude desktop app, you can register your fraud detection server so that you can use it directly in your conversations.</p><p>To register the server, run the following command in your terminal:</p><pre># Register the MCP server with Claude<br>$ mcp install server.py </pre><p>This command uses mcp install to tell the Claude app about your fraud-detection server and the tools it provides.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itJki-8-VX-5GaPd2QwcNg.png" /><figcaption>Claude desktop with our prototype MCP server installed</figcaption></figure><p>Once registered, you can ask Claude to use your tool. For example, you could give it the following prompt:</p><blockquote><em>Analyze this transaction for fraud:</em></blockquote><blockquote><em>{ “amount”: 12000, “location”: “foreign”, “new_device”: true, “failed_logins”: 1 }</em></blockquote><p>Claude will be able to find the check_fraud tool from your server, execute it with the provided data, and use the results in its response. This allows you to integrate your custom logic directly into your workflow with the AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbRTFZkC6GeM7xHOA_N5yA.png" /><figcaption>Clause analysis using tool exposed by our prototype MCP server</figcaption></figure><h3>Conclusion</h3><p>This simple prototype demonstrates how quickly you can stand up a structured, real-time data service in Python. While our rules are basic, they could easily be replaced with calls to more sophisticated logic or machine learning models. The MCP framework provides a clean, standardized way to expose this logic to any client that needs to check for fraud.</p><p>To summarize what is a MCP server:</p><ul><li>An MCP server is a process that exposes structured tools, resources, and prompts over a standard JSON-RPC protocol.</li><li>It doesn’t decide what to do — it just offers capabilities (like “check fraud,” “fetch loan history,” or “generate onboarding docs”).</li><li>MCP servers are stateless by design: each tool call takes inputs and returns outputs, without memory unless you add it.</li><li>They can wrap APIs, databases, local files, or custom logic and make them accessible to AI models in a safe, standardized way.</li></ul><p><em>Enjoyed this guide? Follow me for more hands-on AI and software development content! #Python #AI #MCP #Developer #TechGuide</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d16a7c52737e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own AI Document Assistant (2): Upgrading to Chroma]]></title>
            <link>https://medium.com/@nikos.ka/build-your-own-ai-document-assistant-2-upgrading-to-chroma-10c94eb4a4e1?source=rss-793000d01214------2</link>
            <guid isPermaLink="false">https://medium.com/p/10c94eb4a4e1</guid>
            <dc:creator><![CDATA[Nikos]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 05:08:13 GMT</pubDate>
            <atom:updated>2025-08-28T05:25:34.292Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzrJkPIeTLMN8IbYE2yzIA.png" /><figcaption>source: ChatGPT</figcaption></figure><p>In our last guide, we built an AI assistant using FAISS. It was fast, but required to manually save and load data. Now, it’s time for an upgrade.</p><p>In this guide, we’ll swap out FAISS for <a href="https://docs.trychroma.com/docs/overview/introduction">Chroma</a> to build a more robust application.</p><p>See also the first part in the series: <a href="https://medium.com/@nikos.ka/build-your-own-ai-document-assistant-from-scratch-a-step-by-step-guide-14239f796260">Build Your Own AI Document Assistant from Scratch: A Step-by-Step Guide</a>.</p><p>Why Upgrade to Chroma?</p><ul><li><strong>Automatic persistence</strong>: Chroma saves your data to disk automatically. Your assistant will now “remember” documents across restarts with zero extra code — no more manual file juggling!</li><li><strong>Rich metadata</strong>: We can now easily store metadata (like filenames or tags) alongside our documents. This is crucial for tracking where information comes from.</li><li><strong>A cleaner API</strong>: The code for adding and searching documents becomes simpler and more intuitive.</li></ul><p>Let’s dive in and refactor our assistant!</p><h3>Step 1: Upgrading our toolkit</h3><p>In the first part of our guide, we used FAISS for vector search. It’s fast, but it requires us to manage persistence manually. Let’s upgrade to ChromaDB to simplify our lives.</p><p>First, let’s adjust our Python dependencies.</p><pre># Remove FAISS<br>pip uninstall faiss-cpu<br><br># Install ChromaDB<br>pip install chromadb</pre><p>That’s it! ChromaDB will now handle our vector storage, and we no longer need to worry about saving our index to a file.</p><h3>Step 2: Upgraded storage layer</h3><p>With FAISS, our index and documents were simple global variables. ChromaDB, however, acts as a dedicated database for AI applications, which gives a slightly more robust setup. Let’s update storage to manage our database connection.</p><pre># src/assistant/storage.py<br>&quot;&quot;&quot;<br>Persistent storage module for the vector database.<br>&quot;&quot;&quot;<br>import typing as tp<br>import chromadb<br>from chromadb.utils import embedding_functions<br><br># Use the same sentence transformer model as before<br>embed_fn = embedding_functions.SentenceTransformerEmbeddingFunction(<br>    model_name=&#39;all-MiniLM-L6-v2&#39;<br>)<br><br># Set up a persistent client that stores data in the &#39;.instance/chroma_store&#39;<br># directory<br>chroma_client = chromadb.PersistentClient(path=&#39;.instance/chroma_store&#39;)<br><br>def get_collection() -&gt; chromadb.Collection:<br>    &quot;&quot;&quot;Get or create the persistent document collection.&quot;&quot;&quot;<br>    # The embedding function is attached to the collection,<br>    # so Chroma handles the embedding process for us.<br>    return chroma_client.get_or_create_collection(<br>        name=&#39;docs&#39;, embedding_function=tp.cast(chromadb.EmbeddingFunction, embed_fn)<br>    )</pre><p>By creating a PersistentClient, Chroma automatically saves any data we add to the disk. When our application restarts, it will reconnect to the same store, “remembering” all previously uploaded documents.</p><h3>Step 3: Refactoring the embeddings logic</h3><p>Now we can simplify our embeddings.py module. We’ll replace all the manual FAISS and NumPy handling with clean API calls to our Chroma collection.</p><pre># src/assistant/embeddings.py<br>&quot;&quot;&quot;<br>Vector embeddings module using ChromaDB.<br>&quot;&quot;&quot;<br>import uuid<br>from .storage import get_collection<br><br>collection = get_collection()<br><br>def add_document(text: str, metadata: dict | None = None) -&gt; None:<br>    &quot;&quot;&quot;<br>    Adds a document chunk to the ChromaDB collection.<br>    Chroma handles the embedding automatically.<br>    &quot;&quot;&quot;<br>    # We need a unique ID for each document chunk<br>    doc_id = f&#39;doc_{len(collection.get()[&quot;ids&quot;]) + 1}&#39;<br>    collection.add(ids=[doc_id], documents=[text], metadatas=[metadata or {}])<br><br>def search(query: str, top_k: int = 3) -&gt; list[str]:<br>    &quot;&quot;&quot;<br>    Searches for similar document chunks in ChromaDB.<br>    &quot;&quot;&quot;<br>    doc_id = str(uuid.uuid4())<br>    return results.get(&quot;documents&quot;, [[]])[0]<br><br>def list_documents(limit: int = 50) -&gt; list[dict]:<br>    &quot;&quot;&quot;Lists all documents and their metadata.&quot;&quot;&quot;<br>    data = collection.get(limit=limit)<br>    # Combine the documents and metadata for a nice, clean output<br>    return [<br>        {&quot;id&quot;: i, &quot;document&quot;: d, &quot;metadata&quot;: m}<br>        for i, d, m in zip(data[&quot;ids&quot;], data[&quot;documents&quot;], data[&quot;metadatas&quot;])<br>    ]<br><br>def clear_documents():<br>    &quot;&quot;&quot;Clears all documents from the collection.&quot;&quot;&quot;<br>    collection.delete(ids=collection.get()[&quot;ids&quot;])</pre><p>Look at how much cleaner that is!</p><ul><li>We no longer need to manually encode text with SentenceTransformer.</li><li>We don’t need to manage a separate documents list.</li><li>The add_document function now accepts metadata, which is a huge win.</li></ul><h3>Step 4: Enhancing the API with metadata and management options</h3><p>Our final step is to update our API routes to take advantage of these new capabilities. We’ll pass the document’s filename as metadata and add new endpoints to list and clear our document store.</p><pre># src/assistant/routes.py<br>from litestar import Request, get, post<br># ... other imports<br><br># The &#39;ask&#39; endpoint remains the same!<br><br>@post(&#39;/upload/pdf&#39;)<br>async def upload_pdf(request: Request) -&gt; dict:<br>    form_data = await request.form()<br>    file = form_data.get(&quot;file&quot;)<br>    # ... file validation ...<br><br>    # Save the file and get its path<br>    file_path = await save_upload(file)<br>    text = extract_text_from_pdf(file_path)<br>    chunks = chunk_text(text)<br><br>    # Create metadata to track the source file<br>    metadata = {&quot;source&quot;: file.filename}<br>    for chunk in chunks:<br>        add_document(chunk, metadata=metadata)<br><br>    return {<br>        &quot;status&quot;: &quot;ok&quot;,<br>        &quot;chunks_added&quot;: len(chunks),<br>        &quot;source&quot;: file.filename<br>    }<br><br># Add these new endpoints for managing the document store<br><br>@get(&#39;/list&#39;)<br>async def list_docs() -&gt; dict:<br>    &quot;&quot;&quot;Lists all documents currently in the store.&quot;&quot;&quot;<br>    docs = list_documents()<br>    return {&quot;documents&quot;: docs, &quot;count&quot;: len(docs)}<br><br>@post(&#39;/reset&#39;)<br>async def reset_docs() -&gt; dict:<br>    &quot;&quot;&quot;Clears all documents from the store. This is irreversible!&quot;&quot;&quot;<br>    clear_documents()<br>    return {&quot;status&quot;: &quot;ok&quot;, &quot;message&quot;: &quot;Document store has been cleared.&quot;}</pre><p>Don’t forget to add list_docs and reset_docs to your Litestar app instance in asgi.py.</p><h3>Conclusion: A more robust assistant</h3><p>By swapping FAISS for ChromaDB, we’ve made our AI assistant significantly more powerful and easier to maintain.</p><ul><li>Automatic persistence: Our assistant now remembers documents across restarts with zero extra code.</li><li>Rich metadata: We can track the source of every piece of information, opening the door for more advanced features like filtering searches by document.</li><li>Simplified code: Our embedding logic is cleaner and more readable.</li><li>Management API: We now have endpoints to list and clear all documents, giving us control over the data store.</li></ul><p>You now have a solid foundation for a production-ready RAG application. From here, you can add a user interface, support more document types, or experiment with different embedding and language models.</p><p>You can find a working example in <a href="https://github.com/codcod/ai-doc-assistant">this GitHub repository</a>.</p><p><em>Enjoyed this guide? Follow me for more hands-on AI and software development content! #Python #AI #LLM #RAG #Developer #TechGuide</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10c94eb4a4e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own AI Document Assistant from Scratch: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@nikos.ka/build-your-own-ai-document-assistant-from-scratch-a-step-by-step-guide-14239f796260?source=rss-793000d01214------2</link>
            <guid isPermaLink="false">https://medium.com/p/14239f796260</guid>
            <dc:creator><![CDATA[Nikos]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 20:49:17 GMT</pubDate>
            <atom:updated>2025-08-28T05:24:46.350Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9qqjK7mnAcYo7TBCeLTjg.png" /><figcaption>source: ChatGPT</figcaption></figure><p>Ever wondered how you could build an AI that reads your documents and answers questions about them? It’s easier than you think! In this guide, I’ll walk you through creating a powerful, AI-driven document assistant from scratch using Python.</p><p>See also the second part in the series: <a href="https://medium.com/@nikos.ka/build-your-own-ai-document-assistant-2-upgrading-to-chroma-10c94eb4a4e1">Build Your Own AI Document Assistant (2): Upgrading to Chroma</a>.</p><p>We’ll build a complete application that can:</p><ul><li>Accept PDF and text file uploads via a web API.</li><li>Process and understand the content using vector embeddings.</li><li>Answer your questions based on the information in your documents.</li></ul><p>Let’s get started!</p><h3>Step 1: Project setup</h3><p>First, let’s set up our project structure and install the necessary libraries.</p><h4>Create your project directory:</h4><pre>mkdir ai-assistant<br>cd ai-assistant<br>python -m venv .venv<br>source .venv/bin/activate</pre><h4>Install the core libraries:</h4><p>We’ll need a few key tools:</p><ul><li><a href="https://litestar.dev/">litestar</a>: For our web API.</li><li><a href="https://www.sbert.net/">sentence-transformers</a>: To create vector embeddings from text.</li><li><a href="https://github.com/facebookresearch/faiss">faiss-cpu</a>: For efficient similarity search on our vectors.</li><li><a href="https://github.com/py-pdf/pypdf">pypdf</a>: To extract text from PDF files.</li><li><a href="https://github.com/abetlen/llama-cpp-python">llama-cpp-python</a>: To run our language model locally.</li></ul><p>Install them all with pip:</p><pre>pip install litestar \<br>            sentence-transformers \<br>            faiss-cpu \<br>            pypdf \<br>            llama-cpp-python \<br>            numpy</pre><h3>Step 2: Processing documents</h3><p>Our assistant needs to read and process documents. Let’s create a utils.py file to handle this.</p><h4>Extracting text from PDFs:</h4><p>We’ll use pypdf to get the text from each page of a PDF.</p><pre># src/assistant/utils.py<br>from pypdf import PdfReader<br><br>def extract_text_from_pdf(file_path: str) -&gt; str:<br>    &quot;&quot;&quot;Extracts text content from a PDF file.&quot;&quot;&quot;<br>    reader = PdfReader(file_path)<br>    text = &quot;&quot;<br>    for page in reader.pages:<br>        page_text = page.extract_text()<br>        if page_text:<br>            text += page_text + &quot;\n&quot;<br>    return text.strip()</pre><h4>Chunking text:</h4><p>Language models have a limited context window, so we need to break large documents into smaller, overlapping chunks.</p><pre># src/assistant/utils.py<br>def chunk_text(text: str, chunk_size: int = 500, overlap: int = 50):<br>    &quot;&quot;&quot;Splits text into overlapping chunks.&quot;&quot;&quot;<br>    words = text.split()<br>    chunks = []<br>    start = 0<br>    while start &lt; len(words):<br>        end = min(start + chunk_size, len(words))<br>        chunk = &quot; &quot;.join(words[start:end])<br>        chunks.append(chunk)<br>        start += chunk_size - overlap<br>    return chunks</pre><h3>Step 3: Creating and searching embeddings</h3><p>This is where the magic happens. We’ll convert our text chunks into numerical representations (vectors) so we can find the most relevant ones for a given question.</p><pre># src/assistant/embeddings.py<br>import faiss<br>import numpy as np<br>from sentence_transformers import SentenceTransformer<br>from typing import List<br><br># Load a pre-trained model<br>embedder = SentenceTransformer(&quot;all-MiniLM-L6-v2&quot;)<br><br># Create a FAISS index for storing vectors<br>index = faiss.IndexFlatL2(384)  # 384 is the dimension of our model&#39;s vectors<br>documents: List[str] = []<br><br>def add_document(text: str) -&gt; None:<br>    &quot;&quot;&quot;Converts text to a vector and adds it to the index.&quot;&quot;&quot;<br>    vector = embedder.encode([text])<br>    vector = np.array(vector, dtype=np.float32)<br>    index.add(vector)<br>    documents.append(text)<br><br>def search(query: str, top_k: int = 3) -&gt; List[str]:<br>    &quot;&quot;&quot;Searches for the most similar document chunks.&quot;&quot;&quot;<br>    vector = embedder.encode([query])<br>    vector = np.array(vector, dtype=np.float32)<br>    _, indices = index.search(vector, top_k)<br>    return [documents[i] for i in indices[0]]</pre><h3>Step 4: Generating answers with an LLM</h3><p>Now we need a language model to generate answers. We’ll use llama-cpp-python to run a model locally.</p><pre># src/assistant/llm.py<br>import os<br>from llama_cpp import Llama<br><br># Download a GGUF model (e.g., Phi-3-mini)<br># and place it in a &#39;models&#39; directory<br>MODEL_PATH = os.getenv(&quot;MODEL_PATH&quot;, &quot;models/Phi-3-mini-4k-instruct-q4.gguf&quot;)<br>llm = Llama(model_path=MODEL_PATH, n_ctx=4096)<br><br>def generate(prompt: str) -&gt; str:<br>    &quot;&quot;&quot;Generates a response from the LLM.&quot;&quot;&quot;<br>    output = llm(prompt, max_tokens=512, stop=[&quot;&lt;/s&gt;&quot;], echo=False)<br>    return output[&quot;choices&quot;][0][&quot;text&quot;].strip()</pre><h3>Step 5: Tying it all together with RAG</h3><p>Retrieval-Augmented Generation is the process of retrieving relevant information and feeding it to our LLM to generate an informed answer.</p><pre># src/assistant/rag.py<br>from .embeddings import search<br>from .llm import generate<br><br>def rag_answer(query: str) -&gt; str:<br>    &quot;&quot;&quot;Finds relevant context and generates an answer.&quot;&quot;&quot;<br>    context_chunks = search(query)<br>    context_text = &quot;\n&quot;.join(context_chunks)<br><br>    prompt = f&quot;&quot;&quot;<br>You are a helpful assistant. Use the provided context to answer the question.<br><br>Context:<br>{context_text}<br><br>Question: {query}<br>Answer:<br>&quot;&quot;&quot;<br>    return generate(prompt)</pre><h3>Step 6: Creating the API</h3><p>Finally, let’s expose our logic through a web API using Litestar.</p><pre># src/assistant/routes.py<br>from litestar import post, Request<br>from litestar.datastructures import UploadFile<br>from pydantic import BaseModel<br>from .embeddings import add_document<br>from .rag import rag_answer<br>from .utils import extract_text_from_pdf, chunk_text<br><br>class AskRequest(BaseModel):<br>    question: str<br><br>@post(&quot;/ask&quot;)<br>async def ask(data: AskRequest) -&gt; dict:<br>    answer = rag_answer(data.question)<br>    return {&quot;question&quot;: data.question, &quot;answer&quot;: answer}<br><br>@post(&quot;/upload/pdf&quot;)<br>async def upload_pdf(request: Request) -&gt; dict:<br>    form_data = await request.form()<br>    file = form_data.get(&quot;file&quot;)<br>    if not isinstance(file, UploadFile):<br>        return {&quot;error&quot;: &quot;No file uploaded&quot;}<br>    <br>    # You&#39;ll need a function to save the file first<br>    # For simplicity, let&#39;s assume it&#39;s saved and we have the path<br>    # path = await save_upload(file) <br>    # text = extract_text_from_pdf(path)<br>    <br>    # In a real app, you&#39;d save the file first<br>    content = await file.read()<br>    # This part is simplified; you&#39;d save to a temp file<br>    # and pass the path to extract_text_from_pdf<br>    # For this guide, let&#39;s assume we can process it directly if possible<br>    # text = extract_text_from_pdf(content) # This would need adjustment<br>    <br>    # Simplified for guide: let&#39;s just say we processed it<br>    # In the actual repo, we have a save_upload function<br>    text = &quot;This is a placeholder for extracted PDF text.&quot;<br>    chunks = chunk_text(text)<br>    for chunk in chunks:<br>        add_document(chunk)<br>    return {&quot;status&quot;: &quot;ok&quot;, &quot;chunks_added&quot;: len(chunks)}</pre><p>(<em>Note: The file upload handling is simplified here. In a real application, you would save the uploaded file to a temporary location before processing it</em>.)</p><pre># in src/assistant/asgi.py<br>from litestar import Litestar<br>from .routes import ask, upload_pdf<br><br>app = Litestar(route_handlers=[ask, upload_pdf])</pre><h3>Conclusion</h3><p>And there you have it! You’ve just built the core of a sophisticated, AI-powered document assistant. From here, you can add features like persistent storage, support for more file types, or even a web interface.</p><p>This project demonstrates how powerful modern AI tools are and how you can combine them to create truly useful applications.</p><p>You can find a working example in <a href="https://github.com/codcod/ai-doc-assistant">this Github repository</a>.</p><p><em>Enjoyed this guide? Follow me for more hands-on AI and software development content! #Python #AI #LLM #RAG #Developer #TechGuide</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14239f796260" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>