<?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 Ashutosh Patel on Medium]]></title>
        <description><![CDATA[Stories by Ashutosh Patel on Medium]]></description>
        <link>https://medium.com/@ashu.analytix?source=rss-4dfa55c9d33------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*I3R4V6LlviNXtpLMn0M1lQ.png</url>
            <title>Stories by Ashutosh Patel on Medium</title>
            <link>https://medium.com/@ashu.analytix?source=rss-4dfa55c9d33------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 11:27:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashu.analytix/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[Build a Simple RAG Application in Google Colab with LlamaIndex and an Open-Source LLM]]></title>
            <link>https://medium.com/@ashu.analytix/build-a-simple-rag-application-in-google-colab-with-llamaindex-and-an-open-source-llm-fbd6cdf87ebe?source=rss-4dfa55c9d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbd6cdf87ebe</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llamaindex]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[vectordb]]></category>
            <dc:creator><![CDATA[Ashutosh Patel]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 15:51:33 GMT</pubDate>
            <atom:updated>2026-08-17T15:51:33.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/723/0*ZR-Pvx6lTFs8olcS" /></figure><p>Retrieval-Augmented Generation (RAG) is one of the simplest ways to make an LLM answer questions using information from your own data.</p><p>In this tutorial, we’ll build a <strong>minimal RAG application in Google Colab</strong> using:</p><ul><li><strong>LlamaIndex</strong> — to build the RAG pipeline</li><li><strong>Groq</strong> — to access an open-source LLM</li><li><strong>Hugging Face</strong> — for local embeddings</li><li><strong>SimpleWebPageReader</strong> — to load content from a web page</li></ul><p>The best part? <strong>You can run the entire example in Google Colab without needing a powerful local machine.</strong></p><h3>1. Install the required libraries</h3><p>We start by installing the LlamaIndex packages and supporting libraries.</p><pre>!pip install -q llama-index llama-index-readers-web html2text llama-index-llms-groq llama-index-embeddings-huggingface</pre><h3>2. Import the required packages</h3><p>Next, import the components required to load web content, create embeddings, connect to Groq, and build our vector index.</p><pre>from llama_index.core import VectorStoreIndex, Settings<br>from llama_index.readers.web<br>import SimpleWebPageReader<br>from llama_index.llms.groq import Groq<br>from llama_index.embeddings.huggingface import HuggingFaceEmbedding<br>from google.colab import userdata</pre><p>Notice that we are using <strong>Google Colab’s </strong><strong>userdata</strong> to securely access our API key instead of hardcoding it in the notebook.</p><h3>3. Configure the Groq API key</h3><p>Store your Groq API key in <strong>Google Colab Secrets</strong> using the name GROQ_APIKEY.</p><p>Then retrieve it using</p><pre># Groq API Key<br>os.environ[&quot;GROQ_API_KEY&quot;] = userdata.get(&quot;GROQ_APIKEY&quot;)</pre><p>This keeps the API key outside the code itself.</p><h3>4. Configure the LLM and embedding model</h3><p>Now we configure two important components of our RAG system:</p><ol><li><strong>LLM</strong> — generates the final answer.</li><li><strong>Embedding model</strong> — converts text into vectors for semantic search.</li></ol><p>Here we use Groq with openai/gpt-oss-120b and the Hugging Face embedding model BAAI/bge-small-en-v1.5.</p><pre># Set up the open-source LLM and embedding model<br>Settings.llm = Groq( model=&quot;openai/gpt-oss-120b&quot;, temperature=0.1 )<br>Settings.embed_model = HuggingFaceEmbedding(model_name=&quot;BAAI/bge-small-en-v1.5&quot; )</pre><p>The important point here is that <strong>we are not using OpenAI embeddings or an OpenAI LLM</strong>.</p><p>The embedding model runs locally through Hugging Face, while the LLM is accessed through Groq.</p><h3>5. Load a web page</h3><p>For this example, we’ll use the Analytics India Magazine MLDS website as our knowledge source.</p><pre># Passing a URL which we want to load to our vector store<br>url = &quot;https://mlds.analyticsindiamag.com/&quot;</pre><p>We can load the web page using LlamaIndex’s SimpleWebPageReader</p><pre># Using SimpleWebPageReader to load the URL content<br># html_to_text=True converts HTML into plain text<br>d1 = SimpleWebPageReader( html_to_text=True ).load_data([url])</pre><p>The html_to_text=True option is useful because we want the web page converted into text that can be processed and embedded.</p><h3>6. Create the vector index</h3><p>Now comes the core part of our RAG pipeline.</p><pre># Create a searchable index from the loaded document<br>index = VectorStoreIndex.from_documents(d1)</pre><p>Behind the scenes, LlamaIndex takes the loaded document, generates embeddings using our Hugging Face embedding model, and creates a searchable vector index.</p><p>Conceptually:</p><p><strong>Web Page → Text → Embeddings → Vector Index</strong></p><h3>7. Create the query engine</h3><p>Once our index is ready, we create a query engine.</p><pre># Creating query engine<br>query_engine = index.as_query_engine()</pre><p>The query engine allows us to ask questions against the information we just indexed.</p><h3>8. Ask a question</h3><p>Finally, let’s ask: <strong>“What is MLDS?”</strong></p><pre># Running a query against the loaded URL data<br>r1 = query_engine.query(&quot;What is MLDS?&quot;)<br>print(r1)</pre><p>The query engine searches the indexed content and provides the relevant information to the LLM, which then generates the final response.</p><p>And that’s it — <strong>we have built a simple RAG application!</strong></p><h3>The Complete RAG Flow</h3><p>Our entire application can be understood as this simple pipeline:</p><pre>Web Page<br>   ↓<br>SimpleWebPageReader<br>   ↓<br>Extract Text<br>   ↓<br>Hugging Face Embeddings<br>   ↓<br>VectorStoreIndex<br>   ↓<br>User Question<br>   ↓<br>Relevant Context<br>   ↓<br>Groq LLM<br>   ↓<br>Answer</pre><p>What makes this example particularly useful is its simplicity.</p><p>You don’t need to set up a complicated infrastructure or run a large model on your laptop. <strong>Google Colab + LlamaIndex + Hugging Face embeddings + Groq</strong> is enough to get started.</p><h3>What’s Next?</h3><p>This example is intentionally minimal.</p><p>From here, you can extend it to:</p><ul><li>Load PDFs instead of web pages</li><li>Build RAG over multiple documents</li><li>Persist your vector database</li><li>Add conversational memory</li><li>Implement hybrid search</li><li>Add reranking</li><li>Build an Agentic RAG system</li></ul><p>The basic architecture, however, remains the same:</p><p><strong>Retrieve relevant information → Give it to the LLM → Generate an answer.</strong></p><p>If you’re learning RAG, this is a great place to start because you can experiment with the complete pipeline directly in <strong>Google Colab using an open-source LLM stack</strong>.</p><p>If you found this useful, <strong>please clap 👏 and follow me for more practical AI, GenAI, RAG, and ML engineering tutorials.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbd6cdf87ebe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 4. Iterative Workflow using LangGraph]]></title>
            <link>https://medium.com/@ashu.analytix/part-4-iterative-workflow-using-langgraph-73ff56986c71?source=rss-4dfa55c9d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/73ff56986c71</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ashutosh Patel]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 15:11:22 GMT</pubDate>
            <atom:updated>2026-08-12T15:11:22.505Z</atom:updated>
            <content:encoded><![CDATA[<p>Building an Iterative AI Workflow with LangGraph: Generate, Evaluate &amp; Optimize Your Tweets</p><p>In the previous three articles of this series, we explored three fundamental workflow patterns using LangGraph:</p><ul><li><a href="https://medium.com/@ashu.analytix/build-ai-workflows-with-langgraph-part-1-your-first-agentic-ai-application-ce634fe6e1ef"><strong>Part 1</strong></a><strong> — Sequential Workflow:</strong> Execute tasks one after another</li><li><a href="https://medium.com/@ashu.analytix/build-your-first-parallel-ai-workflow-with-langgraph-part-2-c0fa10580c35"><strong>Part 2 </strong></a><strong>— Parallel Workflow:</strong> Execute independent tasks simultaneously</li><li><a href="https://medium.com/@ashu.analytix/part-3-conditional-workflows-in-langgraph-6eda8d235cc4"><strong>Part 3</strong></a><strong> — Conditional Workflow:</strong> Dynamically choose the next step based on the current state.</li></ul><p>In this article, we’re going one step further. What if our AI doesn’t get the answer right on the first attempt?</p><p>Instead of simply generating an output and returning it, what if the AI could: <strong>Generate → Evaluate → Improve → Evaluate again → Improve again…</strong></p><p>until the output is good enough? That’s exactly what we’ll build in this article.</p><p>If you have landed directly on Part 4, I recommend reading the previous articles first because this implementation builds on the concepts introduced throughout the series. Let’s build it.</p><h3>What Are We Building?</h3><p>Our mini-project is an <strong>AI Tweet Generation and Optimization Agent</strong>. We’ll give the system a topic, for example: <strong><em>Encounter peacock during morning walk</em></strong></p><p>The AI will generate a tweet. But instead of immediately accepting that tweet, another LLM will act as a <strong>strict evaluator</strong>.</p><p>It will check the tweet for:</p><ul><li>Originality</li><li>Humor</li><li>Punchiness</li><li>Virality potential</li><li>Correct tweet format</li><li>Character limit</li><li>Whether it avoids Q&amp;A-style jokes</li></ul><p>If the evaluator approves the tweet, we’re done. If the evaluator says the tweet needs improvement, another LLM will rewrite it based on the feedback.</p><p>Then the improved tweet goes back to the evaluator. This creates an iterative loop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*42YIk8zD1VHIDlWCJAHuUw.png" /></figure><p>There is also a maximum iteration limit so that our workflow doesn’t continue forever. This is an important pattern in Agentic AI:</p><blockquote><strong><em>The agent generates an output, evaluates its own work, learns from the feedback, and iteratively improves the result.</em></strong></blockquote><h3>Why Do We Need an Iterative Workflow?</h3><p>A traditional LLM application often looks like this:</p><pre>User<br> ↓<br>LLM<br> ↓<br>Response</pre><p>The problem is that the first response isn’t necessarily the best response. For many tasks, we need some form of quality control.</p><p>For example:</p><ul><li>Writing</li><li>Code generation</li><li>Marketing content</li><li>SQL generation</li><li>Data analysis</li><li>Report generation</li><li>Customer support responses</li></ul><p>Instead of trusting the first output, we can introduce a feedback loop:</p><pre>Generate<br>   ↓<br>Evaluate<br>   ↓<br>Feedback<br>   ↓<br>Improve<br>   ↓<br>Evaluate Again</pre><p>This is the architecture we’re implementing today.</p><h3>1. Importing the Required Libraries</h3><p>Let’s begin with the imports.</p><pre>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Literal, Annotated<br>from langchain_core.messages import SystemMessage, HumanMessage<br>import operator<br>from pydantic import BaseModel, Field</pre><h3>2. Creating Our Three LLM Roles</h3><p>Now we initialize three LLM instances.</p><pre>generator_llm = ChatGroq(model=&quot;openai/gpt-oss-120b&quot;)<br>evaluator_llm = ChatGroq(model=&quot;openai/gpt-oss-120b&quot;)<br>optimizer_llm = ChatGroq(model=&quot;openai/gpt-oss-120b&quot;)</pre><p>Although we’re using the same underlying model, we’re giving it three different responsibilities.</p><p>Generator: Responsible for creating the initial tweet.</p><p>Evaluator: Responsible for critically reviewing the tweet.</p><p>Optimizer: Responsible for rewriting the tweet based on the evaluator’s feedback.</p><p>This is one of the simplest ways to start thinking about <strong>multi-agent-style workflows</strong>.</p><h3>3. Defining the Evaluation Schema</h3><p>Our evaluator needs to return a predictable response. Instead of allowing the LLM to return arbitrary text, we’ll define a Pydantic schema.</p><pre>class TweetEvaluation(BaseModel):<br>  evaluation: Literal[<br>          &quot;approved&quot;,<br>          &quot;needs_improvement&quot;<br>      ] = Field(<br>          ...,<br>          description=&quot;Final evaluation result.&quot;<br>      )<br>      feedback: str = Field(<br>          ...,<br>          description=&quot;feedback for the tweet.&quot;<br>      )</pre><p>There are two fields.</p><p>evaluationLThis tells us whether the tweet is good enough.</p><p>It can only be: approved or needs_improvement</p><p>feedback:This contains the evaluator’s explanation.</p><p>For example: <em>The tweet is relatable but the punchline is predictable. Make the observation more specific and unexpected.</em></p><p>This feedback will be passed directly to the optimizer.</p><h3>4. Creating the Structured Evaluator</h3><p>Now we convert the evaluator LLM into a structured-output model.</p><pre>structured_evaluator_llm = evaluator_llm.with_structured_output(<br>    TweetEvaluation<br>)</pre><p>This is important because the workflow depends on the evaluator’s decision. We don’t want the model to respond with:<em>“I think this tweet is probably okay.”</em></p><p>We need something deterministic that our Python code can inspect:</p><pre>{<br>    &quot;evaluation&quot;: &quot;approved&quot;,<br>    &quot;feedback&quot;: &quot;...&quot;<br>}</pre><p>This structured output becomes the decision signal for our workflow.</p><h3>5. Designing the Shared State</h3><p>Now we define the most important component of our LangGraph application: the state.</p><pre>class TweetState(TypedDict):<br>  topic: str<br>      tweet: str<br>      evaluation: Literal[&quot;approved&quot;, &quot;needs_improvement&quot;]<br>      feedback: str<br>      iteration: int<br>      max_iteration: int<br>      tweet_history: Annotated[list[str], operator.add]<br>      feedback_history: Annotated[list[str], operator.add]</pre><p>Let’s understand each field.</p><p>topic:The topic for which we want to generate a tweet.</p><p>Example: encounter peacock during morning walk</p><p>tweet:Stores the latest version of the tweet.</p><p>evaluation:Stores the evaluator’s decision: approved or needs_improvement</p><p>feedback:Stores the latest evaluator feedback.</p><p>iteration:Tracks the current optimization iteration.</p><p>max_iteration:Defines the maximum number of iterations allowed.</p><p>This is important because our workflow contains a loop. Without a limit, a poorly designed workflow could potentially keep optimizing indefinitely.</p><p>Keeping Track of History — The last two fields are particularly interesting.</p><pre>tweet_history: Annotated[list[str], operator.add]<br>feedback_history: Annotated[list[str], operator.add]</pre><p>We aren’t just storing the latest tweet and feedback. We’re storing the <strong>entire evolution of the process</strong>. For example:</p><pre>Tweet History<br>Tweet 1 → Original generation<br>Tweet 2 → First optimization<br>Tweet 3 → Second optimization<br>Tweet 4 → Final version</pre><p>Similarly:</p><pre>Feedback History<br>Feedback 1 → First evaluation<br>Feedback 2 → Second evaluation<br>Feedback 3 → Third evaluation</pre><p>The operator.add reducer tells LangGraph to append new values instead of replacing the existing list.</p><p>This is extremely useful for debugging, auditing, and understanding how the agent arrived at its final answer.</p><h3>6. Creating the Tweet Generator</h3><p>Now let’s build our first node.</p><pre>def generate_tweet(state: TweetState):<br>  messages = [<br>          SystemMessage(<br>              content=&quot;You are a funny and clever Twitter/X influencer.&quot;<br>          ),<br>          HumanMessage(<br>              content=f&quot;&quot;&quot;<br>              Write a short, original, and hilarious tweet<br>              on the topic: &quot;{state[&#39;topic&#39;]}&quot;.<br>              Rules:<br>              - Do NOT use question-answer format.<br>              - Max 280 characters.<br>              - Use observational humor, irony, sarcasm,<br>                or cultural references.<br>              - Think in meme logic, punchlines,<br>                or relatable takes.<br>              - Use simple, day to day English.<br>              &quot;&quot;&quot;<br>          )<br>      ]<br>      response = generator_llm.invoke(messages).content<br>      return {<br>          &#39;tweet&#39;: response,<br>          &#39;tweet_history&#39;: [response]<br>      }</pre><p>This node has one responsibility: <em>Generate the initial tweet.</em></p><p>We use two messages.</p><h3>System Message</h3><pre>SystemMessage(...)</pre><p>This establishes the personality of the AI.</p><p>We tell it: <em>You are a funny and clever Twitter/X influencer.</em></p><p>Human Message: The human message contains the actual task and constraints.</p><p>Then we invoke the generator:</p><pre>response = generator_llm.invoke(messages).content</pre><p>Finally, we return two values:</p><pre>return {<br>    &#39;tweet&#39;: response,<br>    &#39;tweet_history&#39;: [response]<br>}</pre><p>The latest tweet is stored in tweet, while the same tweet is also added to tweet_history.</p><h3>7. Creating the Tweet Evaluator</h3><p>Now comes the second stage. The generator has created a tweet, but we don’t immediately trust it.</p><p>We ask another LLM to criticize it.</p><pre>def evaluate_tweet(state: TweetState):<br>  messages = [<br>          SystemMessage(<br>              content=&quot;&quot;&quot;<br>              You are a ruthless, no-laugh-given Twitter critic.<br>              You evaluate tweets based on humor, originality,<br>              virality, and tweet format.<br>              &quot;&quot;&quot;<br>          ),<br>          HumanMessage(<br>              content=f&quot;&quot;&quot;<br>              Evaluate the following tweet:<br>              Tweet: &quot;{state[&#39;tweet&#39;]}&quot;<br>              Use the criteria below:<br>              1. Originality<br>              2. Humor<br>              3. Punchiness<br>              4. Virality Potential<br>              5. Format<br>              Auto-reject if:<br>              - It&#39;s written in question-answer format.<br>              - It exceeds 280 characters.<br>              - It reads like a traditional setup-punchline joke.<br>              - It ends with generic or deflating lines.<br>              Respond only in structured format.<br>              &quot;&quot;&quot;<br>          )<br>      ]<br>      response = structured_evaluator_llm.invoke(messages)<br>      return {<br>          &#39;evaluation&#39;: response.evaluation,<br>          &#39;feedback&#39;: response.feedback,<br>          &#39;feedback_history&#39;: [response.feedback]<br>      }</pre><p>This node is deliberately designed to be critical. The evaluator checks five dimensions.</p><ol><li>Originality: Is the idea fresh?</li><li>Humor: Is it actually funny?</li><li>Punchiness: Does it immediately grab attention?</li><li>Virality Potential: Would people want to share it?</li><li>Format: Does it follow our rules?</li></ol><p>We also explicitly define rejection conditions.</p><h3>8. Creating the Tweet Optimizer</h3><p>Now we create the third AI role.</p><pre>def optimize_tweet(state: TweetState):<br>  messages = [<br>          SystemMessage(<br>              content=&quot;&quot;&quot;<br>              You punch up tweets for virality and humor<br>              based on given feedback.<br>              &quot;&quot;&quot;<br>          ),<br>          HumanMessage(<br>              content=f&quot;&quot;&quot;<br>              Improve the tweet based on this feedback:<br>              &quot;{state[&#39;feedback&#39;]}&quot;<br>              Topic: &quot;{state[&#39;topic&#39;]}&quot;<br>              Original Tweet:<br>              {state[&#39;tweet&#39;]}<br>              Re-write it as a short,<br>              viral-worthy tweet.<br>              Avoid Q&amp;A style and stay under 280 characters.<br>              &quot;&quot;&quot;<br>          )<br>      ]<br>      response = optimizer_llm.invoke(messages).content<br>      iteration = state[&#39;iteration&#39;] + 1<br>      return {<br>          &#39;tweet&#39;: response,<br>          &#39;iteration&#39;: iteration,<br>          &#39;tweet_history&#39;: [response]<br>      }</pre><p>The optimizer receives three important pieces of information:</p><p>The feedback: What did the evaluator dislike?</p><p>The topic: What should the tweet still be about?</p><p>The current tweet: What are we trying to improve?</p><p>The optimizer then creates a new version.</p><p>Every time the optimizer runs, the iteration count increases. This becomes important when deciding whether we should continue looping.</p><h3>9. Creating the Routing Function</h3><p>Now we need to decide what happens after every evaluation.</p><pre>def route_evaluation(state: TweetState):<br>  if (<br>          state[&#39;evaluation&#39;] == &#39;approved&#39;<br>          or state[&#39;iteration&#39;] &gt;= state[&#39;max_iteration&#39;]<br>      ):<br>          return &#39;approved&#39;<br>      else:<br>          return &#39;needs_improvement&#39;</pre><p>This is the <strong>decision-maker</strong> of our workflow. There are two ways the workflow can stop.</p><p>Condition 1 — Tweet Approved</p><p>If: state[‘evaluation’] == ‘approved’</p><p>we stop.</p><p>Condition 2 — Maximum Iterations Reached</p><p>Even if the evaluator continues saying: needs_improvement</p><p>we stop once: iteration &gt;= max_iteration</p><p>This gives us a safety mechanism.</p><h3>10. Creating the Graph</h3><p>Now we can finally construct our LangGraph.</p><pre>graph = StateGraph(TweetState)<br>graph = StateGraph(TweetState)<br><br>graph.add_node(&#39;generate&#39;, generate_tweet)<br>graph.add_node(&#39;evaluate&#39;, evaluate_tweet)<br>graph.add_node(&#39;optimize&#39;, optimize_tweet)<br><br>graph.add_edge(START, &#39;generate&#39;)<br>graph.add_edge(&#39;generate&#39;, &#39;evaluate&#39;)<br><br>graph.add_conditional_edges(&#39;evaluate&#39;, route_evaluation, {&#39;approved&#39;: END, &#39;needs_improvement&#39;: &#39;optimize&#39;})<br>graph.add_edge(&#39;optimize&#39;, &#39;evaluate&#39;)<br><br>workflow = graph.compile()<br><br>workflow</pre><p>We’re telling LangGraph that this workflow will use TweetState as its shared state.</p><h3>The Complete Graph</h3><p>Our final architecture looks like this:</p><pre>                    START<br>                      |<br>                      ▼<br>                ┌───────────┐<br>                │  Generate │<br>                └─────┬─────┘<br>                      |<br>                      ▼<br>                ┌───────────┐<br>          ┌────►│  Evaluate │◄────┐<br>          │     └─────┬─────┘     │<br>          │           / \          │<br>          │          /   \         │<br>          │         /     \        │<br>          │   Approved   Improve   │<br>          │      |          |      │<br>          │      ▼          ▼      │<br>          │     END      Optimize ─┘<br>          │<br>          └── Iterative Loop</pre><p>This is fundamentally different from the workflows we built in Parts 1–3. We’re no longer just moving forward through a graph. We’re creating a <strong>feedback loop</strong>.</p><h3>The Bigger Agentic AI Picture</h3><p>At this point, we can start combining the patterns.</p><p>Imagine an enterprise AI system where:</p><pre>                    User Request<br>                         |<br>                         ▼<br>                  Intent Detection<br>                         |<br>                  Conditional Route<br>                  /       |       \<br>                 /        |        \<br>            Research   Calculation  Support<br>                |          |           |<br>                ▼          ▼           ▼<br>             Parallel Processing<br>                |<br>                ▼<br>             Generate<br>                |<br>                ▼<br>             Evaluate<br>                |<br>          ┌─────┴─────┐<br>          │           │<br>       Approved    Improve<br>          │           │<br>          ▼           └──────► Evaluate<br>         END</pre><p>This is where LangGraph becomes really interesting. The individual patterns are simple. The power comes from <strong>combining them</strong>.</p><h3>Key Takeaways</h3><p>In this article, we built an <strong>iterative Tweet Generation and Optimization Agent</strong> using LangGraph.</p><p>More importantly, we learned how to:</p><ul><li>Create separate generator, evaluator, and optimizer roles.</li><li>Use structured LLM output for evaluation.</li><li>Maintain shared workflow state.</li><li>Maintain tweet and feedback history.</li><li>Track iterations.</li><li>Implement conditional routing.</li><li>Create loops in LangGraph.</li><li>Use feedback to improve LLM-generated content.</li><li>Prevent infinite loops using a maximum iteration limit.</li></ul><p>The central idea can be summarized in one line:</p><blockquote><strong><em>Don’t always accept the first AI-generated answer. Give the AI a mechanism to evaluate and improve its own work.</em></strong></blockquote><h3>A Note on Production Systems</h3><p>The implementation in this article is intentionally simple so that the workflow pattern is easy to understand.</p><p>In a production system, we could make the evaluator more sophisticated. For example, instead of relying entirely on another LLM, we could combine:</p><ul><li>Character-count validation</li><li>Rule-based checks</li><li>LLM evaluation</li><li>Automated tests</li><li>Business constraints</li><li>Human approval</li></ul><h3>What’s Next?</h3><p>This is <strong>Part 4</strong> of my Agentic AI Workflow series.</p><p>So far:</p><p><strong>Part 1 → Sequential Workflow</strong></p><p><strong>Part 2 → Parallel Workflow</strong></p><p><strong>Part 3 → Conditional Workflow</strong></p><p><strong>Part 4 → Iterative Workflow</strong></p><p>In the upcoming articles, I’ll continue exploring how these individual patterns can be combined to build more sophisticated <strong>Agentic AI systems using LangGraph</strong>.</p><p>The goal of this series is not just to learn LangGraph syntax. It’s to learn how to <strong>think in terms of AI workflows</strong>.</p><p>I would like to take a moment to thank <a href="https://learnwith.campusx.in/"><strong>CampusX</strong></a>.</p><p>I’m sharing these articles as part of my own learning journey and hope they can also help someone else who is exploring Agentic AI.</p><h3>Complete Code</h3><p>The complete Google Colab notebook and source code for this project are available in my GitHub repository.</p><p><strong>GitHub:</strong> <a href="https://github.com/ashutosh2909/Agentic-AI/blob/main/Workflow_in_LangGraph.ipynb">https://github.com/ashutosh2909/Agentic-AI/blob/main/Workflow_in_LangGraph.ipynb</a></p><h3>Let’s Connect</h3><p>If you found this article useful, I would love to hear your thoughts.</p><p><strong>Please hit 👏 Clap, leave a 💬 comment, and share the article if you found value in it.</strong></p><p>Your feedback and engagement motivate me to continue writing and sharing what I’m learning while exploring the world of <strong>Agentic AI and LangGraph</strong>.</p><p>If you’re following this series, stay tuned for <strong>Part 5</strong>.</p><p>Until then — <strong>Keep learning. Keep experimenting. Keep building.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73ff56986c71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Trying to Become More Productive: Build Better Habits Instead]]></title>
            <link>https://medium.com/@ashu.analytix/stop-trying-to-become-more-productive-build-better-habits-instead-3cfc15dbd2a4?source=rss-4dfa55c9d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cfc15dbd2a4</guid>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[growth-mindset]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[productivity-hacks]]></category>
            <category><![CDATA[atomic-habit]]></category>
            <dc:creator><![CDATA[Ashutosh Patel]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 07:24:29 GMT</pubDate>
            <atom:updated>2026-08-12T07:27:40.374Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What 10+ years in corporate life and one simple idea from Atomic Habits taught me about making productivity sustainable.</em></p><p>At 8:45 AM, I opened my laptop.</p><p>At 8:47 AM, I opened my email.</p><p>At 8:52 AM, I opened Teams.</p><p>At 8:57 AM, I checked my calendar.</p><p>At 9:03 AM, I opened Excel.</p><p>At 9:07 AM, I checked Teams again.</p><p>At 9:12 AM, I suddenly remembered that I had promised myself I would start working on an important analysis today.</p><p>At 9:15 AM, I decided I needed coffee first.</p><p>By 9:30 AM, I was <em>very productive</em>.</p><p>I had replied to emails, attended to messages, checked dashboards, joined a meeting and had an excellent conversation with my coffee.</p><p>I had done almost everything. Except the important thing.</p><p>Sound familiar?</p><p>After more than 10 years of working in the corporate world, I have realised something uncomfortable about productivity: <strong><em>Most of us don’t have a time-management problem. We have a behavior-design problem.</em></strong></p><p>We know what we should do.</p><p>Exercise.</p><p>Read.</p><p>Write.</p><p>Learn something new.</p><p>Plan our day.</p><p>Work on important projects.</p><p>Spend quality time with family.</p><p>Sleep on time.</p><p>And yet, knowing what to do and actually doing it are two very different things. This is where one of the most useful ideas I came across while reading <em>Atomic Habits</em> becomes extremely practical. The basic idea is beautifully simple:</p><blockquote><em>If you repeatedly fail to adopt a productive behavior, the problem may not be your motivation. The behavior may simply be poorly designed.</em></blockquote><p>The framework described in the material I studied is built around <strong>four laws of behavior change:</strong></p><ol><li>Make it <strong>Obvious</strong></li><li>Make it <strong>Easy</strong></li><li>Make it <strong>Attractive</strong></li><li>Make it <strong>Satisfying</strong></li></ol><p>And when I started looking at productivity through this lens, many of my own habits suddenly made sense.</p><h3>The Productivity Trap: Waiting for Motivation</h3><p>We often imagine productive people as people with extraordinary discipline.</p><p>They wake up at 5 AM.</p><p>Meditate.</p><p>Run 10 kilometres.</p><p>Read 50 pages.</p><p>Write 2,000 words.</p><p>Work deeply for four hours.</p><p>Eat perfectly.</p><p>And somehow still have enough energy to post about it on LinkedIn. Meanwhile, the rest of us are trying to remember where we put our headphones.</p><p>The problem is that we often try to build our lives around <strong>motivation</strong>. But motivation is unreliable.</p><p>Some Monday mornings you feel unstoppable.</p><p>Other Monday mornings, even opening your laptop feels like a strategic transformation initiative. So instead of asking:</p><p><strong>“How can I become more disciplined?”</strong></p><p>a better question is: <strong>“How can I design my environment and routine so that the desired behavior becomes easier to start?”</strong></p><p>That’s a very different question. And it leads us to the first law.</p><h3>Law 1: Make It Obvious</h3><p>Imagine you decide: <em>From tomorrow, I will exercise every morning.</em></p><p>Sounds great. But what exactly happens tomorrow morning?</p><p>Your alarm rings.</p><p>You wake up.</p><p>You check your phone.</p><p>You see WhatsApp.</p><p>Then Instagram.</p><p>Then email.</p><p>Then perhaps a news notification.</p><p>Twenty minutes later, you’re sitting on the edge of your bed wondering where the morning went. The problem wasn’t that you didn’t want to exercise.</p><p><strong>The exercise habit didn’t have a strong cue.</strong></p><p>The source material gives a simple example of how existing habits can become cues for new habits: flushing the toilet naturally became a trigger for washing hands.</p><p>This concept is called <strong>habit stacking</strong>.</p><p>Instead of saying: <em>I will read every night.”\</em></p><p>say: <strong><em>After I brush my teeth at night, I will read one page.</em></strong></p><p>Instead of: <em>I will learn Python.</em></p><p>say: <strong><em>After I start my laptop in the morning, I will spend 10 minutes learning Python before opening email.”</em></strong></p><p>Instead of: <em>I should exercise.</em></p><p>say: <strong><em>After I finish my morning tea, I will put on my walking shoes.</em></strong></p><p>Notice the difference. The second version has a <strong>trigger</strong>.</p><p>You’re not relying on your brain to remember a vague intention. You’re attaching the new behavior to something that already happens.</p><h3>A simple formula</h3><p><strong>After I [existing habit], I will [new habit].</strong></p><ul><li>After morning tea → read 2 pages</li><li>After lunch → walk for 10 minutes</li><li>After opening laptop → write today’s top priority</li><li>After dinner → prepare tomorrow’s workout clothes</li><li>After brushing teeth → journal for 2 minutes</li></ul><p>The old habit becomes the train. Your new habit simply jumps onboard.</p><h3>But There Is a Problem…</h3><p>Let’s say you successfully create a cue.</p><p>Every morning at 7 AM, you see your running shoes. Excellent.</p><p>Except the shoes are sitting next to the door looking at you.</p><p>And you’re looking back at them thinking: <em>“Maybe tomorrow.”</em></p><p>This brings us to Law #2.</p><h3>Law 2: Make It Easy</h3><p>One of the biggest mistakes we make when starting a new habit is making the starting point too ambitious.</p><p>We say: <em>“I’m going to exercise for 60 minutes every day.”</em></p><p>Or: <em>“I’ll read 30 pages every night.”</em></p><p>Or: <em>“I’ll study machine learning for two hours every evening.”</em></p><p>Three days later: <strong>The ambitious new lifestyle has entered the cemetery of New Year’s resolutions.</strong></p><p>The Two-Minute Rule offers a much more practical approach: reduce the new habit to something that takes less than two minutes to start.</p><p>So instead of: <strong>Read every night.</strong></p><p>start with: <strong>Read one page.</strong></p><p>The important insight is this: <strong>The goal initially isn’t to complete the entire activity. The goal is to become the person who starts.</strong></p><p>Once you’ve put on your running shoes, running becomes easier.</p><p>Once you’ve opened the book, reading becomes easier.</p><p>Once you’ve opened your notebook, studying becomes easier.</p><p>Starting is often the hardest part. So make the starting point ridiculously small.</p><h3>My Favorite Productivity Hack: Reduce the Activation Energy</h3><p>Think about a task you keep postponing.</p><p>Perhaps it’s writing.</p><p>You tell yourself: <em>“I need two uninterrupted hours to write.”</em></p><p>That makes writing feel like a major corporate project.</p><p>Instead: <strong>Open the document.</strong></p><p>Write one sentence. That’s it.</p><p>You may stop after one sentence. Or you may continue. But you’ve eliminated the psychological barrier of <em>starting</em>. This is particularly useful for knowledge workers.</p><p>Because many of our important tasks aren’t physically difficult. They’re <strong>mentally expensive to initiate</strong>.</p><p>The trick is to shrink the first step until your brain has very little reason to resist it.</p><h3>Law 3: Make It Attractive</h3><p>Now comes the fun part. Sometimes making something easy isn’t enough. Because let’s be honest: Watching Netflix is attractive but doing expense reports is not.</p><p>Scrolling Instagram is attractive but reading a technical paper after a long workday?</p><p>Let’s not pretend. So why not <strong>pair something you already enjoy with something you want to do?</strong></p><p>Example is combining exercise with enjoyable entertainment.</p><p>This is essentially: <strong>I get something I want only when I do something I need.</strong></p><p>Want to walk more? Listen to your favorite podcast only while walking.</p><p>Want to exercise? Watch your favorite show only while on the treadmill.</p><p>Want to write? Listen to your favorite playlist only while writing.</p><p>Want to study? Make your favorite coffee and sit in your favorite chair only for your learning session.</p><p>Now the brain begins to associate the difficult behavior with something pleasurable.</p><p>Instead of <em>Exercise = punishment</em></p><p>you gradually create: <em>Exercise = Netflix time</em></p><p>That’s a much easier sales pitch to your brain.</p><h3>The Corporate Version of This Trick</h3><p>Suppose you have a task you absolutely hate: <strong>Preparing the weekly report.</strong></p><p>You could pair it with something enjoyable.</p><p>Maybe:</p><ul><li>Your favorite coffee</li><li>Your favorite playlist</li><li>A quiet workspace</li><li>A particular snack</li><li>A walk immediately afterward</li></ul><p>The point isn’t to bribe yourself forever. The point is to reduce the resistance associated with starting. Over time, the behavior itself can become more satisfying. And that takes us to the fourth law.</p><h3>Law 4: Make It Satisfying</h3><p>Here’s a strange thing about the human brain.</p><p>We are often terrible at choosing between: <strong>A reward today </strong>and <strong>A much bigger reward six months from now.</strong></p><p>You know that exercising today is good for your health.</p><p>But your brain says: <em>“Yes, absolutely. But wouldn’t sitting on the sofa be healthier for my emotional wellbeing?”</em></p><p>The problem is that many productive behaviors have <strong>delayed rewards</strong>.</p><p>Study today. Benefit months later.</p><p>Exercise today. Health benefit years later.</p><p>Save money today. Financial security years later.</p><p>Write today. Career benefits perhaps months later.</p><p>The brain needs some immediate feedback. That’s where tracking becomes powerful.</p><p>Use a habit tracker or calendar to record completed behaviors and create visible evidence of progress.</p><p>Imagine looking at a calendar and seeing: <strong>✓ ✓ ✓ ✓ ✓ ✓ ✓</strong></p><p>Seven workouts. Your brain now has evidence: <em>“I am actually doing this.”</em></p><p>That creates a small sense of achievement. And that achievement makes you want to continue.</p><h3>Don’t Track Everything. Track the Behavior.</h3><p>This is where I think productivity systems often become unnecessarily complicated.</p><p>We create:</p><ul><li>17-column Notion dashboards</li><li>elaborate Excel trackers</li><li>color-coded calendars</li><li>five productivity apps</li><li>wearable dashboards</li><li>quarterly OKRs</li><li>weekly reviews</li><li>daily reviews</li></ul><p>And then spend 45 minutes tracking the fact that we didn’t have time to do the actual work. Keep it simple.</p><p>If your goal is exercise: <strong>Workout → ✓</strong></p><p>If your goal is reading: <strong>Read → ✓</strong></p><p>If your goal is writing: <strong>Write → ✓</strong></p><p>The tracker isn’t supposed to become another job. It is simply a mirror showing you what you’re actually doing.</p><h3>The Four Laws Become a Productivity System</h3><p>Now let’s bring everything together.</p><p>Suppose your goal is: “I want to write every day.”</p><p>Don’t simply write: <strong><em>Goal: Write every day.</em></strong></p><p>Design the behavior.</p><h3>1. Make it Obvious</h3><p>After I finish my morning tea, I will open my writing document.</p><h3>2. Make it Easy</h3><p>I only need to write one sentence.</p><p>Not 1,000 words. One sentence.</p><h3>3. Make it Attractive</h3><p>I can listen to my favorite playlist while writing.</p><h3>4. Make it Satisfying</h3><p>I put a ✓ on my calendar after completing the session.</p><p>Now you have a system. And importantly, <strong>the system doesn’t depend entirely on motivation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEJq7zaa4yWCaUlsPOYqKQ.png" /></figure><p>Notice something important. None of these systems begins with: <strong>“I need more willpower.”</strong></p><p>They begin with: <strong>“How can I design the behavior?”</strong></p><h3>The Bigger Lesson: Productivity Is an Identity Game</h3><p>There is another powerful idea hidden inside habit tracking. When you repeatedly perform a behavior, you’re not just completing a task.</p><p>You’re collecting evidence about who you are.</p><p>One workout says: <em>I exercised. </em>Twenty workouts say: <em>I am someone who exercises.</em></p><p>One article says: <em>I wrote an article. </em>Fifty articles say: <em>I am a writer.”</em></p><p>One learning session says: <em>I studied AI. </em>Hundreds of sessions say: <em>I am someone who continuously learns.</em></p><p>The source material describes this as seeing a pattern of behavior that provides evidence that you are becoming the kind of person you want to be. And I think this is one of the most useful ways to think about productivity.</p><p><strong>Don’t focus only on what you want to accomplish. Focus on the person you want your repeated behaviors to create.</strong></p><h3>The 10-Minute Habit Design Exercise</h3><p>Tonight, choose <strong>one habit</strong> you’ve been postponing.</p><p>Write this down: <strong>My habit:</strong></p><p><strong>My existing cue:</strong><br>After I __________</p><p><strong>My two-minute version:</strong><br>I will __________</p><p><strong>My attractive reward:</strong><br>I will enjoy __________ while doing it.</p><p><strong>My tracking method:</strong><br>I will mark __________ whenever I complete it.</p><p>Then start tomorrow.</p><p>Because there is another productivity trap we fall into: <em>“I’ll start properly when I have more time.”</em></p><p>You probably won’t.</p><p>Life will continue producing meetings, emails, deadlines, family commitments, unexpected problems and an impressive number of notifications.</p><p>The goal isn’t to create a perfect life in which nothing interrupts you. <strong>The goal is to create behaviors that survive an imperfect life.</strong></p><h3>Final Thought</h3><p>After more than a decade in corporate life, I’ve become increasingly convinced that sustainable productivity isn’t about squeezing more work into every available minute.</p><p>It’s about making the behaviors that matter <strong>easy enough to repeat</strong>. You don’t need to become a productivity machine.</p><p>You don’t need to wake up at 4:30 AM.</p><p>You don’t need a 37-step morning routine.</p><p>And you definitely don’t need another productivity app.</p><p>Start smaller.</p><p>Attach the behavior to something you already do.</p><p>Make the first step ridiculously easy.</p><p>Give yourself a reason to enjoy it.</p><p>Track the completion.</p><p>Then repeat.</p><p>Because productivity isn’t built in one heroic Monday morning.</p><p><strong>It is built through hundreds of ordinary moments when you choose to do the small thing again.</strong></p><p>Then let the small wins compound.</p><h3>If You Found This Useful…</h3><p>If this blog gave you one idea you can actually use tomorrow, <strong>please give it a like and follow me</strong> for more practical lessons on productivity</p><p>I’ll keep sharing ideas that are simple enough to understand, practical enough to use, and hopefully interesting enough to make you come back for the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cfc15dbd2a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3. Conditional Workflows in LangGraph]]></title>
            <link>https://medium.com/@ashu.analytix/part-3-conditional-workflows-in-langgraph-6eda8d235cc4?source=rss-4dfa55c9d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eda8d235cc4</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Ashutosh Patel]]></dc:creator>
            <pubDate>Sat, 08 Aug 2026 12:53:37 GMT</pubDate>
            <atom:updated>2026-08-12T15:14:57.839Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an AI Customer Support Agent</h3><p>In my previous two articles, I explored two fundamental workflow patterns for building Agentic AI applications with <strong>LangGraph</strong>:</p><ul><li><a href="https://medium.com/@ashu.analytix/build-ai-workflows-with-langgraph-part-1-your-first-agentic-ai-application-ce634fe6e1ef"><strong>Part 1 </strong></a><strong>— Sequential Workflow:</strong> How multiple LLM tasks can be executed one after another.</li><li><a href="https://medium.com/@ashu.analytix/build-your-first-parallel-ai-workflow-with-langgraph-part-2-c0fa10580c35"><strong>Part 2</strong></a><strong> — Parallel Workflow:</strong> How independent LLM tasks can execute in parallel and their outputs can later be combined.</li></ul><p>In this article, we move to the <strong>third fundamental workflow pattern — Conditional Workflow</strong>.</p><p>Instead of always following the same path, our AI system will make a decision based on the information it receives and dynamically choose what to do next.</p><p>And to make the concept practical, we’ll build a small <strong>AI Customer Support Assistant</strong> that analyzes product reviews and generates an appropriate response.</p><p>If you are landing directly on this article, I recommend reading <a href="https://medium.com/@ashu.analytix/build-ai-workflows-with-langgraph-part-1-your-first-agentic-ai-application-ce634fe6e1ef"><strong>Part 1</strong></a><strong> and </strong><a href="https://medium.com/@ashu.analytix/build-your-first-parallel-ai-workflow-with-langgraph-part-2-c0fa10580c35"><strong>Part 2</strong></a> first because this article builds on the LangGraph concepts introduced there.</p><p>Let’s get started.</p><h3>What Is a Conditional Workflow?</h3><p>Before writing any code, let’s understand the problem we’re trying to solve. Imagine a customer leaves the following review:</p><blockquote><em>“The application is smooth and very easy to use. I’m really happy with the experience.”</em></blockquote><p>We probably don’t need a complex customer-support investigation. We can simply thank the customer and ask them to leave feedback on our website.</p><p>Now consider a very different review:</p><blockquote><em>“I’ve been trying to log in for over an hour now, and the app keeps freezing on the authentication screen. I even tried reinstalling it, but no luck.”</em></blockquote><p>This requires a completely different workflow.</p><p>We need to:</p><ol><li>Understand the customer’s sentiment.</li><li>Diagnose the problem.</li><li>Identify the issue type.</li><li>Understand the customer’s tone.</li><li>Determine the urgency.</li><li>Generate an empathetic support response.</li><li>So our workflow should not blindly execute the same steps for every review.</li></ol><p>Instead, it should make a decision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*PhngNDEivV3MWROZNJYn0A.png" /></figure><p>This is the essence of a <strong>Conditional Workflow</strong>. The next node depends on the output of the previous node.</p><h3>What Are We Building?</h3><p>The mini-project in this article is an <strong>AI Customer Support Assistant</strong>. The system takes a customer review as input and automatically determines what should happen next.</p><h3>For a positive review</h3><p>The workflow:</p><pre>Review<br>   ↓<br>Sentiment Analysis<br>   ↓<br>Positive Response<br>   ↓<br>END</pre><h3>For a negative review</h3><p>The workflow becomes:</p><pre>Review<br>   ↓<br>Sentiment Analysis<br>   ↓<br>Diagnosis<br>   ↓<br>Negative Response<br>   ↓<br>END</pre><p>This simple example demonstrates one of the most important ideas in Agentic AI: <strong><em>An AI workflow doesn’t always have to follow a fixed path. It can make decisions and dynamically route execution.</em></strong></p><h3>Setting Up the Environment</h3><p>Let’s start with the imports.</p><pre>from pprint import pprint<br>import os<br>import getpass<br>from IPython.display import Markdown, display<br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Literal<br>from pydantic import BaseModel, Field</pre><p>Let’s understand each import.</p><h3>Configuring the Groq API Key</h3><p>Next, we configure the API key.</p><pre>if &quot;GROQ_API_KEY&quot; not in os.environ:<br>    os.environ[&quot;GROQ_API_KEY&quot;] = getpass.getpass(&quot;GROQ_API_KEY: &quot;)</pre><p>This checks whether the GROQ_API_KEY already exists as an environment variable. If it doesn’t, the notebook asks us to enter the key securely.</p><p>This is preferable to hardcoding an API key directly into the notebook.</p><h3>Selecting the LLM</h3><p>Now we initialize our language model.</p><pre>model = ChatGroq(model=&quot;openai/gpt-oss-120b&quot;)</pre><p>We’re using the ChatGroq integration to interact with the LLM through Groq. The same model will be used for several different tasks:</p><ul><li>Sentiment classification</li><li>Customer response generation</li><li>Negative-review diagnosis</li><li>Final support response generation</li></ul><p>This is a useful pattern because the workflow determines <strong>how the model is used</strong>, while the prompts determine <strong>what each node is responsible for</strong>.</p><h3>Creating a Sentiment Schema</h3><p>Our first AI task is sentiment analysis. We don’t want the LLM to return an arbitrary sentence such as: <em>The customer appears to be somewhat unhappy.</em></p><p>Instead, we want a predictable value. So we define a schema.</p><pre>class SentimentSchema(BaseModel):<br>  sentiment: Literal[&quot;positive&quot;, &quot;negative&quot;] = Field(description=&#39;Sentiment of the review&#39;)</pre><p>The model is now constrained to return one of two values: positive or negative</p><p>This is particularly useful when the output is going to control the next step of a workflow. The LLM isn’t simply generating text here. It is making a <strong>decision</strong> that will determine the path through our graph.</p><h3>Creating the Diagnosis Schema</h3><p>For negative reviews, sentiment alone isn’t enough. We need to understand what actually went wrong. So we create another structured schema.</p><pre>class DiagnosisSchema(BaseModel):<br>  issue_type: Literal[<br>          &quot;UX&quot;,<br>          &quot;Performance&quot;,<br>          &quot;Bug&quot;,<br>          &quot;Support&quot;,<br>          &quot;Other&quot;<br>      ] = Field(<br>          description=&#39;The category of issue mentioned in the review&#39;<br>      )<br>      tone: Literal[<br>          &quot;angry&quot;,<br>          &quot;frustrated&quot;,<br>          &quot;disappointed&quot;,<br>          &quot;calm&quot;<br>      ] = Field(<br>          description=&#39;The emotional tone expressed by the user&#39;<br>      )<br>      urgency: Literal[<br>          &quot;low&quot;,<br>          &quot;medium&quot;,<br>          &quot;high&quot;<br>      ] = Field(<br>          description=&#39;How urgent or critical the issue appears to be&#39;<br>      )</pre><p>We ask the model to classify the negative review across three dimensions.</p><h3>Issue Type</h3><p>What kind of problem is the customer experiencing?</p><p>Possible values: UX, Performance, Bug, Support, Other</p><h3>Tone</h3><p>How does the customer sound ?</p><p>Possible values: Angry, Frustrated, Disappointed, Calm</p><h3>Urgency</h3><p>How serious is the problem ?</p><p>Possible values: Low, Medium, High</p><p>This structured diagnosis will later be passed to another LLM node to generate a more appropriate response.</p><h3>Creating Structured LLM Models</h3><p>Now we convert our normal LLM into two structured-output models.</p><pre>structured_sentiment = model.with_structured_output(SentimentSchema)</pre><p>This makes our workflow much more reliable because downstream nodes don’t have to interpret free-form LLM responses.</p><h3>Testing the Sentiment Model</h3><p>Before putting everything into LangGraph, let’s test the structured sentiment model independently.</p><pre>prompt = &#39;What is the sentiment of the following review - The application is smooth&#39;<br>structured_sentiment.invoke(prompt).sentiment</pre><p>The expected result is: positive</p><h3>Defining the Workflow State</h3><p>Now we define the state that will flow through our graph.</p><pre>class ReviewState(TypedDict):<br>  review: str<br>      sentiment: Literal[&quot;positive&quot;, &quot;negative&quot;]<br>      diagnosis: dict<br>      response: str</pre><p>There are four pieces of information in our state.</p><p>review: The original customer review.</p><p>sentiment: The sentiment identified by our first LLM node.</p><p>diagnosis: The structured diagnosis of a negative review.</p><p>response: The final response generated by our AI customer-support assistant.</p><h3>Node 1: Finding Customer Sentiment</h3><p>Now we create our first LangGraph node.</p><pre>def find_sentiment(state: ReviewState):<br>  prompt = f&#39;&#39;&#39;<br>      For the following review find out the sentiment<br>      {state[&quot;review&quot;]}<br>      &#39;&#39;&#39;<br>      sentiment = structured_sentiment.invoke(prompt).sentiment<br>      return {<br>          &#39;sentiment&#39;: sentiment<br>      }</pre><p>This node performs one simple task: <em>Determine whether the customer review is positive or negative.</em></p><h3>Node 2: The Decision Function</h3><p>This is where conditional workflow actually begins.</p><pre>def check_sentiment(state: ReviewState) -&gt; Literal[&quot;positive_response&quot;, &quot;run_diagnosis&quot;]:<br>  if state[&#39;sentiment&#39;] == &#39;positive&#39;:<br>          return &#39;positive_response&#39;<br>      else:<br>          return &#39;run_diagnosis&#39;</pre><p>This function acts as our <strong>router</strong>. It checks the sentiment stored in the state.</p><ul><li>If the sentiment is positive: positive → positive_response.</li><li>If the sentiment is negative: negative → run_diagnosis</li></ul><p>Notice something important. This function itself doesn’t call an LLM. It simply makes a routing decision based on the state. This separation is a good design principle: <strong><em>Use LLMs for tasks requiring language understanding or generation, and use deterministic Python logic wherever a simple rule is sufficient.</em></strong></p><h3>Node 3: Handling Positive Reviews</h3><p>If the review is positive, there is no reason to perform a detailed diagnosis. We can directly generate a thank-you message.</p><pre>def positive_response(state: ReviewState):<br>  prompt = f&quot;&quot;&quot;<br>      Write a warm thank-you message in response to this review:<br>      &quot;{state[&#39;review&#39;]}&quot;<br>      Also, kindly ask the user to leave feedback on our website.<br>      &quot;&quot;&quot;<br>      response = model.invoke(prompt).content<br>      return {<br>          &#39;response&#39;: response<br>      }</pre><p>Since positive reviews don’t require diagnosis, this branch can directly terminate.</p><h3>Node 4: Diagnosing Negative Reviews</h3><p>Now let’s look at the other branch. If the sentiment is negative, we don’t immediately generate a response. First, we diagnose the issue.</p><pre>def run_diagnosis(state: ReviewState):<br>  prompt = f&quot;&quot;&quot;<br>      Diagnose this negative review:<br>      {state[&#39;review&#39;]}<br>      Return issue_type, tone, and urgency.<br>      &quot;&quot;&quot;<br>      response = structured_diagnosis.invoke(prompt)<br>      return {<br>          &#39;diagnosis&#39;: response.model_dump()<br>      }</pre><p>This node performs a deeper analysis. The structured model determines: Issue Type, Tone, Urgency</p><p>The Pydantic object is converted into a Python dictionary using:</p><pre>response.model_dump()</pre><p>The resulting state could look like:</p><pre>{<br>    &quot;diagnosis&quot;: {<br>        &quot;issue_type&quot;: &quot;Bug&quot;,<br>        &quot;tone&quot;: &quot;frustrated&quot;,<br>        &quot;urgency&quot;: &quot;high&quot;<br>    }<br>}</pre><p>Now another node can use this information to create a more context-aware response.</p><h3>Node 5: Generating the Negative Response</h3><p>Once the diagnosis is available, we generate the final customer response.</p><pre>def negative_response(state: ReviewState):<br>  diagnosis = state[&#39;diagnosis&#39;]<br>      prompt = f&quot;&quot;&quot;<br>      You are a support assistant.<br>      The user had a &#39;{diagnosis[&#39;issue_type&#39;]}&#39; issue,<br>      sounded &#39;{diagnosis[&#39;tone&#39;]}&#39;,<br>      and marked urgency as &#39;{diagnosis[&#39;urgency&#39;]}&#39;.<br>      Write an empathetic, helpful resolution message.<br>      &quot;&quot;&quot;<br>      response = model.invoke(prompt).content<br>      return {<br>          &#39;response&#39;: response<br>      }</pre><p>This is where the diagnosis becomes useful. Instead of simply asking: <em>Respond to this negative review. W</em>e give the LLM additional context. For example:</p><pre>Issue: Bug<br>Tone: Frustrated<br>Urgency: High</pre><p>The LLM can therefore generate a response that is more empathetic and appropriate to the situation. This is an important Agentic AI pattern: <strong><em>One AI node analyzes a problem, and another AI node uses that analysis to perform the next action.</em></strong></p><h3>Building the LangGraph</h3><p>Now that all our nodes are ready, we can construct the workflow.</p><pre>graph = StateGraph(ReviewState)</pre><p>We tell LangGraph that our workflow will use the ReviewState schema.</p><h3>Adding Nodes to the Graph</h3><p>Next, we register all the functions as graph nodes.</p><pre>graph = StateGraph(ReviewState)<br><br>graph.add_node(&#39;find_sentiment&#39;, find_sentiment)<br>graph.add_node(&#39;positive_response&#39;, positive_response)<br>graph.add_node(&#39;run_diagnosis&#39;, run_diagnosis)<br>graph.add_node(&#39;negative_response&#39;, negative_response)<br><br>graph.add_edge(START, &#39;find_sentiment&#39;)<br><br>graph.add_conditional_edges(&#39;find_sentiment&#39;, check_sentiment)<br><br>graph.add_edge(&#39;positive_response&#39;, END)<br><br>graph.add_edge(&#39;run_diagnosis&#39;, &#39;negative_response&#39;)<br>graph.add_edge(&#39;negative_response&#39;, END)<br><br>workflow = graph.compile()</pre><p>Our graph now contains four nodes: find_sentiment, positive_response, run_diagnosis, negative_response</p><p>But at this point, LangGraph doesn’t know how these nodes are connected. That’s what edges are for.</p><h3>Adding the Conditional Edge</h3><p>Now comes the most important line in the entire article.</p><pre>graph.add_conditional_edges(<br>    &#39;find_sentiment&#39;,<br>    check_sentiment<br>)</pre><p>a conditional edge doesn’t specify one fixed destination. Instead, LangGraph calls:</p><pre>check_sentiment</pre><p>and uses the returned value to determine where execution should go.</p><p>Therefore, the graph dynamically becomes:</p><h3>Connecting the Positive Branch</h3><p>For positive reviews:</p><pre>graph.add_edge(<br>    &#39;positive_response&#39;,<br>    END<br>)</pre><p>The flow is:</p><pre>find_sentiment<br>      ↓<br>positive_response<br>      ↓<br>     END</pre><p>There is no reason to run diagnosis for a positive review.</p><p>This is one of the benefits of conditional routing: <strong>we only execute the work that is actually required.</strong></p><h3>Connecting the Negative Branch</h3><p>For negative reviews:</p><pre>graph.add_edge(<br>    &#39;run_diagnosis&#39;,<br>    &#39;negative_response&#39;<br>)</pre><p>The diagnosis must happen before the response is generated.</p><p>Therefore:</p><pre>run_diagnosis<br>      ↓<br>negative_response</pre><p>Finally:</p><pre>graph.add_edge(<br>    &#39;negative_response&#39;,<br>    END<br>)</pre><p>Once the response has been generated, the workflow finishes.</p><h3>Compiling the Workflow</h3><p>Our graph structure is now complete. We compile it:</p><pre>workflow = graph.compile()</pre><p>Compilation converts our graph definition into an executable workflow.</p><h3>Providing the Customer Review</h3><p>We’ll test the workflow with a negative customer review.</p><pre>intial_state={<br>    &#39;review&#39;: &quot;I’ve been trying to log in for over an hour now, and the app keeps freezing on the authentication screen. I even tried reinstalling it, but no luck. This kind of bug is unacceptable, especially when it affects basic functionality.&quot;<br>}<br>result = workflow.invoke({&quot;review&quot;: intial_state[&quot;review&quot;]})<br><br>display(Markdown(f&quot;&quot;&quot;<br># 🤖 AI Customer Support Assistant<br><br>## 📧 Suggested Response<br><br>{result[&#39;response&#39;]}<br><br>---<br><br>## 📋 Issue Summary<br><br>- **Issue Type:** {result[&#39;diagnosis&#39;][&#39;issue_type&#39;]}<br>- **Priority:** {result[&#39;diagnosis&#39;][&#39;urgency&#39;].capitalize()}<br>- **Customer Sentiment:** {result[&#39;sentiment&#39;].capitalize()}<br>- **Customer Tone:** {result[&#39;diagnosis&#39;][&#39;tone&#39;].capitalize()}<br><br>---<br><br>## 💬 Original Customer Review<br><br>&gt; {result[&#39;review&#39;]}<br><br>---<br><br>## 🔍 AI Diagnosis<br><br>| Attribute | Value |<br>|-----------|-------|<br>| Issue Type | {result[&#39;diagnosis&#39;][&#39;issue_type&#39;]} |<br>| Sentiment | {result[&#39;sentiment&#39;].capitalize()} |<br>| Tone | {result[&#39;diagnosis&#39;][&#39;tone&#39;].capitalize()} |<br>| Urgency | {result[&#39;diagnosis&#39;][&#39;urgency&#39;].capitalize()} |<br>&quot;&quot;&quot;))</pre><p>This review contains several useful signals.</p><p>The customer:</p><ul><li>Cannot log in.</li><li>Has been trying for more than an hour.</li><li>Tried reinstalling the application</li><li>Reports the app freezing.</li><li>Explicitly calls it a bug.</li><li>Is clearly frustrated.</li><li>Considers the problem unacceptable.</li></ul><p>This makes it an excellent example for demonstrating our conditional workflow.</p><h3>Executing the Workflow</h3><p>Now we invoke the graph.</p><pre>result = workflow.invoke({<br>    &quot;review&quot;: initial_state[&quot;review&quot;]<br>})</pre><p>Let’s follow what happens internally.</p><h3>Step 1 — Review enters the graph</h3><pre>START<br> ↓<br>find_sentiment</pre><h3>Step 2 — Sentiment is identified</h3><p>The LLM determines:</p><pre>negative</pre><h3>Step 3 — Router makes a decision</h3><p>check_sentiment() sees:</p><pre>negative</pre><p>and returns:</p><pre>run_diagnosis</pre><h3>Step 4 — Diagnosis runs</h3><p>The diagnosis model might determine:</p><pre>Issue Type → Bug<br>Tone       → Frustrated<br>Urgency    → High</pre><h3>Step 5 — Response generation</h3><p>The negative-response node receives the diagnosis and generates an empathetic response.</p><h3>Step 6 — Workflow ends</h3><pre>negative_response<br>       ↓<br>      END</pre><p>The final result contains the accumulated state.</p><h3>Suggested Response</h3><p>The AI-generated message that the support team can use.</p><h3>Issue Summary</h3><p>A quick overview containing:</p><ul><li>Issue type</li><li>Priority</li><li>Sentiment</li><li>Customer tone</li></ul><h3>One Important Observation About the Output Cell</h3><p>There is a small implementation detail worth mentioning. The final display code assumes that:</p><pre>result[&#39;diagnosis&#39;]</pre><p>always exists.</p><p>But in our workflow, positive reviews bypass the diagnosis node. Therefore, if we run the workflow with a positive review, this output cell could raise a KeyError because diagnosis won&#39;t exist.</p><p>A more production-ready implementation should handle both cases.</p><p>For example:</p><pre>if result[&quot;sentiment&quot;] == &quot;negative&quot;:<br>    # display diagnosis<br>else:<br>    # display only positive-review information</pre><p>This is an important lesson when building conditional workflows: <strong><em>The state produced by different branches may not contain the same fields. Your final presentation or downstream nodes should account for that.</em></strong></p><h3>Understanding the Complete Architecture</h3><p>Let’s step back and look at the complete workflow.</p><pre>START<br>                           |<br>                           ▼<br>                  ┌─────────────────┐<br>                  │ Find Sentiment  │<br>                  │      LLM        │<br>                  └────────┬────────┘<br>                           |<br>                    ┌──────┴──────┐<br>                    │             │<br>                Positive       Negative<br>                    │             │<br>                    ▼             ▼<br>          ┌────────────────┐  ┌───────────────┐<br>          │    Positive    │  │   Diagnosis   │<br>          │    Response    │  │      LLM      │<br>          └───────┬────────┘  └───────┬───────┘<br>                  │                   │<br>                  │                   ▼<br>                  │           ┌───────────────┐<br>                  │           │   Negative    │<br>                  │           │   Response    │<br>                  │           └───────┬───────┘<br>                  │                   │<br>                  ▼                   ▼<br>                 END                 END</pre><p>The important thing to notice is that the workflow is <strong>not linear</strong>. The system makes a decision and chooses a path. That’s what makes this an Agentic workflow rather than simply a sequence of LLM calls.</p><h3>Why Conditional Workflows Matter in Agentic AI</h3><p>Conditional routing is one of the building blocks for more sophisticated AI agents. Consider a customer-support system.</p><p>Instead of sending every customer request to the same workflow, we could route requests based on their intent</p><h3>What I Learned From This Mini Project</h3><p>While building this example, one of the biggest lessons for me was that <strong>Agentic AI is not necessarily about using more LLM calls</strong>.</p><p>It is about designing the right workflow around those calls. For example, in our application:</p><ul><li>We use an LLM for sentiment understanding.</li><li>We use deterministic Python logic for routing.</li><li>We use another structured LLM call for diagnosis.</li><li>We use the diagnosis to guide response generation.</li></ul><p>Each component has a specific responsibility. This makes the overall system easier to understand, debug, and extend.</p><h3>Key Takeaways</h3><p>In this article, we built an AI-powered customer-support workflow using LangGraph. More importantly, we learned how to implement <strong>conditional routing</strong>.</p><p>The key concepts were:</p><ul><li>Define a shared state using TypedDict</li><li>Use Pydantic for structured LLM outputs</li><li>Create specialized LangGraph nodes</li><li>Use deterministic Python logic for routing</li><li>Implement add_conditional_edges()</li><li>Dynamically select the next node</li><li>Create different workflows for positive and negative reviews</li><li>Pass the output of one AI node into another</li><li>Generate a final user-friendly response</li></ul><h3>Final Thoughts</h3><p>With <strong>Sequential Workflows</strong>, we learned how to execute tasks step by step.</p><p>With <strong>Parallel Workflows</strong>, we learned how to execute independent tasks simultaneously.</p><p>With <strong>Conditional Workflows</strong>, we introduce something even more interesting: <strong>Decision-making.</strong></p><p>The workflow can now look at the current state and decide what should happen next. And this is a fundamental capability when building real-world Agentic AI applications.</p><h3>Complete Code</h3><p>The complete Google Colab notebook and source code for this project are available in my GitHub repository.</p><p><strong>GitHub:</strong> <a href="https://github.com/ashutosh2909/Agentic-AI/blob/main/Workflow_in_LangGraph.ipynb">https://github.com/ashutosh2909/Agentic-AI/blob/main/Workflow_in_LangGraph.ipynb</a></p><p>If you find the project useful, feel free to ⭐ the repository and share your feedback. Finally, I want to say a sincere <strong>Thank You to </strong><a href="https://learnwith.campusx.in/"><strong>CampusX</strong></a>.</p><p><strong>See you in </strong><a href="https://medium.com/@ashu.analytix/part-4-iterative-workflow-using-langgraph-73ff56986c71?postPublishedType=initial"><strong>Part 4</strong></a><strong>!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eda8d235cc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your First Parallel AI Workflow with LangGraph (Part 2)]]></title>
            <link>https://medium.com/@ashu.analytix/build-your-first-parallel-ai-workflow-with-langgraph-part-2-c0fa10580c35?source=rss-4dfa55c9d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0fa10580c35</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[genrative-ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ashutosh Patel]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 05:19:11 GMT</pubDate>
            <atom:updated>2026-08-08T12:54:36.768Z</atom:updated>
            <content:encoded><![CDATA[<h3>Parallel Execution for Faster and Smarter LLM Applications</h3><p>If you’ve been following my <strong>Agentic AI with LangGraph</strong> series, welcome back!</p><p>In <a href="https://medium.com/@ashu.analytix/build-ai-workflows-with-langgraph-part-1-your-first-agentic-ai-application-ce634fe6e1ef"><strong>Part 1</strong></a>, we learned how to build a <strong>Sequential Workflow</strong> using LangGraph, where each LLM node waits for the previous node to finish before executing. That approach is simple, intuitive, and forms the foundation of most AI workflows.</p><p>However, many real-world AI systems don’t need every task to execute one after another. Often, multiple independent tasks can run simultaneously, significantly reducing the overall execution time.</p><p>In this article, we’ll build exactly that.</p><p>We’ll create a <strong>Parallel Workflow</strong> using LangGraph where multiple LLM agents evaluate an essay simultaneously before combining their outputs into a final assessment.</p><blockquote><strong><em>If you landed directly on this article, I highly recommend reading </em></strong><a href="https://medium.com/@ashu.analytix/build-ai-workflows-with-langgraph-part-1-your-first-agentic-ai-application-ce634fe6e1ef"><strong><em>Part 1</em></strong></a><strong><em> first</em></strong><em>, where I introduced LangGraph fundamentals, StateGraph, nodes, edges, and sequential execution. This article builds directly on those concepts.</em></blockquote><h3>What You’ll Build</h3><p>In this mini project, we’ll create an <strong>AI Essay Evaluation System</strong>.</p><p>Instead of asking one LLM to evaluate an essay on multiple dimensions, we’ll divide the work into multiple independent agents.</p><p>Each agent will specialize in one evaluation criterion. The workflow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*eMnmQ6qOSocOpiWnrjEffQ.png" /></figure><p>Each evaluation happens independently. Finally, another LLM combines all feedback into one summary and calculates the average score. This is a perfect example of <strong>Parallel Workflow</strong> in LangGraph.</p><h3>Installing Dependencies</h3><p>Let’s begin by installing the required libraries.</p><pre>!pip install langchain langgraph langchain_groq</pre><h3>What are these libraries?</h3><ul><li><strong>LangChain</strong> provides abstractions for working with LLMs.</li><li><strong>LangGraph</strong> helps us build graph-based AI workflows.</li><li><strong>LangChain-Groq</strong> allows us to use Groq-hosted language models with just a few lines of code.</li></ul><h3>Importing Required Modules</h3><p>Next, we import all the necessary packages.</p><pre>import getpass<br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Annotated<br>from pydantic import BaseModel, Field<br>import operator # tells LangGraph how to merge lists coming from multiple parallel nodes.<br>from langchain_groq import ChatGroq</pre><h3>Loading the Groq API Key</h3><pre>if &quot;GROQ_API_KEY&quot; not in os.environ:<br>    os.environ[&quot;GROQ_API_KEY&quot;] = getpass.getpass(&quot;GROQ_API_KEY: &quot;)<br>model = ChatGroq(model=&quot;openai/gpt-oss-120b&quot;)</pre><p>Instead of hardcoding secrets, we securely ask the user for the API key. This is a good practice for notebooks and tutorials.Selecting the LLM</p><p>We’ll use the <strong>openai/gpt-oss-120b</strong> model hosted on Groq. Groq provides extremely fast inference, making it ideal for agentic workflows where multiple LLM calls may execute in parallel.</p><h3>Creating Structured Output</h3><p>One common problem with LLMs is inconsistent responses. Sometimes they return paragraphs. Sometimes bullet points. Sometimes JSON. To solve this, we use structured output.</p><pre>class EvaluationSchema(BaseModel):<br>    feedback: str = Field(description=&#39;Detailed feedback for the essay&#39;)<br>    score: float = Field(description=&#39;Score out of 10&#39;, ge=0, le=10)</pre><p>Here we’re telling the model that every response <strong>must</strong> contain:</p><ul><li>Feedback</li><li>Score</li></ul><p>This makes downstream processing much easier. Now we bind the schema.</p><pre>structured_model = model.with_structured_output(EvaluationSchema)</pre><p>From now on, every LLM response automatically follows this schema. No manual parsing required.</p><h3>The Essay</h3><p>Next, we provide the essay to be evaluated.</p><pre><br>essay = &quot;&quot;&quot;India in the Age of AI<br>As the world enters a transformative era defined by artificial intelligence (AI), India stands at a critical juncture — one where it can either emerge as a global leader in AI innovation or risk falling behind in the technology race. The age of AI brings with it immense promise as well as unprecedented challenges, and how India navigates this landscape will shape its socio-economic and geopolitical future.<br><br>India&#39;s strengths in the AI domain are rooted in its vast pool of skilled engineers, a thriving IT industry, and a growing startup ecosystem. With over 5 million STEM graduates annually and a burgeoning base of AI researchers, India possesses the intellectual capital required to build cutting-edge AI systems. Institutions like IITs, IIITs, and IISc have begun fostering AI research, while private players such as TCS, Infosys, and Wipro are integrating AI into their global services. In 2020, the government launched the National AI Strategy (AI for All) with a focus on inclusive growth, aiming to leverage AI in healthcare, agriculture, education, and smart mobility.<br><br>One of the most promising applications of AI in India lies in agriculture, where predictive analytics can guide farmers on optimal sowing times, weather forecasts, and pest control. In healthcare, AI-powered diagnostics can help address India’s doctor-patient ratio crisis, particularly in rural areas. Educational platforms are increasingly using AI to personalize learning paths, while smart governance tools are helping improve public service delivery and fraud detection.<br><br>However, the path to AI-led growth is riddled with challenges. Chief among them is the digital divide. While metropolitan cities may embrace AI-driven solutions, rural India continues to struggle with basic internet access and digital literacy. The risk of job displacement due to automation also looms large, especially for low-skilled workers. Without effective skilling and re-skilling programs, AI could exacerbate existing socio-economic inequalities.<br><br>Another pressing concern is data privacy and ethics. As AI systems rely heavily on vast datasets, ensuring that personal data is used transparently and responsibly becomes vital. India is still shaping its data protection laws, and in the absence of a strong regulatory framework, AI systems may risk misuse or bias.<br><br>To harness AI responsibly, India must adopt a multi-stakeholder approach involving the government, academia, industry, and civil society. Policies should promote open datasets, encourage responsible innovation, and ensure ethical AI practices. There is also a need for international collaboration, particularly with countries leading in AI research, to gain strategic advantage and ensure interoperability in global systems.<br><br>India’s demographic dividend, when paired with responsible AI adoption, can unlock massive economic growth, improve governance, and uplift marginalized communities. But this vision will only materialize if AI is seen not merely as a tool for automation, but as an enabler of human-centered development.<br><br>In conclusion, India in the age of AI is a story in the making — one of opportunity, responsibility, and transformation. The decisions we make today will not just determine India’s AI trajectory, but also its future as an inclusive, equitable, and innovation-driven society.&quot;&quot;&quot;</pre><p>In this project, the essay discusses <strong>India in the Age of AI</strong>. Using a realistic essay makes the evaluation process much more meaningful and demonstrates how the workflow can be applied to real-world educational or assessment use cases.</p><h3>Designing the Shared State</h3><p>Every LangGraph application revolves around a shared state.</p><pre>class UPSCState(TypedDict):<br>    essay: str<br>    language_feedback: str<br>    analysis_feedback: str<br>    clarity_feedback: str<br>    overall_feedback: str<br>    individual_scores: Annotated[list[int], operator.add]<br>    avg_score: float</pre><p>Let’s understand every field.</p><ol><li>essay: The original essay. Every node receives it.</li><li>language_feedback: Stores grammar and language evaluation.</li><li>analysis_feedback: Stores content analysis.</li><li>clarity_feedback: Stores clarity evaluation.</li><li>overall_feedback: Final summarized feedback.</li><li>individual_scores: This is the most interesting field.</li><li>avg_score: Stores the final average score.</li></ol><p>Notice this declaration.</p><pre>Annotated[list[int], operator.add]</pre><p>Each parallel node returns one score. LangGraph automatically merges them.</p><p>Without this reducer, parallel execution would fail because multiple nodes would attempt to update the same state key simultaneously. This reducer is what enables clean aggregation of outputs from parallel branches.</p><h3>Creating Parallel Evaluation Nodes</h3><p>Now comes the exciting part. Instead of one large evaluation prompt, we’ll divide the work into three specialized nodes.</p><h3>Language Evaluation</h3><pre>def evaluate_language(state: UPSCState):<br>  prompt = f&#39;Evaluate the language quality...&#39;<br>  output = structured_model.invoke(prompt)<br>  return {<br>          &#39;language_feedback&#39;: output.feedback,<br>          &#39;individual_scores&#39;: [output.score]<br>      }</pre><p>This node evaluates grammar, vocabulary, sentence construction, and writing quality.</p><h3>Analysis Evaluation</h3><pre>def evaluate_analysis(state: UPSCState):<br><br>    prompt = f&#39;Evaluate the depth of analysis of the following essay and provide a feedback and assign a score out of 10 \n {state[&quot;essay&quot;]}&#39;<br>    output = structured_model.invoke(prompt)<br><br>    return {&#39;analysis_feedback&#39;: output.feedback, &#39;individual_scores&#39;: [output.score]}</pre><p>This node focuses only on: depth, reasoning, arguments, critical thinking. Specialization usually produces better results than asking one prompt to do everything.</p><h3>Clarity Evaluation</h3><pre>def evaluate_thought(state: UPSCState):<br>    prompt = f&#39;Evaluate the clarity of thought of the following essay and provide a feedback and assign a score out of 10 \n {state[&quot;essay&quot;]}&#39;<br>    output = structured_model.invoke(prompt)<br><br>    return {&#39;clarity_feedback&#39;: output.feedback, &#39;individual_scores&#39;: [output.score]}</pre><p>This evaluates: logical flow, readability, coherence, organization. Again, it independently returns feedback and a score.</p><p>Since all three nodes are independent, LangGraph can execute them in parallel.</p><h3>Creating the Final Evaluation Node</h3><p>Once every parallel branch finishes, we combine the outputs.</p><pre>def final_evaluation(state: UPSCState):<br>    # summary feedback<br>    prompt = f&#39;Based on the following feedbacks create a summarized feedback \n language feedback - {state[&quot;language_feedback&quot;]} \n depth of analysis feedback - {state[&quot;analysis_feedback&quot;]} \n clarity of thought feedback - {state[&quot;clarity_feedback&quot;]}&#39;<br>    overall_feedback = model.invoke(prompt).content<br><br>    # avg calculate<br>    avg_score = sum(state[&#39;individual_scores&#39;])/len(state[&#39;individual_scores&#39;])<br><br>    return {&#39;overall_feedback&#39;: overall_feedback, &#39;avg_score&#39;: avg_score}</pre><p>Inside this function, we perform two tasks.</p><ol><li>Generate Overall Feedback</li></ol><pre>overall_feedback = model.invoke(prompt).content</pre><p>The LLM reads all three evaluations and creates a concise summary.</p><p>Think of this node as a senior reviewer who reads reports from three experts before writing the final remarks.</p><p>2. Calculate Average Score</p><pre>avg_score = sum(state[&#39;individual_scores&#39;]) / len(state[&#39;individual_scores&#39;])</pre><p>Because our reducer has already combined all scores into one list, calculating the average becomes straightforward.</p><p>Finally, the node returns the overall feedback and average score.</p><h3>Building the Graph</h3><p>Now we connect everything.</p><pre>graph = StateGraph(UPSCState)<br><br>graph.add_node(&#39;evaluate_language&#39;, evaluate_language)<br>graph.add_node(&#39;evaluate_analysis&#39;, evaluate_analysis)<br>graph.add_node(&#39;evaluate_thought&#39;, evaluate_thought)<br>graph.add_node(&#39;final_evaluation&#39;, final_evaluation)<br><br># edges<br>graph.add_edge(START, &#39;evaluate_language&#39;)<br>graph.add_edge(START, &#39;evaluate_analysis&#39;)<br>graph.add_edge(START, &#39;evaluate_thought&#39;)<br><br>graph.add_edge(&#39;evaluate_language&#39;, &#39;final_evaluation&#39;)<br>graph.add_edge(&#39;evaluate_analysis&#39;, &#39;final_evaluation&#39;)<br>graph.add_edge(&#39;evaluate_thought&#39;, &#39;final_evaluation&#39;)<br><br>graph.add_edge(&#39;final_evaluation&#39;, END)<br><br>workflow = graph.compile()<br>workflow</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*6eEX7oSpEbIpkLReFB3XYw.png" /></figure><p>Then we register all nodes &amp; edges. Notice that all three nodes originate directly from START. This tells LangGraph that these branches are independent and can execute in parallel.</p><p>we connect every branch to the final aggregation node.</p><pre>graph.add_edge(&#39;evaluate_language&#39;, &#39;final_evaluation&#39;)<br>graph.add_edge(&#39;evaluate_analysis&#39;, &#39;final_evaluation&#39;)<br>graph.add_edge(&#39;evaluate_thought&#39;, &#39;final_evaluation&#39;)</pre><p>LangGraph automatically waits until <strong>all incoming branches complete</strong> before executing final_evaluation.</p><p>Finally,</p><pre>graph.add_edge(&#39;final_evaluation&#39;, END)</pre><p>marks the completion of the workflow.</p><p>Once the graph is fully defined, we compile it.</p><pre>workflow = graph.compile()</pre><p>Compilation validates the graph structure and prepares it for execution.</p><h3>Running the Workflow</h3><p>Finally, we execute the graph.</p><pre>intial_state = {<br>    &#39;essay&#39;: essay<br>}<br><br>workflow.invoke(intial_state)</pre><p>The execution flow is:</p><ol><li>Essay enters the workflow.</li><li>Three evaluation agents run simultaneously.</li><li>Their outputs are merged.</li><li>Final evaluation summarizes the feedback.</li><li>Average score is calculated.</li><li>Results are returned to the user.</li></ol><p>This is a concise yet powerful example of how multiple AI agents can collaborate within a single application.</p><h3>Key Takeaways</h3><p>By the end of this project, you have learned how to:</p><ul><li>Build a Parallel Workflow using LangGraph.</li><li>Execute multiple LLM nodes independently.</li><li>Share data using a common state.</li><li>Aggregate outputs using Annotated and operator.add.</li><li>Use structured outputs with Pydantic.</li><li>Synchronize parallel branches before continuing execution.</li><li>Design a scalable multi-agent evaluation pipeline.</li></ul><p>Although this project evaluates essays, the same architecture can be applied to document review, customer support, resume screening, medical report analysis, code review, legal document summarization, financial analysis, and many other enterprise AI applications.</p><h3>What’s Coming Next?</h3><p>Parallel workflows are only one piece of the Agentic AI puzzle.</p><p>In the upcoming parts of this series, we’ll explore more advanced LangGraph patterns such as conditional routing, iterative workflows, human-in-the-loop interactions, tool-calling agents, and multi-agent systems that can reason and collaborate to solve complex tasks.</p><p>Stay tuned!</p><h3>Complete Source Code</h3><p>The complete Google Colab notebook, along with all the code used in this tutorial, is available on my <a href="https://github.com/ashutosh2909/Agentic-AI/blob/main/Workflow_in_LangGraph.ipynb">GitHub repository.</a></p><p>If you found this article helpful, consider giving a clap and drop your comments. It motivates me to continue creating practical, beginner-friendly content on Agentic AI, LangGraph, and LLM application development.</p><h3>A Special Thank You</h3><p>I would also like to express my sincere gratitude to <a href="https://learnwith.campusx.in/"><strong>CampusX</strong></a>. A significant part of my understanding of Generative AI, LangGraph, and modern AI engineering concepts has been shaped through the high-quality educational content shared by CampusX.</p><h3>Final Thoughts</h3><p>I hope this article helped you understand not only <strong>how</strong> to build a parallel workflow, but also <strong>why</strong> this pattern is so powerful.</p><p>If you enjoyed this article, feel free to follow me on Medium for the upcoming parts of this Agentic AI with LangGraph series. Happy learning, and I’ll see you in <a href="https://medium.com/@ashu.analytix/part-3-conditional-workflows-in-langgraph-6eda8d235cc4?postPublishedType=initial"><strong>Part 3</strong>!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0fa10580c35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build AI Workflows with LangGraph (Part 1): Your First Agentic AI Application]]></title>
            <link>https://medium.com/@ashu.analytix/build-ai-workflows-with-langgraph-part-1-your-first-agentic-ai-application-ce634fe6e1ef?source=rss-4dfa55c9d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce634fe6e1ef</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Ashutosh Patel]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 05:36:42 GMT</pubDate>
            <atom:updated>2026-08-04T05:52:01.783Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The first article in my <strong>Agentic AI with Python</strong> series.</blockquote><h3>Introduction</h3><p>Hi, I’m <strong>Ashutosh Patel</strong>.Over the last few years, I’ve worked extensively in Data Science and Generative AI, building machine learning systems and exploring the rapidly evolving world of AI agents. One thing I’ve consistently noticed is that many tutorials assume expensive APIs, complex local setups, or enterprise infrastructure that makes learning difficult for beginners.</p><p>My goal is simple:</p><blockquote><strong><em>Demarketize AI education by creating high-quality, practical tutorials that anyone can reproduce with zero infrastructure headaches.</em></strong></blockquote><p>This article marks the beginning of my <strong>Agentic AI with Python</strong> series. Throughout this series, I will teach Agentic AI by focusing on three principles:</p><ul><li>Google Colab (no local setup)</li><li>Open-source LLMs</li><li>Free and easily reproducible tools</li></ul><p>If you can open a Google Colab notebook, you can follow every tutorial in this series. In this first article, we’ll learn the fundamental building block behind modern AI agents: <strong><em>Workflows with LangGraph</em></strong></p><p>Rather than jumping into complex multi-agent systems, we’ll build our understanding gradually by creating increasingly capable workflows. By the end of this tutorial you’ll understand:</p><ul><li>What LangGraph is</li><li>How workflows are represented as graphs</li><li>How state flows between nodes</li><li>How to integrate an LLM into a workflow</li><li>How to chain multiple AI tasks together</li></ul><p>Let’s begin.</p><h3>What is LangGraph?</h3><p>Traditional Python programs execute line by line. Agentic applications are different.</p><p>Instead of executing everything sequentially, they move through a graph where every node performs a specific task. Think of it like this:</p><pre>Input<br>   ↓<br>Node A<br>   ↓<br>Node B<br>   ↓<br>Node C<br>   ↓<br>Output</pre><p>Each node receives a shared <strong>state</strong>, modifies it, and passes it to the next node. This simple concept enables powerful AI systems with branching logic, memory, planning, reflection, and multi-agent collaboration.</p><h3>Install Dependencies</h3><pre>!pip install langchain langgraph langchain_groq</pre><p>We start by installing the required libraries.</p><ul><li><strong>LangGraph</strong> — builds workflows</li><li><strong>LangChain</strong> — provides LLM abstractions</li><li><strong>LangChain Groq</strong> — connects to Groq’s inference API</li></ul><p>Keeping everything inside Google Colab makes the setup effortless.</p><h3>Import Required Libraries</h3><pre>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict<br>from IPython.display import Image</pre><p>These imports provide the core building blocks.</p><ul><li>StateGraph creates the workflow.</li><li>START and END define where execution begins and finishes.</li><li>TypedDict defines the shared state.</li><li>Image renders the workflow diagram.</li></ul><h3>Example 1 — Simple Sequential Workflow</h3><p>Before introducing an LLM, it’s useful to understand how LangGraph moves information through nodes.</p><h3>Define the State</h3><pre>class BMIState(TypedDict):<br>    weight_kg: float<br>    height_m: float<br>    bmi: float<br>    category: str</pre><p>Every LangGraph application starts with a <strong>State</strong>. Think of the state as a shared dictionary that travels through the workflow. Every node can read from it, update it, and pass it along.</p><p>In this example, the state stores:</p><ul><li>Weight</li><li>Height</li><li>BMI</li><li>BMI category</li></ul><h3>Create the Processing Node</h3><pre># define calculate_bmi node<br>def calculate_bmi(state: BMIState) -&gt; BMIState:<br><br>    weight = state[&#39;weight_kg&#39;]<br>    height = state[&#39;height_m&#39;]<br><br>    bmi = weight/(height**2)<br><br>    state[&#39;bmi&#39;] = round(bmi, 2)<br><br>    return state<br><br># define label_bmi node<br>def label_bmi(state: BMIState) -&gt; BMIState:<br>    bmi = state[&#39;bmi&#39;]<br><br>    if bmi &lt; 18.5:<br>        state[&quot;category&quot;] = &quot;Underweight&quot;<br>    elif 18.5 &lt;= bmi &lt; 25:<br>        state[&quot;category&quot;] = &quot;Normal&quot;<br>    elif 25 &lt;= bmi &lt; 30:<br>        state[&quot;category&quot;] = &quot;Overweight&quot;<br>    else:<br>        state[&quot;category&quot;] = &quot;Obese&quot;<br><br>    return state</pre><p>Now we defines a function that:</p><ul><li>reads the user’s height and weight,</li><li>calculates BMI,</li><li>determines the BMI category,</li><li>returns the updated state.</li></ul><p>This demonstrates an important LangGraph principle: <em>Nodes should receive the current state and return the updated state.</em></p><h3>Build the Graph</h3><pre># define graph<br>graph = StateGraph(BMIState)<br><br># add nodes to your graph<br>graph.add_node(&#39;calculate_bmi&#39;, calculate_bmi)<br>graph.add_node(&#39;label_bmi&#39;, label_bmi)<br><br># add edges to your graph<br>graph.add_edge(START, &#39;calculate_bmi&#39;)<br>graph.add_edge(&#39;calculate_bmi&#39;, &#39;label_bmi&#39;)<br>graph.add_edge(&#39;label_bmi&#39;, END)<br><br><br># compile the graph<br>workflow = graph.compile()<br><br># show the graph<br>Image(workflow.get_graph().draw_mermaid_png())</pre><p>Next, we constructs the workflow.</p><p>The graph:</p><ul><li>adds the BMI calculation node,</li><li>connects it between START and END,</li><li>compiles the workflow.</li></ul><p>At this point we’ve built our first LangGraph application. One of LangGraph’s nicest features is automatic workflow visualization. Instead of guessing how execution flows, you can inspect the graph visually.</p><h3>Execute the Workflow</h3><pre># execute the graph<br>intial_state = {&#39;weight_kg&#39;:80, &#39;height_m&#39;:1.73}<br>final_state = workflow.invoke(intial_state)<br>print(final_state)</pre><p>Finally, we provide an initial state containing weight and height. The workflow executes automatically:</p><p>The returned state now contains the calculated BMI and its corresponding health category.</p><h3>Example 2 — Sequential Workflow with an LLM</h3><p>Now let’s make the workflow intelligent.</p><p>Instead of performing mathematical calculations, the node will call an LLM.</p><h3>Cell 8 — Section Introduction</h3><p>This markdown cell separates the notebook into the next example, keeping the tutorial organized.</p><h3>Import LLM Libraries</h3><p>The notebook imports:</p><ul><li>os</li><li>getpass</li><li>ChatGroq</li></ul><p>These libraries allow secure interaction with Groq-hosted open-source models.</p><h3>Configure the API Key</h3><p>Instead of hardcoding credentials, the notebook securely prompts for the Groq API key.</p><h3>Load the Model</h3><pre>model = ChatGroq(model=&quot;openai/gpt-oss-120b&quot;)</pre><p>This cell initializes the language model. One of the goals of this series is to rely on accessible, open-source models rather than expensive proprietary services.</p><h3>Define the LLM State</h3><pre># create a state<br>class LLMState(TypedDict):<br>    question: str<br>    answer: str</pre><p>A new state is created containing:</p><ul><li>user question</li><li>generated answer</li></ul><p>Notice how the state evolves depending on the workflow being built.</p><h3>Create the LLM Node</h3><pre>def llm_qa(state: LLMState) -&gt; LLMState:<br><br>    # extract the question from state<br>    question = state[&#39;question&#39;]<br><br>    # form a prompt<br>    prompt = f&#39;Answer the following question {question}&#39;<br><br>    # ask that question to the LLM<br>    answer = model.invoke(prompt).content<br><br>    # update the answer in the state<br>    state[&#39;answer&#39;] = answer<br><br>    return state</pre><p>We defines a function that:</p><ol><li>reads the question,</li><li>sends it to the LLM,</li><li>stores the generated answer,</li><li>returns the updated state.</li></ol><p>This is identical to the BMI example. The only difference is <strong>what happens inside the node</strong>. Instead of computing BMI, we’re invoking an AI model.</p><h3>Build the LLM Workflow</h3><pre># create our graph<br>graph = StateGraph(LLMState)<br><br># add nodes<br>graph.add_node(&#39;llm_qa&#39;, llm_qa)<br><br># add edges<br>graph.add_edge(START, &#39;llm_qa&#39;)<br>graph.add_edge(&#39;llm_qa&#39;, END)<br><br># compile<br>workflow = graph.compile()</pre><p>Just like before:</p><ul><li>add node</li><li>connect edges</li><li>compile graph</li></ul><p>The workflow structure remains unchanged. This consistency is one of LangGraph’s biggest strengths.</p><h3>Ask the LLM</h3><pre># execute<br>intial_state = {&#39;question&#39;: &#39;How far is sun from the earth?&#39;}<br>final_state = workflow.invoke(intial_state)<br>print(final_state[&#39;answer&#39;])</pre><p>The workflow sends the question to the model and returns the generated answer. This demonstrates how seamlessly LLMs integrate into LangGraph workflows.</p><h3>Example 3 — Multi-Step AI Workflow</h3><p>Now we move beyond a single LLM call. Real AI applications usually involve multiple reasoning steps. This final example demonstrates exactly that.</p><h3>Define the Blog State</h3><pre>class BlogState(TypedDict):<br>    title: str<br>    outline: str<br>    content: str<br>    rating: int</pre><p>The workflow now maintains:</p><ul><li>blog title</li><li>outline</li><li>content</li><li>rating</li></ul><p>Notice how the shared state grows as the application becomes more sophisticated.</p><h3>Create Workflow Nodes</h3><pre>def create_outline(state: BlogState) -&gt; BlogState:<br>    # fetch title<br>    title = state[&#39;title&#39;]<br><br>    # call llm gen outline<br>    prompt = f&#39;Generate a detailed outline for a blog on the topic - {title}&#39;<br>    outline = model.invoke(prompt).content<br><br>    # update state<br>    state[&#39;outline&#39;] = outline<br><br>    return state<br><br>def create_blog(state: BlogState) -&gt; BlogState:<br>    title = state[&#39;title&#39;]<br>    outline = state[&#39;outline&#39;]<br><br>    prompt = f&#39;Write a short blog (less than 20 lines) on the title - {title} using the follwing outline \n {outline}&#39;<br>    content = model.invoke(prompt).content<br>    state[&#39;content&#39;] = content<br>    return state<br><br>def create_rating(state: BlogState) -&gt; BlogState:<br>    title = state[&quot;title&quot;]<br>    content = state[&quot;content&quot;]<br><br>    prompt = f&quot;&quot;&quot;<br>    Rate the following blog out of 10.<br>    Return ONLY a single integer between 1 and 10.<br><br>    Title: {title}<br><br>    Blog:<br>    {content}<br>    &quot;&quot;&quot;<br><br>    rating = model.invoke(prompt).content.strip()<br><br>    state[&quot;rating&quot;] = int(rating)<br><br>    return state</pre><p>We defines multiple functions responsible for different tasks, including generating a blog outline. Each node has a single responsibility. This modular design keeps workflows clean and easy to maintain.</p><h3>Assemble the Complete Pipeline</h3><pre>graph = StateGraph(BlogState)<br><br># nodes<br>graph.add_node(&#39;create_outline&#39;, create_outline)<br>graph.add_node(&#39;create_blog&#39;, create_blog)<br>graph.add_node(&#39;create_rating&#39;, create_rating)<br><br># edges<br>graph.add_edge(START, &#39;create_outline&#39;)<br>graph.add_edge(&#39;create_outline&#39;, &#39;create_blog&#39;)<br>graph.add_edge(&#39;create_blog&#39;, &#39;create_rating&#39;)<br>graph.add_edge(&#39;create_rating&#39;, END)<br><br>workflow = graph.compile()<br>workflow</pre><p>The graph connects multiple AI tasks together. Conceptually, the workflow looks like this:</p><pre>Title<br>   ↓<br>Create Outline<br>   ↓<br>Generate Blog<br>   ↓<br>Evaluate Blog<br>   ↓<br>END</pre><p>This demonstrates the real power of LangGraph. Rather than asking the model to do everything in one prompt, we divide the problem into logical stages. Each stage improves the output of the next.</p><h3>Execute the Workflow</h3><pre>intial_state = {&#39;title&#39;: &#39;Rise of AI in India&#39;}<br>final_state = workflow.invoke(intial_state)<br>print(final_state[&#39;rating&#39;])</pre><ul><li>creates an outline,</li><li>generates the article,</li><li>evaluates its quality,</li><li>returns the final rating.</li></ul><p>This illustrates how Agentic AI systems can orchestrate multiple AI capabilities within a single pipeline.</p><h3>What We Learned</h3><p>In this tutorial we progressively built three workflows:</p><ol><li>A simple sequential workflow using Python logic.</li><li>A workflow that integrates an open-source LLM.</li><li>A multi-step AI pipeline that chains several tasks together.</li></ol><p>Although these examples are intentionally simple, they introduce the core ideas behind Agentic AI:</p><ul><li>Shared state</li><li>Nodes</li><li>Edges</li><li>Workflow orchestration</li><li>LLM integration</li><li>Multi-step reasoning</li></ul><p>These same concepts scale to sophisticated systems involving tools, memory, branching, and multiple collaborating agents.</p><h3>What’s Next?</h3><p>This is only <strong>Part 1</strong> of the <strong>Agentic AI with Python</strong> series.</p><p>In the upcoming articles, we’ll build progressively more advanced applications, including:</p><ul><li>Conditional workflows</li><li>Parallel execution</li><li>Human-in-the-loop interactions</li><li>Tool calling</li><li>Retrieval-Augmented Generation (RAG)</li><li>Multi-agent systems</li><li>Production-ready Agentic AI applications</li></ul><p>All using <strong>Google Colab</strong>, <strong>Python</strong>, and <strong>open-source models</strong>, so you can follow along without requiring expensive infrastructure.</p><h3>Complete Source Code</h3><p>The complete notebook used in this tutorial, along with future projects from this series, will be available on my <a href="https://github.com/ashutosh2909/Agentic-AI/blob/main/Workflow_in_LangGraph.ipynb"><strong>GitHub</strong> </a>repository. Feel free to explore the code, run it in Google Colab, and experiment with your own workflows.</p><p>If you found this article helpful, consider following me on Medium so you don’t miss the next installment in the <strong>Agentic AI with Python</strong> series. Happy learning!</p><h3>Acknowledgment</h3><p>I’d like to express my sincere gratitude to <a href="https://www.youtube.com/@campusx-official"><strong>CampusX</strong> </a>for creating high-quality educational content on Generative AI and Agentic AI. Their tutorials played an important role in strengthening my understanding, and this article is inspired by the concepts I learned while adding my own explanations, and hands-on implementation using Google Colab and open-source tools.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce634fe6e1ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an Agentic RAG Application from Scratch using Open Source LLMs]]></title>
            <link>https://medium.com/@ashu.analytix/step-by-step-guide-to-agentic-rag-2b244a1a3022?source=rss-4dfa55c9d33------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b244a1a3022</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[advance-rag]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <dc:creator><![CDATA[Ashutosh Patel]]></dc:creator>
            <pubDate>Sat, 01 Aug 2026 16:07:19 GMT</pubDate>
            <atom:updated>2026-08-01T16:53:02.206Z</atom:updated>
            <content:encoded><![CDATA[<h3>A beginner-friendly guide to building an intelligent Retrieval-Augmented Generation (RAG) application that decides whether to answer from its own knowledge base or search the web — using open-source LLMs and Google Colab.</h3><h3>Introduction</h3><p>Retrieval-Augmented Generation (RAG) has become one of the most important techniques for building production-ready Generative AI applications. Traditional RAG systems retrieve information from a vector database and generate responses based on that retrieved context.</p><p>But what happens when the answer <strong>doesn’t exist</strong> in your knowledge base?</p><p>Most beginner tutorials simply return <em>“I don’t know.”</em></p><p>A more intelligent solution is an <strong>Agentic RAG</strong> system.</p><p>Instead of blindly retrieving documents, an Agentic RAG pipeline can <strong>reason</strong>, <strong>make decisions</strong>, and <strong>choose the best information source</strong> before generating an answer.</p><p>In this tutorial, we’ll build an Agentic RAG application completely in <strong>Google Colab</strong> using:</p><ul><li>Open Source LLM</li><li>LangChain</li><li>FAISS Vector Database</li><li>HuggingFace Embeddings</li><li>Groq API</li><li>Web Search</li><li>Web Scraping</li><li>Intelligent Routing Logic</li></ul><p>By the end of this article, you’ll understand every component of an Agentic RAG pipeline and build one from scratch.</p><h3>What We Are Building</h3><p>Our application follows this decision-making process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*l31dQcxjm3aMyXHLJ8nPPA.png" /></figure><p>Unlike traditional RAG, this system can dynamically decide where the answer should come from.</p><h3>Step 1 — Install Dependencies &amp; Imports</h3><p>The notebook starts by installing all required libraries.</p><pre>!pip install -q python-dotenv<br>!pip install -q langchain-community<br>!pip install -q pypdf  # needed by PyPDFLoader<br>!pip install -q langchain<br>!pip install -q langchain-huggingface<br>!pip install -q sentence-transformers  # needed by HuggingFaceEmbeddings<br>!pip install -q langchain-groq<br>!pip install -q langchain_groq<br>!pip install -q langchain-text-splitters<br>!pip install -q faiss-cpu  # needed for FAISS vectorstore<br>!pip install -q &#39;crewai[tools]&#39;  # gives you crewai + crewai_tools</pre><p>After installation, restart the runtime if required.</p><pre>import os # Provides operating system interface utilities.<br>import getpass<br>import dotenv # Loads environment variables<br>from langchain_community.vectorstores import FAISS  # Vector store for similarity search and retrieval.<br>from langchain_community.document_loaders import PyPDFLoader  # Extracts text content from PDF documents.<br>from langchain_groq import ChatGroq # Chat interface powered by Groq hardware acceleration.<br>from langchain_text_splitters import RecursiveCharacterTextSplitter # Splits text into manageable chunks recursively.<br>from langchain_huggingface.embeddings import HuggingFaceEmbeddings  # Generates text embeddings using HuggingFace models.<br>from crewai_tools import SerperDevTool, ScrapeWebsiteTool  # Tool for performing web searches.<br>from crewai import Agent, Task, Crew, LLM # Orchestrates agents and tasks for coordinated workflows.<br>import asyncio</pre><pre>if &quot;GROQ_API_KEY&quot; not in os.environ:<br>  os.environ[&quot;GROQ_API_KEY&quot;] = getpass.getpass(&quot;Enter your Groq API key: &quot;)<br>if &quot;SERPER_API_KEY&quot; not in os.environ:<br>  os.environ[&quot;SERPER_API_KEY&quot;] = getpass.getpass(&quot;Enter your SERPER_ API key: &quot;)<br>if &quot;GEMINI&quot; not in os.environ:<br>  os.environ[&quot;GEMINI&quot;] = getpass.getpass(&quot;Enter your GEMINI API key: &quot;)<br>GEMINI=os.getenv(&quot;GEMINI&quot;)</pre><h3>Initialize the LLM</h3><pre># For general tasks like routing and generating answers.<br>llm = ChatGroq(<br>    model=&quot;llama-3.3-70b-versatile&quot;,<br>    temperature=0,<br>    max_tokens=500,<br>    timeout=None,<br>    max_retries=2,<br>)<br><br># For the web-scraping agent, as it needs a slightly different configuration (like temperature for more creative outputs).<br>crew_llm = LLM(<br>    model=&quot;gemini/gemini-3.5-flash-lite&quot;,#&quot;gemini/gemini-3.6-flash&quot;,<br>    api_key=GEMINI,<br>    max_tokens=500,<br>    temperature=0.7<br>)</pre><p>Instead of using expensive hosted models, this project uses an <strong>open-source language model served through Groq</strong>.</p><p>The LLM is responsible for:</p><ul><li>reasoning</li><li>routing</li><li>answer generation</li><li>evaluating retrieved information</li></ul><p>Since Groq provides extremely low latency inference, the application feels almost instantaneous.</p><h3>Create the Decision Maker Agent</h3><p>This is the most interesting part of the project. Traditional RAG simply performs similarity search. Our notebook introduces a dedicated <strong>Decision Maker</strong>. Its responsibility is to answer one question:</p><blockquote><em>“Does the retrieved knowledge contain enough information to answer the user’s question?”</em></blockquote><p>If yes: Return Local Knowledge, Otherwise: Search Internet</p><p>This simple addition transforms a normal RAG pipeline into an <strong>Agentic RAG system</strong>. Instead of following a fixed workflow, the application makes decisions dynamically.</p><pre>def check_local_knowledge(query, context):<br>    &quot;&quot;&quot;Router function to determine if we can answer from local knowledge&quot;&quot;&quot;<br>    prompt = &#39;&#39;&#39;Role: Question-Answering Assistant<br>Task: Determine whether the system can answer the user&#39;s question based on the provided text.<br>Instructions:<br>    - Analyze the text and identify if it contains the necessary information to answer the user&#39;s question.<br>    - Provide a clear and concise response indicating whether the system can answer the question or not.<br>    - Your response should include only a single word. Nothing else, no other text, information, header/footer.<br>Output Format:<br>    - Answer: Yes/No<br>Study the below examples and based on that, respond to the last question.<br>Examples:<br>    Input:<br>        Text: The capital of France is Paris.<br>        User Question: What is the capital of France?<br>    Expected Output:<br>        Answer: Yes<br>    Input:<br>        Text: The population of the United States is over 330 million.<br>        User Question: What is the population of China?<br>    Expected Output:<br>        Answer: No<br>    Input:<br>        User Question: {query}<br>        Text: {text}<br>&#39;&#39;&#39;<br>    formatted_prompt = prompt.format(text=context, query=query)<br>    response = llm.invoke(formatted_prompt)<br>    return response.content.strip().lower() == &quot;yes&quot;</pre><h3>Build the Web Search Agent</h3><p>If local knowledge is insufficient, the pipeline automatically invokes the Web Search Agent. The agent searches the web for relevant sources. This ensures the application isn’t limited by its vector database. It can answer questions about:</p><ul><li>recent events</li><li>latest technologies</li><li>newly released research</li><li>breaking news</li></ul><p>Search results alone aren’t useful. The notebook therefore extracts the content from selected web pages. The scraping agent:</p><ul><li>downloads webpages</li><li>removes unnecessary HTML</li><li>extracts clean text</li><li>prepares context for the LLM</li></ul><p>Now the model has high-quality external information instead of only search snippets.</p><pre>def setup_web_scraping_agent():<br>    &quot;&quot;&quot;Setup the web scraping agent and related components&quot;&quot;&quot;<br>    search_tool = SerperDevTool()<br>    scrape_website = ScrapeWebsiteTool()<br><br>    web_search_agent = Agent(<br>        role=&quot;Expert Web Search Agent&quot;,<br>        goal=&quot;Identify and retrieve relevant web data for user queries&quot;,<br>        backstory=&quot;An expert in identifying valuable web sources for the user&#39;s needs&quot;,<br>        allow_delegation=False,<br>        verbose=True,<br>        llm=crew_llm<br>    )<br><br>    web_scraper_agent = Agent(<br>        role=&quot;Expert Web Scraper Agent&quot;,<br>        goal=&quot;Extract, filter, and synthesize content from web pages into concise, decision-ready summaries&quot;,<br>        backstory=(<br>            &quot;A highly skilled analyst who reads raw scraped web content and distills it into &quot;<br>            &quot;clear insights. You never dump raw or unprocessed text — you always read, filter, &quot;<br>            &quot;and rewrite content in your own words before presenting it.&quot;<br>        ),<br>        allow_delegation=False,<br>        verbose=True,<br>        llm=crew_llm<br>    )<br><br>    search_task = Task(<br>        description=(<br>            &quot;Identify the most relevant web page or article for the topic: &#39;{topic}&#39;. &quot;<br>            &quot;Run the search tool ONCE. Do not repeat searches unless the first attempt returns &quot;<br>            &quot;no usable results. Pick the single best link from the results.&quot;<br>        ),<br>        expected_output=(<br>            &quot;A single URL for the most relevant source on &#39;{topic}&#39;, plus 1-2 sentences on why &quot;<br>            &quot;it was chosen. Nothing else.&quot;<br>        ),<br>        tools=[search_tool],<br>        agent=web_search_agent,<br>    )<br><br>    scraping_task = Task(<br>        description=(<br>            &quot;Use the scraping tool to fetch the web page identified in the previous task. &quot;<br>            &quot;The tool will return raw page content that includes navigation menus, sidebar links, &quot;<br>            &quot;footers, and other boilerplate — you MUST discard all of that. &quot;<br>            &quot;Read only the substantive body content relevant to &#39;{topic}&#39;, and rewrite it as your &quot;<br>            &quot;own summary. Do NOT copy-paste, quote, or return the raw tool output. &quot;<br>            &quot;Do NOT include navigation items, menu labels, &#39;Tutorial:&#39; links, author bios, &quot;<br>            &quot;newsletter prompts, or related-product callouts.&quot;<br>        ),<br>        expected_output=(<br>            &quot;A 4-6 bullet point summary, written entirely in your own words, covering only the &quot;<br>            &quot;substantive insights about &#39;{topic}&#39;. No navigation text, no boilerplate, no headers &quot;<br>            &quot;copied verbatim from the page. Each bullet should be a complete, standalone insight.&quot;<br>        ),<br>        tools=[scrape_website],<br>        agent=web_scraper_agent,<br>        context=[search_task],  # explicit dependency, don&#39;t rely on default sequential context<br>    )<br><br>    crew = Crew(<br>        agents=[web_search_agent, web_scraper_agent],<br>        tasks=[search_task, scraping_task],<br>        verbose=1,<br>        memory=False,<br>    )<br>    return crew<br><br><br>async def get_web_content_async(query):<br>    crew = setup_web_scraping_agent()<br>    result = await crew.kickoff_async(inputs={&quot;topic&quot;: query})<br>    return result.raw<br><br>def get_web_content(query):<br>    return asyncio.get_event_loop().run_until_complete(get_web_content_async(query))</pre><h3>Build the Vector Database</h3><p>Now we create the local knowledge base. The notebook uses:</p><ul><li>Document Loader</li><li>Text Splitter</li><li>HuggingFace Embeddings</li><li>FAISS</li></ul><p>When the user asks a question: “What is Agentic AI?”</p><p>The application searches the vector database and retrieves the most relevant chunks. Instead of sending the entire document to the LLM, only the most relevant context is provided. This significantly reduces token usage while improving answer quality.</p><pre>def setup_vector_db(<br>    pdf_path,<br>    persist_directory=&quot;YOUR_PATH&quot;<br>):<br>    &quot;&quot;&quot;<br>    Load an existing FAISS vector database if available.<br>    Otherwise create a new one from the PDF and save it.<br><br>    Args:<br>        pdf_path (str): Path to the PDF file.<br>        persist_directory (str): Directory where FAISS index is stored.<br><br>    Returns:<br>        FAISS: Loaded or newly created vector database.<br>    &quot;&quot;&quot;<br><br>    # Initialize embedding model<br>    embeddings = HuggingFaceEmbeddings(<br>        model_name=&quot;sentence-transformers/all-mpnet-base-v2&quot;<br>    )<br><br>    # Check if persisted index exists<br>    if os.path.exists(os.path.join(persist_directory, &quot;index.faiss&quot;)):<br>        print(f&quot;Loading existing FAISS index from: {persist_directory}&quot;)<br><br>        vector_db = FAISS.load_local(<br>            persist_directory,<br>            embeddings,<br>            allow_dangerous_deserialization=True<br>        )<br>        return vector_db<br><br>    print(&quot;No existing FAISS index found. Creating a new one...&quot;)<br><br>    # Load PDF<br>    loader = PyPDFLoader(pdf_path)<br>    documents = loader.load()<br><br>    # Split into chunks<br>    text_splitter = RecursiveCharacterTextSplitter(<br>        chunk_size=1000,<br>        chunk_overlap=50<br>    )<br>    chunks = text_splitter.split_documents(documents)<br><br>    # Create vector database<br>    vector_db = FAISS.from_documents(chunks, embeddings)<br><br>    # Persist to Google Drive<br>    os.makedirs(persist_directory, exist_ok=True)<br>    vector_db.save_local(persist_directory)<br><br>    print(f&quot;FAISS index saved to: {persist_directory}&quot;)<br><br>    return vector_db<br><br>def get_local_content(vector_db, query):<br>    &quot;&quot;&quot;Get content from vector database&quot;&quot;&quot;<br>    docs = vector_db.similarity_search(query, k=5)<br>    return &quot; &quot;.join([doc.page_content for doc in docs])</pre><h3>Generate the Final Answer</h3><p>The final response generator combines:</p><ul><li>user question</li><li>retrieved documents</li><li>web content (if needed)</li></ul><p>and produces a grounded answer. Because the response is always generated from retrieved context, hallucinations are significantly reduced.</p><pre>def generate_final_answer(context, query):<br>    &quot;&quot;&quot;Generate final answer using LLM&quot;&quot;&quot;<br>    messages = [<br>        (<br>            &quot;system&quot;,<br>            &quot;You are a helpful assistant. Use the provided context to answer the query accurately.&quot;,<br>        ),<br>        (&quot;system&quot;, f&quot;Context: {context}&quot;),<br>        (&quot;human&quot;, query),<br>    ]<br>    response = llm.invoke(messages)<br>    return response.content<br><br>def process_query(query, vector_db, local_context):<br>    &quot;&quot;&quot;Main function to process user query&quot;&quot;&quot;<br>    print(f&quot;Processing query: {query}&quot;)<br><br>    # Step 1: Check if we can answer from local knowledge<br>    can_answer_locally = check_local_knowledge(query, local_context)<br>    print(f&quot;Can answer locally: {can_answer_locally}&quot;)<br><br>    # Step 2: Get context either from local DB or web<br>    if can_answer_locally:<br>        context = get_local_content(vector_db, query)<br>        print(&quot;Retrieved context from local documents&quot;)<br>    else:<br>        context = get_web_content(query)<br>        print(&quot;Retrieved context from web scraping&quot;)<br><br>    # Step 3: Generate final answer<br>    answer = generate_final_answer(context, query)<br>    return answer</pre><h3>Putting Everything Together</h3><p>Finally, the notebook integrates every component into a single workflow.</p><p>The main() function orchestrates the complete Agentic RAG pipeline:</p><ol><li>Receive user query</li><li>Retrieve local documents</li><li>Evaluate retrieved context</li><li>Decide whether external knowledge is required</li><li>Search the web if necessary</li><li>Scrape webpages</li><li>Combine all context</li><li>Generate final answer</li></ol><p>This modular architecture makes each component reusable and easy to extend.</p><pre>def main():<br>    # Setup<br>    pdf_path = &quot;/content/drive/MyDrive/skills/genai/data/genai-principles.pdf&quot;<br><br>    # Initialize vector database<br>    print(&quot;Setting up vector database...&quot;)<br>    vector_db = setup_vector_db(pdf_path)<br><br>    # Get initial context from PDF for routing<br>    query = &quot;What is Agentic RAG?&quot;<br>    local_context = get_local_content(vector_db, query)<br><br>    # Example usage<br>    # query = &quot;What is Agentic RAG?&quot;<br>    result = process_query(query, vector_db, local_context)<br>    print(&quot;\nFinal Answer:&quot;)<br>    print(result)<br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>Possible Improvements</h3><p>Once you understand this project, try extending it with:</p><ul><li>LangGraph workflow orchestration</li><li>Memory for multi-turn conversations</li><li>Hybrid Search (BM25 + Vector Search)</li><li>Query rewriting</li><li>Multi-agent architecture</li><li>Reranking models</li><li>Persistent FAISS storage</li><li>Streaming responses</li><li>Source citations</li><li>Evaluation using RAGAS</li></ul><p>Each enhancement moves the project closer to a production-grade AI assistant.</p><h3>GitHub Repository</h3><p>The complete Google Colab notebook, source code, and future improvements for this project are available on my GitHub.</p><p>⭐ If you found this article helpful, please consider giving the artcile a star — it helps others discover the project and motivates me to create more open-source AI tutorials.</p><p>GitHub: <strong>&lt;</strong><a href="https://github.com/ashutosh2909/Agentic-AI/blob/main/Agentic_Rag_Step_by_Step.ipynb">https://github.com/ashutosh2909/Agentic-AI/blob/main/Agentic_Rag_Step_by_Step.ipynb</a><strong>&gt;</strong></p><h3>About the Author</h3><p>Hi, I’m <strong>Ashutosh Patel</strong>.</p><p>I’m passionate about building practical Generative AI and Agentic AI applications using open-source models. I enjoy breaking down complex AI concepts into beginner-friendly, hands-on tutorials with complete code walkthroughs.</p><p>If you enjoyed this article:</p><ul><li>👏 Follow me on Medium for more AI tutorials</li><li>💼 Connect with me on LinkedIn — <a href="https://www.linkedin.com/in/ashutosh-patel-29a669180/">https://www.linkedin.com/in/ashutosh-patel-29a669180/</a></li><li>⭐ Star the GitHub repository</li><li>💬 Share your feedback or questions in the comments</li></ul><p>Happy Building!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b244a1a3022" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>