<?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"><channel><title><![CDATA[Business Edge Analytics Blog]]></title><description><![CDATA[Business Edge Analytics Blog]]></description><link>https://bizedgeanalytics.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 19:37:16 GMT</lastBuildDate><atom:link href="https://bizedgeanalytics.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to Pick Your First AI Automation Project (With a Simple ROI Calculator)]]></title><description><![CDATA[A practical guide for small business owners: find repetitive tasks worth automating, score them, and estimate payback with a short Python script.]]></description><link>https://bizedgeanalytics.hashnode.dev/how-to-pick-your-first-ai-automation-project-with-a-simple-roi-calculator</link><guid isPermaLink="true">https://bizedgeanalytics.hashnode.dev/how-to-pick-your-first-ai-automation-project-with-a-simple-roi-calculator</guid><category><![CDATA[AI]]></category><category><![CDATA[automation]]></category><category><![CDATA[Python]]></category><category><![CDATA[Productivity]]></category><dc:creator><![CDATA[Business Edge Analytics]]></dc:creator><pubDate>Tue, 01 Dec 2026 14:55:26 GMT</pubDate><content:encoded><![CDATA[<p>Everyone tells small business owners to "use AI." Almost nobody tells them where to start.</p>
<p>So the money goes to the flashiest idea. A chatbot nobody asked for. A dashboard nobody opens. Six months later, the team quietly goes back to the old way and AI gets filed under "hype."</p>
<p>There is a better path. Pick one small, boring, repetitive task. Measure it. Automate it. Prove it pays. Then do the next one.</p>
<p>This guide shows you how to find that first project, how to score your options, and how to estimate the return using your own numbers. There is even a short Python script you can run to rank your ideas.</p>
<h2>Why the First Project Matters So Much</h2>
<p>Your first AI project is not really about the technology. It is about trust.</p>
<p>If it works, your team sees proof. They start bringing you ideas. If it flops, every future proposal starts from zero, with people who remember the last one.</p>
<p>That is why the first project should be small enough to finish in weeks, not quarters. It should touch a task people already dislike. And it should produce a result you can count, like hours saved or errors avoided.</p>
<p>Big transformation plans have their place. But they work best after a few quick wins, not before. If you want the bigger picture, our guide to <a href="https://www.businessedgeanalytics.com/blog/ai-strategy-roadmap.html">building an AI strategy roadmap</a> walks through the long view.</p>
<h2>Step 1: List the Tasks Nobody Wants to Do</h2>
<p>Grab a notepad or a spreadsheet. Spend one week writing down every task that makes someone on your team sigh.</p>
<p>Good candidates usually look like this:</p>
<ul>
<li>Copying data from emails or PDFs into another system</li>
<li>Answering the same customer questions again and again</li>
<li>Sorting and routing incoming requests to the right person</li>
<li>Building the same weekly report by hand</li>
<li>Chasing people for missing paperwork or approvals</li>
<li>Checking forms for missing fields before they move forward</li>
</ul>
<p>Ask your team directly. The people doing the work know exactly where the time goes. They will often name things a manager would never notice.</p>
<p>For each task, write down three numbers as best you can:</p>
<ol>
<li><strong>How often it happens</strong> (times per week)</li>
<li><strong>How long it takes</strong> each time (minutes)</li>
<li><strong>Who does it</strong> and roughly what their time costs per hour</li>
</ol>
<p>Estimates are fine. You are looking for the big targets, not accounting precision.</p>
<h2>Step 2: Score Each Task on Four Simple Questions</h2>
<p>Not every annoying task is a good AI project. Some are rare. Some are risky. Some need judgment that only a person should give.</p>
<p>Score each task from 1 to 5 on these four questions:</p>
<p><strong>Volume.</strong> Does it happen often? A task done 50 times a week beats one done twice a month.</p>
<p><strong>Repetition.</strong> Does it follow a pattern? If the steps are mostly the same each time, automation has something to grab onto.</p>
<p><strong>Data access.</strong> Is the input digital and reachable? Emails, PDFs, forms, and spreadsheets are great. Sticky notes and phone calls are harder.</p>
<p><strong>Low risk.</strong> If the automation makes a mistake, is it easy to catch and fix? Drafting a reply that a person reviews is low risk. Sending payments on its own is not.</p>
<p>Add the four scores. The tasks near the top of your list are your best first projects.</p>
<h2>Step 3: Estimate the Return With Your Own Numbers</h2>
<p>Here is the simplest honest ROI math. No industry averages, no borrowed statistics. Just your numbers.</p>
<p><strong>Hours saved per year</strong> = times per week × minutes per task × share of the work automated × 52 ÷ 60</p>
<p><strong>Value of time saved</strong> = hours saved × hourly cost of the person doing it</p>
<p><strong>Payback period</strong> = project cost ÷ (yearly value ÷ 12), shown in months</p>
<p>The "share of the work automated" matters. Very few tasks get automated 100 percent. A realistic first pass might handle the routine cases while people review the tricky ones. Be conservative here. Pick a number you would bet on, not a number you hope for.</p>
<p>Also add yearly running costs, such as software subscriptions or AI usage fees, and subtract them from the value. That keeps the math honest.</p>
<h2>A Small Python Script to Rank Your Ideas</h2>
<p>If you like working in code, this script turns your list into a ranked table. Fill in your own tasks and numbers. Everything below is example data, so replace it.</p>
<pre><code class="language-python">from dataclasses import dataclass

