<?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 Simona Barankova on Medium]]></title>
        <description><![CDATA[Stories by Simona Barankova on Medium]]></description>
        <link>https://medium.com/@milieere?source=rss-7cecf8828340------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*t1Dfi89rcvOOYs8BehRoZA.jpeg</url>
            <title>Stories by Simona Barankova on Medium</title>
            <link>https://medium.com/@milieere?source=rss-7cecf8828340------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:28:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@milieere/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[Cheaper, and It Finally Counts Right: Two MCP Techniques for Agents at Scale]]></title>
            <link>https://levelup.gitconnected.com/cheaper-and-it-finally-counts-right-two-mcp-techniques-for-agents-at-scale-94f874b7fc9e?source=rss-7cecf8828340------2</link>
            <guid isPermaLink="false">https://medium.com/p/94f874b7fc9e</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Simona Barankova]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 16:15:43 GMT</pubDate>
            <atom:updated>2026-08-26T16:15:43.366Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4hyVZ3h9oxOmhGwJhfA9A.png" /></figure><p>Two MCP optimization techniques — field selection and code execution, tested on a real inventory agent. Both cut cost, but not in the same regime — and one of them also fixes a wrong answer. This article will walk you through what each does, and when to reach for which.</p><h3>The $0.22 wrong answer</h3><p>I asked an agent how many of 50 products were missing a description. It answered 20. The truth was 17 — and it cost $0.22 to get that wrong answer to a question a for loop gets right for free, if only the agent were allowed to write one.</p><p>The agent’s job is inventory hygiene: a merchandiser ticks a selection of products — a dozen, a few hundred — and asks it to audit them. Which are missing descriptions? How many lack tags? Draft the blank ones. It works that selection through a few MCP tools over the catalog — read, search, update.</p><p>That’s where the cost hides. To answer the description question, the agent called the read tool — which returned the whole raw record, spec sheets and image URLs and all, straight into context. ~84,000 tokens to look at one field.</p><p>And you don’t pay for that once. Language models are stateless: every turn resends the entire conversation, so the fat result rides along and is re-billed on every turn after.</p><p>That’s the heavy tax — not the tools you load, but the results passing through the model. (Anthropic’s team names both — <a href="https://www.anthropic.com/engineering/code-execution-with-mcp">Code execution with MCP</a>.)</p><p>Two techniques cut it:</p><ul><li>Field selection — the read tool returns only the fields you ask for.</li><li>Code execution — the agent writes a program that reads the records and returns only the answer. They never enter context.</li></ul><p>They are not interchangeable, and tackle the same problem from different ends.</p><h3>The two techniques</h3><p>Field selection — select only the parameter(s) on the read tool that you actually need:</p><pre>// Before: every field, every time.<br>get_products({ ids })                           // ~1,667 tokens/product<br><br>// After: the caller says what it needs.<br>get_products({ ids, fields: [&quot;description&quot;] })  // ~44 tokens/product</pre><p>Code execution — the agent writes this run_code program; it runs outside the conversation:</p><pre>const products = await get_products({ ids: selection, fields: [&quot;description&quot;] });<br>const missing = products.filter(p =&gt; !p.description);<br>return { total: products.length, missing: missing.length };<br>// only this line comes back into context</pre><p>Field selection shrinks what each record weighs. Code execution keeps the records out of the model entirely.</p><p>I tested this with two different versions of the same agent (same underlying model) — one calling the catalog tools directly, one with only run_code. Same questions, same 50-product selection, seeded with a known field mix, so “17 missing a description” is ground truth. Every answer checked against the database, never against the agent’s own report. Costs from the tracing platform by run tag. (GPT-5.4 authoring, Claude Sonnet 4.6 judging, prompt caching on, local server. Counts one run each, sets three.)</p><h3>Field selection: the cheap payload lever</h3><p>The easy win first. Same set, same scoring — every question run twice: once returning the full record, once narrowed to the fields asked for.</p><p>Here’s what “the full record” means. The agent asked one thing — does this product have a description? — and the read tool handed back all of this:</p><pre>// Full record - what the read tool returned by default<br>{<br>  &quot;id&quot;: &quot;prod_8842&quot;,<br>  &quot;title&quot;: &quot;Merino Wool Runner&quot;,<br>  &quot;description&quot;: null,                    // the only field the question was about<br>  &quot;price&quot;: 89.00,<br>  &quot;category&quot;: [&quot;footwear&quot;, &quot;mens&quot;],<br>  &quot;images&quot;: [<br>    { &quot;url&quot;: &quot;https://cdn.store.com/p/8842/hero.jpg?sig=a8f3...e1&quot;, &quot;w&quot;: 2400, &quot;h&quot;: 1600 },<br>    { &quot;url&quot;: &quot;https://cdn.store.com/p/8842/alt1.jpg?sig=91bc...77&quot;, &quot;w&quot;: 2400, &quot;h&quot;: 1600 },<br>    { &quot;url&quot;: &quot;https://cdn.store.com/p/8842/alt2.jpg?sig=42de...0a&quot;, &quot;w&quot;: 2400, &quot;h&quot;: 1600 }<br>  ],<br>  &quot;downloadUrl&quot;: &quot;https://cdn.store.com/dl/8842.zip?sig=f7...c2&amp;exp=1730&quot;,<br>  &quot;supplier&quot;: { &quot;id&quot;: &quot;sup_31&quot;, &quot;name&quot;: &quot;...&quot;, &quot;contact&quot;: &quot;...&quot;, &quot;leadTimeDays&quot;: 14 },<br>  &quot;inventory&quot;: { &quot;warehouse_a&quot;: 120, &quot;warehouse_b&quot;: 0, &quot;reserved&quot;: 8 },<br>  &quot;audit&quot;: { &quot;createdAt&quot;: &quot;...&quot;, &quot;modifiedAt&quot;: &quot;...&quot;, &quot;createdBy&quot;: &quot;...&quot;, &quot;modifiedBy&quot;: &quot;...&quot; },<br>  &quot;seo&quot;: { &quot;slug&quot;: &quot;...&quot;, &quot;metaTitle&quot;: &quot;...&quot;, &quot;metaDescription&quot;: &quot;...&quot; }<br>  // ...plus rights, workflow, variants<br>}</pre><p>Field selection returns only what was asked:</p><pre>// get_products({ ids, fields: [&quot;description&quot;] })<br>{ &quot;id&quot;: &quot;prod_8842&quot;, &quot;description&quot;: null }</pre><p>Same answer to the same question — a fraction of the payload. Across the run:</p><p><strong>Payload per record</strong>: ~1,667 tokens full → ~44 narrowed — the narrow read is just 2.6% of the full one<br><strong>Cost per question</strong>: $0.217 full → $0.019 narrowed — 11.5× cheaper</p><p><strong>The message</strong>: 97% of the full record was fields nothing asked for — most of it those image and download URLs, which are long, high-entropy, and tokenize badly.</p><p><strong>One thing to remember</strong>: an empty fields parameter that returns ids only turns a forgotten parameter into a wrong answer. Ask “which products are missing a description?”, get ids only, and it reads as “all of them.” Default to a useful minimum, never empty.</p><p>Field selection is a payload lever: it makes reads cheaper and does nothing for accuracy. To fix the answer, you have to move the work — not just trim the data. That’s next.</p><h3>Code execution: the result that cuts both ways</h3><p>Field selection made reads cheaper. It did nothing for the wrong answer. Code execution is where that gets fixed — clearest when you ask the same question two ways.</p><p>Same set, same scoring. First, counting the items that match a predicate:</p><pre>Counts                     truth   run_code   plain<br>Missing a description       17       17         16<br>No category tags            37       37         38<br>Description, no alt text    29       29         31</pre><p>Wrong every time — not by much, but wrong, and differently wrong on an earlier version of the server. Now the same questions, asking for the list:</p><pre>Sets - &quot;which ones?&quot;       truth   run_code   plain<br>Missing a description       17        17       17<br>No category tags            37        37       37</pre><p>Both perfect. Only “how many” became “which ones” — and the plain agent went from reliably wrong to reliably right.</p><p>One way to picture it:</p><ul><li><strong>Ask for the list</strong> → it gets it right. Enumerating the ids forces a walk through the records; the count falls out of the walk. This is a real prompt fix — “list them, don’t count them” works today, no code required.</li><li><strong>Ask for the number</strong> → it guesses. With nothing to enumerate, the model emits a plausible figure. Off by one or two here — worse at scale.</li></ul><p>Enumeration is exactly what scales badly. Listing 17 ids is cheap; listing 100+ is slow, token-heavy, and eventually the model stops complying and estimates anyway.</p><p>Code execution sidesteps it:</p><pre>const products = await get_products({ ids: selection, fields: [&quot;description&quot;] });<br>return { missing: products.filter(p =&gt; !p.description).length };</pre><p>The count isn’t generated, it’s computed. .filter().length returns 17 because 17 is the answer. Provably right.</p><p>One caveat, paid off next: at 50 records, code execution is the worse deal — slower, pricier, and its one edge (a correct count) is something a well-prompted plain agent gets for free by enumerating. So why pay for a sandbox at all? Because enumeration is exactly what stops working as the scale grows.</p><h3>Scale is the axis that decides</h3><p>Everything so far was 50 products. At that size, the plain agent with field selection wins.</p><p>On the same set questions, correctness ties — but now the third axis shows up: latency. The plain agent runs at half the cost and answers in ~8s to run_code’s ~18s (six runs per arm). Over 50 records, writing a program to do the job is pure overhead.</p><p>Then you scale. 218 products, how many exceed the threshold? Truth: 119.</p><pre>218 products     answer          cost     latency<br>run_code         119 (correct)   $0.059   40s<br>plain agent      164 (+38%)      $0.112   17s</pre><p>The plain agent kept its speed edge — 17s to run_code’s 40s — and lost everything else. It cost 2× more and answered 164 against a truth of 119, wrong by 45.</p><p>Cost flipped because run_code’s input barely grows — records go to the sandbox, not the context — while the plain agent drags every product through the model. The crossover sits somewhere above 50 for this shape of data.</p><p>Correctness flipped harder. The plain agent answered 164–75% of the pile, where the truth was 55%. It didn’t miscount. It stopped counting and eyeballed a proportion. That’s nowhere-to-live at scale: a number with nowhere to live becomes a guess, and the guess grows with the pile.</p><h3>They overlap — they don’t stack</h3><p>The obvious move is to run both. I did, and measured all four combinations:</p><pre>Cost per question   field selection ON   field selection OFF<br>plain agent         $0.019               $0.217   x11.5<br>run_code            $0.016               $0.019   x1.19</pre><p>Read the columns. For a plain agent, field selection is the whole game — ×11.5. For a code-execution agent, a rounding error — ×1.19. Once records go to the sandbox instead of the context, trimming them saves tokens you were never going to spend.</p><p>So the two don’t compound. They attack the same waste from opposite ends — data flowing through the model — and whichever you add second finds little left to fix.</p><p>That settles the order: ship field selection first, always. A day of work, it helps every caller of your server — including the ones you don’t control — and it’s what lets you measure code execution honestly in the first place.</p><h3>The decision</h3><ul><li><strong>Field selection</strong>: always. There’s no size and no architecture where returning fields nobody asked for is correct.</li><li><strong>Small selection (dozens)</strong>: stay in-context — but make it enumerate. Ask for the list, not the count.</li><li><strong>Large selection (hundreds+)</strong>: move to code. The plain agent’s payload grows with every record; run_code’s barely moves.</li><li><strong>Aggregate answer — count, sum, threshold</strong>: code, at any size. Cheap-and-wrong is still wrong.</li><li><strong>Set answer — “which ones”</strong>: in-context is fine for a small selection. Enumerating is what keeps the list exact.</li></ul><p>Code execution’s cost of admission, so nobody’s surprised: a sandbox you now own, more latency, and an agent that has to write and debug code. It moves cost rather than deleting it — an unbatched map() over 2,000 records is 2,000 backend queries, so past a few hundred your ceiling becomes rate limits and bulk-read paths, not tokens. It’s an investment.</p><h3>Summary</h3><p>Two techniques, one problem: <strong>too much data flowing through the model</strong>.</p><p>Field selection trims what each record weighs. Cheap, helps every caller, never wrong. Ship it always.</p><p>Code execution keeps the records out of the model entirely. It buys exactness on mechanical work and flat cost at scale — at the price of a sandbox and latency. Reach for it when the data is big or the answer is an aggregate that needs to be right.</p><p><em>Thank you for reading!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94f874b7fc9e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/cheaper-and-it-finally-counts-right-two-mcp-techniques-for-agents-at-scale-94f874b7fc9e">Cheaper, and It Finally Counts Right: Two MCP Techniques for Agents at Scale</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Five simple habits that help me be an effective engineer in the AI Era]]></title>
            <link>https://levelup.gitconnected.com/five-simple-habits-that-help-me-be-an-effective-engineer-in-the-ai-era-51205deeacac?source=rss-7cecf8828340------2</link>
            <guid isPermaLink="false">https://medium.com/p/51205deeacac</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Simona Barankova]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 16:35:44 GMT</pubDate>
            <atom:updated>2026-07-15T16:35:44.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xt9i-rmdoYl31EwPwB--aw.png" /></figure><p>I am an AI engineer. I build products that contain AI, with the help of AI. This means that most of my day I work together with coding agents.</p><p>The tooling around this changes real quick, and there is a lot of advice telling you to adopt every new thing immediately. But when I look honestly at what keeps me effective, the list is, well, rather boring. In this article I want to share the five habits that I practice daily, that keep me laser-focused at what I do.</p><h3>1. Curate your context — Document, document, document</h3><p>This is the single most important thing that keeps me effective, so I’m putting it first.</p><p>I capture decisions as they happen — as reusable pieces of context that I can point my agents to, and then discuss with them. I record and transcribe my calls, so the decisions made during a call become a context I can easily reference, instead of disappearing the moment the call ends.</p><p>For any technical topic I maintain 2 levels of documentation granularity — <strong>architecture decisions</strong> (ADRs) — for bigger topics, and<strong> technical decisions log </strong>for more granular ones. I take care in structuring those docs — I actually read them, and I iterate on them with the assistant — so the quality stays high as more of my work builds on top of them. This means anytime I start a new feature implementation I can point to the relevant piece of context. <strong><em>Tip</em></strong><em>: Keep those documents as brief and structured as possible.</em></p><p>This is a real leverage point — documenting things used to be a huge overhead. With AI it is so easy that it can be almost automated, so why not use it to the full potential? For me it is a habit that compounds: every decision I capture makes the next agent session sharper, since the agent is grounded from the beginning.</p><h3>2. Manage your session context efficiently</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-Q9djI5h52ygtwxQUVOFw.png" /></figure><p>This one is about how you manage the context window while you work. A lot of my daily leverage comes from here, and it took me a while to become deliberate about it.</p><p>A few techniques that help me:</p><p><strong>Watch your context usage and hand off sessions.</strong> In Claude Code I use /context to see how much of the window I am using and what takes up the space, so I can react before it gets bloated. My rule of thumb here is that when context is full by more than 60%, the quality tends to deteriorate — at this point, I like to handoff the task to a clean session.</p><p><strong>Hand off before a thread branches too much.</strong> When a working session starts to branch out — an idea appears that deserves its own thread — I ask the agent to write a handoff for that branch, together with a starter prompt for a clean session that points to that handoff. Claude Code comes with an out-of-the-box handoff skill that helps with this. The copy-paste starter prompt makes picking up the new session effortless.</p><p><strong>Store your context in a durable storage that survives restarts.</strong> As mentioned in point 1., I keep my curated pieces of context in the documentation system (Slite), so they survive my PC restarts and my session churn, and I can link them easily when I start a new agent session. Of course, this can be directly in the repo or simply on your filesystem.</p><p><strong>Keep your global </strong><strong>CLAUDE.md minimal.</strong> Mine is rather minimalistic — I follow the <a href="https://www.aibuilderclub.com/blog/karpathy-claude-md-rules">Karpathy-inspired 4 rules</a>. Everything repo-specific lives where it belongs: coding conventions and architecture notes go into the CLAUDE.md and architecture.md of the repo itself, not into the global config.</p><h3>3. Prototyping fast and reviewing the code that goes to production</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3aQ6cL9w_5n-m2zp9kLhgw.png" /></figure><p>AI commoditized writing code. Validating ideas quickly has become a breeze with coding assistants.</p><p>I make use of this all the time — I prototype early, and validate the core of the idea on a scrappy vibe coded build. If the idea stood up well, I follow through with production-grade development — using coding agents, but following an engaged process where I stay in touch with what the agent produces. I still want to <strong><em>know</em></strong> what I put into production.</p><p>The code review itself is a part of a multi-step process. First, and most importantly, I iterate on a <strong>plan</strong> for a feature (this can itself take a significant amount of time to clarify all important considerations and not letting the agent falsely assume things), and then I ask the agent to break it down into <strong>small pieces</strong> that are independently reviewable by a human. Each piece stands on its own, as a contained, separate PR, so I can actually read it, understand it, and be confident about what I merge.</p><p>There’s a lot of hype around letting the agent run and shipping whatever comes out, arguing that if you have good guardrails in place, this will come for free. This is fair, and for some tasks it is fine. But I still like to review my code that ends up in production and is directly tied to customer trust.</p><h3>4. Limiting work in progress</h3><p>There is a lot of excitement about orchestrating many agents in parallel — running many tasks at once, using git worktrees to deliver features to a single repo at the same time, becoming a one-person team. I tried to lean into this, and it does not work for me.</p><p>When I have too many distinct tasks at the same time, my attention gets diluted and the quality of each of them drops. I simply cannot keep enough of each problem in my head to make good decisions. So I keep my work in progress to a few distinct tasks maximum, and I protect this limit.</p><p>The bottleneck is still my attention, and more agents in parallel does not remove this bottleneck — it only strains it.</p><h3>5. Keeping the toolset contained</h3><p>I do not install everything everywhere. I keep a small set of skills and connectors that I actually use, and I add more only when there’s a need for it.</p><p>For connectors and MCP servers, the ones I keep are the ones I use all the time: our ticketing and documentation systems. That is more or less it. Every additional server you load is more surface and more clutter in the context window.</p><p>The same goes for skills — I keep a curated set of engineering skills that I trust, are tested, and perform well. For example, I really like the famous <a href="https://github.com/mattpocock/skills">Skills for Real Engineers</a> from Matt Pocock (which are, by the way, super simple), especially <strong><em>grill-with-docs</em></strong> that forces you to think about architecture decisions in detail.</p><h3>Wrapping up</h3><p>So, these are the five habits that keep me effective in my daily work. Most of them are not fancy, and a few of them go off the hype. But that’s sort of the point: the tools will keep changing, but these habits are what let me keep up.</p><blockquote>Thank you for reading!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51205deeacac" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/five-simple-habits-that-help-me-be-an-effective-engineer-in-the-ai-era-51205deeacac">Five simple habits that help me be an effective engineer in the AI Era</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Writing Code That Already Exists: Teach Claude Code About Your Codebase with RAG and MCP…]]></title>
            <link>https://levelup.gitconnected.com/stop-writing-code-that-already-exists-teach-claude-code-about-your-codebase-with-rag-and-mcp-baeb64824e71?source=rss-7cecf8828340------2</link>
            <guid isPermaLink="false">https://medium.com/p/baeb64824e71</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Simona Barankova]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 07:31:01 GMT</pubDate>
            <atom:updated>2026-02-23T16:53:58.958Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Writing Code That Already Exists: Teach Claude Code About Your Codebase with RAG and MCP (CodeRAG)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UaUXdW6_svq2Jsd0Y02nUA.png" /></figure><p>You’re adding a feature. Maybe a date formatting utility, a retry wrapper, or a validation helper. Claude Code happily writes it from scratch — clean code, works great.</p><p>Except your team already built this six months ago in a shared library. Now you have two implementations to maintain, and the pattern fragmentation you were trying to avoid just got worse.</p><p>Claude Code is good at searching within your working directory. But grep and file search only work when you already know what you’re looking for. If you don’t know the class name, the file location, or even which repo to check — you get nothing.</p><p>The challenge grows when your codebase spans multiple projects. You can’t just point Claude Code at everything and hope for the best.</p><p>Here comes the power of semantic search: instead of “find files containing RetryHandler,&quot; you want to ask &quot;do we have anything that handles retries with exponential backoff?&quot; and get relevant hits across your entire codebase.</p><p>I wanted to see if this was actually feasible. So I built a small proof-of-concept: <strong>an MCP server that gives Claude Code semantic search over internal Python projects</strong>. Here’s how it works.</p><h3>The Solution Overview</h3><blockquote>The <a href="https://github.com/milieere/coderag/">CodeRAG GitHub Repo</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcg6pOss4hhgwdPYseby1A.png" /><figcaption>The components of the solution</figcaption></figure><h4>The Architecture</h4><p>The solution consists of two main high-level components. The doc generation &amp; indexing, and the retrieval.</p><ul><li><strong>Doc Generation &amp; Indexing:</strong> CLI → doc_generator → indexer → LanceDB <em>(triggered by CI/CD or manual)</em></li><li><strong>Retrieval: </strong>Claude Code → mcp_server → LanceDB <em>(triggered by developer queries)</em></li></ul><h4>Doc Generation &amp; Indexing</h4><p>The pipeline runs in three stages:</p><ul><li><strong>Documentation Generation </strong>— Parse Python source files and generate comprehensive documentation using LLM</li><li><strong>Chunking &amp; Enrichment </strong>— Split documentation into semantic chunks and add contextual prefixes for better retrieval</li><li><strong>Indexing</strong> — Generate embeddings for chunks and store in LanceDB vector database</li></ul><p>Supports two modes:</p><ul><li><strong>Full</strong> — Regenerate all documentation and replace existing index</li><li><strong>Incremental</strong> — Process only changed files (detected via git diff), reuse existing topics</li></ul><h4><strong>Retrieval</strong></h4><p>Claude Code queries the index through four MCP tools:</p><ul><li><strong>discover_projects</strong> — Find projects matching a problem description</li><li><strong>search_project_docs</strong> — Search within a specific project for implementation details</li><li><strong>list_projects / get_project_overview</strong> — Browse available projects</li></ul><p>The typical flow is discovery first (which projects might help?), then targeted search within the relevant one.</p><h3>Usage Patterns</h3><ul><li>The final product of the pipeline is the MCP exposing retrieval capabilities over your indexed projects</li></ul><h4>Integration with Claude Code Agents</h4><p>The MCP tools work on their own, but raw tools require developers to know when and how to call them. So I built a custom <a href="https://github.com/milieere/coderag/blob/main/claude_agents/implement-feature.md">Claude Code subagent</a> that orchestrates the workflow. The implement-feature agent is instructed to take user’s instructions that contain the feature description, use the CodeRAG MCP to look for useful internal tooling (“Discovery”), and then use the discovered relevant projects documentation to actually write the code.</p><pre>&gt; /implement-feature async retry wrapper for external API calls</pre><pre>Searching for relevant projects...<br>Found: retry-utils (0.89 relevance) - retry decorators with exponential backoff</pre><pre>Here&#39;s the implementation using retry-utils:</pre><pre>from myorg.retry_utils import with_retry, ExponentialBackoff</pre><pre>@with_retry(strategy=ExponentialBackoff(max_attempts=3))<br>async def call_external_api(endpoint: str) -&gt; dict:<br>    ...</pre><p>One can get really creative with the agents definitions here, and use those to steer your workflow in specific ways. Another example would be an agent that will use the MCP to review existing code against existing patterns from internal projects/libraries.</p><h4>Instructions in global CLAUDE.md</h4><p>To embed this solution by default to your workflow, you could modify the global ~/.claude/CLAUDE.md prompt to instruct Claude Code to always check first if projects that solve the issue already exist in your codebase.</p><p>Example prompt:</p><pre> ## Internal Tooling Discovery                                                                                                                                                                                                                                 <br>                                                                                                                                                                                                                                                                <br>  Before implementing new functionality, ALWAYS check if an internal tooling already exists:                                                                                                                                                                    <br>                                                                                                                                                                                                                                                                <br>  1. **Discovery Phase**: Use the `discover_projects` coderag MCP tool with a description of what you need                                                                                                                                                              <br>     - Example: `discover_projects(&quot;retry logic for API calls&quot;)`                                                                                                                                                                                                <br>     - Review results with high relevance                                                                                                                                                                                                                   <br>                                                                                                                                                                                                                                                                <br>  2. **If a relevant project is found**: Use `search_project_docs` to get implementation details                                                                                                                                                                <br>     - Search for specific patterns: decorators, configuration, error handling                                                                                                                                                                                  <br>     - Follow the project&#39;s/library conventions and import paths exactly                                                                                                                                                                                                <br>                                                                                                                                                                                                                                                                <br>  3. **Only implement from scratch** if no relevant internal projects/libs exist                                                                                                                                                                                    <br>                                                                                                                                                                                                                                                                <br>  This applies to common patterns like:                                                                                                                                                                                                                         <br>  - Retry/backoff logic → check for retry utilities                                                                                                                                                                                                             <br>  - Configuration loading → check for config libraries                                                                                                                                                                                                          <br>  - Caching → check for cache utilities                                                                                                                                                                                                                         <br>  - HTTP clients → check for shared client wrappers                                                                                                                                                                                                             <br>  - Logging/observability → check for instrumentation libraries                                                                                                                                                                                                 <br>                                                                                                                                                                                                                                                                <br>  When using internal code, always show the user which project you found and why it&#39;s relevant before writing code. </pre><h3>RAG pipeline details</h3><p>This section explains the main techniques used in the RAG pipeline. Key parameters (chunk limits, relevance threshold) can be tuned via environment variables.</p><h4>Code analysis and Documentation Generation</h4><p>Python files from the repository are collected and their full source code is passed to an LLM. In a single call, the LLM generates:</p><ul><li><strong>Detailed documentation</strong> — class/function reference with usage examples</li><li><strong>Topic tags </strong>— high-level categories for filtering — useful for large indexes and additional pre-filtering (e.g., “caching”, “retry”, “validation”)</li><li><strong>Project summary</strong> — a 2–3 paragraph overview optimised for discovery (“what problem does this solve?”)</li></ul><h4>Chunking and Context addition</h4><p>Raw chunks lack context. A chunk saying “Returns a User object with profile data” is useless without knowing which class, in which project.</p><p>I implemented contextual prefixes based on <a href="https://www.anthropic.com/engineering/contextual-retrieval">Anthropic’s contextual retrieval</a> technique. Before embedding, each chunk gets a short LLM-generated prefix that situates it:</p><pre>Original: &quot;Returns a User object with profile data loaded from cache...&quot;<br>Enriched: &quot;This is from the UserService class in the auth-utils project, <br>which handles user authentication and session management. <br>Returns a User object with profile data loaded from cache...&quot;</pre><p>The embedding uses the enriched content, improving retrieval relevance without changing what’s displayed to the developer.</p><h4>Two Stage Retrieval</h4><p>The retrieval is split into two phases:</p><ul><li><strong>Discovery</strong> — “Do we have something for this?” Searches project summaries only.</li><li><strong>Guidance</strong> — “How do I use it?” Searches detailed chunks within a chosen project.</li></ul><p>This narrows down results: first find the right projects, then get implementation details.</p><h4>Retrieval defaults</h4><p>By default, the tool returns at most 5 projects for discovery, and 15 chunks for library search. The relevance cutoff is 0.0 (disabled — returns all results up to the limit). These can be tuned via environment variables based on your project size and retrieval quality needs:</p><pre># Retrieval defaults<br>MCP_DEFAULT_DISCOVERY_LIMIT=10                                                           <br>MCP_DEFAULT_SEARCH_LIMIT=20                                                                  <br>MCP_DEFAULT_MIN_RELEVANCE=0.0</pre><h3>Try It Yourself</h3><ul><li>I’ve prepared a small demo with 3 made-up libraries as a part of the coderag project. You can run the demo and try it yourself, or you can skip the demo and try with your own codebase directly.</li></ul><h4><strong>Prerequisites</strong></h4><ul><li>Python 3.11+</li><li><a href="https://docs.astral.sh/uv/">https://docs.astral.sh/uv/</a> package manager</li><li>OpenAI API key or Anthropic API key</li><li><a href="https://claude.ai/download">https://claude.ai/download</a> CLI installed</li></ul><p><strong>Clone and Install</strong></p><pre>git clone https://github.com/yourusername/coderag.git <br>cd coderag <br>uv sync</pre><p><strong>Configure API Keys</strong></p><pre>cp .env.example .env <br># Edit .env and add your API key: <br># OPENAI_API_KEY=sk-…</pre><h4>Run for repo of your choice</h4><p>To run the indexing for repo of your choice, you can point it to a git or local repo, for example:</p><pre>uv run coderag generate --project-name databricks-sqlalchemy-oauth --git-url https://github.com/milieere/databricks-sqlalchemy-oauth --output-dir ./local_dev/raw_data/databrics-sqlalchemy-oauth</pre><p>The output-dir flag ensures also raw JSON files with chunks are going to be saved so that you can explore them (chunks.json and documentation.md)</p><h4>Run the demo</h4><p>Run the following command to index a small demo library (retry-utils) that is part of the coderag project:</p><pre>uv run coderag quickstart</pre><p>You should see the logs that the demo libraries are being indexed, and then instructions to follow through with testing Claude Code queries. Follow the instructions to configure the MCP for your Claude Code:</p><pre>uv run coderag mcp install --lancedb-path /&lt;YOUR_PATH&gt;/coderag/quickstart_output/lancedb</pre><p><strong>Test Claude Code queries</strong></p><p>Verify that the coderag mcp is connected via the <strong><em>/mcp</em></strong> command in Claude Code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*WK8XmerU7jrr0IgKDDXc7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*zSzd7WGxhfitiB5yFD9J7A.png" /></figure><p>Try the following query to see Claude Code implementing a feature using the indexed demo library:</p><pre>Implement a simple HTTP API client wrapping endpoint retry logic with exponential backoff to a simple API client - use coderag MCP</pre><p>Watch as Claude: <br> 1. Discovers demo-retry-utils from your indexed libraries <br> 2. Retrieves implementation patterns <br> 3. Writes working code with correct imports</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlpWQ15Euhw-rSiyG_LxqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*053pHoJFy3qwtpuNca3zQw.png" /></figure><p><strong>Cleanup</strong> <br> <br> When you’re done experimenting:</p><pre>uv run coderag quickstart-cleanup --remove-files</pre><h3>Limitations &amp; Pitfalls</h3><p>This project is a PoC that covers ideas for context engineering for Claude Code. It hasn’t been tested under real-world, production conditions. Potential limitations might be:</p><ul><li><strong>The retrieval accuracy. </strong>To make sure it works well, proper benchmarks should be developed and evaluated.</li><li><strong>Keeping things in sync after changes. </strong>Codebases evolve rapidly.<strong> </strong>The tool presented supports incremental updates, that partially solve this issue and make even-driven updates to the index possible via the CI. Alternative approach would be periodical full re-indexing on schedule.</li><li><strong>Quality of the LLM-produced documentation.</strong> Again, this wasn’t extensively tested and in order to produce the best results, quality benchamrks and evaluations should be developed. This would enable for prompt improvements to achieve higher quality.</li><li><strong>Limited scope to Python.</strong> This example only supports Python projects analysis, which is sufficient for demonstration of the ideas, but in real-world organizations codebases can often be in multiple languages.</li><li><strong>Documentation for large repos.</strong> This can be an issue since this tool uses single LLM call for doc generation. If very large projects, this could become problematic and approach would need to be adapted to some sort of batch documentation generation with its own set of challenges.</li></ul><h3>Summary</h3><ul><li>This article explores a RAG-based approach to context enhancement for coding agents.</li><li>The idea behind it is to address the painpoint of agentic coding, when re-inventing the wheel happens often and codebases grow unnecessarily, resulting in sprawl of slightly different implementations serving the same purpose, violating the DRY principle.</li><li>It provides functional tool to start experimenting with and optimize it to your needs.</li></ul><blockquote>Thank you so much for reading. If you’d have any ideas or questions, let me know in the comments or connect with me on <a href="https://www.linkedin.com/in/sbarankova/">LinkedIn</a> ;)</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baeb64824e71" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/stop-writing-code-that-already-exists-teach-claude-code-about-your-codebase-with-rag-and-mcp-baeb64824e71">Stop Writing Code That Already Exists: Teach Claude Code About Your Codebase with RAG and MCP…</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate building knowledge graphs from Scientific Abstracts with LLMs and Neo4J — 2 ways]]></title>
            <link>https://blog.gopenai.com/automate-building-knowledge-graphs-from-scientific-abstracts-with-llms-and-neo4j-2-ways-b9d5152a12da?source=rss-7cecf8828340------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9d5152a12da</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[knowledge-management]]></category>
            <dc:creator><![CDATA[Simona Barankova]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 16:53:11 GMT</pubDate>
            <atom:updated>2024-10-29T16:57:36.217Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automate building knowledge graphs with LLMs and Neo4J — 2 ways</h3><p>Knowledge graphs and ontologies play a pivotal role in organizing and making sense of complex datasets.</p><p>An ever-increasing volume of unstructured data is being created every day. Unfortunately, due to the limited interpretability of unstructured data by machines, the insights are often locked and can’t be analyzed in an automated fashion.</p><p>Let’s explore a use case focusing on scientific abstracts, extract structured data from the abstracts using a pre-defined ontology, and construct a knowledge graph!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gd5ap5vnJVKZOqU1ijzjcw.jpeg" /></figure><h3>The use case</h3><p>Our use case will focus on the extraction of data about a particular gene and its function in a disease.</p><p>We will query the PubMed database with a natural language query, and retrieve scientific abstracts about our topic of interest, using the <a href="https://medium.com/gopenai/llm-aided-retrieval-of-relevant-scientific-abstracts-via-pubmed-api-using-natural-language-part2-9e10f78575e6">PubMed retriever built in my other Medium article</a> series, and store them locally as a JSON <a href="https://medium.com/gopenai/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-3-create-vector-1e5e401e72e6">using the repository</a> built in the same series.</p><p>Then, using an ontology, we will construct a knowledge graph representation of those data — the knowledge about a particular gene (RAD21) and its role in disease (breast cancer). A graph representation of the data will enable us to query the graph that might lead to uncovering new patterns and connections between the disease and the gene in question, leading to novel ideas for the investigation of the mechanisms involved!</p><h4>Pre-requisites</h4><ul><li>Download and install a desktop free version of Neo4J — <a href="https://neo4j.com/download/?utm_source=Google&amp;utm_medium=PaidSearch&amp;utm_campaign=Evergreen&amp;utm_content=EMEA-Search-SEMCE-DSA-None-SEM-SEM-NonABM&amp;utm_term=&amp;utm_adgroup=DSA&amp;gad_source=1&amp;gclid=CjwKCAjwgfm3BhBeEiwAFfxrG2oBfsX6hKqVmWr7dlME7_OnVFbKUCoZLzWUCc8qCVMs0AXTDDgsIxoC4t0QAvD_BwE">here</a></li><li>Make sure you have APOC procedures enabled on the active database:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l97Jr3t2-GKK4BnCx5ApnQ.png" /><figcaption>Install the APOC plugin on the Neo4J database you’ll be using</figcaption></figure><ul><li>Set up a local development environment with <strong>python</strong>, <strong>pip</strong>, and <strong>venv</strong></li><li>Before following, make sure you set up <strong>environment variables</strong> in a <strong>.env file</strong> located in the root of the folder where you will run the code. Those variables will be used for the LLM access and the Neo4J database access. The .env file (for this tutorial, I will use Azure OpenAI model GPT4T, if you use different commercial model, the variables might differ) should look similar to this, populated with your variables:</li></ul><pre>AZURE_OPENAI_API_KEY=...<br>AZURE_OPENAI_DEPLOYMENT_NAME=...<br>AZURE_ENDPOINT=...<br>API_VERSION_LLM=...<br><br>NEO4J_URI=...<br>NEO4J_USERNAME=...<br>NEO4J_PASSWORD=...</pre><h3>Approaches to an automated creation of a knowledge graph</h3><p>LLMs are a great tool to aid with knowledge graph creation. They handle very well Named Entity Recognition (NER) and assign relationships between the entities. Furthermore, the LLMs can be prompted to follow a particular ontology for the extraction, which can be very useful.</p><p>Recently, several approaches and packages were created to achieve the automated KG creation using LLMs:</p><ul><li><a href="https://python.langchain.com/v0.1/docs/use_cases/graph/constructing/">Langchain’s LLMGraphTransformer</a> — A simple way to extract entities and relationships from text.</li><li><a href="https://neo4j.com/docs/neo4j-graphrag-python/current/user_guide_kg_builder.html#user-guide-kg-builder">Neo4J’s Knowledge Graph Builder Suite </a>—New tooling directly from Neo4J, a leader in graph databases. They provide a new class <a href="https://neo4j.com/docs/neo4j-graphrag-python/current/api.html#llmentityrelationextractor"><em>LLMEntityRelationExtractor </em></a>that enables plugging in an LLM of your choice (implementing a common interface) and an ontology, to extract entities and relationships and load them into Neo4J.</li><li><a href="https://towardsdatascience.com/text-to-knowledge-graph-made-easy-with-graph-maker-f3f890c0dbe8">Knowledge Graph Maker</a> — package from <a href="https://medium.com/u/473e87f4b733">Rahul Nayak</a> built with <em>pydantic </em>and <em>neomodel</em>, that lets you supply an ontology and create a generic knowledge graph for Neo4J.</li></ul><p>I will compare 2 of these tools side-by-side, using the same LLM — GPT4 Turbo from AzureOpenAI for the evaluation.</p><p>We will also have a look at the results with default prompts offered by those tools, and try to customize the prompt to improve the results.</p><p>So, let’s get down on it! 😎</p><h3>The Ontology</h3><p>First of all, let’s define the ontology that we will use for our use case. We are interested in extracting knowledge about concepts such as <strong>genes</strong>, <strong>proteins</strong>, and their <strong>function </strong>or <strong>pathway </strong>acting in a certain <strong>disease</strong>.</p><p>With a little help from ChatGPT, I came up with the following ontology, in an RDF format:</p><pre>@prefix rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt; .<br>@prefix rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt; .<br>@prefix xsd: &lt;http://www.w3.org/2001/XMLSchema#&gt; .<br>@prefix : &lt;http://example.org/ontology#&gt; .<br><br># Classes<br>:Gene a rdfs:Class ;<br>    rdfs:label &quot;Gene&quot; ;<br>    rdfs:comment &quot;Gene name without any qualifiers&quot; .<br><br>:Protein a rdfs:Class ;<br>    rdfs:label &quot;Protein&quot; ;<br>    rdfs:comment &quot;Protein encoded by a gene&quot; .<br><br>:Disease a rdfs:Class ;<br>    rdfs:label &quot;Disease&quot; ;<br>    rdfs:comment &quot;Name of a disease or pathological condition&quot; .<br><br>:Function a rdfs:Class ;<br>    rdfs:label &quot;Function&quot; ;<br>    rdfs:comment &quot;Biological function or process associated with a gene or protein&quot; .<br><br>:Pathology a rdfs:Class ;<br>    rdfs:label &quot;Pathology&quot; ;<br>    rdfs:comment &quot;Observed pathological effects or symptoms&quot; .<br><br>:Mutation a rdfs:Class ;<br>    rdfs:label &quot;Mutation&quot; ;<br>    rdfs:comment &quot;Specific genetic mutation or variant&quot; .<br><br>:Pathway a rdfs:Class ;<br>    rdfs:label &quot;Pathway&quot; ;<br>    rdfs:comment &quot;Biological pathway involving the gene or protein&quot; .<br><br>:CellType a rdfs:Class ;<br>    rdfs:label &quot;CellType&quot; ;<br>    rdfs:comment &quot;Specific cell type where the gene is expressed or relevant&quot; .<br><br>:Experiment a rdfs:Class ;<br>    rdfs:label &quot;Experiment&quot; ;<br>    rdfs:comment &quot;Experimental method or technique used in the study&quot; .<br><br>:Drug a rdfs:Class ;<br>    rdfs:label &quot;Drug&quot; ;<br>    rdfs:comment &quot;Pharmaceutical compound or treatment&quot; .<br><br>:Biomarker a rdfs:Class ;<br>    rdfs:label &quot;Biomarker&quot; ;<br>    rdfs:comment &quot;Biological marker associated with the gene or disease&quot; .<br><br># Properties<br>:encodes a rdf:Property ;<br>    rdfs:label &quot;ENCODES&quot; ;<br>    rdfs:domain :Gene ;<br>    rdfs:range :Protein .<br><br>:associatedWith a rdf:Property ;<br>    rdfs:label &quot;ASSOCIATED_WITH&quot; ;<br>    rdfs:domain [ a owl:Class ; owl:unionOf (:Gene :Protein) ] ;<br>    rdfs:range :Disease .<br><br>:hasFunction a rdf:Property ;<br>    rdfs:label &quot;HAS_FUNCTION&quot; ;<br>    rdfs:domain [ a owl:Class ; owl:unionOf (:Gene :Protein) ] ;<br>    rdfs:range :Function .<br><br>:causes a rdf:Property ;<br>    rdfs:label &quot;CAUSES&quot; ;<br>    rdfs:domain [ a owl:Class ; owl:unionOf (:Gene :Mutation) ] ;<br>    rdfs:range :Pathology .<br><br>:participatesIn a rdf:Property ;<br>    rdfs:label &quot;PARTICIPATES_IN&quot; ;<br>    rdfs:domain [ a owl:Class ; owl:unionOf (:Gene :Protein) ] ;<br>    rdfs:range :Pathway .<br><br>:expressedIn a rdf:Property ;<br>    rdfs:label &quot;EXPRESSED_IN&quot; ;<br>    rdfs:domain :Gene ;<br>    rdfs:range :CellType .<br><br>:studiedBy a rdf:Property ;<br>    rdfs:label &quot;STUDIED_BY&quot; ;<br>    rdfs:domain [ a owl:Class ; owl:unionOf (:Gene :Protein :Disease) ] ;<br>    rdfs:range :Experiment .<br><br>:interactsWith a rdf:Property ;<br>    rdfs:label &quot;INTERACTS_WITH&quot; ;<br>    rdfs:domain :Protein ;<br>    rdfs:range :Protein .<br><br>:regulates a rdf:Property ;<br>    rdfs:label &quot;REGULATES&quot; ;<br>    rdfs:domain [ a owl:Class ; owl:unionOf (:Gene :Protein) ] ;<br>    rdfs:range [ a owl:Class ; owl:unionOf (:Gene :Protein) ] .<br><br>:targets a rdf:Property ;<br>    rdfs:label &quot;TARGETS&quot; ;<br>    rdfs:domain :Drug ;<br>    rdfs:range [ a owl:Class ; owl:unionOf (:Gene :Protein) ] .<br><br>:indicates a rdf:Property ;<br>    rdfs:label &quot;INDICATES&quot; ;<br>    rdfs:domain :Biomarker ;<br>    rdfs:range [ a owl:Class ; owl:unionOf (:Disease :Pathology) ] .<br><br>:hasVariant a rdf:Property ;<br>    rdfs:label &quot;HAS_VARIANT&quot; ;<br>    rdfs:domain :Gene ;<br>    rdfs:range :Mutation .</pre><p>When visualized, the ontology looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHHgyVXlfHI3pucuQlyTKw.png" /><figcaption>Visualization of the RDF using <a href="http://owlgred.lumii.lv/online_visualization">http://owlgred.lumii.lv/online_visualization</a></figcaption></figure><h3>Get data for our Use Case</h3><p>Let’s explore knowledge regarding a gene called <a href="https://en.wikipedia.org/wiki/RAD21">RAD21 </a>and its role in breast cancer.</p><p>In my last Medium series article, I developed a tool to <a href="https://medium.com/gopenai/llm-aided-retrieval-of-relevant-scientific-abstracts-via-pubmed-api-using-natural-language-part2-9e10f78575e6">query PubMed (scientific article database) with natural language</a> and <a href="https://medium.com/gopenai/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-3-create-vector-1e5e401e72e6">store the resulting scientific abstracts to a local filesystem</a>.</p><p>Feel free to provide a different source of data for your follow-through.</p><p>For a reference, this is the code used to fetch &amp; save the data:</p><pre>from metapub import PubMedFetcher<br>from backend.abstract_retrieval.pubmed_retriever import PubMedAbstractRetriever<br>from backend.data_repository.local_storage import LocalJSONStore<br><br><br># Query<br>query = &quot;rad21 in breast cancer&quot;<br><br># Step 1: Use PubMedAbstractRetriever to get abstract data<br>pubmed_fetcher = PubMedFetcher()<br>abstract_retriever = PubMedAbstractRetriever(pubmed_fetcher)<br>abstracts = abstract_retriever.get_abstract_data(query)<br><br># # Step 2: Use the retrieved data with LocalJSONStorage to persist them in local storage<br>storage_folder_path = &quot;backend/data&quot;<br>store = LocalJSONStore(storage_folder_path)<br>query_id = store.save_dataset(abstracts, query)</pre><p>You can find the implemetation of those tools in my last articles or the <a href="https://github.com/milieere/pubmed-rag-screener">GitHub repo</a>, if you want to use it.</p><p>The code above created an entry in my local database with ID ‘<strong>query_6</strong>’ — a JSON file with abstracts looking like this:</p><pre>[<br>    {<br>        &quot;doi&quot;: &quot;10.1016/j.esmoop.2024.102389&quot;,<br>        &quot;title&quot;: &quot;Comprehensive genomic profiling to identify actionable alterations for breast cancer brain metastases in the Chinese population.&quot;,<br>        &quot;authors&quot;: &quot;Lu Q, Wang N, Jiang K, Zhou H, Zhang P, Zhang J, Wang S, Sun P, Xu F&quot;,<br>        &quot;year&quot;: 2024,<br>        &quot;abstract_content&quot;: &quot;BACKGROUND: Breast cancer brain metastasis (BCBM) is a crucial issue in the treatment of breast cancer and is associated with poor prognosis. Therefore, novel therapeutic targets are urgently needed in clinical practice. In this study, we aimed to identify potential actionable targets in brain metastases (BMs) utilising the FoundationOne\u00ae CDx (F1CDx).\nPATIENTS AND METHODS: Formalin-fixed paraffin-embedded archived specimens including 16 primary breast tumours (PTs), 49 BCBMs and 7 extracranial metastases (ECMs) from 54 patients who underwent surgery for BCBM were tested using F1CDx. Tumour-infiltrated lymphocytes (TILs) of BMs were also tested using haematoxylin-eosin staining.\nRESULTS: The median tumour mutational burden (TMB) and TILs in BMs were 5.0 (range 0-29) mut/Mb and 1.0% (range 0%-5.0%), respectively. High TMB (\u226510 mut/Mb) was detected in four cases (8%). Genomic alterations (GAs) were detected in all samples. The top-ranked somatic mutations in BMs were TP53 (82%), PIK3CA (35%), MLL2 (22%), BRCA2 (14%) and ATM (14%) and the most prevalent copy number alterations were ERBB2 (64%), RAD21 (36%), CCND1 (32%), FGF19 (30%) and FGF3 (30%). The most prevalent GAs were relatively consistent between paired PTs and BMs. Actionable GAs were detected in 94% of all BMs. Consistent rate in actionable GAs was 38% (6/16) between paired PTs/ECMs and BMs. Compared to matched PTs/ECMs, additional actionable GAs (BRAF, FGFR1, PTEN, KIT and CCND1) were discovered in 31% (5/16) of the BMs.\nCONCLUSIONS: TMB and TILs were relatively low in BCBMs. Comparable consistency in actionable GAs was identified between BCBMs and matched PTs/ECMs. It was, therefore, logical to carry out genomic testing for BCBMs to identify potential new therapeutic targets when BCBM specimens were available, as \u223c31% of samples carried additional actionable GAs.&quot;<br>    },<br>    {<br>        &quot;doi&quot;: &quot;10.3389/fonc.2024.1291509&quot;,<br>        &quot;title&quot;: &quot;Genetic landscape of breast cancer subtypes following radiation therapy: insights from comprehensive profiling.&quot;,<br>        &quot;authors&quot;: &quot;Wang F, Wang W, Wang M, Chen D&quot;,<br>        &quot;year&quot;: 2024,<br>        &quot;abstract_content&quot;: &quot;BACKGROUND: In breast cancer, in the era of precision cancer therapy, different patterns of genetic mutations dictate different treatments options. However, it is not clear whether the genetic profiling of breast cancer patients undergoing breast-conserving surgery is related to the adverse reactions caused by radiotherapy.\nMETHODS: We collected formalin-fixed paraffin-embedded (FFPE) tumor tissue samples from 54 breast cancer patients treated with radiation after breast-conserving surgery and identified comprehensive molecular information in hundreds of cancer-associated genes by FoundationOne CDx (F1CDx), a next-generation sequencing (NGS)-based assay.\nRESULTS: Among our cohort of 54 breast cancer patients, we found high-frequency mutations in cancer-related genes such as TP53 (56%), RAD21 (39%), PIK3CA (35%), ERBB2 (24%), and MYC (22%). Strikingly, we detected that the WNT pathway appears to be a signaling pathway with specific high-frequency mutations in the HER2 subtype. We also compared the mutation frequencies of the two groups of patients with and without cutaneous radiation injury (CRI) after radiotherapy and found that the mutation frequencies of two genes, FGFR1 and KLHL6, were significantly higher in patients with CRI : No subgroup than in those with CRI : Yes.\nCONCLUSION: Different breast cancer subtypes have their own type-specific mutation patterns. FGFR1 and KLHL6 mutations are protective factors for radiation-induced skin toxicity in breast cancer patients.&quot;<br>    },<br>    ...<br>]</pre><h3>Approach no. 1: Knowledge Graph Maker</h3><p><a href="https://github.com/rahulnyk/graph_maker">Knowledge graph maker is a package</a> developed by <a href="https://medium.com/u/473e87f4b733">Rahul Nayak</a>. It creates a generic KG with one type of relationship ‘RELATED’ and LLM-generated descriptions of those relationships.</p><p><a href="https://towardsdatascience.com/text-to-knowledge-graph-made-easy-with-graph-maker-f3f890c0dbe8">See the associated Medium article from Rahul</a>.</p><h4>Implementation</h4><ul><li>First, I asked ChatGPT to transform my ontology to the format expected by the library — a Pydantic model:</li></ul><pre>from knowledge_graph_maker.graph_maker import Ontology<br><br>ontology = Ontology(<br>    labels=[<br>        {&quot;Gene&quot;: &quot;Gene name without any qualifiers&quot;},<br>        {&quot;Protein&quot;: &quot;Protein encoded by a gene&quot;},<br>        {&quot;Disease&quot;: &quot;Name of a disease or pathological condition&quot;},<br>        {&quot;Function&quot;: &quot;Biological function or process associated with a gene or protein&quot;},<br>        {&quot;Pathology&quot;: &quot;Observed pathological effects or symptoms&quot;},<br>        {&quot;Mutation&quot;: &quot;Specific genetic mutation or variant&quot;},<br>        {&quot;Pathway&quot;: &quot;Biological pathway involving the gene or protein&quot;},<br>        {&quot;CellType&quot;: &quot;Specific cell type where the gene is expressed or relevant&quot;},<br>        {&quot;Experiment&quot;: &quot;Experimental method or technique used in the study&quot;},<br>        {&quot;Drug&quot;: &quot;Pharmaceutical compound or treatment&quot;},<br>        {&quot;Biomarker&quot;: &quot;Biological marker associated with the gene or disease&quot;},<br>    ],<br>    relationships=[<br>        &quot;ENCODES&quot;,  # Gene ENCODES Protein<br>        &quot;ASSOCIATED_WITH&quot;,  # Gene/Protein ASSOCIATED_WITH Disease<br>        &quot;HAS_FUNCTION&quot;,  # Gene/Protein HAS_FUNCTION Function<br>        &quot;CAUSES&quot;,  # Gene/Mutation CAUSES Pathology<br>        &quot;PARTICIPATES_IN&quot;,  # Gene/Protein PARTICIPATES_IN Pathway<br>        &quot;EXPRESSED_IN&quot;,  # Gene EXPRESSED_IN CellType<br>        &quot;STUDIED_BY&quot;,  # Gene/Protein/Disease STUDIED_BY Experiment<br>        &quot;INTERACTS_WITH&quot;,  # Protein INTERACTS_WITH Protein<br>        &quot;REGULATES&quot;,  # Gene/Protein REGULATES Gene/Protein<br>        &quot;TARGETS&quot;,  # Drug TARGETS Gene/Protein<br>        &quot;INDICATES&quot;,  # Biomarker INDICATES Disease/Pathology<br>        &quot;HAS_VARIANT&quot;,  # Gene HAS_VARIANT Mutation<br>    ]<br>)</pre><ul><li>I created a new implementation of an LLM client following the interface <em>LLMClient</em> from the library, since the lib out of the box provided only Mistral and OpenAI. I needed Azure OpenAI:</li></ul><pre>from langchain_openai import AzureChatOpenAI<br>from langchain_core.prompts import PromptTemplate<br>from knowledge_graph_maker.types import LLMClient<br>from dotenv import dotenv_values<br><br><br>config = dotenv_values(&quot;.env&quot;)<br><br># Define the custom LLM client (in this case AzureOpenAI) using the interface LLMClient<br>class AzureOpenAIClient(LLMClient):<br>    def __init__(<br>        self, temperature=0<br>    ):<br>        self._temperature = temperature<br>        self.client = AzureChatOpenAI(<br>            azure_endpoint=config[&#39;AZURE_ENDPOINT&#39;],<br>            api_key=config[&#39;AZURE_OPENAI_API_KEY&#39;],<br>            azure_deployment=config[&#39;AZURE_OPENAI_DEPLOYMENT_NAME&#39;],<br>            api_version=config[&#39;API_VERSION_LLM&#39;],<br>            temperature=self._temperature,<br>            streaming=True<br>        )<br>        self.prompt = PromptTemplate(<br>            input_variables=[&#39;system_message&#39;, &#39;user_message&#39;],<br>            template= &quot;System message: {system_message}, User message: {user_message}&quot;<br>        )<br><br>    def generate(self, user_message: str, system_message: str) -&gt; str:<br>        prompt_formatted_str = self.prompt.format(system_message=system_message, user_message=user_message)<br>        return self.client.invoke(prompt_formatted_str).content</pre><ul><li>I used the method <em>read_documents</em> on my <em>LocalJSONStore</em> class, to retrieve the Documents (a list Langchain <em>Document</em> class) from my local JSON file created for my query ‘RAD21 and breast cancer’, and converted them to the Document model expected by the Knowledge Graph Maker library.</li><li>Using GPT4T, the default prompt from the library achieved very good results in extracting the entities described in the ontology. These entities &amp; relationships were loaded into the Neo4J database via te <em>Neo4JGraphModel </em>class.</li></ul><pre>from backend.data_repository.local_storage import LocalJSONStore<br>from knowledge_graph_maker.graph_maker import GraphMaker<br>from knowledge_graph_maker import Neo4jGraphModel<br>from pydantic import BaseModel<br>from backend.kg_maker.knowledge_graph_maker.azureopenai_client import AzureOpenAIClient<br>from backend.kg_maker.knowledge_graph_maker.ontology import ontology<br><br><br># Retrieve abstracts data from the local storage<br>storage_folder_path = &quot;backend/data&quot;<br>store = LocalJSONStore(storage_folder_path)<br>documents = store.read_documents(&#39;query_6&#39;)<br><br># Define the document model expected by the library<br>class Doc(BaseModel):<br>    text: str<br>    metadata: dict<br><br># Transform the langchain document format to the model expeczed by the library<br>docs = [Doc(text=document.page_content, metadata=document.metadata) for document in documents]<br><br># Instantiate the LLM client<br>llm_client = AzureOpenAIClient()<br># Instantiate the GraphMaker class and pass the ontology and LLM client<br>graph_maker = GraphMaker(ontology=ontology, llm_client=llm_client, verbose=False)<br>#Run the extraction<br>graph = graph_maker.from_documents(docs)<br><br># Load the extracted graph to Neo4J<br>neo4j_graph = Neo4jGraphModel(edges=graph, create_indices=False)<br>neo4j_graph.save()</pre><h4>Result in Neo4J</h4><p>This is how the resulting KG looks like visualized in the Neo4J DB:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJQRXV4meADlokNRG-yVZQ.png" /></figure><ul><li>The default prompt did a great job extracting entities and relationships from the abstract in an unambiguous way (not many entities seem to be duplicated) thanks to the node merging implementation under the hood.</li><li>All the entities are of the same type ‘Entity’. However, the entity type was annotated in properties as ‘label’ property, i.e. Gene, Protein, and therefore could be tracked down. All the relationships in the graph bear the same generic relationship ‘RELATED’. In the relationship properties however, you can find metadata about the source and an LLM-generated description of the relationship, which is very useful in interpreting the relationship and linking the finding to the source of the information:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*xCgAVmOb9UJ3ceQonaUciA.png" /></figure><ul><li>I am pretty happy with this structure of the KG for my use case — hypothesis generation using KG.</li></ul><h3>Approach no. 2: Neo4J Graph Builder</h3><p>Recently, guys from Neo4J <a href="https://github.com/neo4j/neo4j-graphrag-python">released a package</a> to facilitate the GraphRAG pipeline. This package contains modules and classes to aid the creation of a knowledge graph in Neo4J, presumably for later use in GraphRAG.</p><p>As of the day of writing this article, this module of the package was released about a week ago (16.10.2024) and is stored in an ‘experimental’ module within the library.</p><p>I tested out two approaches — creating lexical (lexical graphs highlight the relationships between the structural components of your data, such as a document to chunk), and non-lexical graphs.</p><p>In both cases, post-knowledge graph creation, entity resolution is necessary, because the <em>LLMEntityRelationExtractor </em>by default always creates a new node, instead of trying to merge it with existing nodes.</p><h4>Lexical vs. non-lexical</h4><p>In lexical extraction, the Chunk and Document node types were created in addition to the entities and relationships extracted, representing the source data — i.e. chunk belongs to document, or entity mentioned in chunk, etc. (in this case, 1 document contained only 1 chunk since I did not split the abstracts further). The Chunk and the Document entity types contained the metadata of the abstract (nodes highlighted in dark brown color on the graph).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kNNEe2hhp1OxopF8QVxeew.png" /><figcaption>View on the created lexical graph</figcaption></figure><p>When choosing non-lexical extraction, a KG more similar to the one from the knowledge graph maker was produced, however, it completely lacked metadata about the source and any descriptions for easier interpretation. On the other hand, relationship types and entity types from the ontology were respected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-_Yg12zxDYPtLakprNWVkg.png" /><figcaption>View on the non-lexical graph extracted via the default prompt.</figcaption></figure><p>At this point, I was not very happy with the results of neither approach (lexical &amp; non-lexical extraction with Neo4J package) for my use case. I decided to adjust the default prompt to add something I liked from the knowledge graph maker approach — meaningful descriptions of relationships, and metadata about sources — to the graph.</p><h4>Prompt engineering</h4><p>I decided to develop a prompt for the extraction, where I instruct the LLM to add descriptions to the relationships, and include the metadata.</p><pre>customized_prompt = &quot;&quot;&quot;<br>You are a top-tier algorithm designed for extracting<br>information in structured formats to build a knowledge graph.<br><br>You will be passed a text of scientific abstracts containing the abstract, and the metadata (abstract DOI, author, etc.). This is an example abstract (enclosed in ```):<br>```ABSTRACT_TEXT: The abstract text content. ABSTRACT_METADATA: The abstract metadata```<br><br>Extract the entities (nodes) and specify their type.<br>Also extract the relationships between these nodes.<br><br>Use only fhe following nodes and relationships - ontology:<br>{schema}<br><br>Return result as JSON using the following format:<br><br>{{&quot;nodes&quot;: [ {{&quot;id&quot;: &quot;0&quot;, &quot;label&quot;: &quot;As per the ontology&quot;, &quot;properties&quot;: {{&quot;name&quot;: &quot;Name of the entity&quot;}} }}],<br>&quot;relationships&quot;: [{{&quot;type&quot;: &quot;As per the ontology. If no fitting relationship type is found, used simply RELATED&quot;, &quot;start_node_id&quot;: &quot;0&quot;, &quot;end_node_id&quot;: &quot;1&quot;, &quot;properties&quot;: {{&quot;description&quot;: &quot;Describe the relationship between the nodes as per the context, in a few sentences. Use as much relevant context as possible from the abstract to gain more insight into the relationship.&quot;, &quot;metadata&quot;: &quot;Here go ABSTRACT_METADATA.&quot;}} }}] }}<br><br>Assign a unique ID (string) to each node, and reuse it to define relationships.<br>Do respect the source and target node types for relationship and<br>the relationship direction.<br><br>Do not return any additional information other than the JSON in it.<br><br>Examples:<br><br>{examples}<br><br>Input text:<br><br>{text}<br>&quot;&quot;&quot;</pre><p>The resulting graph contained the relationship descriptions and metadata, just as I asked for in the prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ta532g-Fyjpz6icUujHi5g.png" /><figcaption>Resulting graph with custom prompt</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*ECCkdD-OeoMHDxjaWFLncw.png" /><figcaption>Relationship details with custom prompt, containing description and metadata</figcaption></figure><h4>Implementation</h4><ul><li>First, I defined the ontology in the format expected by the library (again, I used chatGPT providing the RDF format and an example from the Neo4J library to help me with the conversion):</li></ul><pre>from neo4j_graphrag.experimental.components.schema import (<br>    SchemaBuilder,<br>    SchemaEntity,<br>    SchemaProperty,<br>    SchemaRelation,<br>)<br><br>schema_builder = SchemaBuilder()<br><br>schema = schema_builder.create_schema_model(<br>    entities=[<br>        SchemaEntity(<br>            label=&quot;Gene&quot;,<br>            properties=[<br>                SchemaProperty(name=&quot;name&quot;, type=&quot;STRING&quot;),<br>                SchemaProperty(name=&quot;description&quot;, type=&quot;STRING&quot;),<br>            ],<br>        ),<br>        SchemaEntity(<br>            label=&quot;Protein&quot;,<br>            properties=[<br>                SchemaProperty(name=&quot;name&quot;, type=&quot;STRING&quot;),<br>                SchemaProperty(name=&quot;description&quot;, type=&quot;STRING&quot;),<br>            ],<br>        ),<br>        SchemaEntity(<br>            label=&quot;Disease&quot;,<br>            properties=[<br>                SchemaProperty(name=&quot;name&quot;, type=&quot;STRING&quot;),<br>                SchemaProperty(name=&quot;description&quot;, type=&quot;STRING&quot;),<br>            ],<br>        ),<br>        SchemaEntity(<br>            label=&quot;Function&quot;,<br>            properties=[<br>                SchemaProperty(name=&quot;name&quot;, type=&quot;STRING&quot;),<br>                SchemaProperty(name=&quot;description&quot;, type=&quot;STRING&quot;),<br>            ],<br>        ),<br>        SchemaEntity(<br>            label=&quot;Pathology&quot;,<br>            properties=[<br>                SchemaProperty(name=&quot;name&quot;, type=&quot;STRING&quot;),<br>                SchemaProperty(name=&quot;description&quot;, type=&quot;STRING&quot;),<br>            ],<br>        ),<br>        SchemaEntity(<br>            label=&quot;Mutation&quot;,<br>            properties=[<br>                SchemaProperty(name=&quot;name&quot;, type=&quot;STRING&quot;),<br>                SchemaProperty(name=&quot;description&quot;, type=&quot;STRING&quot;),<br>            ],<br>        ),<br>        SchemaEntity(<br>            label=&quot;Pathway&quot;,<br>            properties=[<br>                SchemaProperty(name=&quot;name&quot;, type=&quot;STRING&quot;),<br>                SchemaProperty(name=&quot;description&quot;, type=&quot;STRING&quot;),<br>            ],<br>        ),<br>        SchemaEntity(<br>            label=&quot;CellType&quot;,<br>            properties=[<br>                SchemaProperty(name=&quot;name&quot;, type=&quot;STRING&quot;),<br>                SchemaProperty(name=&quot;description&quot;, type=&quot;STRING&quot;),<br>            ],<br>        ),<br>        SchemaEntity(<br>            label=&quot;Experiment&quot;,<br>            properties=[<br>                SchemaProperty(name=&quot;name&quot;, type=&quot;STRING&quot;),<br>                SchemaProperty(name=&quot;description&quot;, type=&quot;STRING&quot;),<br>            ],<br>        ),<br>        SchemaEntity(<br>            label=&quot;Drug&quot;,<br>            properties=[<br>                SchemaProperty(name=&quot;name&quot;, type=&quot;STRING&quot;),<br>                SchemaProperty(name=&quot;description&quot;, type=&quot;STRING&quot;),<br>            ],<br>        ),<br>        SchemaEntity(<br>            label=&quot;Biomarker&quot;,<br>            properties=[<br>                SchemaProperty(name=&quot;name&quot;, type=&quot;STRING&quot;),<br>                SchemaProperty(name=&quot;description&quot;, type=&quot;STRING&quot;),<br>            ],<br>        ),<br>    ],<br>    relations=[<br>        SchemaRelation(label=&quot;ENCODES&quot;),<br>        SchemaRelation(label=&quot;ASSOCIATED_WITH&quot;),<br>        SchemaRelation(label=&quot;HAS_FUNCTION&quot;),<br>        SchemaRelation(label=&quot;CAUSES&quot;),<br>        SchemaRelation(label=&quot;PARTICIPATES_IN&quot;),<br>        SchemaRelation(label=&quot;EXPRESSED_IN&quot;),<br>        SchemaRelation(label=&quot;STUDIED_BY&quot;),<br>        SchemaRelation(label=&quot;INTERACTS_WITH&quot;),<br>        SchemaRelation(label=&quot;REGULATES&quot;),<br>        SchemaRelation(label=&quot;TARGETS&quot;),<br>        SchemaRelation(label=&quot;INDICATES&quot;),<br>        SchemaRelation(label=&quot;HAS_VARIANT&quot;),<br>    ],<br>    potential_schema=[<br>        (&quot;Gene&quot;, &quot;ENCODES&quot;, &quot;Protein&quot;),<br>        (&quot;Gene&quot;, &quot;ASSOCIATED_WITH&quot;, &quot;Disease&quot;),<br>        (&quot;Protein&quot;, &quot;ASSOCIATED_WITH&quot;, &quot;Disease&quot;),<br>        (&quot;Gene&quot;, &quot;HAS_FUNCTION&quot;, &quot;Function&quot;),<br>        (&quot;Protein&quot;, &quot;HAS_FUNCTION&quot;, &quot;Function&quot;),<br>        (&quot;Gene&quot;, &quot;CAUSES&quot;, &quot;Pathology&quot;),<br>        (&quot;Mutation&quot;, &quot;CAUSES&quot;, &quot;Pathology&quot;),<br>        (&quot;Gene&quot;, &quot;PARTICIPATES_IN&quot;, &quot;Pathway&quot;),<br>        (&quot;Protein&quot;, &quot;PARTICIPATES_IN&quot;, &quot;Pathway&quot;),<br>        (&quot;Gene&quot;, &quot;EXPRESSED_IN&quot;, &quot;CellType&quot;),<br>        (&quot;Gene&quot;, &quot;STUDIED_BY&quot;, &quot;Experiment&quot;),<br>        (&quot;Protein&quot;, &quot;STUDIED_BY&quot;, &quot;Experiment&quot;),<br>        (&quot;Disease&quot;, &quot;STUDIED_BY&quot;, &quot;Experiment&quot;),<br>        (&quot;Protein&quot;, &quot;INTERACTS_WITH&quot;, &quot;Protein&quot;),<br>        (&quot;Gene&quot;, &quot;REGULATES&quot;, &quot;Gene&quot;),<br>        (&quot;Gene&quot;, &quot;REGULATES&quot;, &quot;Protein&quot;),<br>        (&quot;Protein&quot;, &quot;REGULATES&quot;, &quot;Gene&quot;),<br>        (&quot;Protein&quot;, &quot;REGULATES&quot;, &quot;Protein&quot;),<br>        (&quot;Drug&quot;, &quot;TARGETS&quot;, &quot;Gene&quot;),<br>        (&quot;Drug&quot;, &quot;TARGETS&quot;, &quot;Protein&quot;),<br>        (&quot;Biomarker&quot;, &quot;INDICATES&quot;, &quot;Disease&quot;),<br>        (&quot;Biomarker&quot;, &quot;INDICATES&quot;, &quot;Pathology&quot;),<br>        (&quot;Gene&quot;, &quot;HAS_VARIANT&quot;, &quot;Mutation&quot;),<br>    ],<br>)</pre><p>And then constructed the client code with data retrieval from local storage and KG creation:</p><pre>from neo4j_graphrag.experimental.components.entity_relation_extractor import (<br>    LLMEntityRelationExtractor,<br>    TextChunks, TextChunk, DocumentInfo<br>)<br>from neo4j_graphrag.experimental.components.resolver import SinglePropertyExactMatchResolver<br>import neo4j<br>import asyncio<br>from neo4j_graphrag.experimental.components.kg_writer import Neo4jWriter<br>from neo4j_graphrag.llm.openai_llm import AzureOpenAILLM<br>from backend.kg_maker.neo4j.neo4j_ontology import schema<br>from backend.data_repository.local_storage import LocalJSONStore<br>from backend.kg_maker.neo4j.kg_extraction_prompt import customized_prompt<br>from dotenv import dotenv_values<br><br># Load environment variables<br>config = dotenv_values(&quot;.env&quot;)<br><br># Retrieve the abstracts from our local storage and read them as list of Langchain documents<br>storage_folder_path = &quot;backend/data&quot;<br>store = LocalJSONStore(storage_folder_path)<br>documents = store.read_documents(&#39;query_6&#39;)<br><br># Instantiate the extractor, set the lexical_graph property to True or False depending on requirements<br>extractor = LLMEntityRelationExtractor(<br>    llm=AzureOpenAILLM(<br>        model_name=config[&#39;AZURE_OPENAI_DEPLOYMENT_NAME&#39;],<br>        model_params={<br>            &quot;temperature&quot;: 0,<br>            &quot;response_format&quot;: {&quot;type&quot;: &quot;json_object&quot;},<br>        },<br>        azure_endpoint=config[&#39;AZURE_ENDPOINT&#39;],<br>        api_key=config[&#39;AZURE_OPENAI_API_KEY&#39;],<br>        azure_deployment=config[&#39;AZURE_OPENAI_DEPLOYMENT_NAME&#39;],<br>        api_version=config[&#39;API_VERSION_LLM&#39;],<br>    ),<br>    create_lexical_graph=False,<br>    prompt_template = customized_prompt<br>)<br><br># Instantiate the Neo4J driver<br>driver = neo4j.GraphDatabase.driver(<br>    config[&quot;NEO4J_URI&quot;], auth=(config[&quot;NEO4J_USERNAME&quot;], config[&quot;NEO4J_PASSWORD&quot;])<br>)<br><br>async def main():<br>    # Iterate over the documents, each document represents an abstract<br>    for doc in documents:<br>        # This will only have one chunk in it, since we do not split the abstracts to multiple chunks<br>        chunks=TextChunks(chunks=[TextChunk(text=f&#39;ABSTRACT_TEXT: {doc.page_content}, ABSTRACT_METADATA: {str(doc.metadata)}&#39;, index=0, metadata=doc.metadata)])<br>        # Create the doc info from the metadata<br>        doc_info =  DocumentInfo(<br>            path=storage_folder_path,<br>            metadata={key: str(value) for key, value in doc.metadata.items()}<br>        )<br>        # Run extraction<br>        graph = await extractor.run(chunks=chunks, document_info=doc_info, schema=schema)<br>        # Write the results to Neo4J<br>        writer = Neo4jWriter(driver)<br>        await writer.run(graph)<br><br>    # Resolve properties<br>    resolver = SinglePropertyExactMatchResolver(driver, filter_query=&quot;WHERE not entity:Resolved&quot;)<br>    await resolver.run()<br><br># Run the async code with asyncio<br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><p>Note that I formatted the chunk ‘text’ part in a way that included the metadata as well, in order for the LLM to extract it and put it in the relationship as a property. This is not a very efficient way of doing this, as it could’ve been easily done using simple programming and not wasting LLM tokens (especially when you use a commercial LLM). However, that would need to be somehow monkey-patched into the library functionality.</p><h3>Summary</h3><p><a href="https://github.com/milieere/pubmed-rag-screener/tree/main/app/backend/kg_maker">Find the complete code in the pubmed-rag-screener repository in my GitHub — in the app/backend/kg_maker module</a></p><ul><li>I tried two approaches to automated knowledge graph creation, using different python libraries.</li><li>Each approach yielded a different result, and as always, customizing the prompt is key to adapting the result (within the library limitations). Both libraries offer prompt customization, but I used this option only for Neo4J, since I was happy with the default results yielded by the knowledge graph maker.</li><li>I liked the knowledge graph maker library due to its simplicity and the flexibility of the extracted graph, with a very generic model (only one node type ‘Entity’ and one relationship type ‘RELATED’). I also liked very much that no entity resolution is needed — the default approach is to merge nodes with the same name and label.</li><li>The Neo4J library, on the other hand, is more focused on the subsequent use in the GraphRAG application (which I would like to dedicate another article to) but still can be adapted to create a general-purpose knowledge graph with the structure of your choice by prompt customization.</li><li>For my use case of scientific hypothesis generation, I will proceed with the knowledge graph maker approach which provides simplicity, flexibility, and less ambiguity. <strong>Stay tuned for the next articles, where I will elaborate on this use case further!</strong></li></ul><blockquote>And how do you extract KG in an automated way? I am curious to know! Feel free to get in touch to chat and develop ideas.</blockquote><h4><strong>Thank you for reading and have a great day! ☀️</strong></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9d5152a12da" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/automate-building-knowledge-graphs-from-scientific-abstracts-with-llms-and-neo4j-2-ways-b9d5152a12da">Automate building knowledge graphs from Scientific Abstracts with LLMs and Neo4J — 2 ways</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a RAG-based scientific ChatBot with LangChain, Streamlit & PubMed — Part 4(Put it all…]]></title>
            <link>https://blog.gopenai.com/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-4-put-it-all-ba7bbf706bbd?source=rss-7cecf8828340------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba7bbf706bbd</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Simona Barankova]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 14:53:06 GMT</pubDate>
            <atom:updated>2024-09-17T09:20:54.904Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a RAG-based scientific ChatBot with LangChain, Streamlit &amp; PubMed — Part 4 (Put it all together via RAG — chat with scientific abstracts)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQ7XtBd9WHn5n-gAMgd6pQ.jpeg" /></figure><p>Hello and welcome to the last part of the series to build a scientific ChatBot with Langchain, Streamlit, and PubMed!</p><p>In the previous part, we built the data persistence and RAG pipeline with vectorstore. Now, it is time to put everything we’ve built together, and create the chatbot UI that will use the backend functionality we built, and that our scientist will use to answer their scientific questions!</p><p>As a reminder, this is the full solution that we were building during the series:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*NFCO_uRjlAgm0WYH.png" /></figure><h3>App demo</h3><ul><li>As a teaser, let’s first have a look at an illustration of what the app will look like!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKEQO_2kwnV93Va4SAVWZg.gif" /></figure><h3>Building</h3><h4>Overview of steps already done</h4><ul><li>If you haven’t followed through the <a href="https://medium.com/@milieere/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-1-set-up-streamlit-37550b44b266">first</a> , the <a href="https://medium.com/gopenai/llm-aided-retrieval-of-relevant-scientific-abstracts-via-pubmed-api-using-natural-language-part2-9e10f78575e6">second</a>, and the <a href="https://medium.com/gopenai/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-3-create-vector-1e5e401e72e6">third part</a>, please do so, because we will be building on that further. At the end of the last part, we ended up with a project structure looking like this:</li></ul><pre>.<br>├── app<br>│   ├── app.py<br>│   ├── backend<br>│   │  ├── abstract_retrieval<br>│   │  │   ├── interface.py<br>│   │  │   ├── pubmed_retriever.py<br>│   │  │   └── pubmed_query_simplification.py<br>│   │  ├── data_repository<br>│   │  │   ├── interface.py<br>│   │  │   ├── local_data_store.py<br>│   │  │   └── models.py<br>│   │  └── rag_pipeline<br>│   │      ├── interface.py<br>│   │      ├── chromadb_rag.py<br>│   │      └── embeddings.py<br>│   ├── components<br>│   │   ├── chat_utils.py<br>│   │   ├── llm.py<br>│   │   └── prompts.py<br>│   └── tests<br>│       └── test_chat_utils.py<br>├── assets<br>│   └── pubmed-screener-logo.jpg<br>└── environment<br>    └── requirements.txt</pre><p>In this last part of the series, we will focus on the part of code base that defines our Streamlit UI — <strong><em>app/app.py</em></strong> and the <strong><em>app/components</em></strong> module.</p><h4>Modify chat_utils.py to include RAG logic</h4><p><a href="https://medium.com/@milieere/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-1-set-up-streamlit-37550b44b266">In the first part</a>, we built a preliminary version of <strong><em>chat_utils.py</em></strong> that contained a simple QA chatbot implementation (without RAG). Now, we will dive in and convert this into a context-aware QA chatbot, that will construct answers based on user questions and retrieve relevant context (abstracts) from our vector index via similarity search.</p><p>We will use all the backend functionality <a href="https://medium.com/gopenai/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-3-create-vector-1e5e401e72e6">built in part three</a> for this purpose.</p><p><strong>app/components/chat_utils.py</strong></p><pre>from typing import List<br>import streamlit as st<br>from langchain_core.documents.base import Document<br>from langchain_core.runnables.history import RunnableWithMessageHistory<br>from langchain_core.runnables.base import Runnable<br>from langchain_core.runnables.utils import Output<br>from langchain_community.chat_message_histories import StreamlitChatMessageHistory<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain.vectorstores import VectorStore<br><br><br>class ChatAgent:<br>    def __init__(self, prompt: ChatPromptTemplate, llm: Runnable):<br>        &quot;&quot;&quot;<br>        Initialize the ChatAgent.<br><br>        Args:<br>        - prompt (ChatPromptTemplate): The chat prompt template.<br>        - llm (Runnable): The language model runnable.<br>        &quot;&quot;&quot;<br>        self.history = StreamlitChatMessageHistory(key=&quot;chat_history&quot;)<br>        self.llm = llm<br>        self.prompt = prompt<br>        self.chain = self.setup_chain()<br>    <br>    def reset_history(self) -&gt; None:<br>        &quot;&quot;&quot;<br>        Clean up chat history to start new chat session.<br>        &quot;&quot;&quot;<br>        self.history.clear()<br><br>    def setup_chain(self) -&gt; RunnableWithMessageHistory:<br>        &quot;&quot;&quot;<br>        Set up the chain for the ChatAgent.<br><br>        Returns:<br>        - RunnableWithMessageHistory: The configured chain with message history.<br>        &quot;&quot;&quot;<br>        chain = self.prompt | self.llm<br>        return RunnableWithMessageHistory(<br>            chain,<br>            lambda session_id: self.history,<br>            input_messages_key=&quot;question&quot;,<br>            history_messages_key=&quot;history&quot;,<br>        )<br><br>    def display_messages(self, selected_query: str) -&gt; None:<br>        &quot;&quot;&quot;<br>        Display messages in the chat interface.<br>        If no messages are present, adds a default AI message.<br>        &quot;&quot;&quot;<br>        if len(self.history.messages) == 0:<br>            self.history.add_ai_message(f&quot;Let&#39;s chat about your query: {selected_query}&quot;)<br>        for msg in self.history.messages:<br>            st.chat_message(msg.type).write(msg.content)<br>    <br>    def format_retreieved_abstracts_for_prompt(self, documents: List[Document]) -&gt; str:<br>        &quot;&quot;&quot;<br>        Format retrieved documents in a string to be passed to LLM.<br>        &quot;&quot;&quot;<br>        formatted_strings = []<br>        for doc in documents:<br>            formatted_str = f&quot;ABSTRACT TITLE: {doc.metadata[&#39;title&#39;]}, ABSTRACT CONTENT: {doc.page_content}, ABSTRACT DOI: {doc.metadata[&#39;source&#39;] if &#39;source&#39; in doc.metadata.keys() else &#39;DOI missing..&#39;}&quot;<br>            formatted_strings.append(formatted_str)<br>        return &quot;; &quot;.join(formatted_strings)<br>    <br>    def get_answer_from_llm(self, question: str, retrieved_documents: List[Document]) -&gt; Output:<br>        &quot;&quot;&quot;<br>        Get response from LLM given user question and retrieved documents.<br>        &quot;&quot;&quot;<br>        config = {&quot;configurable&quot;: {&quot;session_id&quot;: &quot;any&quot;}}<br>        return self.chain.invoke(<br>            {<br>                &quot;question&quot;: question, <br>                &quot;retrieved_abstracts&quot;: retrieved_documents,<br>            }, config<br>        )<br>    <br>    def retrieve_documents(self, retriever: VectorStore, question: str, cut_off: int = 5) -&gt; List[Document]:<br>        &quot;&quot;&quot;<br>        Retrieve documents using similarity search <br>        cut_off parameter controls how many results are retrieved (default is 5)<br>        &quot;&quot;&quot;<br>        return retriever.similarity_search(question)[:cut_off]<br><br>    def start_conversation(self, retriever: VectorStore, selected_query: str) -&gt; None:<br>        &quot;&quot;&quot;<br>        Start a conversation in the chat interface.<br>        Displays messages, prompts user for input, and handles AI response.<br>        &quot;&quot;&quot;<br>        self.display_messages(selected_query)<br>        user_question = st.chat_input(placeholder=&quot;Ask me anything..&quot;)<br>        if user_question:<br>            documents = self.retrieve_documents(retriever, user_question)<br>            retrieved_abstracts = self.format_retreieved_abstracts_for_prompt(documents)<br>            st.chat_message(&quot;human&quot;).write(user_question)<br>            response = self.get_answer_from_llm(user_question, retrieved_abstracts)<br>            st.chat_message(&quot;ai&quot;).write(response.content)</pre><p><strong>What has changed:</strong></p><ul><li>We added the method <strong><em>retrieve_documents </em></strong>that takes our vector index (retriever) as argument, and calls a method similarity_search on the retriever to get the most similar records to user’s question from the vector index of our scientific abstracts. Note the parameter cut_off that specifies the number of results to be retrieved (defaults to 5).</li><li>Added method <strong><em>format_retreieved_abstracts_for_prompt</em></strong>, that takes the documents retrieved via retrieve_documents method, and formats them for the LLM. This will come very handy when we will ask the LLM in our prompt to cite the relevant sources (article DOIs, and titles).</li><li>Added method <strong><em>get_answer_from_llm </em></strong>that serves for calling the LLM with necessary variables, to keep the client function start_conversation clean.</li><li>Modified the <strong><em>start_conversation </em></strong>method to include the RAG logic.</li></ul><h4>Create chat prompts for QA</h4><ul><li>We will be modifying the existing chat prompt to include retrieved abstracts and construct the answer based on those.</li><li>We will also include an additional (simple) prompt that will serve for a simple immediate answer outside of the chatbot section, so that the user gets a direct answer to his question displayed on the UI.</li></ul><p><strong>app/components/chat_prompts.py</strong></p><pre>from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder, PromptTemplate<br><br><br>chat_prompt_template = ChatPromptTemplate.from_messages(<br>    [<br>        (&quot;system&quot;, &quot;You are a knowledgeable expert chatbot in the biomedicine field.&quot;),<br>        MessagesPlaceholder(variable_name=&quot;history&quot;),<br>        (<br>            &quot;human&quot;, <br>            &quot;&quot;&quot;<br>            Answer the following scientific question: {question}, <br>            using the following context retrieved from scientific articles: {retrieved_abstracts}.<br><br>            The user might refer to the history of your conversation. Please, use the following history of messages for the context as you see fit.<br><br>            The abstracts will come formatted in the following way: ABSTRACT TITLE: &lt;abstract title&gt;; ABSTRACT CONTENT: &lt;abstract content&gt;, ABSTRACT DOI: &lt;abstract doi&gt; (the content inside &lt;&gt; will be variable).<br>            In your answer, ALWAYS cite the abstract title and abstract DOI when citing a particular piece of information from that given abstract.<br><br>            Your example response might look like this:<br><br>            In the article (here in the brackets goes the contents of ABSTRACT_TITLE), it was discussed, that Cannabis hyperemesis syndrome (CHS) is associated with chronic, heavy cannabis use. The endocannabinoid system (ECS) plays a crucial role in the effects of cannabis on end organs and is central to the pathophysiology of CHS. (here, in the end of the cited chunk, the ABSTRACT_DOI goes)<br>            &quot;&quot;&quot;<br>        ),<br>    ]<br>)<br><br>qa_template = PromptTemplate(<br>    input_variables=[&#39;question&#39;, &#39;retrieved_abstracts&#39;],<br>    template=&quot;&quot;&quot;<br>        Answer the following scientific question: {question}, <br>        using the following context retrieved from scientific articles: {retrieved_abstracts}.<br><br>        The abstracts will come formatted in the following way: ABSTRACT TITLE: &lt;abstract title&gt;; ABSTRACT CONTENT: &lt;abstract content&gt;, ABSTRACT DOI: &lt;abstract doi&gt; (the content inside &lt;&gt; will be variable).<br>        In your answer, ALWAYS cite the abstract title and abstract DOI when citing a particular piece of information from that given abstract.<br><br>        Your example response might look like this:<br><br>        In the article (here in the brackets goes the contents of ABSTRACT_TITLE), it was discussed, that Cannabis hyperemesis syndrome (CHS) is associated with chronic, heavy cannabis use. The endocannabinoid system (ECS) plays a crucial role in the effects of cannabis on end organs and is central to the pathophysiology of CHS. (here, in the end of the cited chunk, the ABSTRACT_DOI goes)<br>    &quot;&quot;&quot;<br>)</pre><ul><li>Note that the contents of the two prompts is almost identical, but the chat prompt contains a reference for the chat history with the MessagesPlaceholder and an instruction to use the chat history as the LLM sees fit during the conversation.</li></ul><h4>Create new file app/components/layout_extensions.py</h4><ul><li>This file will hold a helper function that will render a part of the layout of our app with examples of queries (cues on how to use the app) to the user. I decided to create this extensions file to not clutter our app.py file and keep it clean, since this code is quite lengthy and contains some custom styling (the app info will be displayed to the user on hover):</li></ul><pre>import streamlit as st<br><br><br>def render_app_info():<br>    st.title(&quot;PubMed Screener&quot;)<br>    st.markdown(&quot;&quot;&quot;<br>        PubMed Screener is a ChatGPT &amp; PubMed powered insight generator from biomedical abstracts.<br>    &quot;&quot;&quot;)<br><br>    # Adding custom HTML and CSS for an improved hover-over tooltip<br>    st.markdown(&quot;&quot;&quot;<br>        &lt;style&gt;<br>        .tooltip {<br>            position: relative;<br>            display: inline-block;<br>            border-bottom: 1px dotted black; /* Style for the hoverable text */<br>        }<br><br>        .tooltip .tooltiptext {<br>            visibility: hidden;<br>            width: 800px; /* Width to fit content */<br>            background-color: #f9f9f9;<br>            color: #000;<br>            text-align: left;<br>            border-radius: 6px;<br>            padding: 15px;<br>            position: absolute;<br>            z-index: 1;<br>            bottom: 100;<br>            right: -430px; /* Positioning to the right and slightly offset */<br>            opacity: 0;<br>            transition: opacity 0.5s;<br>            box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.8); /* Adding some shadow for better visibility */<br>        }<br><br>        .tooltip:hover .tooltiptext {<br>            visibility: visible;<br>            opacity: 1;<br>        }<br>        &lt;/style&gt;<br>        &lt;div class=&quot;tooltip&quot;&gt;🔍 Example Questions<br>            &lt;span class=&quot;tooltiptext&quot;&gt;<br>                &lt;strong&gt;Example scientific questions:&lt;/strong&gt;<br>                &lt;ul&gt;<br>                    &lt;li&gt;How can advanced imaging techniques and biomarkers be leveraged for early diagnosis and monitoring of disease progression in neurodegenerative disorders?&lt;/li&gt;<br>                    &lt;li&gt;What are the potential applications of stem cell technology and regenerative medicine in the treatment of neurodegenerative diseases, and what are the associated challenges?&lt;/li&gt;<br>                    &lt;li&gt;What are the roles of gut microbiota and the gut-brain axis in the pathogenesis of type 1 and type 2 diabetes, and how can these interactions be modulated for therapeutic benefit?&lt;/li&gt;<br>                    &lt;li&gt;What are the molecular mechanisms underlying the development of resistance to targeted cancer therapies, and how can these resistance mechanisms be overcome?&lt;/li&gt;<br>                &lt;/ul&gt;<br>            &lt;/span&gt;<br>        &lt;/div&gt;<br>        &quot;&quot;&quot;, unsafe_allow_html=True)<br>    <br>    st.text(&quot;&quot;)py</pre><h4>Modify the app/app.py</h4><ul><li>Finally, time to put everything we’ve built together and expose it as a streamlit application!</li></ul><pre>import streamlit as st<br>from metapub import PubMedFetcher<br>from components.chat_utils import ChatAgent<br>from components.chat_prompts import chat_prompt_template, qa_template<br>from components.llm import llm<br>from components.layout_extensions import render_app_info<br>from backend.abstract_retrieval.pubmed_retriever import PubMedAbstractRetriever<br>from backend.data_repository.local_storage import LocalJSONStore<br>from backend.rag_pipeline.chromadb_rag import ChromaDbRag<br>from backend.rag_pipeline.embeddings import embeddings<br><br><br># Instantiate objects<br>pubmed_client = PubMedAbstractRetriever(PubMedFetcher())<br>data_repository = LocalJSONStore(storage_folder_path=&quot;backend/data&quot;)<br>rag_client = ChromaDbRag(persist_directory=&quot;backend/chromadb_storage&quot;, embeddings=embeddings)<br>chat_agent = ChatAgent(prompt=chat_prompt_template, llm=llm)<br><br>def main():<br>    st.set_page_config(<br>        page_title=&quot;Pubmed Abstract Screener&quot;,<br>        page_icon=&#39;💬&#39;,<br>        layout=&#39;wide&#39;<br>    )<br><br>    # Define columns - this will make layout split horizontally<br>    column_logo, column_app_info, column_answer = st.columns([1, 4, 4])<br><br>    # Place the logo in the first column<br>    with column_logo:<br>        st.image(&#39;../assets/pubmed-screener-logo.jpg&#39;)<br><br>    # In the second column, place text explaining the purpose of the app and some example scientific questions that your user might ask.<br>    with column_app_info:<br><br>        # Runder app info including example questions as cues for the user<br>        render_app_info()<br><br>        # Section to enter scientific question<br>        st.header(&quot;Enter your scientific question!&quot;)<br>        placeholder_text = &quot;Type your scientific question here...&quot;<br>        scientist_question = st.text_input(&quot;What is your question?&quot;, placeholder_text)<br>        get_articles = st.button(&#39;Get articles &amp; Answer&#39;)<br><br>        # Processing user question, fetching data<br>        with st.spinner(&#39;Fetching abstracts. This can take a while...&#39;):<br>            if get_articles:<br>                if scientist_question and scientist_question != placeholder_text:<br><br>                    # Get abstracts data<br>                    retrieved_abstracts = pubmed_client.get_abstract_data(scientist_question)<br>                    if not retrieved_abstracts:<br>                        st.write(&#39;No abstracts found.&#39;)<br>                    else:<br>                        # Save abstarcts to storage and create vector index<br>                        query_id = data_repository.save_dataset(retrieved_abstracts, scientist_question)<br>                        documents = data_repository.create_document_list(retrieved_abstracts)<br>                        rag_client.create_vector_index_for_user_query(documents, query_id)<br>                        <br>                        # Answer the user question and display the answer on the UI directly<br>                        vector_index = rag_client.get_vector_index_by_user_query(query_id)<br>                        retrieved_documents = chat_agent.retrieve_documents(vector_index, scientist_question)<br>                        chain = qa_template | llm<br>                        <br>                        with column_answer:<br>                            st.markdown(f&quot;##### Answer to your question: &#39;{scientist_question}&#39;&quot;)<br>                            st.write(chain.invoke({<br>                                &quot;question&quot;: scientist_question, <br>                                &quot;retrieved_abstracts&quot;: retrieved_documents,<br>                            }).content)<br><br>    # Beginning of the chatbot section<br>    # Display list of queries to select one to have a conversation about<br>    query_options = data_repository.get_list_of_queries()<br><br>    if query_options:<br>        st.header(&quot;Chat with the abstracts&quot;)<br>        selected_query = st.selectbox(&#39;Select a past query&#39;, options=list(query_options.values()), key=&#39;selected_query&#39;)<br>        <br>        # Initialize chat about some query from the history of user questions<br>        if selected_query:<br>            selected_query_id = next(key for key, val in query_options.items() if val == selected_query)<br>            vector_index = rag_client.get_vector_index_by_user_query(selected_query_id)<br><br>            # Clear chat history when switching query to chat about<br>            if &#39;prev_selected_query&#39; in st.session_state and st.session_state.prev_selected_query != selected_query:<br>                chat_agent.reset_history()<br><br>            st.session_state.prev_selected_query = selected_query<br><br>            # Start chat session<br>            chat_agent.start_conversation(vector_index, selected_query)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><ul><li>The code contains the following parts:</li></ul><ol><li>Instantiate all objects that we built in previous parts of the series → <strong><em>PubMedAbstractRetriever</em></strong>, <strong><em>LocalJSONStore</em></strong>, <strong><em>ChromaDbRag</em></strong>, and <strong><em>ChatAgent</em></strong>. We will be using all those objects in our app code.</li><li>Define layout to render app title, logo, and app info.</li><li>Define input for the user’s question, and a button to submit it. When the button is clicked, this triggers the logic to search &amp; fetch PubMed articles (using <strong><em>PubMedAbstractRetriever — </em></strong>pubmed_client), save them to the local data repository (with <strong><em>LocalJSONStore —</em></strong>data_repository<strong><em> </em></strong>), and create a vector index for them (with <strong><em>ChromaDbRag — </em></strong>rag_client).</li><li>Answer the user question directly and show it on the UI.</li><li>Display ChatBot section that will let you select a past query to chat about, in case you want to interrogate the abstracts further. After the selection of a past query, the corresponding vector index is loaded, and a chat session is initiated (<strong><em>chat_agent.start_conversation(…)</em></strong>). Now you can chat with your abstracts!</li></ol><h3>Limitations</h3><p>I am happy you went with me through this series where we built a prototype of a scientific chatbot! It is necessary to say though, that this application is a PoC scope ONLY, and the implementation presented has its caveats that would need to be addressed before deploying in a production manner.</p><p><strong>Naive RAG limitations and considerations</strong></p><ul><li><strong>Retrieved content relevance</strong>: you can’t be sure if the retrieved content (the content most similar to user’s question) is the most relevant piece of information. There are some techniques of advanced RAG, like <em>H</em><strong><em>ypothetical Questions</em>, </strong>or<strong> <em>Hierarchical indexing</em> </strong>that can help with that — read more about those techniques and more <a href="https://medium.com/@krtarunsingh/advanced-rag-techniques-unlocking-the-next-level-040c205b95bc">in this article</a></li><li><strong>Retrieved content cut off</strong>: It is hard to assess whether all the relevant information was retrieved. Also, it can be challenging to fit all the context to the prompt due to the token limits of LLMs. The default cut off in our case equals to 5 abstracts (in our ChatAgent retrieve_documents method), which can certainly not be enough if the user asks a broad question.</li><li><strong>Limited applicability</strong>: Sometimes, the user question can be rather of a summarization character, and a different technique than RAG would be more appropriate for this purpose. For example, you could build an agent that decides whether task is summarization / retrieval based on user question. After this evaluation, there would be a function executing different logic that performs summarization or retrieval, respectively.</li></ul><p><strong>Deployment architecture considerations</strong></p><ul><li><strong>Runtime environment</strong>: For the scope of this series, we only built our chatbot locally, not considering any architectural decisions we would need to make if we would like to deploy this app to serve some real users.</li><li><strong>Synchronous processing</strong>: Since the data fetching can take a considerable amount of time, it would be more efficient to implement a queue-based asynchronous processing of user requests, and notify user when data fetching is done. Doing this in a synchronous manner can take a lot of time which can result in timeouts in many servers.</li><li><strong>Backend technologies</strong>: The backend used in our case was ChromaDB with local storage using JSON files. For a deployed application serving users, this should be re-evaluated and appropriate technology selected. This can be easily achieved by building on the interface definitions in the app backend code (<strong><em>RagWorkflow </em></strong>and <strong><em>UserQueryDataStore </em></strong>interfaces).</li></ul><p><strong>Including more scientific databases</strong></p><ul><li>In the series, we focused on PubMed only, but to provide a rich context base, another scientific paper databases (i.e. Scopus) could be added. This can be easily achieved by building on the interface definitions in the app backend code (<strong><em>AbstractRetriever </em></strong>interface).</li></ul><h3>Full codebase GitHub link</h3><p>Feel free to fork the repo and adapt it to your UC!</p><h4><a href="https://github.com/milieere/pubmed-rag-screener">Link to GitHub repo pubmed-rag-screener</a></h4><h3>Summary</h3><ul><li>In this last part of the series to build a scientific ChatBot, we put together all the previously built pieces to create a user interface, where our scientist can formulate her/his question, get an answer based on scientific abstracts, and then chat with the abstracts for further insights.</li><li>The application logic is modular and enables easy extension using provided interfaces.</li><li>The limitations of the approach were outlined and highlighted, and some suggestions to build a production-grade application were included.</li></ul><blockquote>Thanks so much for going through this series with me! I hope you enjoyed building this exciting use case :)</blockquote><blockquote>Do not hesitate to get in touch with me if you want to discuss anything about dev, data, AI, or just connect — <a href="https://www.linkedin.com/in/sbarankova/">reach out on LinkedIn</a></blockquote><h3>Contents of the series</h3><ul><li><a href="https://medium.com/@milieere/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-1-set-up-streamlit-37550b44b266">Part 1 — Explaining the use case, first steps to set up the Streamlit app with chatbot interface.</a></li><li><a href="https://medium.com/@milieere/llm-aided-retrieval-of-relevant-scientific-abstracts-via-pubmed-api-using-natural-language-part2-9e10f78575e6">Part 2 — LLM-aided retrieval of relevant scientific abstracts via PubMed API using natural language</a></li><li><a href="https://medium.com/gopenai/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-3-create-vector-1e5e401e72e6">Part 3 — Setting up the backend — Create vector embeddings from the retrieved scientific abstracts and store them in a vector store</a></li><li><strong>Part 4 (this article) — Put it all together via RAG — chat with scientific abstracts</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba7bbf706bbd" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-4-put-it-all-ba7bbf706bbd">Build a RAG-based scientific ChatBot with LangChain, Streamlit &amp; PubMed — Part 4(Put it all…</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a RAG-based scientific ChatBot with LangChain, Streamlit & PubMed — Part 3 (create vector…]]></title>
            <link>https://blog.gopenai.com/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-3-create-vector-1e5e401e72e6?source=rss-7cecf8828340------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e5e401e72e6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Simona Barankova]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 15:23:43 GMT</pubDate>
            <atom:updated>2024-10-18T08:28:14.471Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a RAG-based scientific ChatBot with LangChain, Streamlit &amp; PubMed — Part 3 (c<strong><em>reate vector embeddings from the retrieved scientific abstracts and store them in a vector store</em></strong>)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UICombbdDCWSsnXcFGccMg.jpeg" /></figure><p>This is Part 3 of the series in which we will build a RAG-based chatbot to answer scientific questions and chat with abstracts.</p><p><a href="https://medium.com/@milieere/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-1-set-up-streamlit-37550b44b266">In the previous part</a>, we’ve built the logic around getting relevant scientific abstracts from the PubMed database, based on the scientist’s natural language question. Now, we will focus on persisting our data, creating vector embeddings from the retrieved abstracts, and storing them in a vector store of your choice (using ChromaDB as an example).</p><p>As a reminder, this is the full solution that we’ll be building during the series:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Vd1pCCtF3_sddzLc.png" /></figure><h3>Building</h3><h4>Overview of steps already done</h4><ul><li>If you haven’t followed through the <a href="https://medium.com/@milieere/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-1-set-up-streamlit-37550b44b266">first</a> and the <a href="https://medium.com/gopenai/llm-aided-retrieval-of-relevant-scientific-abstracts-via-pubmed-api-using-natural-language-part2-9e10f78575e6">second part</a>, please do so, because we will be building on that further. At the end of the last part, we ended up with a project structure looking like this:</li></ul><pre>.<br>├── app<br>│   ├── app.py<br>│   ├── backend<br>│   │  ├── abstract_retrieval<br>│   │  │   ├── interface.py<br>│   │  │   ├── pubmed_retriever.py<br>│   │  │   └── pubmed_query_simplification.py<br>│   │  └── data_repository<br>│   │      └── models.py<br>│   ├── components<br>│   │   ├── chat_utils.py<br>│   │   ├── llm.py<br>│   │   └── prompts.py<br>│   └── tests<br>│       └── test_chat_utils.py<br>├── assets<br>│   └── pubmed-screener-logo.jpg<br>└── environment<br>    └── requirements.txt</pre><h4>Create an abstraction layer for your data</h4><ul><li>In the last part, we learned how to<a href="https://medium.com/gopenai/llm-aided-retrieval-of-relevant-scientific-abstracts-via-pubmed-api-using-natural-language-part2-9e10f78575e6"> retrieve scientific abstracts using a natural language query</a>. Now, we will build a logic to persist the data for subsequent use in our <a href="https://medium.com/@milieere/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-1-set-up-streamlit-37550b44b266">Streamlit application</a>.</li><li>We will follow the <a href="https://samjoness92332.medium.com/repository-pattern-is-insane-if-you-know-how-to-use-it-properly-python-8fc0dff90075">repository pattern</a> (one of my favorites!) to create a layer of abstraction for our data. This is particularly useful if you decide to use another data store than the one I will use in this tutorial (for the sake of simplicity, we will use the local filesystem). For example, you might want to use a Postgres database (<em>I will write a bonus article on the Postgres data store implementation!</em>). Following the repository pattern, you can simply plug in your implementation of the common interface.</li></ul><p><strong>Steps for building the data repository</strong></p><ul><li>Define pydantic models that will represent database records containing details about the user query (UserQueryRecord), and a model for the retrieved abstract (ScientificAbstract).</li><li>We will add this to our existing <strong>models.py</strong> file under the <strong>data_repository</strong> module:</li></ul><pre>from typing import Optional, List<br>from pydantic import BaseModel<br><br><br>class ScientificAbstract(BaseModel):<br>    doi: Optional[str] = None<br>    title: Optional[str] = None<br>    authors: Optional[str] = None<br>    year: Optional[int] = None<br>    abstract_content: str<br><br>class UserQueryRecord(BaseModel):<br>    user_query_id: str<br>    user_query: str</pre><ul><li>In UserQueryRecord we want to keep track of the original user query, which will be displayed in the UI, and the user_query_id — a unique integer identified used to name the files and retrieve them via their ID.</li><li>In ScientificAbstract class, we model the abstract entry with its content and metadata.</li><li>Next, create an <strong>interface.py</strong> file in the <strong>data_repository </strong>module:</li></ul><pre>from abc import ABC, abstractmethod<br>from typing import List, Dict<br>from langchain_core.documents.base import Document<br>from backend.data_repository.models import UserQueryRecord, ScientificAbstract<br><br><br>class UserQueryDataStore(ABC):<br>    &quot;&quot;&quot;Repository for interaction with abstract database&quot;&quot;&quot;<br><br>    @abstractmethod <br>    def save_dataset(self, abstracts_data: List[ScientificAbstract], user_query: str) -&gt; str:<br>        &quot;&quot;&quot;<br>        Save abstracts and details about the query to data storage.<br>        Return string that corresponds to newly assigned query ID.<br>        &quot;&quot;&quot;<br>        raise NotImplementedError<br>    <br>    @abstractmethod <br>    def read_dataset(self, query_id: str) -&gt; List[ScientificAbstract]:<br>        &quot;&quot;&quot;<br>        Retrieve abstracts for a given user query from data storage.<br>        &quot;&quot;&quot;<br>        raise NotImplementedError<br>    <br>    @abstractmethod<br>    def delete_dataset(self, query_id: str) -&gt; None:<br>        &quot;&quot;&quot;<br>        Delete all data for a given query id from the database.<br>        &quot;&quot;&quot;<br>        raise NotImplementedError<br><br>    @abstractmethod <br>    def get_list_of_queries(self) -&gt; Dict[str, str]:<br>        &quot;&quot;&quot;<br>        Retrieve a dict with query id : user_query. Used to displayed list of queries on UI and for lookup. <br>        &quot;&quot;&quot;<br>        raise NotImplementedError<br>    <br>    def create_document_list(self, abstracts_data: List[ScientificAbstract]) -&gt; List[Document]:<br>        return [<br>            Document(<br>                page_content=entry.abstract_content, metadata={<br>                    &quot;source&quot;: entry.doi, &quot;title&quot;: entry.title, <br>                    &quot;authors&quot;: entry.authors, &quot;year_of_publication&quot;: entry.year<br>                }<br>            )<br>            for entry in abstracts_data<br>        ]<br>    <br>    def read_documents(self, query_id: str) -&gt; List[Document]:<br>        &quot;&quot;&quot; Read the dataset and convert it to the required List[Document] &quot;&quot;&quot;<br>        query_record = self.read_dataset(query_id)<br>        return self.create_document_list(query_record)</pre><ul><li>This interface defines the main methods that we’ll use to interact with our database of abstracts for a given user query.</li><li>There are three abstract methods to be implemented, and two common methods that will be inherited — <strong><em>create_document_list </em></strong>that will take our list of abstracts and return a list of <a href="https://api.python.langchain.com/en/latest/documents/langchain_core.documents.base.Document.html">LangChain Documents</a>, and <strong><em>read_documents </em></strong>— a wrapper for read_dataset and create_document_list for convenience.</li></ul><blockquote>Note that we are creating Documents from the abstracts as they are — in their <strong>full length</strong>, since the abstracts are quite short. For longer pieces of text, additional method for <strong>chunking </strong>the text before loading it into the LangChain Documents should be implemented.</blockquote><ul><li>Now, create an implementation of the abstract methods in this interface — <strong>local_data_store.py</strong> under the <strong>data_repository </strong>module. This file will contain implementations of the abstract methods that will store the data locally, as JSON files (<em>or feel free to provide your own implementation for any other data store type!</em>):</li></ul><pre>import json<br>import os<br>import re<br>import shutil<br>from typing import Dict, List<br>from backend.data_repository.models import UserQueryRecord, ScientificAbstract<br>from backend.data_repository.interface import UserQueryDataStore<br>from config.logging_config import get_logger<br><br><br>class LocalJSONStore(UserQueryDataStore):<br>    &quot;&quot;&quot; <br>    For local testing, to simulate database via local JSON files. <br>    &quot;&quot;&quot;<br><br>    def __init__(self, storage_folder_path: str):<br>        self.storage_folder_path = storage_folder_path<br>        self.index_file_path = os.path.join(storage_folder_path, &#39;index.json&#39;)<br>        self.logger = get_logger(__name__)<br>        self.metadata_index = None<br><br>    def get_new_query_id(self) -&gt; str:<br>        &quot;&quot;&quot;<br>        Compute a new query ID by incrementing previous query ID integer suffix by 1.<br>        &quot;&quot;&quot;<br>        try:<br>            with open(self.index_file_path, &#39;r&#39;) as file:<br>                data = json.load(file)<br>        except (FileNotFoundError, json.JSONDecodeError):<br>            data = {}<br>        keys = [k for k in data.keys() if k.startswith(&#39;query_&#39;)]<br>        if not keys:<br>            return &#39;query_1&#39;<br>        numbers = [int(k.split(&#39;_&#39;)[-1]) for k in keys]<br>        max_number = max(numbers)<br>        return f&#39;query_{max_number + 1}&#39;<br><br>    def read_dataset(self, query_id: str) -&gt; List[ScientificAbstract]:<br>        &quot;&quot;&quot; <br>        Read dataset containing abstracts from local storage. <br>        &quot;&quot;&quot;<br>        try:<br>            with open(f&#39;{self.storage_folder_path}/{query_id}/abstracts.json&#39;, &#39;r&#39;) as file:<br>                data = json.load(file)<br>                return [ScientificAbstract(**abstract_record) for abstract_record in data]<br>        except FileNotFoundError:<br>            self.logger.error(f&#39;The JSON file for this query: {query_id} was not found.&#39;)<br>            raise FileNotFoundError(&#39;JSON file was not found.&#39;)<br><br>    def save_dataset(self, abstracts_data: List[ScientificAbstract], user_query: str) -&gt; str:<br>        &quot;&quot;&quot; <br>        Save abstract dataset and query metadata to local storage, rebuild index, and return query ID.<br>        &quot;&quot;&quot;<br>        try:<br>            query_id = self.get_new_query_id()<br>            user_query_details = UserQueryRecord(<br>                user_query_id=query_id, <br>                user_query=user_query<br>            )<br><br>            os.makedirs(f&#39;{self.storage_folder_path}/{query_id}&#39;, exist_ok=True)<br>            <br>            with open(f&quot;{self.storage_folder_path}/{query_id}/abstracts.json&quot;, &quot;w&quot;) as file:<br>                list_of_abstracts = [model.model_dump() for model in abstracts_data]<br>                json.dump(list_of_abstracts, file, indent=4)<br><br>            with open(f&quot;{self.storage_folder_path}/{query_id}/query_details.json&quot;, &quot;w&quot;) as file:<br>                json_data = user_query_details.model_dump_json(indent=4)<br>                file.write(json_data)<br><br>            self.logger.info(f&quot;Data for query ID {query_id} saved successfully.&quot;)<br>            self._rebuild_index()  # Rebuild index after saving new data<br><br>            return query_id<br><br>        except Exception as e:<br>            self.logger.error(f&quot;Failed to save dataset for query ID {query_id}: {e}&quot;)<br>            raise RuntimeError(f&quot;Failed to save dataset due to an error: {e}&quot;)<br>        <br>    def delete_dataset(self, query_id: str) -&gt; None:<br>        &quot;&quot;&quot; <br>        Delete abstracts dataset and query metadata from local storage. <br>        &quot;&quot;&quot;<br>        path_to_data = f&#39;{self.storage_folder_path}/{query_id}&#39;<br>        if os.path.exists(path_to_data):<br>            shutil.rmtree(path_to_data)<br>            self.logger.info(f&quot;Directory &#39;{path_to_data}&#39; has been deleted.&quot;)<br>            self._rebuild_index()  # Rebuild index after deleting data<br>        else:<br>            self.logger.warning(f&quot;Directory &#39;{path_to_data}&#39; does not exist and cannot be deleted.&quot;)<br><br>    def get_list_of_queries(self) -&gt; Dict[str, str]:<br>        &quot;&quot;&quot; <br>        Get a dictionary containing query ID (as a key) and original user query (as a value) from the index. <br>        &quot;&quot;&quot;<br>        return self.metadata_index<br><br>    def _rebuild_index(self) -&gt; Dict[str, str]:<br>        &quot;&quot;&quot; <br>        Rebuild the index from all query details files, to serve for a lookup purposes.<br>        &quot;&quot;&quot;<br>        index = {}<br>        query_data_paths = [os.path.join(self.storage_folder_path, name) for name in os.listdir(self.storage_folder_path)<br>            if os.path.isdir(os.path.join(self.storage_folder_path, name))]<br>        <br>        for query_data_path in query_data_paths:<br>            metadata_path = os.path.join(query_data_path, &#39;query_details.json&#39;)<br>            if os.path.exists(metadata_path):<br>                with open(metadata_path, &#39;r&#39;) as file:<br>                    metadata = json.load(file)<br>                    index[metadata[&#39;user_query_id&#39;]] = metadata[&#39;user_query&#39;]<br>            else:<br>                self.logger.warning(f&quot;No query_details.json file found in {query_data_path}&quot;)<br>        <br>        with open(self.index_file_path, &#39;w&#39;) as file:<br>            json.dump(index, file, indent=4)<br>        self.metadata_index = index<br>        return index</pre><ul><li>This implementation contains the logic necessary to store our retrieved abstracts in a local filesystem, in JSON files. Each user query will have its subfolder named with the query ID, and this subfolder will contain two files: <strong><em>abstracts.json</em></strong> containing the list of retrieved abstracts (<strong><em>List[ScientificAbstracts]</em></strong>), and <strong><em>query_details.json</em></strong> containing details about the user query (<strong><em>UserQueryRecord</em></strong>)</li><li>Additionally, in the storage folder, there will be <strong><em>index.json</em></strong> file that will contain a list of all queries in a dictionary with query ID as a key, and the full user query as a value.</li></ul><p>OK, our data repository interface and implementation are done now! Let’s move on to the vector DB part.</p><h4>Building the RAG pipeline</h4><blockquote>For the purpose of this series, we will follow a naive RAG scenario (with all it’s limitations). However, I will be preparing articles about more advanced techniques like GraphRAG building on this example. <a href="https://medium.com/@drjulija/what-are-naive-rag-advanced-rag-modular-rag-paradigms-edff410c202e">Read more about different RAG approaches</a></blockquote><ul><li>To build the RAG pipeline, we will need to choose two main things: The <a href="https://python.langchain.com/v0.1/docs/integrations/text_embedding/">vector embedding model</a> and the <a href="https://python.langchain.com/v0.1/docs/modules/data_connection/vectorstores/">vector store</a></li><li>For this demonstration purpose, I chose the <a href="https://python.langchain.com/v0.2/docs/integrations/text_embedding/azureopenai/">AzureOpenAI vector embedding model</a> and the <a href="https://python.langchain.com/v0.2/docs/integrations/vectorstores/chroma/">Chroma vector store</a> but feel free to plug in any embedding model and vector store combination of your choice!</li></ul><p><strong>Steps to build the RAG pipeline</strong></p><ul><li>First, an additional dependency, the chromadb driver, should be installed:</li></ul><pre>pip install chromadb==0.4.24</pre><ul><li>So, the full list of requirements.txt now looks like this:</li></ul><pre>streamlit==1.36.0<br>langchain==0.2.6<br>langchain-community==0.2.6<br>langchain-openai==0.1.13<br>python-dotenv==1.0.1<br>pydantic==2.8.2<br>metapub==0.5.12<br>chromadb==0.4.24</pre><ul><li>To put our RAG logic, create a new submodule under backend — <strong>backend/rag_pipeline</strong></li><li>Let’s start with defining the interface for our RAG workflow. Create a new file under the newly created rag_pipeline submodule, called <strong><em>interface.py:</em></strong></li></ul><pre>from typing import List<br>from abc import ABC, abstractmethod<br>from langchain_core.documents.base import Document<br>from langchain_core.embeddings import Embeddings<br>from langchain.vectorstores import VectorStore<br><br>class RagWorkflow(ABC):<br>    &quot;&quot;&quot; <br>    Interface for the rag workflow <br>    &quot;&quot;&quot;<br><br>    def __init__(self, embeddings: Embeddings):<br>        self.embeddings = embeddings<br>    <br>    @abstractmethod<br>    def create_vector_index_for_user_query(self, documents: List[Document], query_id: str) -&gt; VectorStore:<br>        &quot;&quot;&quot; <br>        Create vector index based on documents retrieved for a specific user query <br>        &quot;&quot;&quot;<br>        raise NotImplementedError<br>    <br>    @abstractmethod<br>    def get_vector_index_by_user_query(self, documents: List[Document], query_id: str) -&gt; VectorStore:<br>        &quot;&quot;&quot; <br>        Get existing vector index from a query ID<br>        &quot;&quot;&quot;<br>        raise NotImplementedError</pre><ul><li>The interface contains two abstract methods — one for creating a vector index for a given query ID, and the other for getting an existing vector index by query ID.</li><li>Let’s have a look at the implementation for Chroma DB. Create a new file under rag_pipeline and call it <strong>chromadb_rag.py</strong>:</li></ul><pre>from typing import List<br>import chromadb<br>from langchain.vectorstores import VectorStore<br>from langchain_community.vectorstores import Chroma<br>from langchain_core.embeddings import Embeddings<br>from langchain_core.documents.base import Document<br>from backend.rag_pipeline.interface import RagWorkflow<br>from config.logging_config import get_logger<br><br><br>class ChromaDbRag(RagWorkflow):<br>    &quot;&quot;&quot; <br>    Simple RAG workflow with Chroma as vector store <br>    &quot;&quot;&quot;<br><br>    def __init__(self, persist_directory: str, embeddings: Embeddings):<br>        self.persist_directory = persist_directory<br>        self.embeddings = embeddings<br>        self.client = self._create_chromadb_client()<br>        self.logger = get_logger(__name__)<br>    <br>    def _create_chromadb_client(self):<br>        return chromadb.PersistentClient(path=self.persist_directory)<br>    <br>    def create_vector_index_for_user_query(self, documents: List[Document], query_id: str) -&gt; VectorStore:<br>        &quot;&quot;&quot;<br>        Create Chroma vector index and set query ID as collection name.<br>        &quot;&quot;&quot;<br>        self.logger.info(f&#39;Creating vector index for {query_id}&#39;)<br>        try:<br>            index = Chroma.from_documents(<br>                documents, <br>                self.embeddings,<br>                client=self.client, <br>                collection_name=query_id<br>            )<br>            return index<br>        except Exception as e:<br>            self.logger.error(f&#39;There was an issue creating vector index for query: {query_id}. The issue: {e}&#39;)<br>            raise<br>    <br>    def get_vector_index_by_user_query(self, query_id: str) -&gt; VectorStore:<br>        &quot;&quot;&quot;<br>        Retrieve existing Chroma index by collection name set to query ID.<br>        &quot;&quot;&quot;<br>        self.logger.info(f&#39;Loading vector index for query: {query_id}&#39;)<br>        try:<br>            index = Chroma(<br>                client=self.client,<br>                collection_name=query_id,<br>                embedding_function=self.embeddings,<br>            )<br>            return index<br>        except Exception as e:<br>            self.logger.error(f&#39;There was an issue retrieving vector index for query: {query_id}. The issue: {e}&#39;)<br>            raise</pre><ul><li>This implementation takes care of creating new vector indexes and getting existing indexes from ChromaDB.</li><li>The last step is to set up your embedding model (in our case AzureOpenAIEmbeddings). For this, set up the necessary environment variables in .env file:</li></ul><pre>AZURE_OPENAI_API_KEY_EMBEDDINGS=&lt;your-api-key&gt;<br>AZURE_OPENAI_DEPLOYMENT_NAME_EMBEDDINGS=&lt;your-deployment-name&gt;<br>AZURE_ENDPOINT_EMBEDDINGS=https://&lt;your-endpoint&gt;.openai.azure.com/<br>API_VERSION_EMBEDDINGS=&lt;your-api-version&gt;</pre><ul><li>Create a new file<strong> embeddings.py</strong> in the rag_pipeline module and populate it with your embeddings instance:</li></ul><pre>import os<br>from langchain_openai import AzureOpenAIEmbeddings<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br><br>AZURE_OPENAI_API_KEY_EMBEDDINGS = os.environ.get(&#39;AZURE_OPENAI_API_KEY_EMBEDDINGS&#39;)<br>AZURE_OPENAI_DEPLOYMENT_NAME_EMBEDDINGS = os.environ.get(&#39;AZURE_OPENAI_DEPLOYMENT_NAME_EMBEDDINGS&#39;)<br>AZURE_ENDPOINT_EMBEDDINGS = os.environ.get(&#39;AZURE_ENDPOINT_EMBEDDINGS&#39;)<br>API_VERSION_EMBEDDINGS = os.environ.get(&#39;API_VERSION_EMBEDDINGS&#39;)<br><br>embeddings = AzureOpenAIEmbeddings(<br>    azure_endpoint=AZURE_ENDPOINT_EMBEDDINGS,<br>    azure_deployment=AZURE_OPENAI_DEPLOYMENT_NAME_EMBEDDINGS,<br>    api_key=AZURE_OPENAI_API_KEY_EMBEDDINGS,<br>    api_version=API_VERSION_EMBEDDINGS<br>)</pre><h4>Test out the client code!</h4><ul><li>We are now good to go ahead and test the client code, including the code we created during the <a href="https://medium.com/gopenai/llm-aided-retrieval-of-relevant-scientific-abstracts-via-pubmed-api-using-natural-language-part2-9e10f78575e6">last part of this series</a> (PubMedRetriever) that will fetch the PubMed articles for us.</li><li>Let’s create a test script, i.e. test_rag_pipeline.py, and populate it with the following client code:</li></ul><pre>from metapub import PubMedFetcher<br>from backend.rag_pipeline.embeddings import embeddings<br>from backend.abstract_retrieval.pubmed_retriever import PubMedAbstractRetriever<br>from backend.data_repository.local_storage import LocalJSONStore<br>from backend.rag_pipeline.chromadb_rag import ChromaDbRag<br><br>query = &quot;Does abamectin cause cancer?&quot;<br><br># Step 1: Use PubMedAbstractRetriever to get abstract data for a query &quot;Does abamectin cause cancer?&quot;<br>pubmed_fetcher = PubMedFetcher()<br>abstract_retriever = PubMedAbstractRetriever(pubmed_fetcher)<br>abstracts = abstract_retriever.get_abstract_data(query)<br><br># Step 2: Use the retrieved data with LocalJSONStorage to persist them in local storage<br>storage_folder_path = &quot;backend/data&quot;<br>store = LocalJSONStore(storage_folder_path)<br>query_id = store.save_dataset(abstracts, query)<br><br># Step 3: Use ChromDBRAGWorkflow to create a vector index using the list of documents created via LocalJSONStorage<br>persist_directory = &quot;backend/chromadb_storage&quot;<br>rag_workflow = ChromaDbRag(persist_directory, embeddings)<br>documents = store.read_documents(query_id)<br>vector_index = rag_workflow.create_vector_index_for_user_query(documents, query_id)<br><br># Run similarity search on newly created index, using the original user query: <br>print(vector_index.similarity_search(query))</pre><ul><li>The client code uses PubMedAbstractRetriever get_abstract_data method to retrieve abstracts, LocalJSONStore to save abstracts to the local filesystem, and ChromaDbRag to create a vector index and finally, on the last line, run a similarity search against this index using the original user query.</li><li>The output log should look like this:</li></ul><pre>INFO Trying to simplify scientist query Does abamectin cause cancer?<br>INFO Initial query is simple enough and does not need simplification.<br>INFO Searching abstracts for query: Does abamectin cause cancer?<br>INFO Fetching abstract data for following pubmed_ids: [&#39;38453362&#39;, &#39;35649672&#39;, &#39;32201246&#39;, &#39;28753233&#39;, &#39;25865432&#39;, &#39;22926678&#39;, &#39;20444629&#39;, &#39;19879343&#39;, &#39;10841270&#39;, &#39;8949985&#39;]<br>INFO Total of 10 abstracts retrieved.<br>INFO Data for query ID &lt;query_id&gt; saved successfully.<br>INFO Creating vector index for &lt;query_id&gt;</pre><ul><li>Below this log, you’ll be able to see the printed list of Documents that have the highest score on similarity search using the initial query.</li></ul><h3>Conclusions</h3><ul><li>We’ve finished building the backend part for our scientific chatbot application based on PubMed, by implementing data persistence and vectorization.</li><li>We’ve tested how all the backend components built so far work together.</li><li>We’ve set examples for local storage of data using JSON files and local filesystem, and ChromDB for local vector store.</li><li>We’ve set up interfaces so that you can easily swap your preferred vector store and data repository implementation.</li></ul><blockquote>So, that was it for this part! See you soon during the last part of this series, where we will use the similarity search in conjunction with LLM, to construct an answer for our scientist’s initial question and use our chat interface built in Streamlit to interrogate the data further.</blockquote><blockquote>Thank you for reading!</blockquote><h4>Contents of the series</h4><ul><li><a href="https://medium.com/@milieere/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-1-set-up-streamlit-37550b44b266">Part 1 — Explaining the use case, first steps to set up the Streamlit app with chatbot interface.</a></li><li><a href="https://medium.com/@milieere/llm-aided-retrieval-of-relevant-scientific-abstracts-via-pubmed-api-using-natural-language-part2-9e10f78575e6">Part 2 — LLM-aided retrieval of relevant scientific abstracts via PubMed API using natural language</a></li><li><strong>Part 3 (this article) — Setting up the backend — Create vector embeddings from the retrieved scientific abstracts and store them in a vector store</strong></li><li><a href="https://medium.com/gopenai/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-4-put-it-all-ba7bbf706bbd">Part 4 — Put it all together via RAG — chat with scientific abstracts</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e5e401e72e6" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-3-create-vector-1e5e401e72e6">Build a RAG-based scientific ChatBot with LangChain, Streamlit &amp; PubMed — Part 3 (create vector…</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a RAG-based scientific ChatBot with LangChain, Streamlit & PubMed — Part 2 (LLM-aided…]]></title>
            <link>https://blog.gopenai.com/llm-aided-retrieval-of-relevant-scientific-abstracts-via-pubmed-api-using-natural-language-part2-9e10f78575e6?source=rss-7cecf8828340------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e10f78575e6</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Simona Barankova]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 12:10:21 GMT</pubDate>
            <atom:updated>2024-10-18T08:27:37.620Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a RAG-based scientific ChatBot with LangChain, Streamlit &amp; PubMed — Part 2 (LLM-aided retrieval of scientific abstracts via PubMed API using natural language)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_VifZKBBAD7I-dafjflnw.jpeg" /></figure><p>This is Part 2 of the series in which we will build a RAG-based chatbot to answer scientific questions and chat with abstracts.</p><p><a href="https://medium.com/@milieere/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-1-set-up-streamlit-37550b44b266">In the previous part</a>, we’ve set up the Stremlit UI and the Chat interface, now we’ll build the logic around getting relevant scientific abstracts from the PubMed database, based on the scientist’s natural language question. And, we will use LLM in that process to enhance our PubMed search results!</p><p>As a reminder, this is the full solution that we’ll be building during the series:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NURX25ByNlNghPXM7UNOQ.png" /><figcaption>Scientific RAG chatbot solution overview</figcaption></figure><h3>Problem statement</h3><ul><li>In our chatbot UI, there will be an input field for the scientist to formulate his question. Examples of such questions would be:</li></ul><ol><li><em>Has there been any significant progress in Alzheimer’s disease treatment using monoclonal antibodies in the last five years?</em></li><li><em>What are the emerging therapies for triple-negative breast cancer?</em></li><li><em>What are the recent developments in artificial intelligence applications in diagnostic radiology?</em></li></ol><ul><li>With the help of LLM, we will translate those scientific questions into a PubMed query, and fetch the relevant abstracts that will be used for question answering grounded in the scientific data.</li></ul><h3>Building</h3><h4>Overview of steps already done</h4><ul><li>If you haven’t followed through<a href="https://medium.com/@milieere/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-1-set-up-streamlit-37550b44b266"> the previous part</a>, please do so, because we will be building on that further. At the end of the last part we ended up with a project structure looking like this:</li></ul><pre>.<br>├── app<br>│   ├── app.py<br>│   ├── components<br>│   │   ├── chat_utils.py<br>│   │   ├── llm.py<br>│   │   └── prompts.py<br>│   └── tests<br>│       └── test_chat_utils.py<br>├── assets<br>│   └── pubmed-screener-logo.jpg<br>└── environment<br>    └── requirements.txt</pre><h4>Install additional dependencies</h4><ul><li>In this part, we will use some more dependencies in addition to what we’ve installed during the last part.</li><li>This is the list of newly added dependencies to our <em>requirements.txt</em> file:</li></ul><pre>pydantic==2.8.2<br>metapub==0.5.12</pre><h4>Create a new module ‘backend’</h4><ul><li>In this article, we will build a new module under the /app subfolder, and call it <strong><em>backend.</em></strong></li><li>The part of the project that we will be building today looks like this:</li></ul><pre>.<br>└── app<br>    ├── app.py<br>    └── backend<br>       ├── abstract_retrieval<br>       │   ├── interface.py<br>       │   ├── pubmed_retriever.py<br>       │   └── pubmed_query_simplification.py<br>       └── data_repository<br>           └── models.py</pre><h4>app/backend/data_repository</h4><ul><li>To create an abstraction of our data layer, we will use the data_repository module. We will place our data models and our database interaction logic here (we will talk in detail about database interaction logic in the next part).</li></ul><p><strong>models.py</strong></p><ul><li>In models.py, we will define a data model for our Scientific Abstract entity, that will, as the name suggests, hold data of one abstract — its title, doi, author, year of publication, and abstract content. We will use the <a href="https://pypi.org/project/pydantic/">pydantic </a>library for that:</li></ul><pre>from typing import Optional<br>from pydantic import BaseModel<br><br><br>class ScientificAbstract(BaseModel):<br>    doi: Optional[str]<br>    title: Optional[str]<br>    authors: Optional[list]<br>    year: Optional[int]<br>    abstract_content: str</pre><blockquote>Pydantic is my favourite library to deal with data layer in my code! Read more about the benefits of pydantic <a href="https://www.apptension.com/blog-posts/pydantic">in this article</a></blockquote><ul><li>This is going to be our data model that will be agnostic to the type of (vector) database that you decide to use. We will talk about databases and building vector indexes in the next part of this series.</li></ul><h4><strong>app/backend/abstract_retrieval</strong></h4><ul><li>The abstract_retrieval module will contain logic for the abstract retrieval.</li></ul><p><strong>interface.py</strong></p><ul><li>The <strong><em>interface.py</em></strong> file serves to decouple the Abstract Retriever client from its concrete implementation in <strong><em>pubmed_retriever.py</em></strong>.</li><li>This is to make our solution more future-proof, when we might want to enhance our app and add another scientific abstract source — i.e. Wikipedia, or Scopus. This way, we can ensure better scalability and maintainability of our app, adhering to a common method, with predictable inputs and outputs for abstract retrieval (with different implementations for concrete retrievers):</li></ul><pre>from abc import ABC, abstractmethod<br>from typing import List<br>from backend.data_repository.models import ScientificAbstract<br><br><br>class AbstractRetriever(ABC):<br><br>    @abstractmethod<br>    def get_abstract_data(self, scientist_question: str) -&gt; List[ScientificAbstract]:<br>        &quot;&quot;&quot; Retrieve a list of scientific abstracts based on a given query. &quot;&quot;&quot;<br>        raise NotImplementedError</pre><p><strong>pubmed_retriever.py</strong></p><ul><li>This .py file contains a concrete implementation of the AbstractRetriever abstract class.</li><li>We will use the <a href="https://pypi.org/project/metapub/">metapub library</a> to aid with the Pubmed search and abstract fetching via its API:</li></ul><pre>from typing import List<br>from metapub import PubMedFetcher<br>from backend.data_repository.models import ScientificAbstract<br>from backend.abstract_retrieval.interface import AbstractRetriever<br><br><br>class PubMedAbstractRetriever(AbstractRetriever):<br>    def __init__(self, pubmed_fetch_object: PubMedFetcher):<br>        self.pubmed_fetch_object = pubmed_fetch_object<br>        self.logger = get_logger(__name__)<br><br>    def _get_abstract_list(self, query: str) -&gt; List[str]:<br>        &quot;&quot;&quot; Fetch a list of PubMed IDs for the given query. &quot;&quot;&quot;<br>        self.logger.info(f&#39;Searching abstracts for query: {query}&#39;)<br>        return self.pubmed_fetch_object.pmids_for_query(query)<br><br>    def _get_abstracts(self, pubmed_ids: List[str]) -&gt; List[ScientificAbstract]:<br>        &quot;&quot;&quot; Fetch PubMed abstracts  &quot;&quot;&quot;<br>        self.logger.info(f&#39;Fetching abstract data for following pubmed_ids: {pubmed_ids}&#39;)<br>        scientific_abstracts = []<br>        <br>        for id in pubmed_ids:<br>            abstract = self.pubmed_fetch_object.article_by_pmid(id)<br>            if abstract.abstract is None:<br>                continue<br>            abstract_formatted = ScientificAbstract(<br>                doi=abstract.doi,<br>                title=abstract.title,<br>                authors=abstract.authors,<br>                year=abstract.year,<br>                abstract_content=abstract.abstract<br>            )<br>            scientific_abstracts.append(abstract_formatted)<br>        <br>        return scientific_abstracts<br><br>    def get_abstract_data(self, scientist_question: str) -&gt; List[ScientificAbstract]:<br>        &quot;&quot;&quot;  Retrieve abstract list for scientist query. &quot;&quot;&quot;<br>        pmids = self._get_abstract_list(scientist_question)<br>        abstracts = self._get_abstracts(pmids)<br>        return abstracts</pre><ul><li>The <em>pmids_for_query </em>method from the metapub library will search for relevant abstracts using a free-form user query. i.e. ‘<em>what is the relationship between dental cavities and osteoporosis</em>’.</li><li>The PubMed search engine uses a knowledge graph under the hood, that will enrich this query and return synonyms to the keywords in the query, which are then translated by the PubMed search engine to the PubMed query.</li><li>The <em>article_by_pmid </em>(wrapped in _get_abstracts)<em> </em>method then fetches the abstracts for the given PubMed ID’s (pmids).</li><li>You can go ahead and try executing the code for an example query of your choice, for example:</li></ul><pre>pubmed_fetch = PubMedAbstractRetriever(PubMedFetcher())<br>abstracts = pubmed_fetch.get_abstract_data(&#39;what is the relationship between dental cavities and osteoporosis&#39;)<br><br>for abstract in abstracts:<br>    print(f&#39;doi: {abstract.doi} \n title: {abstract.title} \n author: {abstract.authors} \n content:{abstract.abstract_content} \n \n&#39;)</pre><h4>Enhancement of PubMed query via LLM</h4><ul><li>Sometimes, the user’s natural language query might be a bit lengthy and convoluted. Take into account one of the questions presented at the beginning of the article, like:</li></ul><p><em>Has there been any significant progress in Alzheimer’s disease treatment using monoclonal antibodies in the last five years?</em></p><ul><li>If you try to run the above code for this query, no results are returned by our PubMed fetch client. Whereas if you shorten this query to a simple:</li></ul><p><em>“Alzheimer’s disease treatment using monoclonal antibodies”</em></p><ul><li>You get back a lot of results. Therefore, it might be a good idea to simplify the user query a bit if necessary. Here, LLMs are great candidates for this job!</li></ul><blockquote>Note: In the above example, during the simplification, we removed some specificities like ‘last 5 years’ — which are relevant for our user’s query, since he is interested in this period. We will fetch all articles for that topic for now, regardless of the age. We will filter out the last 5 year articles during the QA process — more on this in the next parts!</blockquote><p><strong>Build the prompt for user query to PubMed query simplification</strong></p><ul><li>First, we will build a prompt with examples for the LLM, to indicate when simplification is needed, and when it is not.</li><li>Create a new <em>pubmed_query_simplification.py</em> file in the <em>abstract_retrieval </em>module, that will contain the simplification prompt with a few examples, and a function that will wrap the simplification prompt and call the LLM (<a href="https://medium.com/@milieere/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-1-set-up-streamlit-37550b44b266">defined in Part1 of this tutoria</a>l) to get the simplified query:</li></ul><pre><br>from langchain_core.prompts import PromptTemplate<br>from components.llm import llm<br><br><br>def simplify_pubmed_query(scientist_question: str) -&gt; str:<br>    &quot;&quot;&quot; Transform verbose queries to simplified queries for PubMed &quot;&quot;&quot;<br>    prompt_formatted_str = pubmed_query_simplification_prompt.format(question=scientist_question)<br>    return llm.invoke(prompt_formatted_str).content<br><br>pubmed_query_simplification_prompt = PromptTemplate.from_template(&quot;&quot;&quot;<br>    You are an expert in biomedical search queries. Your task is to simplify verbose and detailed user queries into concise and effective search queries suitable for the PubMed database. Focus on capturing the essential scientific or medical elements relevant to biomedical research.<br><br>    Here are examples of the queries that need simplification, and what the simplification should look like:<br><br>    Example 1:<br>    Verbose Query: Has there been any significant progress in Alzheimer&#39;s disease treatment using monoclonal antibodies in the last five years?<br>    Is simplification needed here: Yes.<br>    Simplified Query: Alzheimer&#39;s disease monoclonal antibodies treatment progress<br><br>    Example 2:<br>    Verbose Query: What are the latest findings on the impact of climate change on the incidence of vector-borne diseases in tropical regions?<br>    Is simplification needed here: Yes.<br>    Simplified Query: Climate change and vector-borne diseases in tropics<br><br>    Example 3:<br>    Verbose Query: Can you provide detailed insights into the recent advancements in gene therapy for treating hereditary blindness?<br>    Is simplification needed here: Yes.<br>    Simplified Query: Gene therapy for hereditary blindness advancements<br><br>    Example 4:<br>    Verbose Query: I am interested in understanding how CRISPR technology has been applied in the development of cancer therapies over the recent years.<br>    Is simplification needed here: Yes.<br>    Simplified Query: CRISPR technology in cancer therapy development<br><br>    Example 5:<br>    Verbose Query: Alzheimer&#39;s disease and amyloid plaques<br>    Is simplification needed here: No.<br>    Simplified Query: Alzheimer&#39;s disease and amyloid plaques<br><br>    Example 6:<br>    Verbose Query: Effects of aerobic exercise on elderly cognitive function<br>    Is simplification needed here: No.<br>    Simplified Query: Effects of aerobic exercise on elderly cognitive function<br><br>    Example 7:<br>    Verbose Query: Molecular mechanisms of insulin resistance in type 2 diabetes<br>    Is simplification needed here: No.<br>    Simplified Query: Molecular mechanisms of insulin resistance in type 2 diabetes<br><br>    Example 8:<br>    Verbose Query: Role of gut microbiota in human health and disease<br>    Is simplification needed here: No.<br>    Simplified Query: Role of gut microbiota in human health and disease<br><br>    This is the user query:<br>    {question}<br><br>    Only decide to simplify the user&#39;s question if it is verbose. If it is already simple enough, just return the original user question.<br>    Only output the simplified query, or the original query if it is simple enough already, nothing else!<br>&quot;&quot;&quot;)</pre><ul><li>Now, we want to ecome back to our Retriever logic and include the option of query simplification to the PubMed search (adding a new method _simplify_pubmed_query and adding additional parameter to the _get_abstract_list and get_abstract_data):</li></ul><pre>from typing import List<br>from metapub import PubMedFetcher<br>from backend.data_repository.models import ScientificAbstract<br>from backend.abstract_retrieval.interface import AbstractRetriever<br>from backend.abstract_retrieval.pubmed_query_simplification import simplify_pubmed_query<br>from config.logging_config import get_logger<br><br><br>class PubMedAbstractRetriever(AbstractRetriever):<br>    def __init__(self, pubmed_fetch_object: PubMedFetcher):<br>        self.pubmed_fetch_object = pubmed_fetch_object<br>        self.logger = get_logger(__name__)<br><br>    def _simplify_pubmed_query(self, query: str, simplification_function: callable = simplify_pubmed_query) -&gt; str:<br>        return simplification_function(query)<br><br>    def _get_abstract_list(self, query: str, simplify_query: bool = True) -&gt; List[str]:<br>        &quot;&quot;&quot; Fetch a list of PubMed IDs for the given query. &quot;&quot;&quot;<br>        if simplify_query:<br>            self.logger.info(f&#39;Trying to simplify scientist query {query}&#39;)<br>            query_simplified = self._simplify_pubmed_query(query)<br><br>            if query_simplified != query:<br>                self.logger.info(f&#39;Initial query simplified to: {query_simplified}&#39;)<br>                query = query_simplified<br>            else:<br>                self.logger.info(&#39;Initial query is simple enough and does not need simplification.&#39;)<br><br>        self.logger.info(f&#39;Searching abstracts for query: {query}&#39;)<br>        return self.pubmed_fetch_object.pmids_for_query(query)<br><br>    def _get_abstracts(self, pubmed_ids: List[str]) -&gt; List[ScientificAbstract]:<br>        &quot;&quot;&quot; Fetch PubMed abstracts  &quot;&quot;&quot;<br>        self.logger.info(f&#39;Fetching abstract data for following pubmed_ids: {pubmed_ids}&#39;)<br>        scientific_abstracts = []<br>        <br>        for id in pubmed_ids:<br>            abstract = self.pubmed_fetch_object.article_by_pmid(id)<br>            if abstract.abstract is None:<br>                continue<br>            abstract_formatted = ScientificAbstract(<br>                doi=abstract.doi,<br>                title=abstract.title,<br>                authors=&#39;, &#39;.join(abstract.authors),<br>                year=abstract.year,<br>                abstract_content=abstract.abstract<br>            )<br>            scientific_abstracts.append(abstract_formatted)<br><br>        self.logger.info(f&#39;Total of {len(scientific_abstracts)} abstracts retrieved.&#39;)<br>        <br>        return scientific_abstracts<br><br>    def get_abstract_data(self, scientist_question: str, simplify_query: bool = True) -&gt; List[ScientificAbstract]:<br>        &quot;&quot;&quot;  Retrieve abstract list for scientist query. &quot;&quot;&quot;<br>        pmids = self._get_abstract_list(scientist_question, simplify_query)<br>        abstracts = self._get_abstracts(pmids)<br>        return abstracts</pre><ul><li>Now, you can create a test script, i.e. <em>test_pubmed_fetch.py,</em> and test your PubMed fetching client with simplification, to see what results it yields:</li></ul><pre>from metapub import PubMedFetcher<br>from backend.abstract_retrieval.pubmed_retriever import PubMedAbstractRetriever<br><br>pubmed_fetcher = PubMedFetcher()<br>abstract_retriever = PubMedAbstractRetriever(pubmed_fetcher)<br><br># Retrieve abstracts without query simplification<br>scientist_question = &quot;Has there been any significant progress in Alzheimer&#39;s disease treatment using monoclonal antibodies in the last five years?&quot;<br>abstracts = abstract_retriever.get_abstract_data(scientist_question, simplify_query=False)<br><br># Retrieve abstracts with query simplification (default behavior)<br>abstracts = abstract_retriever.get_abstract_data(scientist_question)</pre><blockquote>Note: When your search query refers to a very popular topic, it will take considerable amount of time for the retrieval to complete.</blockquote><p>From the output logs, you’ll be able to see that in case without simplification, 0 abstracts were retrieved, whereas with simplification 241 abstracts were retrieved.</p><h3>Conclusions</h3><ul><li>In this part of the series ‘Build a RAG-based scientific ChatBot with LangChain, Streamlit &amp; PubMed’, we’ve built the abstract retrieval pipeline using the <a href="https://pypi.org/project/metapub/">metapub library</a>.</li><li>We used LLM to refine the natural language query from our scientist, to increase our chances of retrieving relevant results.</li><li>In the following part, we will focus on persisting the retrieved abstracts in a database, and creating a vector index for our RAG system.</li></ul><blockquote>Thank you for reading and see you in Part 3!</blockquote><h4>Contents of the series</h4><ul><li><a href="https://medium.com/@milieere/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-1-set-up-streamlit-37550b44b266">Part 1 — Explaining the use case, first steps to set up the Streamlit app with chatbot interface.</a></li><li><strong>Part 2 — (this article) LLM-aided retrieval of relevant scientific abstracts via PubMed API using natural language</strong></li><li><a href="https://medium.com/@milieere/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-3-create-vector-1e5e401e72e6">Part 3 — Setting up the backend — Create vector embeddings from the retrieved scientific abstracts and store them in a vector store</a></li><li><a href="https://medium.com/gopenai/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-4-put-it-all-ba7bbf706bbd">Part 4 — Put it all together via RAG — chat with scientific abstracts</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e10f78575e6" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/llm-aided-retrieval-of-relevant-scientific-abstracts-via-pubmed-api-using-natural-language-part2-9e10f78575e6">Build a RAG-based scientific ChatBot with LangChain, Streamlit &amp; PubMed — Part 2 (LLM-aided…</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The best local development environment for Windows — set up in ~10 mins!]]></title>
            <link>https://medium.com/@milieere/the-best-local-development-environment-for-windows-set-up-in-10-mins-680ca1653608?source=rss-7cecf8828340------2</link>
            <guid isPermaLink="false">https://medium.com/p/680ca1653608</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Simona Barankova]]></dc:creator>
            <pubDate>Thu, 11 Jul 2024 16:06:42 GMT</pubDate>
            <atom:updated>2024-07-11T16:06:42.223Z</atom:updated>
            <content:encoded><![CDATA[<h3>The best local development environment for Windows — set up in ~10 mins! (with Python, WSL2, and VScode)</h3><p>If you’re a Python developer, and your company only distributes Windows machines, or you just happen to like Windows for its indisputable advantages, this article is for you!</p><p>I will show you how to set up your Windows machine to have the best of both worlds — Windows for, well, the ‘normal’ stuff, and WSL2 for a native Linux developer experience 🤩 This is my time-tested approach that is very comfy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iu-4vmVwKLOr_nA6IQrFqA.png" /></figure><p>This article is tailored for Python, but of course, steps for installation of WSL and VScode will be common for any programming language of your choice.</p><h4>Pre-requisites</h4><ul><li>Windows version &gt;= 10</li><li>Before you start, ensure that you have all updates possible installed both for your machine and for Windows</li></ul><h3>Step 1: Install WSL2</h3><ul><li>To install WSL on your machine, open the command prompt in administrator mode:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*PDjzuHzo965i16Wn-NS3UA.png" /></figure><ul><li>And type in:</li></ul><pre>wsl --install</pre><p>This will trigger the installation of WSL Ubuntu. At the end (When the progress bar shows 100%), you should reboot your machine.</p><ul><li>After you’ve rebooted your machine, a subsystem command prompt will appear after several minutes, asking you to set up your credentials for Ubuntu:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*OtOxX4ys4DEy8IiP_l863w.png" /></figure><ul><li>If the subsystem prompt doesn’t appear by itself, open windows command prompt and type in:</li></ul><pre>wsl</pre><p>This should start the subsystem and ask you to provide the credentials.</p><ul><li>Finally, open windows command prompt and verify what version of WSL you have installed:</li></ul><pre>wsl -l -v</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*EmL0YJoOfVEV2CNLGmiQ9w.png" /><figcaption>You should see this info</figcaption></figure><ul><li>At any time, to open the wsl command prompt, just type in the Windows start search bar ‘wsl’, in that way you can access the command line interface for your subsystem.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*X0FiMPt_ee7IxYM56XWdHg.png" /><figcaption>WSL command prompt access via Start search bar</figcaption></figure><h3>Step 2: Install VScode</h3><ul><li>OK, we have our subsystem successfully set up. Now, we want to install VScode and make it work with our WSL seamlessly!</li><li>Go ahead and download the VScode for Windows from the official site: <a href="https://code.visualstudio.com/download">https://code.visualstudio.com/download</a></li><li>Follow the installation wizard with the default options to install VScode and on the end, launch VScode.</li><li>In the left menu, select extensions and search for WSL. Install the WSL plugin:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*ZFYvNjOIcPd9hdaUPaVmaQ.png" /><figcaption>Install the WSL plugin in VScode</figcaption></figure><ul><li>When the plugin install is finished, click on the following left bottom corner button in VScode:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*CAxogvnU_1CyL9XQCGiSug.png" /></figure><ul><li>this will open the following dropdown on the top. Click on ‘Connect to WSL’</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RE7mnUs0tPPvIVT5Uzkuw.png" /></figure><ul><li>Next, open the terminal (command prompt) in VScode:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*S66aW0lHgMug2Q2BKn5cKA.png" /></figure><ul><li>Voila, you have now set up your VScode with WSL!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*WqWG_qCIYKC8BR6Owa192g.png" /><figcaption>Bash terminal of WSL in VScode</figcaption></figure><ul><li>Next, we will install all necessary development tools, using this terminal.</li></ul><h3>Step3: Install development tools</h3><h4>Git</h4><ul><li>WSL Ubuntu comes with git installed, so you can just verify that by running from the terminal:</li></ul><pre>git --version</pre><h4>Python</h4><ul><li>WSL Ubuntu also comes with a default version of Python already pre-installed. On the day of writing this article, it is python 3.10.</li><li>You can check the python installed by running:</li></ul><pre>python3 --version</pre><ul><li>If this is OK with you, you can skip the following step of upgrade to python 3.11, and continue with the tutorial.</li></ul><h4>Upgrade Python version (3.10 -&gt; 3.11)</h4><ul><li>Run the following steps from your terminal, to install python 3.11:</li></ul><pre># Add repository for python distribution download<br>sudo add-apt-repository ppa:deadsnakes/ppa<br><br># Update &amp; upgrade the repositories<br>sudo apt update<br>sudo apt upgrade<br><br># Install python 3.11<br>sudo apt-get install python3.11</pre><ul><li>This will install python3.11. You can now check the two coexisting python versions from the terminal:</li></ul><pre># python3 shows 3.10 and python3.11 shows 3.11 as version<br>python3 --version<br>python3.11 --version</pre><ul><li>If you want to be able to reference python3.11 with simple ‘python’, you can do so via:</li></ul><pre>sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1<br>sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 2<br><br>#choose 2 for python 3.11<br>sudo update-alternatives --config python3<br><br># 3.11 will be shown as version<br>python3 --version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*vPwZwebBS6iUwxnLSX89bg.png" /><figcaption>Type ‘2’ for python 3.11</figcaption></figure><ul><li>Finally, install the following to reference python 3.11 with simple ‘python’:</li></ul><pre>sudo apt install python-is-python3</pre><ul><li>Voila!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*xE_ZlrIQZ0hOGiBqdLfOaA.png" /><figcaption>python — version points to python 3.11</figcaption></figure><h4>Pip and venv</h4><ul><li>Now, let’s install the last missing thing for our essentials Python developer pack — the <strong><em>pip </em></strong>package manager, and <strong><em>venv </em></strong>virtual environment manager.</li><li>Install pip &amp; venv:</li></ul><pre>sudo apt install python3-pip<br><br># In case you installed python 3.11:<br>sudo apt install python3.11-venv<br><br># In case you kept python 3.10:<br>sudo apt install python3.10-venv</pre><ul><li>OK! That was all we needed to start coding in Python using WSL! Let’s see now an example use on a new python project :)</li></ul><h3>Step 4: Start coding</h3><h4>Create a folder and virtual environment for your project</h4><pre># Create a folder for your test project<br>mkdir test-python-project</pre><ul><li>Open the newly created folder from the VScode UI:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7w04x4nHrfPn22O6bBVm_g.png" /></figure><ul><li>Now, open a new terminal (because opening a folder will close the terminal we were working on until now), and create a virtual environment with venv:</li></ul><pre># Create virtual environment<br>python -m venv venv</pre><ul><li>Note that for the name of my virtual environment, I simply use venv. It is like a muscle memory — always that I navigate to my project folder, the environment is always called the same so it is easier to work with it.</li><li>Activate virtual environment and install packages</li><li>To activate the venv, run:</li></ul><pre>source venv/bin/activate</pre><ul><li>You will see the name of the virtual environment in the brackets on the terminal:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*YyxzE_pZ7Zu9jpr1KTR36A.png" /><figcaption>activated venv</figcaption></figure><ul><li>Once you activated your venv, you can install packages of your choice. For our example, we will use the colorama package that will produce colorful messages on terminal:</li></ul><pre>pip install colorama</pre><h4>Create a Python script and run it from the terminal</h4><ul><li>Before you start creating your python script, enable auto save on VScode. Like this, you will never lose your work when machine fails:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*K7xRjIdaobZy3ZCNt0Cflw.png" /><figcaption>enable auto save</figcaption></figure><ul><li>Create a main.py file in the explorer by right clicking and ‘New File…’:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*dE8u8HHPonpJGmTxmWEhnw.png" /></figure><ul><li>Populate the main.py with the following code:</li></ul><pre>from colorama import Fore, Style<br><br>def print_colored_text():<br>    print(Fore.RED + &quot;This text is red!&quot;)<br>    print(Fore.GREEN + &quot;This text is green!&quot;)<br>    print(Fore.BLUE + &quot;This text is blue!&quot;)<br>    print(Style.RESET_ALL + &quot;This text is back to normal.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    print_colored_text()</pre><ul><li>And run the Python script from the terminal:</li></ul><pre>python -m main</pre><ul><li>This is the result:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*vNVTrvX7A_ChU5TJuXexIA.png" /><figcaption>Output of our main.py script</figcaption></figure><blockquote>That was all — thank you for reading, and enjoy your new local development environment set up. See you in the next article!</blockquote><h3>References</h3><ul><li>Install WSL: <a href="https://learn.microsoft.com/en-us/windows/wsl/install">https://learn.microsoft.com/en-us/windows/wsl/install</a></li><li>WSL development with VScode: <a href="https://code.visualstudio.com/docs/remote/wsl-tutorial">https://code.visualstudio.com/docs/remote/wsl-tutorial</a></li><li>Upgrade python version on WSL: <a href="https://medium.com/python-mvp/upgrade-python-3-10-to-3-11-on-ubuntu-22-04-2f63e4d326f9">https://medium.com/python-mvp/upgrade-python-3-10-to-3-11-on-ubuntu-22-04-2f63e4d326f9</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=680ca1653608" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a RAG-based scientific ChatBot with LangChain, Streamlit & PubMed— Part 1 (set up Streamlit…]]></title>
            <link>https://medium.com/@milieere/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-1-set-up-streamlit-37550b44b266?source=rss-7cecf8828340------2</link>
            <guid isPermaLink="false">https://medium.com/p/37550b44b266</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Simona Barankova]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 21:22:41 GMT</pubDate>
            <atom:updated>2024-10-18T08:27:10.198Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a RAG-based scientific ChatBot with LangChain, Streamlit &amp; PubMed— Part 1 (set up Streamlit ChatBot)</h3><p>In this series, I will walk you through building a Retrieval Augmented Generation (RAG)-based Streamlit chatbot app from scratch.</p><p>The use case is exciting — to enable scientists from the biotech field to reach relevant information, and answer their scientific questions quickly!</p><p>The code in this series is built in a way that will provide standard interfaces to plug in any LLM and vector store of your choice.</p><p>The explanations will be very detailed, therefore this is suitable also for absolute beginners!</p><p>During the last part of the series, a GitHub repository will be shared to get the full source code and adapt it for your projects.</p><h4>Contents of the series</h4><ul><li><strong>Part 1 (this article) — <em>Explaining the use case, first steps to set up the Streamlit app with chatbot interface.</em></strong></li><li><a href="https://medium.com/@milieere/llm-aided-retrieval-of-relevant-scientific-abstracts-via-pubmed-api-using-natural-language-part2-9e10f78575e6">Part 2 —LLM-aided retrieval of relevant scientific abstracts via PubMed API using natural language</a></li><li><a href="https://medium.com/@milieere/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-3-create-vector-1e5e401e72e6">Part 3 — Setting up the backend — Create vector embeddings from the retrieved scientific abstracts and store them in a vector store</a></li><li><a href="https://medium.com/gopenai/build-a-rag-based-scientific-chatbot-with-langchain-streamlit-pubmed-part-4-put-it-all-ba7bbf706bbd">Part 4 — Put it all together via RAG— chat with scientific abstracts</a></li></ul><h4>Pre-requisites</h4><p>To follow this series hands-on successfully, you will need:</p><ul><li>Access to a <a href="https://python.langchain.com/v0.2/docs/integrations/chat/"><em>Chat model of your choice</em></a>, for this tutorial, we will use the <a href="https://python.langchain.com/v0.2/docs/integrations/chat/azure_chat_openai/">AzureChatOpenAI </a>(GPT4.0)</li><li>Local development environment with Python (v. 3.11), and an IDE of your choice</li></ul><p><em>Disclaimer: I work on Linux — Ubuntu</em></p><h3>The use case — PubMed screener app</h3><p>Imagine you’re a scientist conducting a literature search to find hints about the question you are researching. A good chance is that you will screen public scientific publication databases, such as <a href="https://pubmed.ncbi.nlm.nih.gov/">PubMed</a>, to get to relevant papers.</p><p>Wouldn’t it be great to have a tool that would screen the relevant results for you, and provide an interactive interface, where you could interrogate the scientific abstracts without reading every single one of them?</p><p>We will develop a tool, that will enable the scientist to query the PubMed scientific database using natural language, and provide quick insight into the retrieved data to accelerate the literature search.</p><h4>The use case workflow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RQNkNKi2xIvsJoa1-NouVA.png" /></figure><ul><li>Scientist asks initial question (in natural language).</li><li>The question is translated to PubMed query language via LLM.</li><li>PubMed API is used to search and fetch relevant abstracts.</li><li>Vector embeddings are generated from the abstracts and stored in a vector DB.</li><li>Scientist’s original question is answered, using RAG. Scientist can then have follow up questions using the chat interface.</li></ul><blockquote>What is RAG and why is it useful?</blockquote><p>Retrieval-Augmented Generation (RAG) combines a language model with a retrieval system to retrieve and incorporate factual information from external sources. This grounding in factual knowledge improves the accuracy of the language model’s generated text.</p><h3>Building the app</h3><p>So, let’s get our hands dirty and build the base for our Scientific ChatBot!</p><h4>Environment set up</h4><p>Start with creating a virtual environment in the folder you will use to build this project with your favorite Python environment manager. For me, it is <strong><em>venv</em></strong>.</p><ul><li>create new folder for the project</li></ul><pre>mkdir pubmed-rag-screener</pre><ul><li>create virtual environment</li></ul><pre>python3 -m venv venv</pre><ul><li>and activate it</li></ul><pre>source venv/bin/activate</pre><h4>Set up the project structure</h4><ul><li>We will create a project with the following structure:</li></ul><pre>.<br>├── app<br>│   ├── app.py<br>│   ├── components<br>│   │   ├── chat_utils.py<br>│   │   ├── llm.py<br>│   │   └── prompts.py<br>│   └── tests<br>│       └── test_chat_utils.py<br>├── assets<br>│   └── pubmed-screener-logo.jpg<br>└── environment<br>    └── requirements.txt</pre><ul><li><strong>environment/requirements.txt</strong> should contain all dependencies for your project, in our case it will be:</li></ul><pre>streamlit==1.36.0<br>langchain==0.2.6<br>langchain-community==0.2.6<br>langchain-openai==0.1.13<br>python-dotenv==1.0.1</pre><ul><li>go ahead, create that <strong>requirements.txt</strong> file and install all dependencies via:</li></ul><pre>pip install -r environment/requirements.txt</pre><ul><li>The <strong>assets </strong>folder contains an image — a logo for the app. This is voluntary — feel free to add an image that you like.</li><li>Finally, the <strong>app </strong>folder will contain all the code of our app.</li></ul><p>Let’s have a look at each of the .py files in the app folder, and describe the code in detail.</p><h4>components/llm.py</h4><ul><li>In this file resides the langchain Chat Model class instance that defines the connection to our LLM.</li><li>This object is the LangChain Chat Model. For this tutorial, I am using AzureChatOpenAI, but feel free to choose any of the <a href="https://python.langchain.com/v0.1/docs/integrations/chat/">available chat model classes</a> from LangChain (<a href="https://github.com/langchain-ai/langchain/tree/master/libs/langchain/langchain/chat_models">GitHub reference</a>).</li><li>For your OpenAI model to work, you will have to set up environment variables. Create a file with name ‘<em>.env</em>’ in your project root. For the AzureOpenAI GPT4 model, my <em>.env</em> file looks like this:</li></ul><p><strong>.env</strong></p><pre><br>AZURE_OPENAI_API_KEY=XXXXXXXXXXXXXXXX<br>AZURE_OPENAI_DEPLOYMENT_NAME=my-deployment<br>AZURE_ENDPOINT=https://my-endpoint.openai.azure.com/<br>API_VERSION_LLM=2023-07-01-preview</pre><p><strong>llm.py with AzureChatOpenAI model</strong></p><pre>import os<br>from langchain_openai import AzureChatOpenAI<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br><br>AZURE_OPENAI_API_KEY = os.environ.get(&#39;AZURE_OPENAI_API_KEY&#39;)<br>AZURE_OPENAI_DEPLOYMENT_NAME = os.environ.get(&#39;AZURE_OPENAI_DEPLOYMENT_NAME&#39;)<br>AZURE_ENDPOINT = os.environ.get(&#39;AZURE_ENDPOINT&#39;)<br>API_VERSION = os.environ.get(&#39;API_VERSION_LLM&#39;)<br><br>llm = AzureChatOpenAI(<br>    azure_endpoint=AZURE_ENDPOINT,<br>    api_key=AZURE_OPENAI_API_KEY,<br>    azure_deployment=AZURE_OPENAI_DEPLOYMENT_NAME,<br>    api_version=API_VERSION,<br>    temperature=0,<br>    streaming=True<br>)</pre><ul><li>In case you decide for the OpenAI ChatGPT model, your code would look like this</li></ul><p><strong>llm.py with ChatOpenAI model</strong></p><pre>from langchain_openai import ChatOpenAI<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br><br>OPENAI_API_KEY = os.environ.get(&#39;OPENAI_API_KEY&#39;)<br><br>llm = ChatOpenAI(<br>    model=&quot;model-name&quot;, <br>    temperature=0,<br>    api_key=OPENAI_API_KEY<br>)</pre><h4>components/prompts.py</h4><ul><li>In this .py file, we will define the prompt template for our chat:</li></ul><pre>from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder<br><br>chat_prompt_template = ChatPromptTemplate.from_messages(<br>    [<br>        (&quot;system&quot;, &quot;You are an AI chatbot having a conversation with a human.&quot;),<br>        MessagesPlaceholder(variable_name=&quot;history&quot;),<br>        (&quot;human&quot;, &quot;{question}&quot;),<br>    ]<br>)</pre><ul><li>The prompt template determines the format that your LLM will receive with each invocation.</li><li>Here, we have one system instruction (“You are an AI chatbot having a conversation with a human.”), MessagesPlaceholder object that refers to the chat history that will be included in the prompt, and the reference to the question of the user (“{question}”)</li><li><em>Note that this is just intial simple example for this part of the series, going forward, we will create a more complex prompt including the retrieved chunks for RAG.</em></li></ul><h4>components/chat_utils.py</h4><ul><li>This is the core functionality of the ChatBot</li><li>The class <strong><em>ChatAgent </em></strong>contains methods necessary for setting up the chain (the chatbot engine), managing the chat history, and displaying the messages on the UI.</li></ul><pre>import streamlit as st<br>from langchain_core.runnables.history import RunnableWithMessageHistory<br>from langchain_core.runnables.base import Runnable<br>from langchain_community.chat_message_histories import StreamlitChatMessageHistory<br>from langchain_core.prompts import ChatPromptTemplate<br><br>class ChatAgent:<br>    def __init__(self, prompt: ChatPromptTemplate, llm: Runnable):<br>        &quot;&quot;&quot;<br>        Initialize the ChatAgent.<br><br>        Args:<br>        - prompt (ChatPromptTemplate): The chat prompt template.<br>        - llm (Runnable): The language model runnable.<br>        &quot;&quot;&quot;<br>        self.history = StreamlitChatMessageHistory(key=&quot;chat_history&quot;)<br>        self.llm = llm<br>        self.prompt = prompt<br>        self.chain = self.setup_chain()<br><br>    def setup_chain(self) -&gt; RunnableWithMessageHistory:<br>        &quot;&quot;&quot;<br>        Set up the chain for the ChatAgent.<br><br>        Returns:<br>        - RunnableWithMessageHistory: The configured chain with message history.<br>        &quot;&quot;&quot;<br>        chain = self.prompt | self.llm<br>        return RunnableWithMessageHistory(<br>            chain,<br>            lambda session_id: self.history,<br>            input_messages_key=&quot;question&quot;,<br>            history_messages_key=&quot;history&quot;,<br>        )<br><br>    def display_messages(self):<br>        &quot;&quot;&quot;<br>        Display messages in the chat interface.<br>        If no messages are present, adds a default AI message.<br>        &quot;&quot;&quot;<br>        if len(self.history.messages) == 0:<br>            self.history.add_ai_message(&quot;How can I help you?&quot;)<br>        for msg in self.history.messages:<br>            st.chat_message(msg.type).write(msg.content)<br><br>    def start_conversation(self):<br>        &quot;&quot;&quot;<br>        Start a conversation in the chat interface.<br>        Displays messages, prompts user for input, and handles AI response.<br>        &quot;&quot;&quot;<br>        self.display_messages()<br>        user_question = st.chat_input(placeholder=&quot;Ask me anything!&quot;)<br>        if user_question:<br>            st.chat_message(&quot;human&quot;).write(user_question)<br>            config = {&quot;configurable&quot;: {&quot;session_id&quot;: &quot;any&quot;}}<br>            response = self.chain.invoke({&quot;question&quot;: user_question}, config)<br>            st.chat_message(&quot;ai&quot;).write(response.content)</pre><h4>app.py</h4><ul><li>This is the entry point and the only page of the Streamlit application.</li><li>The code contains the layout of the Streamlit app page, it instantiates the <strong><em>ChatAgent </em></strong>class, and calls the <strong><em>start_conversation </em></strong>method on that class:</li></ul><pre>import streamlit as st<br>from components.chat_utils import ChatAgent<br>from components.prompts import chat_prompt_template<br>from components.llm import llm<br><br>def main():<br>    st.set_page_config(<br>        page_title=&quot;Pubmed Abstract Screener&quot;,<br>        page_icon=&#39;💬&#39;,<br>        layout=&#39;wide&#39;<br>    )<br><br>    # Define two columns - this will make layout split horizontally<br>    col1, col2 = st.columns([1, 3])<br><br>    # Place the logo in the first column<br>    with col1:<br>        st.image(&#39;../assets/pubmed-screener-logo.jpg&#39;)<br><br>    # In the second column, place text explaining the purpose of the app and some example scientific questions that your user might ask.<br>    with col2:<br>        st.title(&quot;PubMed Screener&quot;)<br>        st.markdown(&quot;&quot;&quot;<br>            PubMed Screener is a ChatGPT &amp; PubMed powered insight generator from biomedical abstracts. <br><br>            #### Example scientific questions<br>            - How can advanced imaging techniques and biomarkers be leveraged for early diagnosis and monitoring of disease progression in neurodegenerative disorders?<br>            - What are the potential applications of stem cell technology and regenerative medicine in the treatment of neurodegenerative diseases, and what are the associated challenges?<br>            - What are the roles of gut microbiota and the gut-brain axis in the pathogenesis of type 1 and type 2 diabetes, and how can these interactions be modulated for therapeutic benefit?<br>            - What are the molecular mechanisms underlying the development of resistance to targeted cancer therapies, and how can these resistance mechanisms be overcome?<br>        &quot;&quot;&quot;)<br><br>    # This is the chatbot component<br>    chat_agent = ChatAgent(prompt=chat_prompt_template, llm=llm)<br>    chat_agent.start_conversation()<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><ul><li>Since this is the entry point, we can now run our application and explore it in the browser!</li></ul><h4>Run the application</h4><ul><li>Navigate to the <strong><em>/app</em></strong> subfolder, and run the following command:</li></ul><pre>streamlit run app.py</pre><ul><li>Then navigate to your browser and visit the following URL: <a href="http://localhost:8501/">http://localhost:8501/</a></li><li>You should see a similar result to this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AeNVe4IvLXjBBb0gKiR-UQ.png" /><figcaption>The Streamlit app UI</figcaption></figure><ul><li>As you can see, our chatbot app is now functional, but gives us only a high level generic responses based on the knowledge of the LLM at the time of training. This is not the best for science, since the LLM can miss the novel knowledge, and also, there is a risk of hallucination since we can’t know where that piece of information comes from.</li><li>In the next parts of this series, we will address this challenge by retrieving scientific abstracts to ground the LLM responses, and teach the LLM to give us citations of the sources in its answers.</li></ul><blockquote><strong>So, stay tuned for the upcoming parts!</strong></blockquote><p><em>Thank you for reading.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37550b44b266" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I extract data from PowerPoint with Gemini 1.5 and Python]]></title>
            <link>https://medium.com/@milieere/how-i-use-multimodal-gemini1-5-6f7db346776b?source=rss-7cecf8828340------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f7db346776b</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-extraction]]></category>
            <dc:creator><![CDATA[Simona Barankova]]></dc:creator>
            <pubDate>Sun, 26 May 2024 18:32:49 GMT</pubDate>
            <atom:updated>2024-05-27T09:42:17.450Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will look at how to use the multimodal Gemini 1.5 Pro and Python, to extract data from a PowerPoint presentation into a structured format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XMHySG919y8Gx7xS4xquyA.jpeg" /></figure><h4>Why do we need to structure unstructured data?</h4><p>Today, 80–90% of all enterprise data assets are in an unstructured format. PDF files, PPTX presentations, you name it. Yet, only about 50 percent of these data are actively analyzed to derive insights. Furthermore, analyzing such data programmatically poses an additional challenge, since machines can’t easily interpret them.</p><p>Fortunately, methods exist that can help unlock the potential of unstructured data. One of the rising stars in the field is using <em>multimodal large language models</em> (MM-LLMs), such as <strong>Gemini 1.5 Pro</strong>. Models like this accept a prompt of a mixed format — you can pass images together with your textual prompt.</p><p>So, let’s get into it!</p><p><strong><em>Disclaimer</em></strong><em>: I work on a Windows machine</em></p><h4>1. Converting PPTX to images</h4><blockquote>To follow through, on the same PPTX material as I have, download the <a href="https://www.visionofhumanity.org/resources/ecological-threat-report-2023-presentation/">Ecological Threat Report 2023</a></blockquote><p>The first step is converting our PowerPoint slides into a bunch of images, one image per slide.</p><p>For this purpose, I used the <a href="https://pypi.org/project/Aspose.Slides/"><strong>aspose.slides</strong></a> library:</p><pre>import aspose.slides as slides<br>import aspose.pydrawing as drawing<br><br>with slides.Presentation(&quot;Ecological-Threat-Report-2023.pptx&quot;) as presentation:<br>    for slide in presentation.slides:<br>        slide.get_thumbnail(2, 2).save(f&quot;.\pptx_img\presentation_slide_{str(slide.slide_number)}.jpg&quot;, drawing.imaging.ImageFormat.jpeg)</pre><p>Running this code produced images of our PowerPoint slides, and saved them into the pptx_img folder.</p><p><em>NOTE: The images have a watermark, that was added by the Aspose tool. This is OK since we can tell our model to ignore it.</em></p><h4>2. Constructing the prompt</h4><p>When you explore the presentation used for this example, you will find out, that it contains different forms of content — text, images, graphs. We will instruct Gemini in our prompt to extract all contents of the presentation as <strong>text</strong>, extracting the text in its form, and textually describing images, diagrams, and graphs.</p><p>In the prompt, we also specify the desired structure of the output. Here, I chose a generic JSON format with heading, text, images, and graphs as keys.</p><blockquote>Remember, in Generative AI, your prompt is everything! The better &amp; clearer your prompt, the better your result.</blockquote><p>Since different PPTX do not follow the same layout, it is a good idea to adjust your prompt for different scenarios to achieve the best results.</p><pre>prompt = &quot;&quot;&quot;<br>Extract all texts from this presentation slide (literal extraction, do not summarize!) and tabular data, when image or diagram is present describe it.<br>When a graph with data is present, describe what it represents in detail, with key messages on data points.  When extracting texts, those that are part of a diagram or graph should be only extracted within this context, not within the &quot;text&quot; category.<br><br>There is a watermark over the slides, ignore it. Extract the contents below it. The watermark says: Evaluation only. Created with Aspose.Slides for Python via .NET 24.4. Copyright 2004-2024 Aspose Pty Ltd.<br><br>Write the extracted contents in JSON format, that will follow this structure:<br><br>[<br>    {<br>        &quot;heading&quot;: &quot;Example slide heading&quot;,<br>        &quot;text&quot;: &quot;Example text on the slide&quot;<br>        &quot;images&quot;: [<br>            &quot;Example image or diagram description&quot;,<br>            &quot;Example image or diagram description&quot;,<br>            &quot;Example image or diagram description&quot;<br>        ],<br>        &quot;graphs&quot;: [<br>            &quot;Example graph description&quot;<br>        ]<br>    }<br>]<br><br>If there is any part missing (like there is no heading on the slide) - just represent it as null.<br>Output the JSON file. Make sure your response is a VALID JSON! Do not put backticks around the output.<br><br>SYNTACTICALLY CORRECT EXAMPLE RESPONSE:<br>[<br>    {<br>        &quot;slide_heading&quot;: &quot;Ecological Threat Report 2023&quot;,<br>        &quot;subheading&quot;: null,<br>        &quot;text&quot;: &quot;Key Findings\nCountry Hotspots\nEcological Threats\nMegacities\nPolicy Recommendations&quot;,<br>        &quot;images&quot;: [<br>            &quot;Example image&quot;<br>        ],<br>        &quot;graphs&quot;: []<br>    }<br>]<br>&quot;&quot;&quot;</pre><p>Now, let’s let Gemini do the magic! :)</p><h4>3. Letting Gemini to extract the data</h4><p>Firstly, you will need a Google Cloud account and an active project. If you don’t have one, go ahead and <a href="https://cloud.google.com/">create it</a>. You will get a free 300 USD from Google upon your registration.</p><p>Next, <a href="https://cloud.google.com/sdk/docs/install-sdk">install the Google Cloud SDK</a> on your machine, and configure your project to enable calling the Gemini model over an API.</p><p>Before running the code below, make sure you authorize via the Google Cloud SDK by running <em>gcloud auth login </em>from your CLI.</p><p>Let’s use the following code to iterate over the images created in Step 1., convert them to bytes, pass them together with our prompt from Step 2. to Gemini, and save the result JSON files to their designated directory:</p><pre>import os<br>import json<br>import natsort<br>import vertexai<br>from vertexai.preview.generative_models import GenerativeModel, Part<br>from extraction_prompt import prompt<br><br>def image_to_blob(image_path):<br>    with open(image_path, &#39;rb&#39;) as file:<br>        return file.read()<br><br>def initialize_vertex_ai(project, location):<br>    vertexai.init(project=project, location=location)<br>    return GenerativeModel(model_name=&quot;gemini-1.5-pro-001&quot;)<br><br>def get_sorted_image_filenames(directory_path):<br>    image_filenames = [f for f in os.listdir(directory_path) if f.endswith(&quot;.jpg&quot;)]<br>    return natsort.natsorted(image_filenames)<br><br>def process_images(model, directory_path, filenames, output_directory):<br>    for filename in filenames:<br>        print(f&#39;Processing {filename}&#39;)<br>        try:<br>            image_path = os.path.join(directory_path, filename)<br>            image_blob = image_to_blob(image_path)<br><br>            image_part = Part.from_data(data=image_blob, mime_type=&quot;image/jpeg&quot;)<br>            text_part = prompt<br><br>            response = model.generate_content([image_part, text_part])<br>            data = str(response.text)<br>            slides_data = json.loads(data)<br><br>            save_to_json(slides_data, filename, output_directory)<br>        except json.JSONDecodeError as e:<br>            print(f&#39;Failed to parse JSON for {filename}: {e}&#39;)<br>        except Exception as e:<br>            print(f&#39;An error occurred while processing {filename}: {e}&#39;)<br><br>def save_to_json(data, filename, output_directory):<br>    output_filename = os.path.join(output_directory, f&#39;slide_data_{filename}.json&#39;)<br>    with open(output_filename, &#39;w&#39;) as json_file:<br>        json.dump(data, json_file, indent=4)<br>    print(f&#39;Saved data to {output_filename}&#39;)<br><br>def main():<br>    project = &#39;&lt;your-project-id&gt;&#39; # Replace with your project ID<br>    location = &#39;us-central-1&#39; # Replace with your desired location for Gemini<br>    directory_path = r&#39;&lt;your-path-prefix&gt;\pptx_img&#39; # Replace with path to your images<br>    output_directory = r&#39;&lt;your-path-prefix&gt;\extracted_json&#39;  # Replace with your desired output directory<br><br>    model = initialize_vertex_ai(project, location)<br>    sorted_filenames = get_sorted_image_filenames(directory_path)<br>    process_images(model, directory_path, sorted_filenames, output_directory)<br>    print(&quot;The slide data has been saved to individual JSON files in the specified output directory&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>OK. Let’s assess the results!</p><h4>4. Checking Gemini output &amp; iterating on the prompt engineering</h4><p>Let’s have a look at an example output. This is slide 13 from the presentation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_dtQlB_MsYXUTZD7r8whvA.jpeg" /><figcaption>Slide 13 of the IEP Ecological Threat Report 2023</figcaption></figure><p>And this is the JSON file outputted by Gemini:</p><pre>[<br>    {<br>        &quot;heading&quot;: &quot;2023 highlights \u2013 continued&quot;,<br>        &quot;text&quot;: &quot;The distribution of ecological threat severity.\n\n&gt; 66 countries score severe\n\n&gt; 33 countries score high\n\n&gt; 56 countries score medium\n\n&gt; 23 countries score low\n\n&gt; 43 countries score very low&quot;,<br>        &quot;images&quot;: [],<br>        &quot;graphs&quot;: [<br>            &quot;The donut chart represents the distribution of ecological threat severity scores across countries in 2023.\nThe total number of countries included in the data is not specified.\n\nThe distribution is broken down as follows:\n- Severe: 30% of countries\n- High: 15%\n- Medium: 25%\n- Low: 10%\n- Very Low: 19%&quot;<br>        ]<br>    }<br>]</pre><p>Pretty good, no? OK. Let’s check some more complex slide:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGadBXkhlb5TvWY7AVDfiQ.jpeg" /><figcaption>Slide 15 of the IEP Ecological Threat Report 2023</figcaption></figure><pre>[<br>    {<br>        &quot;heading&quot;: &quot;Ecological Threat and the Green Transition&quot;,<br>        &quot;text&quot;: &quot;Efforts to keep global temperatures below a 1.5-degree Celsius increase require a massive shift from fossil fuels to zero carbon emissions energy sources. \nThis shift is essential for global emission goals but challenging for countries that are dependent on fossil fuel revenues \nAccording to the UNDP, these nations could face losses of over 60% of their current GDP by 2040 under a net-zero 2050 scenario.\nThis loss, combined with limited opportunities for economic diversification and ecological threats, might lead to significant social and economic disruptions.&quot;,<br>        &quot;images&quot;: [],<br>        &quot;graphs&quot;: [<br>            &quot;The graph explores the relationship between fossil fuel dependence and ecological threat levels across different countries. The x-axis represents &#39;Fossil Fuel Rents (% GDP),&#39; indicating the percentage of a country&#39;s GDP derived from fossil fuel rents. The y-axis, labeled &#39;GDP PER CAPITA (US$ THOUSANDS),&#39; represents the GDP per capita of each country.  The chart is color-coded based on the &#39;Ecological Threat Level&#39;, with shades of green indicating lower risk (Very Low, Low) and shades of orange indicating higher risk (Medium, High). Notably, countries like Timor-Leste and Iraq, despite having high fossil fuel dependence, face lower ecological threats. Conversely, countries like Kazakhstan and Libya, with relatively lower fossil fuel dependence, experience a higher ecological threat.  The graph highlights that while fossil fuel dependence is a factor, it doesn&#39;t directly correlate to higher ecological threats. Other factors, not represented in this graph, likely contribute to a country&#39;s overall ecological vulnerability.&quot;<br>        ]<br>    }<br>]</pre><p>Note that here, the model skips the third bullet point. Also, in its description of the graph, slightly misleading terminology is used like ‘fossil fuel dependence’, whereas what the graph describes could be summarized better as ‘dependency on fossil fuel revenues’.</p><p>To improve the results, go ahead and modify the prompt from Step 2. By iterating on the prompt and comparing the results, you can modify the model outputs to better fit the objectives of your use case.</p><h4>Summary of outcomes &amp; next steps</h4><ul><li>We’ve learned how to transform the contents of a PPTX presentation into a JSON format for further processing.</li><li>This is a step in a pipeline that enables transforming unstructured datasets, originally intended to be consumed by a human, into databases of knowledge that are machine-interpretable.</li><li>The data can now easily be used further, i.e. to build a RAG-based ChatBot.</li><li>Prompt engineering is essential to achieve good results, and customization is needed for specific use cases.</li><li>Even though the results are impressive, there is still a risk of model hallucination. In use cases where high-precision information needs to be retained, this method might not be suitable.</li></ul><blockquote>Thank you and have a good day!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f7db346776b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>