<?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 Nishan Jain on Medium]]></title>
        <description><![CDATA[Stories by Nishan Jain on Medium]]></description>
        <link>https://medium.com/@gr8nishan?source=rss-64cc8e986127------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OZEweIVJoUO94sfW7fbbjg.png</url>
            <title>Stories by Nishan Jain on Medium</title>
            <link>https://medium.com/@gr8nishan?source=rss-64cc8e986127------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:47:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gr8nishan/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[Stop Writing Prompts: Classify Text with LLMs Automatically]]></title>
            <link>https://python.plainenglish.io/stop-writing-prompts-classify-text-with-llms-automatically-adbf7cc814b9?source=rss-64cc8e986127------2</link>
            <guid isPermaLink="false">https://medium.com/p/adbf7cc814b9</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Nishan Jain]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 01:05:01 GMT</pubDate>
            <atom:updated>2025-09-15T01:05:01.192Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n46CDGNUru21r3DD" /><figcaption>Photo by <a href="https://unsplash.com/@julientromeur?utm_source=medium&amp;utm_medium=referral">julien Tromeur</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You’ve probably spent hours tweaking prompts to make an LLM classify text correctly:<br> “Add this phrase… remove that… oh, now it works for one example but fails on another.”<br> <br> Prompt engineering feels like black magic. But what if you could skip all of that?<br> With <strong>DSPy</strong>, you don’t hand-craft prompts at all. Instead, you describe what you want in terms of inputs and outputs, and DSPy automatically generates, tests, and optimizes the prompts for you.</p><h3>Why DSPy Matters</h3><p>— No manual prompt writing → you define schemas, not words.<br> — Optimized automatically → DSPy searches prompt variants and improves accuracy.<br> — Model-agnostic → you can run optimizations with a large model and deploy on a smaller, cheaper one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pE-yVgR0SzwPykbPrzpfAA.png" /><figcaption>Difference between Traditional Prompt Engineering and Dspy</figcaption></figure><h3>Example: Classifying Historic Events</h3><h4>Step 1. Define the Signature</h4><pre>from typing import Literal <br>import dspy  <br>class Categorize(dspy.Signature):     <br>  event: str = dspy.InputField()     <br>  category: Literal[         <br>      &quot;Wars and Conflicts&quot;,         <br>      &quot;Politics and Governance&quot;,         <br>      &quot;Science and Innovation&quot;,         <br>      &quot;Cultural and Artistic Movements&quot;,         <br>      &quot;Exploration and Discovery&quot;,         <br>      &quot;Economic Events&quot;,         <br>      &quot;Social Movements&quot;,         <br>      &quot;Man-Made Disasters and Accidents&quot;,         <br>      &quot;Natural Disasters and Climate&quot;,         <br>      &quot;Sports and Entertainment&quot;,         <br>      &quot;Famous Personalities and Achievements&quot;     <br>] = dspy.OutputField()     <br>confidence: float = dspy.OutputField() </pre><p>This schema describes what we want:<br> — Input: an `event` (string)<br> — Output: `category` (from a fixed set) and `confidence` (float)</p><h4>Step 2. Create a Classifier</h4><pre>classify = dspy.Predict(Categorize)  <br>result = classify(event=&quot;The Wright brothers make their first powered flight.&quot;) <br>print(result.category, result.confidence) </pre><p>DSPy takes care of prompt formatting. No manual engineering required.</p><h4>Step 3. Evaluate Performance</h4><p>Once we have a working classifier, the next step is to measure how well it performs. In DSPy, this can be done by writing a simple validation function and then running the Evaluate utility.</p><p>A metric function takes an example and a prediction, then returns True or False depending on whether the prediction was correct.<br> For a single-label classification task, a straightforward equality check works:</p><pre>def validate_category(example, prediction, trace=None):<br>    return prediction.category == example.category</pre><p>Now let’s evaluate our raw (unoptimized) classifier:</p><pre>evaluator = Evaluate(devset=trainset, num_threads=1, display_progress=True, display_table=5)<br>evaluator(classify, metric=validate_category)</pre><p>This gives us a <strong>baseline performance</strong>. Think of this as the “before” picture — it shows how well the initial prompt works before any optimization.</p><h3>Step 4. Improve with MIPROv2</h3><p>DSPy comes with a range of optimizers that can refine your prompts automatically.<br>For this article, we’ll use <strong>MIPROv2</strong>, which is designed for efficiency and effectiveness.</p><pre>from dspy.teleprompt import *<br><br># Load our model<br>lm = dspy.LM(&#39;ollama_chat/llama3.2:1b&#39;, api_base=&#39;http://localhost:11434&#39;)<br>dspy.configure(lm=lm)<br><br># Optimize<br>tp = dspy.MIPROv2(metric=validate_category, auto=&quot;light&quot;)<br>optimized_classify = tp.compile(classify, trainset=trainset, max_labeled_demos=0, max_bootstrapped_demos=0)</pre><p>Here, auto=&quot;light&quot; tells DSPy to run a lightweight optimization. You can adjust this to &quot;medium&quot; or &quot;heavy&quot; for more aggressive tuning (though that comes at the cost of speed).</p><h3>Step 5. Evaluate Again</h3><p>Finally, let’s measure performance again — this time with the optimized classifier:</p><pre>evaluator(optimized_classify, metric=validate_category)</pre><p>By comparing the <strong>baseline</strong> vs <strong>optimized</strong> results, you’ll see how prompt optimization improves accuracy.</p><h3>Why This Works</h3><ul><li><strong>Schema-first</strong> → You define <em>what</em> you want, not <em>how</em> to say it.</li><li><strong>Smarter search space</strong> → DSPy explores variations and strategies that humans often miss.</li><li><strong>Separation of concerns</strong> → Use a powerful model to optimize prompts once, then run inference cheaply on a smaller one.</li></ul><h3>Final Thoughts</h3><p>Prompt engineering isn’t going away anytime soon, but frameworks like <strong>DSPy</strong> make it <em>practical and scalable</em>.<br> Instead of hand-crafting fragile text prompts, you declare your task, provide a few examples, and let the system do the heavy lifting.</p><p>So the next time you need to build a text classifier (or any structured LLM task), remember this:<br> 👉 <strong>Don’t just prompt — optimize.</strong></p><h3><strong>References</strong></h3><ul><li><a href="https://www.dbreunig.com/2024/12/12/pipelines-prompt-optimization-with-dspy.html">Pipelines &amp; Prompt Optimization with DSPy</a></li><li><a href="https://dspy.ai/tutorials/">Tutorials Overview - DSPy</a></li></ul><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adbf7cc814b9" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/stop-writing-prompts-classify-text-with-llms-automatically-adbf7cc814b9">Stop Writing Prompts: Classify Text with LLMs Automatically</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Post-Training Large Language Models: SFT, DPO, and RLHF Explained]]></title>
            <link>https://python.plainenglish.io/post-training-large-language-models-sft-dpo-and-rlhf-explained-3e0d17a84914?source=rss-64cc8e986127------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e0d17a84914</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Nishan Jain]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 00:49:44 GMT</pubDate>
            <atom:updated>2025-09-01T00:49:44.226Z</atom:updated>
            <content:encoded><![CDATA[<p>Large Language Models (LLMs) are incredibly capable right out of the box, but they don’t always behave exactly the way we want. Pre-training teaches them to understand and generate language; <strong>post-training teaches them to act like a reliable assistant</strong>, aligned with human goals and capable of tackling real-world tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-HKrEefqu9YRElqvf5OTw.png" /></figure><p>Think of it this way: <strong>pre-training teaches your model to speak, post-training teaches it to think, reason, and respond effectively.</strong></p><p>In this post, we’ll explore the three main post-training strategies — <strong>Supervised Fine-Tuning (SFT), Direct Preference Optimization (DPO), and Online Reinforcement Learning (RLHF)</strong> — and demonstrate how careful dataset curation is crucial to the success of each method.</p><h3>1. Supervised Fine-Tuning (SFT): Teaching the Basics</h3><p><strong>What it is:</strong> SFT trains the model on <strong>labeled prompt-response pairs</strong>, teaching it to produce high-quality outputs given specific instructions. It minimizes the negative log likelihood for the response given the prompt with cross-entropy loss.</p><p><strong>How it works:</strong> Only response tokens are used for loss computation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*TAt8VjCpBjlqmOTjXpqtHQ.png" /><figcaption>SFT Loss Function</figcaption></figure><p><strong>Example:</strong></p><pre>Prompt: Who are you?  <br>Response: I am an AI assistant.</pre><p><strong>Use Cases:</strong></p><p><strong>1. Jumpstarting New Model Behavior</strong></p><p>Convert <strong>pre-trained base models into instruct models</strong> that can follow human instructions.</p><p>Upgrade <strong>non-reasoning models into reasoning-capable models</strong> for problem-solving tasks.</p><p>Enable the model to <strong>use tools or APIs</strong> without embedding detailed tool instructions in every prompt.</p><p><strong>2. Improving Model Capabilities</strong></p><p><strong>Distill knowledge from stronger models</strong>: train smaller or less capable models on high-quality synthetic data generated by larger LLMs.</p><p>Rapidly enhance <strong>reasoning, domain expertise, or task-specific skills</strong> without needing massive labeled datasets.</p><p><strong>Dataset Curation for SFT:</strong></p><ol><li><strong>Distillation:</strong> Generate responses from high-quality instruct models.</li><li><strong>Best-of-K / Rejection Sampling:</strong> Generate multiple outputs per prompt; select the best.</li><li><strong>Filtering:</strong> Ensure <strong>quality and diversity</strong> of prompts and responses.</li></ol><p><strong>Tip:</strong> Quality &gt; quantity: <em>1,000 high-quality examples outperform 1 million low-quality examples.</em></p><p><strong>Training Options:</strong> Full fine-tuning or parameter-efficient fine-tuning (PEFT), depending on compute resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYdFJ40QV_gaPUO9MOXWBA.png" /><figcaption>Image Credits : DeepLearning.AI</figcaption></figure><h3>2. Direct Preference Optimization (DPO): Refining Subtle Preferences</h3><p><strong>What it is:</strong> In <strong>DPO</strong>, for each prompt, the model sees a <strong>good (positive) response</strong> and a <strong>bad (negative) response</strong>. DPO minimizes a <strong>contrastive loss</strong>, typically implemented as a <strong>cross-entropy loss on the reward difference</strong> computed by a re-parameterized reward model. The model learns to assign higher probability to the positive response relative to the negative one, refining subtle behaviors without large distributional shifts.</p><p><strong>Loss function:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*hfNitxiSK0jBotob1bttqQ.png" /></figure><p><strong>Example:</strong></p><pre>Prompt: Who are you?  <br>Good Response: I am an AI assistant.  <br>Bad Response: I am an assistant.</pre><p><strong>Use Cases:</strong></p><ul><li>Tweaking tone, identity, multilingual responses, or instruction-following style.</li><li>Safety alignment: penalize borderline or unsafe outputs.</li><li>Often improves capabilities better than SFT due to its contrastive nature.</li></ul><p><strong>Dataset Curation for DPO:</strong></p><ol><li><strong>Corrections:</strong> Use original model outputs as negative samples; improved outputs as positive samples.</li><li><strong>Online / On-policy Sampling:</strong> Generate multiple outputs from the current model; select the best as positive, the worst as negative.</li><li><strong>Avoid Overfitting:</strong> Ensure negative examples are non-trivial to prevent shortcut learning.</li></ol><p><strong>Tip:</strong> DPO is excellent for refining nuanced behaviors without requiring full retraining.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*3ffdPtWjw31qU4_VNfCsPg.png" /><figcaption>Image Credits: DeepLearning.AI</figcaption></figure><h3>3. Online Reinforcement Learning (RLHF-style): Learning from Feedback</h3><p><strong>What it is:</strong> RLHF enables the model to <strong>continuously improve</strong> by generating responses, receiving scalar rewards, and updating its policy.</p><p><strong>Training Modes</strong></p><p><strong>Online RLHF: </strong>The model learns by generating new responses in real time. It iteratively collects new responses and their rewards, updates its weights, and explores new responses as it learns.</p><p><strong>Offline learning: </strong>The model learns purely from a pre-collected prompt response (-reward) tuple. No fresh response is generated during the learning process.</p><p><strong>Reward Functions:</strong></p><ol><li><strong>Trained Reward Model:</strong> Works for open-ended generation, chat, and safety.</li><li><strong>Verifiable Reward:</strong> Ground truth, unit tests, or sandbox execution; more reliable for coding, math, or multi-turn reasoning tasks.</li></ol><p><strong>Policy Optimization Algorithms:</strong></p><ul><li><strong>PPO (Proximal Policy Optimization):</strong> Efficient with scalar or binary rewards; requires a value model; more GPU usage.</li><li><strong>GRPO (Group Relative Policy Optimization):</strong> Better for binary rewards; simpler KL-regularized updates; lower memory footprint; requires more samples.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*KMjiiRVYz4mAgo4cgUj4TA.png" /><figcaption>Difference between PPO and GRPO</figcaption></figure><p><strong>Example:</strong></p><pre>Prompt: Who are you?  <br>Response: I am an AI assistant.  <br>Reward: 1.9</pre><p><strong>Use Cases:</strong></p><ul><li>Continuous optimization for chatbots or interactive tools.</li><li>Correctness-critical domains like math, coding, or agent tasks.</li><li>Dynamic adaptation to new user needs and scenarios.</li></ul><p><strong>Dataset Curation for RLHF:</strong></p><ol><li>Collect <strong>prompt-response-reward tuples</strong> from online generation or offline datasets.</li><li>Filter for <strong>reward consistency, diversity, and relevance</strong>.</li><li>Use <strong>augmentation</strong>: scenario simulations, multi-turn dialogues, edge cases.</li><li>Maintain a <strong>balance</strong> between positive and negative examples to prevent reward hacking.</li><li>Algorithm-specific tips:</li></ol><ul><li>PPO: stabilize value model training.</li><li>GRPO: Use larger batch sizes to compensate for binary rewards.</li></ul><p><strong>Tip:</strong> Online RLHF allows your model to <strong>continually evolve</strong>, combining reward signals with adaptive policy updates for robust, real-world behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*nPtwKV3vYqr-0riW53jMUg.png" /><figcaption>Image Credits: DeepLearning.io</figcaption></figure><h3>Key Takeaways</h3><ul><li><strong>Post-training is more than algorithms; it’s about high-quality, well-curated datasets.</strong></li><li><strong>SFT</strong> teaches the basics and establishes strong instruction-following behavior.</li><li><strong>DPO</strong> refines subtle preferences and corrects nuanced behaviors.</li><li><strong>RLHF</strong> enables ongoing, reward-driven adaptation for dynamic or correctness-critical applications.</li><li>By combining these methods with <strong>careful dataset curation</strong>, your LLM transforms from a generic language model into a precise, reliable, and adaptive AI partner.</li></ul><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e0d17a84914" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/post-training-large-language-models-sft-dpo-and-rlhf-explained-3e0d17a84914">Post-Training Large Language Models: SFT, DPO, and RLHF Explained</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built an Automated Stock Picker with CrewAI]]></title>
            <link>https://ai.plainenglish.io/how-i-built-an-automated-stock-picker-with-crewai-55d4354ff394?source=rss-64cc8e986127------2</link>
            <guid isPermaLink="false">https://medium.com/p/55d4354ff394</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Nishan Jain]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 19:27:17 GMT</pubDate>
            <atom:updated>2025-08-24T19:27:17.559Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>Disclaimer:</em></strong><em> This project is for </em><strong><em>educational purposes only</em></strong><em>. Do </em><strong><em>not rely on it for real financial decisions or investments</em></strong><em>. Always do your own research before making any investment.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2jgmaExpzB-MV_Ca" /><figcaption>Photo by <a href="https://unsplash.com/@nampoh?utm_source=medium&amp;utm_medium=referral">Maxim Hopman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Multi-agent AI apps are no longer a future concept — they’re here today. Using <a href="https://crewai.com/">CrewAI</a>, I built a <strong>Stock Selector</strong> that automatically finds trending companies, researches them, and picks the most promising one.</p><p>Here’s a step-by-step breakdown:</p><h3>1. Kickstart a New CrewAI Project</h3><p>Open your terminal and run:</p><pre>crewai create crew stock_selector</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PL33H5o7MVQMuYyXtTSE6g.png" /></figure><ul><li>Pick your provider (OpenAI, Groq, etc.)</li><li>Select a model (e.g., Llama-3.1 405B reasoning)</li><li>Add API keys if needed</li></ul><p>CrewAI scaffolds your project with agents.yaml, tasks.yaml, and starter Python files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*WFgcfddAkvBkwh9vOSYS9A.png" /></figure><p><strong>Tip:</strong> These files are the backbone of your agent/task definitions.</p><h3>2. Define Your Agents &amp; Tasks</h3><p><strong>agents.yaml</strong> → defines who your agents are and what they do.</p><p>This YAML file describes who your agents are and what they do. Each agent has a:</p><ul><li>role (summary of responsibility)</li><li>goal (the task to achieve)</li><li>backstory (a helpful prompt for nuanced responses)</li><li>llm (language model used for the agent)</li></ul><p>Example agent:</p><pre>trending_company_finder:<br>  role: Financial News Analyst<br>  goal: Find 2–3 trending companies in {sector}<br>  backstory: Market expert picking interesting companies based on latest news.<br>  llm: ollama/gemma2:9b-instruct-fp16</pre><p><strong>tasks.yaml</strong> → defines the tasks and how outputs are handled.</p><p>This file explains what needs to be done, by whom, and how outputs are handled.</p><p>Key fields:</p><ul><li>description</li><li>expected_output</li><li>agent (which agent is assigned)</li><li>context (dependencies between tasks)</li><li>output_file (where to store results)</li></ul><p>Example task:</p><pre>find_trending_companies:<br>  description: Find top trending companies in {sector} via latest news.<br>  expected_output: List of trending companies<br>  agent: trending_company_finder<br>  output_file: output/trending_companies.json</pre><h3>3. Deep Dive: crew.py and Pydantic Schemas</h3><p>The real power is in your crew.py. This file:</p><ul><li>Connects your YAML agent/task definitions to code.</li><li>Uses Pydantic schemas to define and validate structured data output from each agent and task.</li><li>Implements the Crew class using @CrewBase for orchestration.</li></ul><p><strong>Pydantic Models</strong><br>These ensure you get reliable, structured output from agents.</p><pre>from pydantic import BaseModel, Field<br>from typing import List<br><br>class TrendingCompany(BaseModel):<br> name: str = Field(description=&quot;Company name&quot;)<br> ticker: str = Field(description=&quot;Stock ticker symbol&quot;)<br> reason: str = Field(description=&quot;Reason this company is trending in the news&quot;)<br><br>class TrendingCompanyList(BaseModel):<br> companies: List[TrendingCompany] = Field(description=&quot;List of companies trending in the news&quot;)</pre><p>Agents now return clean, structured JSON for further processing.</p><h3>4. Orchestrate Agents and Tasks with crew.py</h3><p>The orchestration layer is where your multi-agent workflow comes to life. CrewAI provides <strong>decorators</strong> (@CrewBase, @agent, @task, @crew) that make it easy to connect your YAML configurations to Python logic. Let’s unpack this step by step.</p><h3>4.1 @CrewBase – The Crew Skeleton</h3><pre>@CrewBase<br>class StockSelector():<br>    agents_config = &#39;config/agents.yaml&#39;<br>    tasks_config = &#39;config/tasks.yaml&#39;</pre><ul><li><strong>Purpose:</strong> Marks the class as a CrewAI “crew” definition.</li><li><strong>Role:</strong> Loads agent and task configurations from YAML.</li><li><strong>Benefit:</strong> Provides a structured way to manage multiple agents and tasks from a single class.</li></ul><p>Think of @CrewBase as the <strong>skeleton of your workflow</strong>—all agents and tasks will attach to this class.</p><h3>4.2 @agent – Define Agent Behavior</h3><p>Each agent represents a <strong>specialized AI worker</strong>. Use the @agent decorator to define them:</p><pre>@agent<br>def trending_company_finder(self) -&gt; Agent:<br>    return Agent(config=self.agents_config[&#39;trending_company_finder&#39;],<br>                 tools=[SerperDevTool()], memory=True)</pre><ul><li><strong>config:</strong> Tells the agent which YAML definition to use.</li><li><strong>tools:</strong> Adds external tools (e.g., web search APIs) the agent can use.</li><li><strong>memory:</strong> Enables the agent to <strong>remember previous outputs</strong> — useful for multi-step reasoning.</li></ul><p>Other agents, like financial_researcher, can be defined similarly. Each agent can have <strong>different tools and memory settings</strong>, depending on their role.</p><h3>4.3 @task – Connect Agents to Actions</h3><p>Tasks describe <strong>what work each agent does</strong>:</p><pre>@task<br>def find_trending_companies(self) -&gt; Task:<br>    return Task(<br>        config=self.tasks_config[&#39;find_trending_companies&#39;],<br>        output_pydantic=TrendingCompanyList,<br>    )</pre><ul><li><strong>config:</strong> Links to the YAML task definition.</li><li><strong>output_pydantic:</strong> Validates that the agent produces <strong>structured output</strong> (like a list of trending companies).</li></ul><p>By combining agents + tasks, you ensure that <strong>each task is performed by the right agent</strong> and that results are consistent.</p><h3>4.4 @crew – Glue Everything Together</h3><p>The @crew decorator defines the <strong>workflow orchestration</strong>:</p><pre>@crew<br>def crew(self) -&gt; Crew:<br>    manager = Agent(<br>        config=self.agents_config[&#39;manager&#39;],<br>        allow_delegation=True<br>    )<br>    return Crew(<br>        agents=self.agents,<br>        tasks=self.tasks, <br>        process=Process.hierarchical,<br>        verbose=True,<br>        manager_agent=manager,<br>    )</pre><ul><li><strong>manager_agent:</strong> Oversees the workflow and delegates tasks.</li><li><strong>process:</strong> Process.hierarchical ensures tasks run in the <strong>right sequence</strong>, respecting dependencies.</li><li><strong>verbose:</strong> Enables logging for debugging.</li></ul><h3>5. Run the End-to-End Flow</h3><p>Finally, execute the workflow using :</p><pre>from stock_selector.crew import StockSelector<br>from datetime import datetime<br><br>inputs = {<br>    &#39;sector&#39;: &#39;Technology&#39;,<br>    &#39;current_date&#39;: str(datetime.now())<br>}<br>result = StockSelector().crew().kickoff(inputs=inputs)<br>print(&quot;\n\n=== FINAL DECISION ===\n\n&quot;)<br>print(result.raw)</pre><ul><li>CrewAI coordinates all agents automatically.</li><li>Outputs are saved as JSON/Markdown files.</li><li>Final decision = best company pick.</li><li>Finally run the program using</li><li>uv run crew</li></ul><p>Look at this github repo for complete code <a href="https://github.com/gr8nishan/llm_agents/tree/master/stock_selector">https://github.com/gr8nishan/llm_agents/tree/master/stock_selector</a></p><h3>💡 Takeaway</h3><p>With CrewAI, you can go from <strong>idea → multi-agent automation</strong> in hours. YAML handles configuration, Pydantic ensures structured data, and Python ties everything together.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55d4354ff394" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/how-i-built-an-automated-stock-picker-with-crewai-55d4354ff394">How I Built an Automated Stock Picker with CrewAI</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Python Coding Tasks with Your Own CrewAI Agent]]></title>
            <link>https://blog.gopenai.com/automate-python-coding-tasks-with-your-own-crewai-agent-a0e66745ad0f?source=rss-64cc8e986127------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0e66745ad0f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Nishan Jain]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 09:47:39 GMT</pubDate>
            <atom:updated>2025-08-05T09:55:04.705Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine giving your AI assistant a prompt like “Sort a CSV by date and email me the results” — and it plans, writes, and runs the code for you.<br> Welcome to the world of <strong>agentic AI development</strong> — where autonomous agents go beyond chatting and actually <em>do things</em>.</p><p>In this post, we’ll walk through how to build a Python code-writing AI using CrewAI, a lightweight orchestration framework for building multi-agent systems.</p><h3>🧩 The Problem: Static Chatbots Can’t Execute</h3><p>While traditional LLM tools like ChatGPT can write code, they leave you with the burden of:</p><ul><li>figuring out how to run it,</li><li>checking if it works,</li><li>and iterating when it doesn’t.</li></ul><p>Agentic systems flip this by giving agents <em>goals</em> and letting them <em>act autonomously</em> — writing, executing, and validating results.</p><h3>🛠️ The Stack</h3><p>We’ll use:</p><ul><li>🧠 <strong>CrewAI</strong> to define agents and tasks</li><li>🐍 <strong>Python</strong> to run everything locally</li><li>🔁 <strong>Prompt templates</strong> to give agents structure</li><li>⚙️ <strong>GPT-4o Mini</strong> (or your favorite OpenAI model) for reasoning + code-writing</li></ul><h3>🧠 Agent Design: The Python Coder</h3><p>Here’s the agent we define in agents.yaml:</p><pre>coder:<br>  role: &gt;<br>    Python Developer<br>  goal: &gt;<br>    You write python code to achieve this assignment: {assignment}<br>    First you plan how the code will work, then you write the code, then you run it and check the output.<br>  backstory: &gt;<br>    You&#39;re a seasoned python developer with a knack for writing clean, efficient code.<br>  llm: gpt-4o-mini</pre><h3>✅ Task: Code + Output</h3><p>In tasks.yaml, we define a single task:</p><pre>coding_task:<br>  description: &gt;<br>    Write python code to achieve this: {assignment}<br>  expected_output: &gt;<br>    A text file that includes the code itself, along with the output of the code.<br>  agent: coder<br>  output_file: output/code_and_output.txt</pre><p>It expects the result in a text file containing both the source code and its execution output — like a self-contained notebook output.</p><p>So when we give it an assignment like:</p><blockquote><em>“Calculate an approximation of Pi using the Leibniz series up to 10,000 terms”</em></blockquote><p>…it knows it has to plan, write, run, and output.</p><h3>🧪 The Glue Code</h3><p>The crew.py file sets up the agent and the task, and wires everything together:</p><pre>from crewai import Agent, Task, Crew, Process<br>from agents import coder  # from agents.yaml<br>from tasks import coding_task  # from tasks.yaml<br><br>crew = Crew(<br>    agents=[coder],<br>    tasks=[coding_task],<br>    process=Process.sequential<br>)<br><br>result = crew.kickoff()<br>print(&quot;Result:&quot;, result)</pre><p>The main.py acts as the entry point where you pass in the assignment:</p><pre>from crew import crew<br><br>if __name__ == &quot;__main__&quot;:<br>    result = crew.kickoff(inputs={&quot;assignment&quot;: &quot;Write a python script to print prime numbers between 1 and 100&quot;})<br>    print(result)</pre><h3>🏃 Running the Crew</h3><p>Once your files are ready, all you have to do is:</p><pre>crew run</pre><p>This triggers the agent lifecycle defined by CrewAI — no additional Python scripting needed.</p><h3>🖥️ Output: AI-Written &amp; Executed Code</h3><p>After running, check the file output/code_and_output.txt.</p><p>Here’s what the agent wrote:</p><pre># Python code to calculate the first 10,000 terms of the series<br>total = 0.0<br>for i in range(10000):<br>    term = 1 / (2 * i + 1)  # Calculates the term 1/(2n+1)<br>    if i % 2 == 0:<br>        total += term  # Add for even indices<br>    else:<br>        total -= term  # Subtract for odd indices<br><br>result = total * 4  # Multiply the total by 4<br>print(result)</pre><p>Not bad for an autonomous agent, right?</p><h3>🧱 Why This Matters</h3><p>This is more than just LLM-as-a-chatbot.</p><p>You’re now building systems where AI <em>acts</em>:</p><ul><li>Plans its own approach</li><li>Validates execution</li><li>Produces artifacts like real devs</li></ul><p>And because it’s modular, you can add more agents — a tester, reviewer, or even a deployer.</p><h3>🚀 Bonus Ideas</h3><p>To take this further:</p><ul><li>✅ Add a <strong>reviewer agent</strong> to critique the code</li><li>🔁 Use feedback loops to retry on failures</li><li>🧪 Generate test cases for each code run</li><li>🔧 Add tools: file uploads, API fetchers, etc.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0e66745ad0f" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/automate-python-coding-tasks-with-your-own-crewai-agent-a0e66745ad0f">Automate Python Coding Tasks with Your Own CrewAI Agent</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangGraph Tutorial 4: Build a MongoDB Chat Agent with MCP]]></title>
            <link>https://blog.gopenai.com/langgraph-tutorial-4-build-a-mongodb-chat-agent-with-mcp-88e27602b4b9?source=rss-64cc8e986127------2</link>
            <guid isPermaLink="false">https://medium.com/p/88e27602b4b9</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nishan Jain]]></dc:creator>
            <pubDate>Sat, 19 Jul 2025 14:12:58 GMT</pubDate>
            <atom:updated>2025-07-19T16:29:20.813Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tired of writing complex scripts just to query your MongoDB database? In this guide, you’ll learn how to build an AI agent that lets you chat with your data using plain English, powered by LangGraph, the Model Context Protocol (MCP), and Gradio.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oW9nEOXY-fMehLCY" /><figcaption>Photo by <a href="https://unsplash.com/@coopery?utm_source=medium&amp;utm_medium=referral">Mohamed Nohassi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine asking your database, “How many user accounts were created last week?” and getting a direct answer, without writing a single line of an aggregation pipeline. This is the promise of AI agents that can interact with real-world tools.</p><p>This tutorial will guide you through building a powerful AI agent that understands natural language, queries a live MongoDB database, and delivers answers through a clean web interface. You will learn to:</p><ul><li>Connect to MongoDB securely using the Model Context Protocol (MCP), an open standard for AI.</li><li>Build a stateful agent with LangGraph that can reason and act.</li><li>Leverage a pre-built ReAct agent to think, execute tools, and find answers.</li><li>Wrap everything in a user-friendly UI with Gradio.</li></ul><p>By the end, you’ll have a functional and extensible chatbot for your own database, built on industry-standard protocols.</p><h3>The Tech Stack: A High-Level View</h3><p>Before we dive in, let’s understand the core components and how they fit together.</p><ul><li><strong>LangGraph</strong>: An extension of LangChain for building complex, stateful AI applications. It uses graphs to create cycles, which are essential for agents that need to think, act, and re-evaluate, just like a human would.</li><li><strong>ReAct Agent</strong>: A specific agent design that stands for “Reason and Act.” It works by generating a thought process, choosing a tool (like a database query), executing it, and observing the result to decide its next step.</li><li><strong>Model Context Protocol (MCP)</strong>: An open-source standard for connecting large language models to external tools and data sources. It acts as a universal language, allowing any compliant AI to communicate with any compliant tool.</li><li><strong>Gradio</strong>: A Python library that makes it incredibly simple to create and share interactive web UIs for machine learning models and AI agents.</li></ul><p>Here’s a simple diagram of our application’s architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zTUqahN3KThifCAvHyAFEA.png" /><figcaption>Data Interaction Flow</figcaption></figure><h3>Prerequisites</h3><p>First, ensure you have the necessary Python libraries installed.</p><pre>pip install langgraph langchain_openai langchain_mcp_adapters gradio &quot;npx&quot;</pre><p>Next, set your OpenAI API key as an environment variable.</p><pre>export OPENAI_API_KEY=&quot;your-actual-api-key&quot;</pre><h3>Step 1: Connecting to MongoDB via an MCP Client</h3><p>Our first step is to set up the MultiServerMCPClient. This client langchain_mcp_adapters is responsible for starting and managing the mongodb-mcp-server process, which speaks the Model Context Protocol.</p><pre>from langchain_mcp_adapters.client import MultiServerMCPClient<br><br># This client will manage the connection to the MongoDB MCP server.<br>client = MultiServerMCPClient(<br>    {<br>        &quot;MongoDB&quot;: {<br>            # &quot;stdio&quot; means the agent communicates with the server process<br>            # via standard input/output.<br>            &quot;transport&quot;: &quot;stdio&quot;,<br>            # &quot;npx&quot; is used to run the server package without a global installation.<br>            &quot;command&quot;: &quot;npx&quot;,<br>            &quot;args&quot;: [<br>                &quot;-y&quot;,<br>                &quot;mongodb-mcp-server&quot;,<br>                &quot;--connectionString&quot;,<br>                # IMPORTANT: Replace this with your actual MongoDB connection string.<br>                &quot;&lt;mongo db connection string&gt;&quot;<br>            ]<br>        }<br>    }<br>)</pre><h3>Step 2: Fetch Tools from MCP Server</h3><pre>tools = await client.get_tools()</pre><h3>Step 3: Defining the ReAct Agent in LangGraph</h3><p>Next, we’ll define the “brain” of our application — the ReAct agent. We initialize our chosen language model (gpt-4o-mini) and then create the agent within our main chat function. This is because the tools the agent can use are fetched asynchronously from the MCP client.</p><pre>model = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br>agent = create_react_agent(model=model, tools=tools)</pre><h3>Step 4: Building a Web Interface with Gradio</h3><p>To make our agent interactive, we’ll use Gradio’s ChatInterface. We will define a single async function, chat_function, that Gradio will call every time a user sends a message.</p><pre>iface = gr.ChatInterface(<br>    fn=chat_function,<br>    title=&quot;LangGraph MongoDB Agent&quot;,<br>    description=&quot;Ask your questions about the MongoDB collections. For example: &#39;Tell me all mongo collections&#39;&quot;,<br>    examples=[[&quot;Tell me all mongo collections&quot;], [&quot;List all databases&quot;]],<br>    cache_examples=False,</pre><h3>The Complete Code</h3><p>Here is the full, commented script. Save it as app.py.</p><pre>import gradio as gr<br>from langchain_mcp_adapters.client import MultiServerMCPClient<br>from langgraph.prebuilt import create_react_agent<br>from langchain_openai import ChatOpenAI<br>import os<br><br># It&#39;s a best practice to load secrets from environment variables.<br># os.environ[&quot;OPENAI_API_KEY&quot;] = &quot;sk-...&quot; <br><br># --- 1. Initialize Non-Async Components ---<br>client = MultiServerMCPClient(<br>    {<br>        &quot;MongoDB&quot;: {<br>            &quot;transport&quot;: &quot;stdio&quot;,<br>            &quot;command&quot;: &quot;npx&quot;,<br>            &quot;args&quot;: [<br>                &quot;-y&quot;,<br>                &quot;mongodb-mcp-server&quot;,<br>                &quot;--connectionString&quot;,<br>                # IMPORTANT: Replace this with your actual MongoDB connection string.<br>                &quot;&lt;conection string&gt;&quot;<br>            ]<br>        }<br>    }<br>)<br>model = ChatOpenAI(model=&quot;gpt-4-turbo&quot;, temperature=0)<br><br># --- 2. Define the Core Asynchronous Logic ---<br>async def chat_function(message: str, history: list):<br>    tools = await client.get_tools()<br>    agent = create_react_agent(model=model, tools=tools)<br>    response_dict = await agent.ainvoke(<br>        {&quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message}]}<br>    )<br>    final_response = response_dict[&#39;messages&#39;][-1].content<br>    return final_response<br><br># --- 3. Create and Launch the Gradio UI ---<br>iface = gr.ChatInterface(<br>    fn=chat_function,<br>    title=&quot;LangGraph MongoDB Agent&quot;,<br>    description=&quot;Ask questions about your MongoDB database using the Model Context Protocol.&quot;,<br>    examples=[<br>        [&quot;Tell me all mongo collections&quot;], <br>        [&quot;List all databases&quot;],<br>        [&quot;How many documents are in the &#39;users&#39; collection?&quot;]<br>    ],<br>    cache_examples=False,<br>)<br><br>if __name__ == &quot;__main__&quot;:<br>    iface.launch()</pre><h3>Running Your Application</h3><p>To start your agent, run the script from your terminal:</p><pre>python app.py</pre><p>Gradio will provide a local URL (e.g., http://127.0.0.1:7860). Open it in your browser to start chatting with your database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxLTRTYtKAoZtjMa1UQunA.png" /><figcaption>Running Gradio Interface</figcaption></figure><h3>Conclusion</h3><p>You have successfully built a sophisticated AI application that bridges the gap between natural language and structured data using industry-standard protocols.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88e27602b4b9" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/langgraph-tutorial-4-build-a-mongodb-chat-agent-with-mcp-88e27602b4b9">LangGraph Tutorial 4: Build a MongoDB Chat Agent with MCP</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangGraph Tutorial Part 3: Empowering Your Travel Assistant with Tool Calling, Memory, and Tracing]]></title>
            <link>https://blog.gopenai.com/langgraph-tutorial-part-3-empowering-your-travel-assistant-with-tool-calling-memory-and-tracing-3b504598254b?source=rss-64cc8e986127------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b504598254b</guid>
            <dc:creator><![CDATA[Nishan Jain]]></dc:creator>
            <pubDate>Sun, 29 Jun 2025 13:26:12 GMT</pubDate>
            <atom:updated>2025-07-05T14:03:42.848Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back to the final installment of our LangGraph tutorial series! In <a href="https://medium.com/@gr8nishan/langgraph-tutorial-part-1-build-a-simple-agent-workflow-in-python-18a5c6b8e34a">Part 1</a> and <a href="https://medium.com/@gr8nishan/langgraph-tutorial-part-2-mastering-tools-and-parallel-execution-in-a-travel-agent-workflow-089fa52a6e04">Part 2</a>, we laid the groundwork for building intelligent agents and explored the power of parallel execution. Now, it’s time to elevate our <strong>Travel Assistant</strong> to new heights by integrating crucial features: <strong>dynamic tool calling</strong>, <strong>persistent memory</strong>, and <strong>insightful tracing</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qRfOWwf2tkbWdUAT" /><figcaption>Photo by <a href="https://unsplash.com/@lingapp?utm_source=medium&amp;utm_medium=referral">Ling App</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This blog post will guide you through enhancing our travel agent with the ability to:</p><ul><li><strong>Intelligently use external tools</strong> like weather and flight search.</li><li><strong>Remember past conversations</strong> to provide a seamless user experience.</li><li><strong>Visualize the agent’s decision-making process</strong> for debugging and understanding.</li></ul><p>You can find the <strong>complete implementation</strong> here:<br> 🔗 <a href="https://github.com/gr8nishan/llm_agents/blob/master/langgraph-travelagent/travel_agent_memory.py">github.com/gr8nishan/llm_agents/blob/master/langgraph-travelagent/travel_agent_memory.py</a></p><p>Let’s dive in!</p><h3>🛠 1. Dynamic Tool Calling — Equipping the Agent to Interact with the World</h3><p>Language models (LLMs) are powerful in isolation, but their utility is bound to the training data they were exposed to. If your assistant needs up-to-date information — say, the current weather in Rome or the best restaurants in Dubai — it needs access to <strong>external tools</strong>.</p><p>LangGraph allows seamless integration of such tools through its native support for LangChain tools and smart node orchestration.</p><h3>Defining the Agent’s State</h3><p>We begin by defining the shared state. Our assistant maintains a list of messages exchanged in the conversation.</p><pre>from typing import Annotated, List<br>from typing_extensions import TypedDict<br>from langgraph.graph.message import add_messages</pre><pre>class TravelState(TypedDict):<br>    messages: Annotated[List, add_messages]</pre><p>This state is automatically updated as new messages (from user, LLM, or tool) are added.</p><h3>Defining Tools for Real-Time Info</h3><p>We define tool functions using the @tool decorator. These simulate external APIs using LangChain’s GoogleSerperAPIWrapper:</p><pre>@tool<br>def search_weather(destination: str) -&gt; str:<br>    &quot;&quot;&quot;Get current weather in a location.&quot;&quot;&quot;<br>    return GoogleSerperAPIWrapper().run(f&quot;current weather in {destination}&quot;)</pre><p>We also create tools for:</p><ul><li>search_flights: “flights from Delhi to Paris”</li><li>search_attractions: “things to do in Rome”</li><li>search_restaurants: “best places to eat in Dubai”</li></ul><p>All tools are added to a list:</p><pre>tools = [search_weather, search_flights, search_attractions, search_restaurants]</pre><h3>Binding Tools to the LLM</h3><p>Now, we bind the tools to our LLM using bind_tools():</p><pre>llm = init_chat_model(&quot;groq:llama3-8b-8192&quot;)<br>llm_with_tools = llm.bind_tools(tools)</pre><p>This tells the model what tools it can use, when appropriate.</p><h3>ToolNode and tools_condition — Core of Dynamic Tool Use</h3><p>Here’s where <strong>LangGraph</strong> shines.</p><p>Instead of writing custom logic for every possible tool invocation, LangGraph provides built-in support to <strong>let the LLM decide</strong> whether a tool is needed, and handles the execution automatically.</p><h4>ToolNode</h4><p>ToolNode is a special node type that:</p><ul><li>Inspects the last LLM message for a tool call.</li><li>Executes the matching tool if found.</li><li>Appends the result back to the conversation as a ToolMessage.</li></ul><pre>graph_builder.add_node(&quot;tools&quot;, ToolNode(tools=tools))</pre><h4>tools_condition</h4><p>After the chatbot node executes, tools_condition checks:</p><ul><li>If a tool is requested → it routes to the tools node.</li><li>If not → it proceeds to the next node or ends the flow.</li></ul><pre>graph_builder.add_conditional_edges(&quot;chatbot&quot;, tools_condition)</pre><p>This system eliminates hardcoded branching logic and gives your agent autonomy to act based on the context of the conversation.</p><h4>The Complete Graph</h4><p>This defines the full LangGraph flow:</p><ul><li>chatbot: The LLM processes user input and may request a tool.</li><li>tools: Executes the requested tool if needed.</li><li>START → chatbot: Conversation begins with the LLM.</li><li>chatbot → tools (via tools_condition): If the LLM requests a tool.</li><li>tools → chatbot: After tool execution, return to LLM.</li><li>chatbot → END: If no tool is needed, end the flow.</li></ul><pre>graph_builder = StateGraph(TravelState)<br>graph_builder.add_node(&quot;chatbot&quot;, chatbot_node)<br>graph_builder.add_node(&quot;tools&quot;, ToolNode(tools=tools))<br>graph_builder.add_edge(START, &quot;chatbot&quot;)<br>graph_builder.add_conditional_edges(&quot;chatbot&quot;, tools_condition)<br>graph_builder.add_edge(&quot;tools&quot;, &quot;chatbot&quot;)<br>graph_builder.add_edge(&quot;chatbot&quot;, END)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*pwqoquJmvWz2j1br3TOabg.png" /></figure><h3>🧠 2. Memory — Making Your Assistant Context-Aware</h3><p>Let’s make our assistant truly conversational.</p><p>Imagine this sequence:</p><blockquote><strong><em>User</em></strong><em>: What’s the weather in Paris?<br> </em><strong><em>User</em></strong><em>: What about Rome?</em></blockquote><p>Without memory, the model treats both prompts as separate. It has no clue that “What about Rome?” refers to the weather.</p><p>To support continuity, we need <strong>persistent memory</strong>. LangGraph supports this via <strong>checkpointers</strong> that store the graph’s state per session (thread_id).</p><h3>MemorySaver — Simple In-Memory Persistence</h3><p>The easiest way to add memory is with MemorySaver:</p><pre>from langgraph.checkpoint.memory import MemorySaver<br>saver = MemorySaver()<br>graph = graph_builder.compile(checkpointer=saver)</pre><p>This stores the entire conversation state in memory for the duration of a session.</p><p>🧠 <strong>Important</strong>:</p><ul><li>MemorySaver is great for prototyping.</li><li>For production, replace it with persistent checkpointers like SQLiteSaver, RedisSaver, or PostgresSaver to maintain the state across restarts.</li></ul><h3>🔍 3. Tracing with LangSmith — Visualizing Agent Behavior</h3><p>LangGraph offers powerful control over flow, but as complexity grows, debugging becomes harder.</p><p>That’s where <strong>LangSmith</strong> comes in — a tracing and observability tool from LangChain that shows you:</p><ul><li>Every message and LLM call</li><li>What tool was used and why</li><li>How the state transitioned between nodes</li></ul><h3>Enabling LangSmith Tracing</h3><p>Add this to enable visual debugging:</p><pre>import os<br>from dotenv import load_dotenv<br><br>load_dotenv()<br>os.environ[&quot;LANGCHAIN_TRACING_V2&quot;] = &quot;true&quot;</pre><p>Make sure your .env file has:</p><pre>LANGCHAIN_API_KEY=your_key<br>LANGCHAIN_PROJECT=travel_assistant</pre><p>Once enabled, you’ll see a beautiful UI showing each interaction and graph transition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gFPJyS1D9GoNisDr8XGPQ.png" /></figure><h3>💬 Adding a Gradio Interface — Making It Interactive</h3><p>To test everything end-to-end, let’s hook up a basic Gradio interface:</p><pre>import gradio as gr<br><br>def gradio_chat(user_input, chat_history_state):<br>    chat_history_state.append((user_input, None))<br>    result = run_graph(user_input, session_id)<br>    chat_history_state[-1] = (user_input, result)<br>    return chat_history_state, chat_history_state</pre><p>Inside the run_graph() function, we invoke our compiled LangGraph with:</p><ul><li>Current user input</li><li>Session-scoped memory</li><li>LLM and tools are already wired in</li></ul><p>Finally, we launch the Gradio interface:</p><pre>with gr.Blocks() as demo:<br>    gr.Markdown(&quot;🧳 Travel Assistant with Memory&quot;)<br>    ...<br>    demo.launch()</pre><p>This Gradio interface provides a simple chat window. When you type a query, it calls our run_graph function, which in turn leverages the LangGraph agent with its integrated tools, in-memory conversation history, and tracing.</p><h3>🧩 <strong>Full Code Available</strong></h3><p>Here’s the complete code combining everything: tool definitions, state management, graph setup, memory, and UI.<br> 🔗 <a href="https://github.com/gr8nishan/llm_agents/blob/master/langgraph-travelagent/travel_agent_memory.py">github.com/gr8nishan/llm_agents/blob/master/langgraph-travelagent/travel_agent_memory.py</a></p><h3>Conclusion</h3><p>Congratulations! You’ve now built a sophisticated travel assistant powered by LangGraph, capable of:</p><ul><li><strong>Intelligently calling external tools</strong> to fetch real-time information.</li><li><strong>Maintaining conversational context</strong> within a running session using in-memory state.</li><li><strong>Providing transparency</strong> into its decision-making process with LangSmith tracing.</li></ul><p>This is a major leap from prompt-only applications. With a bit of wiring, we’ve built something <strong>scalable, stateful, and interactive </strong>— ready for real-world use.</p><h3>💡 What’s Next?</h3><p>🔹 Add itinerary planning or booking workflows<br> 🔹 Experiment with SQLite or vector store checkpointers<br> 🔹 Try multi-agent collaboration using LangGraph!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b504598254b" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/langgraph-tutorial-part-3-empowering-your-travel-assistant-with-tool-calling-memory-and-tracing-3b504598254b">LangGraph Tutorial Part 3: Empowering Your Travel Assistant with Tool Calling, Memory, and Tracing</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangGraph Tutorial Part 2: Mastering Tools and Parallel Execution in a Travel Agent Workflow]]></title>
            <link>https://blog.gopenai.com/langgraph-tutorial-part-2-mastering-tools-and-parallel-execution-in-a-travel-agent-workflow-089fa52a6e04?source=rss-64cc8e986127------2</link>
            <guid isPermaLink="false">https://medium.com/p/089fa52a6e04</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nishan Jain]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 09:05:15 GMT</pubDate>
            <atom:updated>2025-07-05T14:04:11.068Z</atom:updated>
            <content:encoded><![CDATA[<h4>Speed up your AI agents by learning how to orchestrate concurrent tasks and use tools with LangGraph. We will also understand the state’s evolution in Langgraph.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GbZEmg-2FNkvXbiP" /><figcaption>Photo by <a href="https://unsplash.com/@lingapp?utm_source=medium&amp;utm_medium=referral">Ling App</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In <a href="https://medium.com/@gr8nishan/langgraph-tutorial-part-1-build-a-simple-agent-workflow-in-python-18a5c6b8e34a">Part 1 of this LangGraph series</a>, we dipped our toes into the exciting world of <strong>LangGraph</strong> by creating a simple, sequential agent. We learned how to define states, create nodes, and connect them to form a basic workflow. Now, it’s time to level up!</p><p>In this second installment, we’re going to build a more sophisticated <strong>Travel Agent</strong> that leverages the power of <strong>parallel execution</strong> and integrates <strong>external tools</strong>. Imagine asking your agent about a destination, and it simultaneously fetches the weather and lists top attractions, then combines all this information into a helpful summary. That’s exactly what we’ll achieve!</p><h3>🌟 <strong>Why Parallel Processing</strong></h3><p>In real-world applications, many tasks can run <strong>independently</strong>. For example:</p><ul><li>Fetching weather 🌦️</li><li>Finding top attractions 🗺️</li></ul><p>These don’t depend on each other, so why wait for one to finish before starting the other?</p><p>With LangGraph’s support for parallel edges, you can run them <strong>concurrently</strong>, reducing latency and improving UX.</p><h3>⚙️ Setting Up Our Environment</h3><p>Install the necessary packages:</p><pre>pip install langgraph langchain-community requests python-dotenv gradio</pre><p>Set up your .env file with API keys:</p><pre>GOOGLE_SERPER_API_KEY=&quot;your_serper_api_key&quot;<br>GROQ_API_KEY=&quot;your_groq_api_key&quot;</pre><h3>🧩 Helper Functions and Setup</h3><pre>from typing import Annotated, List, Dict, Any<br>import operator<br>from langgraph.graph import StateGraph, START, END<br>from dotenv import load_dotenv<br>from typing import TypedDict<br>import requests<br>import os<br>from langchain_community.utilities import GoogleSerperAPIWrapper<br>import gradio as gr<br><br># Load environment variables<br>load_dotenv()<br>GOOGLE_SERPER_API_KEY = os.getenv(&quot;GOOGLE_SERPER_API_KEY&quot;)<br>GROQ_API_KEY = os.getenv(&quot;GROQ_API_KEY&quot;)<br>GROQ_API_URL = &quot;https://api.groq.com/openai/v1/chat/completions&quot;<br><br># External tool clients<br>serper = GoogleSerperAPIWrapper()<br><br># --- Groq LLM Helper ---<br>def call_groq_llm(messages, model=&quot;llama3-8b-8192&quot;):<br>    headers = {<br>        &quot;Authorization&quot;: f&quot;Bearer {GROQ_API_KEY}&quot;,<br>        &quot;Content-Type&quot;: &quot;application/json&quot;<br>    }<br>    payload = {<br>        &quot;model&quot;: model,<br>        &quot;messages&quot;: messages,<br>        &quot;max_tokens&quot;: 512,<br>        &quot;temperature&quot;: 0.0<br>    }<br>    response = requests.post(GROQ_API_URL, headers=headers, json=payload)<br>    response.raise_for_status()<br>    return response.json()[&quot;choices&quot;][0][&quot;message&quot;][&quot;content&quot;]</pre><h3>🧠 Defining the State: TravelState</h3><p>The <strong>TypedDict</strong> in LangGraph, it is crucial for managing the flow of information between our nodes. Our TravelState will keep track of user messages, potential errors, and the information we gather:</p><pre># Define the TravelState<br>class TravelState(TypedDict):<br>    messages: Annotated[List[str], operator.add]<br>    error: Annotated[List[str], operator.add]</pre><ul><li><strong>messages: Annotated[List[str], operator.add]</strong>This is where all the conversational turns and informational snippets (like search results) will accumulate. operator.add ensures that new messages are appended to the list from various nodes.</li><li><strong>error: Annotated[List[str], operator.add]</strong> A list to capture any errors that occur during the execution of our nodes.</li></ul><h3>🔍 Node 1: extract_destination_node</h3><p>This is our entry point. It takes the user’s initial query and uses an LLM to extract the core travel destination. This is our first “tool” usage (the LLM itself).</p><pre># Node 1: Extract destination<br>def extract_destination_node(state: TravelState) -&gt; TravelState:<br>    print(&quot;Extracting destination from messages:&quot;, state)<br>    user_query = state[&quot;messages&quot;][-1]  # Get the last user message<br>    messages = [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Extract the travel destination from the user&#39;s message. Only return the destination name.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_query},<br>    ]<br>    try:<br>        # The extracted destination will be appended to the messages list<br>        state[&quot;messages&quot;].append(call_groq_llm(messages).strip())<br>    except Exception as e:<br>        state[&quot;error&quot;].append(f&quot;LLM error: {e}&quot;)<br>    return state</pre><p>Notice how the extracted destination is appended to state[&quot;messages&quot;]. This allows subsequent nodes to access it.</p><h3>📍Node 2: attractions_search_node</h3><p>Once we have the destination, we can search for attractions. This node utilizes the <strong>GoogleSerperAPIWrapper</strong> to perform a web search – a classic example of an external tool integration.</p><pre># Node 2: Search for attractions<br>def attractions_search_node(state: TravelState) -&gt; TravelState:<br>    print(&quot;Searching for attractions in:&quot;, state[&#39;messages&#39;][-1])<br>    if state.get(&quot;error&quot;):<br>        return state # Skip if there&#39;s an error<br>    try:<br>        # We assume the last message from extract_destination_node is the destination<br>        result = serper.run(f&quot;top tourist attractions in {state[&#39;messages&#39;][-1]}&quot;)<br>        state[&quot;messages&quot;].append(result)<br>    except Exception as e:<br>        state[&quot;error&quot;].append(f&quot;Attractions search error: {e}&quot;)<br>    return state</pre><h3>🌦️ Node 3: weather_search_node</h3><p>Similar to attractions, this node fetches the current weather for the extracted destination. This is another parallel tool call using the <strong>GoogleSerperAPIWrapper</strong>.</p><pre># Node 3: Search for weather<br>def weather_search_node(state: TravelState) -&gt; TravelState:<br>    print(&quot;Searching for weather in:&quot;, state[&#39;messages&#39;][-1])<br>    if state.get(&quot;error&quot;):<br>        return state # Skip if there&#39;s an error<br>    try:<br>        # We assume the last message from extract_destination_node is the destination<br>        result = serper.run(f&quot;current weather in {state[&#39;messages&#39;][-1]}&quot;)<br>        state[&quot;messages&quot;].append(result)<br>    except Exception as e:<br>        state[&quot;error&quot;].append(f&quot;Weather search error: {e}&quot;)<br>    return state</pre><p><strong>Important:</strong> Both attractions_search_node and weather_search_node Check for existing errors. This is a simple error-handling mechanism to prevent further processing if a critical error has already occurred upstream.</p><h3>🧾 Node 4: final_response_node</h3><p>Uses LLM to combine everything into a friendly travel summary.</p><pre>def final_response_node(state: TravelState) -&gt; TravelState:<br>    if state.get(&quot;error&quot;):<br>        return state<br><br>    summary_prompt = [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a friendly travel assistant. Create a helpful summary for a traveler.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;User asked: {state[&#39;messages&#39;][0]}&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;Destination: {state[&#39;messages&#39;][1]}\nAttractions: {state[&#39;messages&#39;][4]}\nWeather: {state[&#39;messages&#39;][5]}&quot;},<br>    ]<br>    try:<br>        result = call_groq_llm(summary_prompt).strip()<br>        state[&quot;messages&quot;].append(result)<br>    except Exception as e:<br>        state[&quot;error&quot;].append(f&quot;Final response generation error: {e}&quot;)<br>    return state</pre><p>The prompt for final_response_node is carefully crafted. Notice how we access state[&#39;messages&#39;][0] the original user query, state[&#39;messages&#39;][1] for the extracted destination, and then state[&#39;messages&#39;][4] and state[&#39;messages&#39;][5] for the attractions and the weather, respectively. This is because it operator.add appends to the list, and by the time it final_response_node runs, these results will be at those indices. This highlights the importance of understanding the state&#39;s evolution in LangGraph.</p><h3>🔀 Building the Graph: The Magic of Parallel Execution</h3><p>Now for the exciting part — defining our graph and enabling <strong>parallel execution</strong>!</p><pre># Define and compile the graph<br>graph_builder = StateGraph(TravelState)<br>graph_builder.add_node(&quot;extract_destination&quot;, extract_destination_node)<br>graph_builder.add_node(&quot;attractions_search&quot;, attractions_search_node)<br>graph_builder.add_node(&quot;weather_search&quot;, weather_search_node)<br>graph_builder.add_node(&quot;final_response&quot;, final_response_node)<br><br># Add edges (with parallel branching)<br>graph_builder.add_edge(START, &quot;extract_destination&quot;)<br>graph_builder.add_edge(&quot;extract_destination&quot;, &quot;attractions_search&quot;)<br>graph_builder.add_edge(&quot;extract_destination&quot;, &quot;weather_search&quot;) # This creates the parallel branch!<br>graph_builder.add_edge(&quot;attractions_search&quot;, &quot;final_response&quot;)<br>graph_builder.add_edge(&quot;weather_search&quot;, &quot;final_response&quot;) # Both branches converge here<br>graph_builder.add_edge(&quot;final_response&quot;, END)<br><br>graph = graph_builder.compile()</pre><p>The key lines for parallel processing are:</p><pre>graph_builder.add_edge(&quot;extract_destination&quot;, &quot;attractions_search&quot;)<br>graph_builder.add_edge(&quot;extract_destination&quot;, &quot;weather_search&quot;)</pre><p>By adding two distinct edges from &quot;extract_destination&quot; to &quot;attractions_search&quot; and &quot;weather_search&quot;, we instruct LangGraph to execute these two nodes <strong><em>in parallel</em></strong> after extract_destination completes. Both of these parallel branches then converge into the &quot;final_response&quot; node. LangGraph intelligently waits for all incoming edges to a node to complete before executing that node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*N-4PNchbSXbtx2ySXgbDjw.png" /><figcaption>Computing Nodes Parallely in Langgraph</figcaption></figure><h3>🧪 Running Our Travel Agent with Gradio</h3><p>To make our travel agent interactive, we’ll use <strong>Gradio</strong> to create a simple web interface.</p><pre># Function to invoke the graph<br>def gradio_chat(user_input):<br>    state = TravelState(<br>        messages=[user_input],<br>        error=[]<br>    )<br>    result = graph.invoke(state)<br><br>    if result[&quot;error&quot;]:<br>        return &quot;\n&quot;.join(result[&quot;error&quot;])<br>    print(&quot;Final messages:&quot;, result[&quot;messages&quot;][-1])<br>    return result[&quot;messages&quot;][-1]  # Return the final response<br><br># Sample run<br>gr.Interface(<br>    fn=gradio_chat,<br>    inputs=gr.Textbox(label=&quot;Where do you want to travel?&quot;),<br>    outputs=gr.Textbox(label=&quot;Travel Recommendation&quot;),<br>    title=&quot;🧳 Travel Agent&quot;,<br>    description=&quot;Ask about any destination, and get current weather, top attractions, and a helpful summary.&quot;<br>).launch()</pre><p>The gradio_chat function initializes the TravelState with the user&#39;s input and then calls graph.invoke(state). The final result, or any errors, are then displayed.</p><p>Save the complete code as a Python file (e.g., travel_agent.py) and run it:</p><pre>python travel_agent.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1_5weyHD31kajnbkkOscg.png" /><figcaption>Gradio UI for travel Assistant</figcaption></figure><h3>🧠 What We’ve Mastered</h3><p>In this second part of our LangGraph journey, we’ve moved beyond simple sequential workflows to build a more powerful and efficient travel agent. Key takeaways include:</p><ul><li><strong>Mastering </strong><strong>TypedDict for robust state management:</strong> How Annotated with operator.add helps in accumulating information from various nodes.</li><li><strong>Implementing parallel execution in LangGraph:</strong> Understanding how simply adding multiple edges from a single node enables concurrent processing.</li><li><strong>Orchestrating LLM interactions and external tool calls:</strong> Seamlessly integrating our Groq LLM and Google Serper API calls within the graph.</li><li><strong>Building a practical application with Gradio:</strong> Creating an interactive interface to demonstrate our LangGraph agent.</li></ul><h3>🚀 Try This!</h3><p>Want a challenge?</p><ul><li>Add a <strong>restaurant search</strong> as another parallel node.</li><li>Add <strong>conditional logic</strong>: If the user mentions a budget, include budget-friendly tips!</li></ul><p>This example showcases the true power of LangGraph in orchestrating complex, multi-step workflows, especially when some steps can run in parallel. As you build more sophisticated agents, the ability to design concurrent operations will become an invaluable tool in your arsenal.</p><p>Stay tuned for Part 3, where we’ll explore even more advanced LangGraph features, perhaps incorporating conditional routing or human-in-the-loop interactions! What kind of agent would you like to build next with LangGraph?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=089fa52a6e04" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/langgraph-tutorial-part-2-mastering-tools-and-parallel-execution-in-a-travel-agent-workflow-089fa52a6e04">LangGraph Tutorial Part 2: Mastering Tools and Parallel Execution in a Travel Agent Workflow</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangGraph Tutorial (Part 1): Build a Simple Agent Workflow in Python]]></title>
            <link>https://blog.gopenai.com/langgraph-tutorial-part-1-build-a-simple-agent-workflow-in-python-18a5c6b8e34a?source=rss-64cc8e986127------2</link>
            <guid isPermaLink="false">https://medium.com/p/18a5c6b8e34a</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Nishan Jain]]></dc:creator>
            <pubDate>Thu, 12 Jun 2025 18:55:11 GMT</pubDate>
            <atom:updated>2025-07-05T14:04:28.250Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In this article, you will learn about key LangGraph terminologies — including State, Nodes, and Edges — and see how to build a basic agent workflow in 5 simple steps. We will also explore some common real-world scenarios where LangGraph shines and why it is a powerful choice for building scalable, intelligent AI agents.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dJuDrIiocE8W5BlD" /><figcaption>Photo by <a href="https://unsplash.com/@julientromeur?utm_source=medium&amp;utm_medium=referral">julien Tromeur</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine you want to build a smart workflow where different steps, such as making decisions, calling other programs, or modifying data, work together smoothly and adapt to the current situation. What if you could design these workflows as simple diagrams called graphs, which are easy to understand, change, and fix?</p><p>LangGraph is a Python tool that helps you do exactly that. It turns complicated workflows into clear, connected steps called nodes. Suppose you’ve ever worked with simple step-by-step programs or pipelines. In that case, LangGraph will feel familiar, but it also lets you handle more complex situations like changing paths based on conditions, keeping track of information as you go, and reusing parts easily.</p><h3>Why LangGraph?</h3><p>Building intelligent agents and workflows with large language models (LLMs) often means juggling complex logic:</p><ul><li>How do you manage branching decisions that depend on previous results?</li><li>How do you keep track of shared data or “state” across multiple steps?</li><li>How can you build reusable, testable components without ending up with tangled, hard-to-follow code?</li></ul><p>Traditional approaches — scripting, chaining functions, or using orchestration tools — can quickly become brittle and hard to scale as your workflow grows.</p><p>LangGraph solves these challenges by letting you model your workflow as a graph:</p><ul><li>Nodes represent discrete steps or actions.</li><li>Edges define how you move from one step to another, including conditional branches.</li><li>A shared state flows through the graph, updated at each node, keeping your context consistent.</li></ul><p>This approach brings clarity, modularity, and flexibility to your agent workflows, making it easier to build, test, and evolve complex logic.</p><h3>Key LangGraph Terms</h3><h3>1. State</h3><p>A <strong>State</strong> is the central data store for a LangGraph workflow. It represents the current context or memory of the system. It moves from one node to another and can be updated at each step. Typically, this is implemented using Python’s TypedDict to enforce a schema for consistency.</p><h3>2. Node</h3><p>A <strong>Node</strong> is an individual processing unit in your graph. It is a Python function that receives the current state, performs an action (like calling an API or transforming input), and returns an updated state. Each node encapsulates a logical step in the workflow.</p><h3>3. Edge</h3><p>An <strong>Edge</strong> connects nodes and determines the next step. It can be a static connection (always goes from Node A to Node B) or dynamic (chooses the next node based on conditions in the state). This makes LangGraph powerful for conditional branching and flexible flows.</p><h3>Building a Simple Graph in 5 Steps</h3><p>Let’s build a simple LangGraph that checks if a number is greater than 5 and branches into a “win” or “lose” path accordingly. We’ll cover the five key steps.</p><h3>Step 1: Define the State Class</h3><pre>class MyState(TypedDict):<br>    number: int</pre><h3>Step 2: Start the Graph Builder</h3><pre>builder = StateGraph(MyState)</pre><h3>Step 3: Create Nodes</h3><pre>def check_number(state: MyState) -&gt; MyState:<br>    print(f&quot;Received number: {state[&#39;number&#39;]}&quot;)<br>    return state<br><br>def win(state: MyState) -&gt; MyState:<br>    print(&quot;Win!&quot;)<br>    return state<br><br>def lose(state: MyState) -&gt; MyState:<br>    print(&quot;Lose!&quot;)<br>    return state<br><br>builder.add_node(&quot;check_number&quot;, check_number)<br>builder.add_node(&quot;win&quot;, win)<br>builder.add_node(&quot;lose&quot;, lose)</pre><h3>Step 4: Create Edges</h3><pre>def decide_win_or_lose(state: MyState) -&gt; str:<br>    return &quot;win&quot; if state[&quot;number&quot;] &gt; 5 else &quot;lose&quot;<br><br>builder.set_entry_point(&quot;check_number&quot;)<br><br>builder.add_conditional_edges(<br>    &quot;check_number&quot;,<br>    decide_win_or_lose,<br>    {<br>        &quot;win&quot;: &quot;win&quot;,<br>        &quot;lose&quot;: &quot;lose&quot;,<br>    }<br>)<br><br>builder.add_edge(&quot;win&quot;, END)<br>builder.add_edge(&quot;lose&quot;, END)</pre><h3>Step 5: Compile the Graph</h3><pre>app = builder.compile()</pre><p>Run it:</p><pre>app.invoke({&quot;number&quot;: 8})  # Prints: Win!<br>app.invoke({&quot;number&quot;: 2})  # Prints: Lose!</pre><h3>Complete Code Example</h3><pre>from typing import TypedDict<br>from langgraph.graph import StateGraph, END<br><br># Define the structure of the shared state using a TypedDict.<br># This represents the data that flows through the graph.<br>class MyState(TypedDict):<br>    number: int  # The number we will evaluate to determine win or lose<br><br># Define a node that simply prints the received number and returns the state unchanged<br>def check_number(state: MyState) -&gt; MyState:<br>    print(f&quot;Received number: {state[&#39;number&#39;]}&quot;)<br>    return state<br><br># Define the &quot;win&quot; node — logic for when the number meets the win condition<br>def win(state: MyState) -&gt; MyState:<br>    print(&quot;Win!&quot;)<br>    return state<br><br># Define the &quot;lose&quot; node — logic for when the number fails the win condition<br>def lose(state: MyState) -&gt; MyState:<br>    print(&quot;Lose!&quot;)<br>    return state<br><br># Define the logic for deciding which path to take based on the number.<br># If the number is greater than 5, the flow should go to the &quot;win&quot; node; otherwise, to &quot;lose&quot;.<br>def decide_win_or_lose(state: MyState) -&gt; str:<br>    return &quot;win&quot; if state[&quot;number&quot;] &gt; 5 else &quot;lose&quot;<br><br># Initialize the graph builder with the state schema<br>builder = StateGraph(MyState)<br><br># Register the nodes in the graph<br>builder.add_node(&quot;check_number&quot;, check_number)  # First node that checks the number<br>builder.add_node(&quot;win&quot;, win)                    # Node for the &quot;win&quot; path<br>builder.add_node(&quot;lose&quot;, lose)                  # Node for the &quot;lose&quot; path<br><br># Set the entry point of the graph — this is where execution starts<br>builder.set_entry_point(&quot;check_number&quot;)<br><br># Add conditional branching from the &quot;check_number&quot; node<br># The decide_win_or_lose function determines whether to go to &quot;win&quot; or &quot;lose&quot;<br>builder.add_conditional_edges(<br>    &quot;check_number&quot;,        # Source node<br>    decide_win_or_lose,    # Function that returns &quot;win&quot; or &quot;lose&quot; based on state<br>    {<br>        &quot;win&quot;: &quot;win&quot;,       # If decision is &quot;win&quot;, go to win node<br>        &quot;lose&quot;: &quot;lose&quot;,     # If decision is &quot;lose&quot;, go to lose node<br>    }<br>)<br><br># Define the endpoints of the graph — both win and lose nodes terminate the execution<br>builder.add_edge(&quot;win&quot;, END)<br>builder.add_edge(&quot;lose&quot;, END)<br><br># Compile the graph into an executable app<br>app = builder.compile()<br><br># Run the graph with a test input where number &gt; 5 (should print &quot;Win!&quot;)<br>app.invoke({&quot;number&quot;: 8})<br><br># Run the graph with a test input where number &lt;= 5 (should print &quot;Lose!&quot;)<br>app.invoke({&quot;number&quot;: 2})</pre><p>Let us plot the graph also :-</p><pre>from IPython.display import Image, display<br>display(Image(app.get_graph().draw_mermaid_png()))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*pRq8eTmeuoCvgiKpZaansw.png" /></figure><h3>Real-World Use Cases for LangGraph</h3><p>LangGraph is ideal for building complex AI workflows such as:</p><ul><li>Chatbots that branch conversations based on user input</li><li>Multi-agent coordination pipelines</li><li>Decision-making systems with dynamic control flow</li><li>Modular, reusable agent components in large projects</li></ul><p>By structuring workflows as graphs, LangGraph makes your code more maintainable, scalable, and testable compared to traditional scripting.</p><h3>Recap</h3><p>In this first post of the LangGraph series, we:</p><ul><li>Defined a state</li><li>Built nodes that print messages based on a number</li><li>Used conditional edges to route control</li><li>Compiled and executed the graph</li></ul><p>LangGraph makes it easy to model complex agent workflows using modular Python code. In the next posts, we’ll explore:</p><ul><li>Branching logic with multiple conditions</li><li>Looping and recursion</li><li>Multi-agent orchestration</li><li>LLM tool calling and chaining with LangChain</li></ul><p>Stay tuned, and happy graphing!</p><h3><strong>References</strong></h3><ul><li><a href="https://academy.langchain.com/courses/intro-to-langgraph">Foundation: Introduction to LangGraph - Python</a></li><li><a href="https://github.com/langchain-ai/langgraph">GitHub - langchain-ai/langgraph: Build resilient agents.</a></li><li><a href="https://www.langchain.com/langgraph">LangGraph: Agent Orchestration Framework for Reliable AI Agents</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18a5c6b8e34a" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/langgraph-tutorial-part-1-build-a-simple-agent-workflow-in-python-18a5c6b8e34a">LangGraph Tutorial (Part 1): Build a Simple Agent Workflow in Python</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Are AI Agents? Fundamentals, Examples & Best Practices]]></title>
            <link>https://medium.com/@gr8nishan/what-are-ai-agents-fundamentals-examples-best-practices-6ce0c22a79fa?source=rss-64cc8e986127------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ce0c22a79fa</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Nishan Jain]]></dc:creator>
            <pubDate>Sun, 04 May 2025 15:10:26 GMT</pubDate>
            <atom:updated>2025-05-04T15:10:26.404Z</atom:updated>
            <content:encoded><![CDATA[<p>AI agents rapidly transform how we interact with technology, automate workflows, and tackle complex tasks. This comprehensive guide explores the foundations, design patterns, practical implementations, and challenges of AI agents, equipping you with the knowledge to build intelligent, responsive systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GV5QnI_dvNoww5YH" /><figcaption>Photo by <a href="https://unsplash.com/@ekrull?utm_source=medium&amp;utm_medium=referral">Eric Krull</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What are AI Agents</h3><p>AI Agents are programs where LLM output controls the workflow. These are programs that are capable of reasoning, planning, and interacting with their environment to achieve a user-defined behaviour. In practice, an AI Agent is a solution that involves ayor all of these</p><ol><li>Multiple LLM Call</li><li>Ability to use tools</li><li>An environment where LLMs interact</li><li>A planner to coordinate activities</li><li>Autonomy</li></ol><p>The difference between <strong>Workflows and AI agents </strong>is<strong> </strong>that<strong> </strong>Workflows are systems where LLMs and Tools are orchestrated through predefined code paths, whereas in AI agents, LLMs dynamically direct their usage, maintaining control over how they accomplish tasks.</p><h3>Key Components of an Agentic System</h3><p>AI agents operate through a continuous feedback loop of <strong>Thinking → Acting → Observing</strong>. This <strong>Thought → Action → Observation (TAO)</strong> cycle allows them to reason, execute tasks, and adapt dynamically based on feedback. Let’s break down how these components work together:</p><h3>1. 🧠 Thought</h3><p>The <strong>Large Language Model (LLM)</strong> powers the agent’s thinking process. It reasons over the task, plans the next step, and decides which tool to use.</p><ul><li><strong>Goal:</strong> “Find the latest news about OpenAI.”</li><li><strong>Memory:</strong> No recent search found.</li><li><strong>Planning:</strong> Determine that a web search is needed.</li><li><strong>Reasoning:</strong> The LLM generates a tool invocation such as search(&quot;OpenAI latest news&quot;).</li></ul><p><strong><em>Agent thinks:</em></strong><em> “To answer this, I’ll use the web search tool.”</em></p><h3>2. 🔧 Action</h3><p>Based on the plan, the agent <strong>executes an action</strong> by invoking the chosen tool with appropriate inputs.</p><ul><li><strong>Action taken:</strong> Calls the search() tool</li><li><strong>Execution:</strong> The tool runs a web search</li><li><strong>Output:</strong> &quot;OpenAI launches GPT-5 with multimodal features...&quot;</li></ul><p><strong><em>Agent acts:</em></strong><em> Calls the tool with a specific query to gather information.</em></p><h3>3. 👀 Observation</h3><p>After the tool completes its action, the agent <strong>receives and reflects</strong> on the outcome.</p><ul><li><strong>Observation:</strong> The tool returns relevant news</li><li><strong>Reflection:</strong> Does this result answer the original query?</li><li><strong>Next Step:</strong></li><li>✅ If yes: Summarize and respond</li><li>🔁 If no: Loop back to <strong>Thought</strong> with updated context</li></ul><p><strong><em>Agent observes:</em></strong><em> “Got the info. I can now summarize and respond.”</em></p><p>This loop continues until the agent determines that the goal is achieved or further steps are no longer necessary. The <strong>TAO cycle</strong> enables agents to carry out complex, multi-step tasks flexibly and autonomously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*w00uZ7tX1mnqj-W2w3hdzg.gif" /><figcaption><a href="https://huggingface.co/learn/agents-course/en/unit1/agent-steps-and-structure">https://huggingface.co/learn/agents-course/en/unit1/agent-steps-and-structure</a></figcaption></figure><h3>Types of Thoughts, Actions, and Observations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bSIAsVFpFGZNT_u6pJcznw.png" /></figure><h3>Agent Architectures and Techniques</h3><h3>1. 🧠 ReAct Agents</h3><ul><li><strong>Imagine this</strong>: You’re assembling IKEA furniture. You don’t read the entire manual at once — you look at one step, do it, then move on to the next. That’s what ReAct agents do.</li><li><strong>How it works</strong>: They don’t try to solve a big problem all at once. Instead, they <strong>think a little, take an action (like searching the web), learn something</strong>, then think again based on what they found.</li><li><strong>Why it matters</strong>: It makes the agent more accurate and smarter over time, especially for tricky tasks like research or decision-making.</li></ul><h3>2. 💻 CodeAct Agents</h3><ul><li><strong>Imagine this</strong>: You tell a junior developer to write a program. They write it, test it, see an error, fix it, and improve it until it works.</li><li><strong>How it works</strong>: CodeAct agents can <strong>write code, run it, spot problems, and fix them</strong> on their own — like a smart intern who never sleeps.</li><li><strong>Why it matters</strong>: These agents are great for automating coding tasks, data analysis, or creating small tools, especially for people who don’t know how to code.</li></ul><h3>3. 🛠️ Tool-Using Agents</h3><ul><li><strong>Imagine this</strong>: You ask your assistant, “What’s the weather like tomorrow?” and they open a weather app, read the forecast, and tell you what to wear.</li><li><strong>How it works</strong>: These agents are connected to <strong>tools</strong> like web search, calculators, calendars, APIs, and even databases. They use these tools to find or do things, just like a human would.</li><li><strong>Why it matters</strong>: Instead of guessing, the agent can check real data before responding, making it <strong>more reliable</strong> and useful.</li></ul><h3>4. 🪞 Self-Reflective Agents (They Learn from Their Mistakes)</h3><ul><li><strong>Imagine this</strong>: You cook a dish, taste it, and realize it needs more salt, so next time, you adjust the recipe.</li><li><strong>How it works</strong>: These agents do something, then <strong>stop to evaluate what they did</strong>, ask themselves “Did this work?” and make changes if needed.</li><li><strong>Why it matters</strong>: This makes agents better at complex tasks that need careful reasoning, like solving math problems, writing essays, or giving advice.</li></ul><h3>5. 👥 Multi-Agent Workflows</h3><ul><li><strong>Imagine this</strong>: You run a company with a writer, a designer, and a project manager. Each one does their job, and they collaborate to finish a project.</li><li><strong>How it works</strong>: Instead of one agent doing everything, we now have <strong>multiple agents</strong> that specialize — one might be good at research, another at writing, another at checking facts.</li><li><strong>Why it matters</strong>: This makes the system more efficient, more accurate, and faster, like building a startup made of mini-AIs!</li></ul><h3>6. 📚 AGENTIC-RAG</h3><ul><li><strong>Imagine this</strong>: You’re writing a report and you search Google, read a few sources, compare the info, throw out the junk, and summarize the truth.</li><li><strong>How it works</strong>: AGENTi-RAG is like that — but done by an agent. It doesn’t just fetch info like ChatGPT with the internet. It <strong>strategically decides what to search, where to search, and how to use that info to answer your question.</strong></li><li><strong>Why it matters</strong>: This creates <strong>more accurate, well-researched answers</strong>, especially for tasks like legal help, medical info, or enterprise use.</li></ul><h3>Building a Simple Math Agent with a Custom Calculation Tool Using OpenAI SDK</h3><p>The OpenAI Agents SDK allows you to define custom tools that your agent can utilize to perform specific tasks. In this case, we’ll create a calculate function that evaluates arithmetic expressions.</p><h4>1. Set Up Your Environment</h4><p>Ensure you have the OpenAI Agents SDK installed:</p><pre>pip install openai-agents</pre><h4>2. Define the Calculation Tool</h4><p>We’ll use the @function_tool decorator to define a tool that evaluates arithmetic expressions</p><pre>from agents import function_tool<br><br>@function_tool<br>def calculate(expression: str) -&gt; str:<br>    &quot;&quot;&quot;Evaluates a basic arithmetic expression.&quot;&quot;&quot;<br>    try:<br>        result = eval(expression)<br>        return str(result)<br>    except Exception as e:<br>        return f&quot;Error: {str(e)}&quot;</pre><h4>3. Create the Agent with the Tool</h4><p>Now, we’ll create an agent that uses the calculate tool to solve arithmetic problems.</p><pre>from agents import Agent, Runner<br><br># Define the agent<br>agent = Agent(<br>    name=&quot;MathAgent&quot;,<br>    instructions=&quot;Solve arithmetic expressions using the calculate tool.&quot;,<br>    tools=[calculate]<br>)</pre><h4>4. Run the Agent</h4><p>Finally, we’ll run the agent with a sample input.</p><pre>result = await Runner.run(agent, &quot;What is 10 * 2?&quot;)<br>print(result.final_output)</pre><h3>🧠 How It Works</h3><ul><li><strong>Agent Initialization:</strong> We define an agent named “MathAgent” with instructions to solve arithmetic expressions.</li><li><strong>Tool Integration:</strong> The calculate function is added as a tool, allowing the agent to evaluate expressions.</li><li><strong>Agent Execution:</strong> UsingRunner.run, we asynchronously run the agent with a sample input.</li></ul><h3>⚠️ Common Drawbacks of AI Agents and Mitigation Strategies</h3><h3>1. Compliance and Security Risks</h3><ul><li><strong>Problems</strong>: Privacy violations, unauthorized data access, and prompt injection.</li><li><strong>Fix</strong>: Use data anonymization, access controls, input sanitization, and regular audits.</li></ul><h3>2. Hallucinations and Inaccuracies</h3><ul><li><strong>Problems</strong>: AI generates false or misleading responses.</li><li><strong>Fix</strong>: Use RAG to ground responses, validate outputs with logic, or involve multiple agents to verify facts.</li></ul><h3>3. Overreliance and Lack of Oversight</h3><ul><li><strong>Problems</strong>: Users blindly trust AI decisions.</li><li><strong>Fix</strong>: Add human checks for important decisions, make agent behavior transparent, and educate users.</li></ul><h3>4. Scalability Challenges</h3><ul><li><strong>Problems</strong>: The System slows down or fails as the workload grows.</li><li><strong>Fix</strong>: Build modular systems, use cloud infrastructure, implement load balancing, and monitor performance.</li></ul><h3>✅ Best Practices for Building Secure and Compliant AI Agents</h3><ol><li><strong>Adopt a Privacy-by-Design Approach</strong><br> Integrate privacy considerations into every stage of AI agent development — from data collection to decision-making.</li><li><strong>Regular Training and Awareness</strong><br> Ensure that developers, operators, and users are trained on security protocols, ethical guidelines, and compliance standards.</li><li><strong>Continuous Monitoring and Evaluation</strong><br> Use monitoring tools to track agent behavior, detect anomalies, and evaluate performance in real time.</li><li><strong>Engage with Regulatory Bodies</strong><br> Stay informed and aligned with evolving legal requirements by maintaining dialogue with industry regulators and legal advisors.</li><li><strong>Implement Robust Incident Response Plans</strong><br> Prepare for security breaches or compliance violations with well-documented, regularly tested response protocols.</li><li><strong>Set Up Guardrails for Safe Behavior</strong><br> Define strict limits on what the AI agent can and cannot do — including restricting sensitive topics, preventing harmful outputs, and enforcing ethical constraints.<br> Guardrails help ensure that the agent behaves predictably and stays aligned with business and societal norms.</li></ol><h3>🧠 Wrapping Up: The Promise and Responsibility of AI Agents</h3><p>AI agents are not just a futuristic concept — they are rapidly becoming powerful tools for automating tasks, enhancing productivity, and transforming how we interact with technology. From simple task-based bots to complex multi-agent systems with memory, planning, and tool-use capabilities, agents are evolving fast and becoming more capable every day.</p><p>But with great power comes great responsibility.</p><p>As builders and users of AI agents, it’s crucial to go beyond the excitement and ensure we address key challenges: from accuracy and hallucinations to compliance, security, and responsible usage. By following best practices — including setting guardrails, involving humans in the loop, and designing with privacy and scalability in mind — we can unlock the full potential of AI agents while keeping safety, ethics, and trust at the core.</p><p>The agentic future is here. Let’s build it wisely.</p><h3>References</h3><p><a href="https://huggingface.co/learn/agents-course/">https://huggingface.co/learn/agents-course/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ce0c22a79fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Model Context Protocol (MCP)? A Beginner-Friendly Guide for AI Developers]]></title>
            <link>https://medium.com/@gr8nishan/what-is-model-context-protocol-mcp-a-beginner-friendly-guide-for-ai-developers-1badf2c4a4e3?source=rss-64cc8e986127------2</link>
            <guid isPermaLink="false">https://medium.com/p/1badf2c4a4e3</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nishan Jain]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 17:00:32 GMT</pubDate>
            <atom:updated>2025-04-26T17:00:32.439Z</atom:updated>
            <content:encoded><![CDATA[<p>Model Context Protocol (MCP) is a new standard that makes it easy for AI models to connect with apps, tools, and data sources securely. In this beginner-friendly guide, we’ll explain what MCP is, how it works, and how you can set up your own MCP server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d--41Hr3HChvioOI" /><figcaption>Photo by <a href="https://unsplash.com/@almoya?utm_source=medium&amp;utm_medium=referral">Alberto Moya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine you’re building a travel app that helps users book flights using an AI assistant.</p><p>At first, it sounds simple: you collect details like dates, destinations, and passenger info, and send them to the AI.<br> But here’s the real problem:</p><ul><li>The payment system expects one format.</li><li>The seat selection system expects another format.</li><li>The baggage service expects yet another format.</li></ul><p>Now, <strong>you’re not just sending information — you’re writing separate “translators” for every single tool. </strong>Every time you connect to a new service, you have to figure out <em>their</em> way of talking to the AI.<br> And if one of them changes their format later? You have to rewrite your code.</p><p><strong>It becomes a huge overhead:</strong></p><ul><li>More custom code to maintain.</li><li>More bugs to debug.</li><li>More delays every time you add a new tool.</li><li>Harder to scale your app across different services.</li></ul><p>Without a common language, <strong>every new connection becomes a mini project of its own.</strong><br>And for companies, this means higher costs, slower development, and a bigger chance of things breaking.</p><p><strong>This is why the Model Context Protocol (MCP) is so powerful and useful.</strong></p><p>MCP gives everyone — the AI model, the booking app, the payment tool, the baggage system — <strong>one simple, shared way</strong> to exchange context.<br>No more guessing. No more messy translations. Just clean, reliable connections. It standardizes how applications provide context to LLMs.</p><p>In short, MCP is an <strong>Integration Problem Solver.</strong></p><h3>Why MCP?</h3><p>MCP helps you build agents and complex workflows on top of LLMs. LLMs frequently need to integrate with data and tools, and MCP provides:</p><ul><li>A growing list of pre-built integrations that your LLM can directly plug into</li><li>The flexibility to switch between LLM providers and vendors</li><li>Best practices for securing your data within your infrastructure</li></ul><h3>Technical Overview of MCP</h3><p>At its core, MCP follows a client-server architecture where a host application can connect to multiple servers.</p><figure><img alt="Architecture diagram of a Model Context Protocol" src="https://cdn-images-1.medium.com/max/1024/1*hxjaNzsA0OXUtUo1C06tjg.png" /><figcaption><a href="https://modelcontextprotocol.io/docs/concepts/architecture">https://modelcontextprotocol.io/docs/concepts/architecture</a></figcaption></figure><p>In Model Context Protocol (MCP), there are <strong>three main parts</strong>:</p><p><strong>Host</strong></p><p>The main environment where everything runs, like a desktop app (Claude Desktop), browser, IDE, or other platforms. It <em>manages</em> both clients and servers, helping them find and talk to each other.</p><p>The <strong>Host</strong> acts like a <strong>bridge</strong>:</p><ul><li>It connects clients and servers inside the same app or environment.</li><li>It manages how communication happens.</li><li>It ensures security, discovery, and smooth messaging.</li></ul><p><strong>Client</strong></p><p>Usually, an AI application (like a chatbot or agent). It requests context: documents, tools, prompts, etc.</p><p><strong>Server</strong></p><p>An <strong>MCP server</strong> connects to a tool or data source (like a file app, database, or chat app) and exposes specific <strong>capabilities</strong> that an AI app can use, such as searching files, fetching mentions, or updating status.</p><p>MCP servers provide three kinds of things:</p><ul><li><strong>Prompts:</strong> Pre-made templates that users can trigger.</li><li><strong>Resources:</strong> Structured data like files, commits, or database rows.</li><li><strong>Tools:</strong> Actions the AI can perform, like calling APIs or modifying files.</li></ul><p>All the communication between client and server follows:</p><ul><li><strong>Protocol Layer:</strong> Message formats (requests, responses, notifications) using JSON-RPC 2.0.</li><li><strong>Transport Layer:</strong> defines how the messages travel, using things like stdio (standard input/output for local communication) or HTTP+SSE (for remote communication).</li></ul><h3>How to Create and Run a Sample MCP Server</h3><p><strong>Install the MCP Python SDK</strong></p><pre>brew install uv #install uv(this command works for Mac)<br><br># Create a new project<br>uv init mcp-server-demo<br>cd mcp-server-demo<br># Install mcp as dependency<br>uv add &quot;mcp[cli]&quot;</pre><p><strong>Create a Basic MCP Server</strong></p><p>Create a file called server.py:</p><pre>from mcp.server.fastmcp import FastMCP<br><br># Step 1: Create an MCP server<br>mcp = FastMCP(&quot;Demo Server&quot;)<br><br># Step 2: Add a simple tool<br>@mcp.tool()<br>def add(a: int, b: int) -&gt; int:<br>    &quot;&quot;&quot;Adds two numbers.&quot;&quot;&quot;<br>    return a + b<br><br># Step 3: Add a resource<br>@mcp.resource(&quot;greeting://{name}&quot;)<br>def get_greeting(name: str) -&gt; dict:<br>    &quot;&quot;&quot;Returns a greeting message.&quot;&quot;&quot;<br>    return {&quot;message&quot;: f&quot;Hello, {name}!&quot;}<br><br># Step 4: Run the server<br>if __name__ == &quot;__main__&quot;:<br>    mcp.serve()</pre><h3>Run the Server</h3><pre>mcp install server.py</pre><p>This will start your MCP server locally, exposing:</p><ul><li>A <strong>tool</strong> (add) that adds two numbers.</li><li>A <strong>resource</strong> (greeting) that generates a greeting message.</li></ul><p>When you run the server command, Claude Desktop should automatically detect and add your MCP server.<br> If you don’t see it appear immediately, try restarting the Claude Desktop app. You can check your Demo Server in the MCP server list.</p><figure><img alt="MCP server in Claude Desktop" src="https://cdn-images-1.medium.com/max/1024/1*fCFOK0fZibOVz2NgdF9LVg.png" /></figure><figure><img alt="MCP server in Claude Desktop" src="https://cdn-images-1.medium.com/max/1024/1*KgcnMKg7XghHKsDIKBTWVw.png" /></figure><p>When you run the MCP server command, Claude Desktop automatically updates its internal claude_desktop_config.json file by adding an entry like this:</p><pre>&quot;Demo Server&quot;: {<br>      &quot;command&quot;: &quot;uv&quot;,<br>      &quot;args&quot;: [<br>        &quot;run&quot;,<br>        &quot;--with&quot;,<br>        &quot;mcp[cli]&quot;,<br>        &quot;mcp&quot;,<br>        &quot;run&quot;,<br>        &quot;/Users/nishanjain/Desktop/mcp-server-demo/server.py&quot;<br>      ]<br>    }</pre><h3>Security Considerations for MCP</h3><p>While <strong>Model Context Protocol (MCP)</strong> makes connecting AI models to tools and data much easier, it also opens up new security risks.<br> Because AI models can now <em>use</em> tools (not just read data), securing these connections becomes very important.</p><p>Here are the major security risks you should be aware of:</p><ul><li><strong>Prompt Injection:</strong><br> Clever prompts can trick the AI into misusing tools (e.g., leaking sensitive files).</li><li><strong>Tool Description Poisoning:</strong><br> If a server describes its tools in a misleading way, the AI might perform unsafe actions without realizing it.</li><li><strong>Malicious or Compromised Servers:</strong><br> Not all MCP servers may be trustworthy. A rogue server can manipulate tool outputs or leak data.</li><li><strong>Lack of Authentication:</strong><br> Without verifying clients and servers properly, unauthorized tools could be connected, or private data could be exposed.</li><li><strong>Credential Leaks and Data Exfiltration:</strong><br> Sensitive information accessed by the AI (like API keys or database records) could accidentally be leaked through tool outputs.</li></ul><h3>Best Practices to Secure MCP Servers</h3><p>To build safer MCP-based systems, follow these principles:</p><ul><li><strong>Strong Authentication:</strong><br> Always verify the identity of MCP clients and servers before allowing access.</li><li><strong>Scoped Authorization:</strong><br> Limit what each tool or client is allowed to do — follow the principle of least privilege.</li><li><strong>Input Validation and Output Sanitization:</strong><br> Treat all inputs as potentially dangerous and strictly validate them; sanitize outputs before returning them to the AI.</li></ul><h3>Conclusion</h3><p>Model Context Protocol (MCP) makes it much easier to connect AI models with real-world tools, apps, and data — all through a clean, standardized approach.<br> Instead of building custom integrations for every app, developers can now expose capabilities quickly using MCP servers.</p><p>However, with this new power also comes responsibility. Since MCP allows models to <strong>read and take action</strong>, it’s important to think about security, like verifying servers, controlling tool permissions, and validating inputs, to prevent potential risks.</p><p>With good practices, MCP can unlock amazing possibilities safely and securely.</p><h3>References</h3><ul><li><a href="https://modelcontextprotocol.io/">What is the Model Context Protocol (MCP)? - Model Context Protocol</a></li><li><a href="https://zapier.com/blog/mcp/">What is MCP (Model Context Protocol)? | Zapier</a></li><li><a href="https://huggingface.co/blog/Kseniase/mcp">🦸🏻#14: What Is MCP, and Why Is Everyone - Suddenly!- Talking About It?</a></li><li><a href="https://github.com/modelcontextprotocol/python-sdk">GitHub - modelcontextprotocol/python-sdk: The official Python SDK for Model Context Protocol servers and clients</a></li></ul><p><a href="https://writer.com/engineering/mcp-security-considerations/#:~:text=In%20enterprise%20settings%2C%20compliance%20requirements,key%20aspect%20of%20MCP%20security">https://writer.com/engineering/mcp-security-considerations</a>/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1badf2c4a4e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>