@dataclass
class Task:
    name: str
    per_week: float        # how many times it happens each week
    minutes_each: float    # minutes per occurrence
    hourly_cost: float     # cost of the person's time per hour
    automatable: float     # share you expect to automate, 0.0 to 1.0
    volume: int            # 1 to 5
    repetition: int        # 1 to 5
    data_access: int       # 1 to 5
    low_risk: int          # 1 to 5
    build_cost: float      # one time project cost estimate
    yearly_running: float  # subscriptions, API usage, upkeep

    @property
    def score(self) -&gt; int:
        return self.volume + self.repetition + self.data_access + self.low_risk

    @property
    def hours_saved_per_year(self) -&gt; float:
        return self.per_week * self.minutes_each * self.automatable * 52 / 60

    @property
    def net_yearly_value(self) -&gt; float:
        return self.hours_saved_per_year * self.hourly_cost - self.yearly_running

    @property
    def payback_months(self) -&gt; float | None:
        monthly = self.net_yearly_value / 12
        return None if monthly &lt;= 0 else self.build_cost / monthly


# Example data only. Replace with your own tasks and estimates.
tasks = [
    Task("Key invoice PDFs into accounting", 40, 6, 30, 0.7, 5, 5, 5, 3, 6000, 600),
    Task("Answer repeat customer emails",   60, 4, 25, 0.5, 5, 4, 4, 4, 5000, 900),
    Task("Build weekly sales report",        1, 120, 45, 0.9, 2, 5, 4, 5, 3000, 200),
]

ranked = sorted(tasks, key=lambda t: (t.score, t.net_yearly_value), reverse=True)

print(f"{'Task':38} {'Score':&gt;5} {'Hrs/yr':&gt;7} {'Net $/yr':&gt;9} {'Payback':&gt;8}")
for t in ranked:
    pb = "n/a" if t.payback_months is None else f"{t.payback_months:.1f} mo"
    print(f"{t.name:38} {t.score:&gt;5} {t.hours_saved_per_year:&gt;7.0f} "
          f"{t.net_yearly_value:&gt;9,.0f} {pb:&gt;8}")
</code></pre>
<p>Run it with <code>python rank_tasks.py</code>. You get a table sorted by fit score, with hours saved, net yearly value, and payback in months.</p>
<p>Two things to notice. First, a task that happens once a week can still score well if it is long and easy to automate. Second, a task with high volume but high risk might rank lower than you expect. That is the point. The score keeps you from chasing value that comes with too much danger for a first project.</p>
<h2>Step 4: Pick One and Define "Done"</h2>
<p>Now choose the top task and write a one paragraph project brief. Keep it plain:</p>
<ul>
<li><strong>The task:</strong> what the automation will handle</li>
<li><strong>The boundary:</strong> what it will not handle and when a person steps in</li>
<li><strong>The measure:</strong> how you will know it worked, such as minutes per task before and after</li>
<li><strong>The timeline:</strong> a few weeks to a working pilot</li>
</ul>
<p>Measure the task before you change anything. Time ten examples by hand. Without a baseline, you cannot prove the gain later, and proof is the whole reason for a first project.</p>
<h2>Step 5: Start With a Person in the Loop</h2>
<p>The safest first version suggests, and a person approves.</p>
<p>An email assistant drafts replies, and someone clicks send. A document tool pulls fields from an invoice, and someone glances at them before they post. A routing tool tags the request, and a manager can override it.</p>
<p>This design does three things at once. It catches mistakes early. It gives your team control, which makes them far more willing to use it. And it collects real feedback you can use to improve the system.</p>
<p>Once the error rate is low and steady, you can let routine cases flow through on their own and keep people focused on the exceptions. Our <a href="https://www.businessedgeanalytics.com/services/ai-automation.html">AI workflow automation services</a> follow this same pattern: start supervised, then widen what runs on its own as the results earn it.</p>
<h2>Common Traps to Avoid</h2>
<p><strong>Automating a broken process.</strong> If the current steps are messy, AI will just make the mess faster. Clean up the process first.</p>
<p><strong>Starting with the hardest problem.</strong> Save the complex, judgment heavy work for later. Win the easy ones first.</p>
<p><strong>Skipping the baseline.</strong> No "before" number means no credible "after" number.</p>
<p><strong>Ignoring running costs.</strong> Subscriptions and usage fees add up. Put them in the math from day one.</p>
<p><strong>Building for one person.</strong> If only one employee understands the tool, it breaks when they go on vacation. Document how it works and who owns it.</p>
<h2>What a Good First Project Looks Like</h2>
<p>Put it all together and a strong first project has a clear shape. It handles a frequent, repetitive task. Its inputs are already digital. A person reviews the output at first. It has a measured baseline. And it can reach a working pilot in a few weeks.</p>
<p>Document heavy tasks often fit this shape well. Invoices, intake forms, and applications arrive constantly and follow patterns. If that sounds like your business, take a look at how <a href="https://www.businessedgeanalytics.com/services/intelligent-document-processing.html">intelligent document processing</a> can turn those files into clean, structured data.</p>
<h2>Ready to Find Your First Win?</h2>
<p>You do not need a big AI budget to get started. You need one well chosen task, honest numbers, and a plan to prove the result.</p>
<p>If you would like a second set of eyes on your list, Business Edge Analytics helps small and midsize businesses find, scope, and build practical AI automations. Visit <a href="https://www.businessedgeanalytics.com">businessedgeanalytics.com</a> to start the conversation.</p>
]]></content:encoded></item><item><title><![CDATA[How to Build a RAG Assistant for Your Company Docs in Python]]></title><description><![CDATA[A practical guide for small business owners and developers: turn your policies and FAQs into an AI assistant that answers from your own documents and cites…]]></description><link>https://bizedgeanalytics.hashnode.dev/how-to-build-a-rag-assistant-for-your-company-docs-in-python</link><guid isPermaLink="true">https://bizedgeanalytics.hashnode.dev/how-to-build-a-rag-assistant-for-your-company-docs-in-python</guid><category><![CDATA[AI]]></category><category><![CDATA[Python]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[RAG ]]></category><dc:creator><![CDATA[Business Edge Analytics]]></dc:creator><pubDate>Sun, 15 Nov 2026 14:56:59 GMT</pubDate><content:encoded><![CDATA[<p>Your team already knows the answers. They are just buried.</p>
<p>The refund policy lives in a PDF from two years ago. The onboarding steps sit in a shared drive folder nobody can find. The answer to "do we offer weekend service?" is in an email thread from last spring. So people ask each other, over and over, and the same questions eat the same hours every week.</p>
<p>A RAG assistant fixes that. RAG stands for retrieval augmented generation. In plain words: before the AI answers, it first looks up the right passages in your own documents, then writes an answer based on those passages and tells you where it found them.</p>
<p>This guide walks through building a small, working version in Python. It is aimed at small business owners who want to understand what they are buying, and at the developer on the team who will actually build it.</p>
<h2>Why RAG instead of just asking a chatbot</h2>
<p>A general chatbot knows a lot about the world and nothing about your business. Ask it about your return window and it will either refuse or, worse, guess.</p>
<p>You could paste your whole handbook into every prompt, but that gets slow and expensive fast, and it stops working once your documents outgrow the model's context window.</p>
<p>RAG takes a smarter path:</p>
<ol>
<li>Split your documents into small chunks.</li>
<li>Turn each chunk into an embedding, a list of numbers that captures its meaning.</li>
<li>When a question comes in, find the chunks whose meaning is closest to the question.</li>
<li>Hand only those chunks to the language model and ask it to answer from them.</li>
</ol>
<p>The result is an assistant that answers from your sources, stays current when you update a file, and can show its work with citations.</p>
<h2>What you need</h2>
<p>Keep the first version small. You need:</p>
<ul>
<li>A folder of documents. Start with plain text or Markdown exports of your FAQs, policies, and how to guides.</li>
<li>Python 3.10 or newer.</li>
<li>An embedding model. We will use a free model that runs on your own machine through the <code>sentence-transformers</code> library.</li>
<li>A language model API for the final answer. The example uses the OpenAI Python client, but any provider with a chat API works the same way.</li>
</ul>
<p>Install the pieces:</p>
<pre><code class="language-bash">pip install sentence-transformers numpy openai
</code></pre>
<p>Library APIs change, so pin versions in a <code>requirements.txt</code> once things work.</p>
<h2>Step 1: Load and chunk your documents</h2>
<p>Chunking matters more than most people expect. Chunks that are too big bury the answer in noise. Chunks that are too small lose context. A few hundred words with a little overlap is a sensible starting point.</p>
<pre><code class="language-python">from pathlib import Path

def load_docs(folder: str):
    docs = []
    for path in Path(folder).rglob("*"):
        if path.suffix.lower() in {".txt", ".md"}:
            docs.append({"source": path.name, "text": path.read_text(encoding="utf-8")})
    return docs

def chunk_text(text: str, size: int = 200, overlap: int = 40):
    words = text.split()
    chunks = []
    start = 0
    while start &lt; len(words):
        chunks.append(" ".join(words[start:start + size]))
        start += size - overlap
    return chunks

docs = load_docs("company_docs")
chunks = []
for doc in docs:
    for i, piece in enumerate(chunk_text(doc["text"])):
        chunks.append({"id": f"{doc['source']}#{i}", "source": doc["source"], "text": piece})

print(f"{len(docs)} documents, {len(chunks)} chunks")
</code></pre>
<p>Each chunk keeps its source file name. That is what lets the assistant cite where an answer came from later.</p>
<h2>Step 2: Create embeddings</h2>
<p>Now we turn every chunk into a vector. <code>all-MiniLM-L6-v2</code> is a small, popular model that runs fine on a laptop CPU.</p>
<pre><code class="language-python">import numpy as np
from sentence_transformers import SentenceTransformer

embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")

texts = [c["text"] for c in chunks]
vectors = embedder.encode(texts, normalize_embeddings=True, show_progress_bar=True)
vectors = np.asarray(vectors, dtype="float32")

np.save("vectors.npy", vectors)
</code></pre>
<p>Setting <code>normalize_embeddings=True</code> means a simple dot product gives you cosine similarity, which keeps the search code tiny.</p>
<p>For a few thousand chunks, a NumPy array in memory is all you need. When you grow into tens of thousands of chunks or want filtering by department or date, move to a vector database such as pgvector, Qdrant, or Chroma. The logic stays the same.</p>
<h2>Step 3: Retrieve the best matches</h2>
<p>When a question arrives, embed it with the same model and find the closest chunks.</p>
<pre><code class="language-python">def retrieve(question: str, k: int = 4, min_score: float = 0.3):
    q = embedder.encode([question], normalize_embeddings=True)[0]
    scores = vectors @ q
    best = np.argsort(scores)[::-1][:k]
    return [
        {**chunks[i], "score": float(scores[i])}
        for i in best
        if scores[i] &gt;= min_score
    ]

for hit in retrieve("How long do customers have to request a refund?"):
    print(round(hit["score"], 3), hit["id"])
</code></pre>
<p>That <code>min_score</code> threshold is your first guardrail. If nothing in your documents is a reasonable match, you want the assistant to say so instead of stretching a weak match into an answer. Tune the number by testing real questions against your own files.</p>
<h2>Step 4: Generate a grounded answer</h2>
<p>Here is where the language model comes in. The prompt does three jobs: it supplies the retrieved passages, tells the model to answer only from them, and asks it to cite sources.</p>
<pre><code class="language-python">from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY from the environment

SYSTEM = (
    "You answer questions for our staff using ONLY the provided context. "
    "If the context does not contain the answer, say you could not find it "
    "and suggest who to ask. Cite sources in square brackets, like [refunds.md]."
)

def answer(question: str):
    hits = retrieve(question)
    if not hits:
        return "I could not find that in our documents. Try asking the office manager."

    context = "\n\n".join(f"[{h['source']}]\n{h['text']}" for h in hits)
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0,
        messages=[
            {"role": "system", "content": SYSTEM},
            {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},
        ],
    )
    return response.choices[0].message.content

print(answer("Do we offer weekend service appointments?"))
</code></pre>
<p>Swap the model name for whatever your provider offers. A temperature of zero keeps answers consistent from one run to the next, which is what you want for policy questions.</p>
<p>That is a complete RAG assistant in well under a hundred lines. Wrap <code>answer()</code> in a small web app, a Slack bot, or an internal page and your team can start using it.</p>
<h2>Step 5: Test it like you mean it</h2>
<p>The demo always looks great. The real test is the question nobody planned for.</p>
<p>Before anyone relies on the assistant, build a simple evaluation set:</p>
<ul>
<li>Write down 20 to 30 real questions your team actually asks.</li>
<li>Next to each one, note the correct answer and the document it should come from.</li>
<li>Include a few questions your documents cannot answer, so you can confirm the assistant admits it.</li>
</ul>
<pre><code class="language-python">tests = [
    {"q": "What is our refund window?", "expect_source": "refunds.md"},
    {"q": "Who approves overtime?", "expect_source": "hr_policy.md"},
    {"q": "What is the CEO's favorite color?", "expect_source": None},
]

for t in tests:
    hits = retrieve(t["q"])
    sources = {h["source"] for h in hits}
    if t["expect_source"] is None:
        ok = not hits
    else:
        ok = t["expect_source"] in sources
    print("PASS" if ok else "FAIL", t["q"], sorted(sources))
</code></pre>
<p>This checks retrieval, which is where most RAG problems start. If the right chunk never reaches the model, no prompt can save the answer. Rerun this list every time you change chunk sizes, the embedding model, or the prompt.</p>
<h2>Common mistakes to avoid</h2>
<p><strong>Messy source documents.</strong> Scanned PDFs, tables pasted as images, and five versions of the same policy will confuse any assistant. Clean up and remove outdated files first. If much of your knowledge lives in scanned paperwork, that is a document processing problem to solve before retrieval.</p>
<p><strong>No access control.</strong> If payroll files and customer FAQs sit in the same index, someone will eventually get an answer they should not see. Tag chunks with who may read them and filter at retrieval time.</p>
<p><strong>Treating documents as trusted.</strong> Text inside a document can try to instruct the model. Keep the assistant read only, and never let retrieved text trigger actions on its own.</p>
<p><strong>Skipping the "I don't know" path.</strong> An assistant that admits it cannot find something earns trust. One that confidently invents a policy loses it in a single afternoon.</p>
<p><strong>Never updating the index.</strong> Rebuild embeddings whenever documents change. A nightly job is usually enough for a small team.</p>
<h2>Where this goes next</h2>
<p>Once the basic version is answering well, there are a few natural upgrades:</p>
<ul>
<li><strong>Hybrid search.</strong> Combine embeddings with classic keyword search so exact terms like part numbers and policy codes still match.</li>
<li><strong>Reranking.</strong> Retrieve 20 candidates, then use a cross encoder model to pick the best 4. This often improves answer quality noticeably.</li>
<li><strong>More file types.</strong> Add loaders for PDFs, Word files, and your help desk or wiki.</li>
<li><strong>Agents.</strong> Let the assistant not only answer, but also look up an order status or open a ticket, with a person approving any action.</li>
</ul>
<p>The customer facing version of this pattern is a support assistant on your website. If that is where you are headed, our guide to <a href="https://www.businessedgeanalytics.com/blog/ai-chatbots-customer-service.html">AI chatbots for customer service</a> covers what to plan for before you launch one.</p>
<h2>Build it yourself or bring in help?</h2>
<p>The code above is honest about what RAG is: a search step and a writing step. A capable developer can have a prototype running in a day.</p>
<p>The harder part is everything around it. Cleaning years of documents, connecting to the systems your knowledge actually lives in, setting permissions, and building an evaluation set that reflects how your team really talks. That is where most of the effort, and most of the value, sits.</p>
<p>If you would rather have that handled for you, we build <a href="https://www.businessedgeanalytics.com/services/custom-ai-solutions.html">custom AI solutions</a> like RAG knowledge assistants that plug into the tools you already use. We also work with smaller teams through our <a href="https://www.businessedgeanalytics.com/services/ai-for-small-business.html">AI for small business</a> service, with a written scope and clear acceptance criteria up front.</p>
<h2>Wrapping up</h2>
<p>You do not need a giant platform to give your team instant answers from your own documents. Chunk the files, embed them, retrieve the best matches, and ask the model to answer only from what it found. Then test it with real questions before anyone depends on it.</p>
<p>Start with one folder and one team. Once people stop asking each other the same five questions every week, you will know it is working.</p>
<hr />
<p><em>Want a RAG assistant built around your company's documents and systems? <a href="https://www.businessedgeanalytics.com">Business Edge Analytics</a> designs and builds practical AI for small and mid sized businesses, fully remote from Louisville, KY. Reach out through the site to talk through your use case.</em></p>
]]></content:encoded></item><item><title><![CDATA[Build a Small-Business Invoice Agent with LangChain Deep Agents and MCP]]></title><description><![CDATA[A practical walkthrough: expose your business data through an MCP server, then orchestrate a planner and specialist subagents with LangChain Deep Agents to…]]></description><link>https://bizedgeanalytics.hashnode.dev/build-a-small-business-invoice-agent-with-langchain-deep-agents-and-mcp</link><guid isPermaLink="true">https://bizedgeanalytics.hashnode.dev/build-a-small-business-invoice-agent-with-langchain-deep-agents-and-mcp</guid><category><![CDATA[langchain]]></category><category><![CDATA[mcp]]></category><category><![CDATA[Python]]></category><category><![CDATA[AI]]></category><dc:creator><![CDATA[Business Edge Analytics]]></dc:creator><pubDate>Wed, 04 Nov 2026 03:06:24 GMT</pubDate><content:encoded><![CDATA[<p>Most "AI agent" tutorials stop at a chatbot that calls a weather API. Real small-business work looks different: a stack of PDFs in an inbox, a spreadsheet of vendors, and a person who has to decide what gets paid. In this post we'll build a small but realistic multi-agent system that triages incoming invoices, using two pieces that fit together well:</p>
<ul>
<li><strong>MCP (Model Context Protocol)</strong> to expose business data and actions as tools in a standard way.</li>
<li><strong>LangChain Deep Agents</strong> to plan the work and delegate to specialist subagents.</li>
</ul>
<p>The goal isn't a production system in 1,200 words. It's a clean architecture you can extend. Library APIs move fast, so pin your versions and check the docs for <code>deepagents</code>, <code>langchain-mcp-adapters</code> and <code>mcp</code> before you copy this into anything serious.</p>
<h2>The use case</h2>
<p>A small company receives vendor invoices by email. For each one, someone has to:</p>
<ol>
<li>Pull out the vendor, invoice number, date, line items and total.</li>
<li>Check the vendor is known and the invoice isn't a duplicate.</li>
<li>Flag anything unusual (a new vendor, a total far above that vendor's history).</li>
<li>Write a short summary for the owner to approve.</li>
</ol>
<p>None of this needs a model to "be creative". It needs reliable extraction, a few lookups, and a clear audit trail. That's a good fit for agents with narrow tools.</p>
<h2>Architecture</h2>
<pre><code>            â”Œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”
            â”‚   Orchestrator (Deep     â”‚
            â”‚   Agent: plans + todo)   â”‚
            â””â”€â”€â”€â”€â”€â”¬â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”¬â”€â”€â”€â”€â”€â”€â”€â”€â”˜
                  â”‚           â”‚
        â”Œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â–¼â”€â”€â”   â”Œâ”€â”€â”€â”€â–¼â”€â”€â”€â”€â”€â”€â”€â”€â”€â”
        â”‚ extractor  â”‚   â”‚  reviewer    â”‚
        â”‚ subagent   â”‚   â”‚  subagent    â”‚
        â””â”€â”€â”€â”€â”€â”¬â”€â”€â”€â”€â”€â”€â”˜   â””â”€â”€â”€â”€â”¬â”€â”€â”€â”€â”€â”€â”€â”€â”€â”˜
              â”‚  MCP tools    â”‚
        â”Œâ”€â”€â”€â”€â”€â–¼â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â–¼â”€â”€â”€â”€â”€â”€â”€â”€â”
        â”‚ MCP server: vendors, invoice â”‚
        â”‚ history, file reader         â”‚
        â””â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”˜
</code></pre>
<p>The orchestrator never touches the database directly. Everything goes through MCP tools, which means the same server can later serve a different agent framework, a desktop assistant, or an internal app.</p>
<h2>Step 1: Expose business data with an MCP server</h2>
<p>Install the dependencies:</p>
<pre><code class="language-bash">pip install "mcp[cli]" langchain-mcp-adapters deepagents langchain-openai
</code></pre>
<p>Here's a minimal MCP server using <code>FastMCP</code>. For the demo, the "database" is SQLite.</p>
<pre><code class="language-python"># invoice_server.py
import sqlite3
from pathlib import Path
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("invoices")
DB = Path("business.db")

def q(sql: str, params: tuple = ()):
    with sqlite3.connect(DB) as conn:
        conn.row_factory = sqlite3.Row
        return [dict(r) for r in conn.execute(sql, params).fetchall()]

@mcp.tool()
def read_invoice_text(filename: str) -&gt; str:
    """Return the extracted text of an invoice file in the inbox folder."""
    path = Path("inbox") / Path(filename).name  # prevent path traversal
    return path.read_text()

@mcp.tool()
def lookup_vendor(name: str) -&gt; list[dict]:
    """Find known vendors whose name matches (case-insensitive)."""
    return q("SELECT id, name, payment_terms FROM vendors WHERE name LIKE ?",
             (f"%{name}%",))

@mcp.tool()
def invoice_history(vendor_id: int) -&gt; list[dict]:
    """Past invoices for a vendor: number, date, total."""
    return q("SELECT number, date, total FROM invoices WHERE vendor_id = ? "
             "ORDER BY date DESC LIMIT 24", (vendor_id,))

@mcp.tool()
def is_duplicate(vendor_id: int, invoice_number: str) -&gt; bool:
    """True if this vendor already has an invoice with this number."""
    return bool(q("SELECT 1 FROM invoices WHERE vendor_id = ? AND number = ?",
                  (vendor_id, invoice_number)))

if __name__ == "__main__":
    mcp.run(transport="stdio")
</code></pre>
<p>A few deliberate choices:</p>
<ul>
<li><strong>Read-only tools.</strong> The agent can look things up but cannot pay or approve anything. Approval stays human.</li>
<li><strong>Narrow, well-described tools.</strong> The docstring is what the model sees. Specific beats clever.</li>
<li><strong>Input hygiene.</strong> <code>Path(filename).name</code> stops the model (or a malicious PDF) from reading files outside the inbox.</li>
</ul>
<p>You can poke at it with the MCP inspector: <code>mcp dev invoice_server.py</code>.</p>
<h2>Step 2: Load MCP tools into LangChain</h2>
<p><code>langchain-mcp-adapters</code> turns MCP tools into regular LangChain tools:</p>
<pre><code class="language-python">from langchain_mcp_adapters.client import MultiServerMCPClient

client = MultiServerMCPClient({
    "invoices": {
        "command": "python",
        "args": ["invoice_server.py"],
        "transport": "stdio",
    }
})

tools = await client.get_tools()  # inside an async function
by_name = {t.name: t for t in tools}
</code></pre>
<p>Splitting by name matters. Each subagent should only see the tools it needs.</p>
<h2>Step 3: Define specialist subagents</h2>
<p>Deep Agents gives you a planning tool (a todo list), a virtual file system for scratch notes, and the ability to spawn subagents with their own prompt and toolset. Subagents keep the orchestrator's context clean: the extractor can wade through a messy invoice without dumping all of that text into the main conversation.</p>
<pre><code class="language-python">extractor = {
    "name": "extractor",
    "description": "Reads one invoice file and returns structured JSON.",
    "system_prompt": (
        "You extract invoice data. Call read_invoice_text, then return ONLY JSON "
        "with keys: vendor_name, invoice_number, date (YYYY-MM-DD), "
        "line_items (list of {description, amount}), total. "
        "If a field is missing, use null. Never guess numbers."
    ),
    "tools": [by_name["read_invoice_text"]],
}

reviewer = {
    "name": "reviewer",
    "description": "Checks extracted invoice JSON against vendor records.",
    "system_prompt": (
        "You review invoices. Given extracted JSON: look up the vendor, check for "
        "duplicates, and compare the total to that vendor's history. Report "
        "flags: UNKNOWN_VENDOR, DUPLICATE, TOTAL_MISMATCH (line items don't sum), "
        "UNUSUAL_AMOUNT (well above typical). Explain each flag in one sentence."
    ),
    "tools": [by_name["lookup_vendor"], by_name["invoice_history"],
              by_name["is_duplicate"]],
}
</code></pre>
<p>Note what's <em>not</em> delegated to the model: the definition of each flag. You decide the business rules. The model applies them and explains its reasoning.</p>
<h2>Step 4: The orchestrator</h2>
<pre><code class="language-python">import asyncio
from deepagents import create_deep_agent

ORCHESTRATOR_PROMPT = """You triage vendor invoices for a small business.
For each file you are given:
1. Plan the work with your todo list.
2. Delegate extraction to the `extractor` subagent.
3. Pass its JSON to the `reviewer` subagent.
4. Write a summary per invoice: vendor, number, total, flags, and a
   recommendation of APPROVE or NEEDS_HUMAN_REVIEW.
You never approve payments yourself."""

async def main(files: list[str]):
    agent = create_deep_agent(
        model="openai:gpt-4.1",      # any tool-calling model works
        tools=[],                      # orchestrator delegates everything
        system_prompt=ORCHESTRATOR_PROMPT,
        subagents=[extractor, reviewer],
    )
    result = await agent.ainvoke({
        "messages": [{"role": "user",
                      "content": f"Triage these invoices: {', '.join(files)}"}]
    })
    print(result["messages"][-1].content)

asyncio.run(main(["acme-1043.txt", "newco-0007.txt"]))
</code></pre>
<p>(In real code, create the MCP client and subagent dicts inside <code>main</code> so <code>await client.get_tools()</code> runs in the same event loop.)</p>
<h2>Step 5: Make it trustworthy</h2>
<p>The demo works. Here's what turns it into something a business can actually rely on:</p>
<p><strong>Validate structured output.</strong> Don't trust the extractor's JSON. Parse it with Pydantic and send it back for a retry on failure:</p>
<pre><code class="language-python">from pydantic import BaseModel, model_validator

class LineItem(BaseModel):
    description: str
    amount: float

class Invoice(BaseModel):
    vendor_name: str
    invoice_number: str
    date: str
    line_items: list[LineItem]
    total: float

    @model_validator(mode="after")
    def totals_match(self):
        if abs(sum(i.amount for i in self.line_items) - self.total) &gt; 0.01:
            raise ValueError("line items do not sum to total")
        return self
</code></pre>
<p>Arithmetic checks belong in code, not in a prompt.</p>
<p><strong>Keep a human in the loop.</strong> The agent recommends, a person approves. Deep Agents supports interrupting before sensitive tool calls if you later add write tools like <code>mark_approved</code>.</p>
<p><strong>Log everything.</strong> Store every tool call and result. When the owner asks "why was this flagged?", you can show them.</p>
<p><strong>Evaluate with real samples.</strong> Gather 20â€“30 anonymized past invoices with known correct answers, and re-run them every time you change a prompt or model. That's your regression suite.</p>
<p><strong>Treat documents as untrusted input.</strong> An invoice can contain text like "ignore previous instructions". Read-only tools and narrow subagent permissions limit what a prompt injection can do.</p>
<h2>Why this pattern generalizes</h2>
<p>Swap "invoices" for insurance claims intake, real estate transaction documents, or permit applications, and the shape is the same: an MCP server wrapping your systems, an extractor, a reviewer that applies your rules, and an orchestrator that writes a decision-ready summary. That's the core of most <a href="https://www.businessedgeanalytics.com/services/intelligent-document-processing.html">intelligent document processing</a> work. The hard parts are the business rules and the evaluation set, not the framework.</p>
<p>If you're deciding whether to build something like this or buy a SaaS tool, I wrote a longer comparison of <a href="https://www.businessedgeanalytics.com/blog/custom-ai-vs-off-the-shelf.html">custom AI vs. off-the-shelf solutions</a>. For more workflow ideas beyond invoices, see <a href="https://www.businessedgeanalytics.com/blog/ai-workflow-automations.html">5 AI workflow automations every business needs</a>.</p>
<hr />
<p><em>Jimmy Hernandez is a senior AI engineer and founder of <a href="https://www.businessedgeanalytics.com">Business Edge Analytics</a>, a Louisville, KY firm that builds multi-agent systems, RAG assistants and document automation for businesses and public-sector teams. He works with LangChain Deep Agents, MCP and Python, and has a background in insurance and real estate.</em></p>
]]></content:encoded></item></channel></rss>