<?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 Atul Kumar on Medium]]></title>
        <description><![CDATA[Stories by Atul Kumar on Medium]]></description>
        <link>https://medium.com/@atulkumar8?source=rss-8073e9223796------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G-98q4vpb_3ZJ8q9VqF9NA.png</url>
            <title>Stories by Atul Kumar on Medium</title>
            <link>https://medium.com/@atulkumar8?source=rss-8073e9223796------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 09:09:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@atulkumar8/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[ LangChain Series #5: Runnables Explained — Building Blocks of LCEL and AI Workflows]]></title>
            <link>https://atulkumar8.medium.com/langchain-series-5-runnables-explained-building-blocks-of-lcel-and-ai-workflows-bde67a3eb645?source=rss-8073e9223796------2</link>
            <guid isPermaLink="false">https://medium.com/p/bde67a3eb645</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[runnable-primitives]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[runnable]]></category>
            <dc:creator><![CDATA[Atul Kumar]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 11:58:44 GMT</pubDate>
            <atom:updated>2026-07-05T11:58:44.970Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtirW3pY7p3r8BYS5PCBSQ.png" /></figure><p>In the previous article, we explored <strong>Chains</strong> and learned how LangChain allows us to connect prompts, language models, and output parsers into complete AI workflows using the LangChain Expression Language (LCEL).</p><p>However, one important question remains:</p><blockquote><strong><em>What actually makes these workflows possible?</em></strong></blockquote><p>The answer is <strong>Runnables</strong>.</p><p>Every major LangChain component — including prompt templates, chat models, retrievers, output parsers, and even custom Python functions — is built around the <strong>Runnable interface</strong>.</p><p>This common interface allows different components to communicate seamlessly, making it possible to create reusable, composable, and scalable AI applications.</p><p>In this article, we’ll explore what Runnables are, why they exist, and how different Runnable primitives simplify complex AI workflows.</p><h3>What are Runnables?</h3><p>A <strong>Runnable</strong> is the fundamental execution unit in LangChain.</p><p>Think of it as a reusable block that:</p><ul><li>Accepts an input</li><li>Performs some processing</li><li>Produces an output</li></ul><p>Every Runnable follows the same execution pattern.</p><h3>Why Do We Need Runnables?</h3><p>Without Runnables, developers would need to manually manage:</p><ul><li>Passing outputs between components</li><li>Sequential execution</li><li>Parallel execution</li><li>Conditional routing</li><li>Streaming</li><li>Batch processing</li></ul><p>Every component would have a different API.</p><p>With Runnables, everything behaves the same way.</p><p>Whether it’s:</p><ul><li>PromptTemplate</li><li>ChatOpenAI</li><li>ChatHuggingFace</li><li>Output Parser</li><li>Retriever</li><li>Custom Python Function</li></ul><p>They all expose a common interface.</p><h3>Common Runnable Methods</h3><p>Every Runnable provides a common set of methods.</p><h4>invoke()</h4><p>Runs on a single input.</p><pre>model.invoke(&quot;Explain LangChain&quot;)</pre><h4>batch()</h4><p>Runs multiple inputs simultaneously.</p><pre>model.batch([<br>    &quot;Explain AI&quot;,<br>    &quot;Explain ML&quot;,<br>    &quot;Explain DL&quot;<br>])</pre><h4>stream()</h4><p>Streams tokens as they are generated.</p><pre>for chunk in model.stream(&quot;Tell me a joke&quot;):<br>    print(chunk)</pre><p>These common methods are one of the biggest advantages of the Runnable architecture.</p><h3>Types of Runnables</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*384xp8qg3F0sNJAGfJ3zNw.png" /><figcaption>Types Of Runnables</figcaption></figure><h4>Task Specific Runnables:</h4><p>These are core LangChain components that have been converted into runnables so they can be used in pipelines.</p><blockquote><strong><em>Purpose:</em></strong><em> </em>perform tasks specififc operations like LLM calls, prompting, reterival etc.</blockquote><p><strong>Example:</strong></p><pre>Chat OpenAI ----------&gt; Runs on LLM Model<br>Prompt Template ------&gt; Format Prompt dynamically<br>Reteriver ------------&gt; Reterivers relevant documents</pre><h4>Runnable Primitives:</h4><p>Fundamental building block for structuring execution logic in AI workflows.</p><blockquote><strong><em>Purpose: </em></strong>They help orchestrate execution by defining how different runnables interact.</blockquote><p><strong>Example:</strong></p><pre>Runnable Sequence, Runnable Parallel, Runnable Lambda, Runnable Map, <br>Runnable Branch, Runnable PassThrough</pre><p>Here we will discuss some of the runnables: — -</p><h3>RunnableSequence</h3><p>RunnableSequence executes multiple Runnables <strong>sequentially</strong>. Each Runnable receives the output produced by the previous Runnable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvOK-Ri6zxHX96OwCTc5fA.png" /><figcaption>WorkFlow Runnables Sequnce</figcaption></figure><pre>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint<br>from dotenv import load_dotenv<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnableSequence<br><br>load_dotenv()<br><br><br>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;Qwen/Qwen2.5-7B-Instruct&quot;,<br>    task=&quot;text-generation&quot;<br>)<br><br>model = ChatHuggingFace(llm=llm)<br><br>parser = StrOutputParser()<br><br><br>prompt1 = PromptTemplate(<br>    template=&#39;Write a joke about {topic}&#39;,<br>    input_variables=[&#39;topic&#39;]<br>)<br><br>prompt2 = PromptTemplate(<br>    template=&#39;Explain the following joke - {text}&#39;,<br>    input_variables=[&#39;text&#39;]<br>)<br><br>chain = RunnableSequence(prompt1, model, parser, prompt2, model, parser)<br><br>print(chain.invoke({&#39;topic&#39;:&#39;AI&#39;}))</pre><h3>💡 Note 1</h3><p>Only the <strong>first Runnable</strong> receives the user input.</p><pre>chain.invoke({<br>    &quot;topic&quot;: &quot;Artificial Intelligence&quot;<br>})</pre><p>After that, every Runnable automatically receives the output from the previous Runnable.</p><h3>💡 Note 2</h3><p>Notice how we never manually pass the joke to the second prompt.</p><p>LangChain automatically does that for us.</p><pre>Topic<br>   │<br>Prompt 1<br>   │<br>Model<br>   │<br>Parser<br>   │<br>Prompt </pre><h3>💡 Note 3</h3><p>RunnableSequence is equivalent to using the LCEL operator.</p><p>Instead of writing:</p><pre>chain = RunnableSequence(prompt1, model, parser, prompt2, model, parser)</pre><p>You can simply write:</p><pre>chain = ( prompt1 | model | parser | prompt2 | model | parser)</pre><p>The | operator internally creates a RunnableSequence.</p><h3>💡 Note 4:</h3><p>Use RunnableSequence Whenever one task <strong>depends on the output of a previous task</strong>.</p><p>Examples:</p><ul><li>Generate → Summarize</li><li>Translate → Explain</li><li>Retrieve → Answer</li><li>Generate Report → Summarize Report</li><li>Generate SQL → Execute SQL</li></ul><h3>RunnableParallel</h3><p>RunnableParallel executes multiple Runnables simultaneously.</p><p>Instead of waiting for one task to finish before starting another, all tasks receive the same input and run concurrently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZ7vfw-EzsnKNeH6bbLK5w.png" /><figcaption>WorkFlow Runnables Parllel</figcaption></figure><pre>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint<br>from dotenv import load_dotenv<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnableSequence, RunnableParallel<br><br>load_dotenv()<br><br><br>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;Qwen/Qwen2.5-7B-Instruct&quot;,<br>    task=&quot;text-generation&quot;<br>)<br><br>model = ChatHuggingFace(llm=llm)<br><br>prompt1 = PromptTemplate(<br>    template=&#39;Generate a tweet about {topic}&#39;,<br>    input_variables=[&#39;topic&#39;]<br>)<br><br>prompt2 = PromptTemplate(<br>    template=&#39;Generate a Linkedin post about {topic}&#39;,<br>    input_variables=[&#39;topic&#39;]<br>)<br><br><br><br>parser = StrOutputParser()<br><br>parallel_chain = RunnableParallel({<br>    &#39;tweet&#39;: RunnableSequence(prompt1, model, parser),<br>    &#39;linkedin&#39;: RunnableSequence(prompt2, model, parser)<br>})<br><br>result = parallel_chain.invoke({&#39;topic&#39;:&#39;AI&#39;})<br><br>print(result[&#39;tweet&#39;])<br>print(result[&#39;linkedin&#39;])</pre><h3>💡 Note 1</h3><p>Unlike RunnableSequence<strong>No Runnable depends on another Runnable</strong>. Both tasks execute independently.</p><h3>💡 Note 2</h3><p>RunnableParallel Returns a <strong>dictionary</strong>.</p><pre>result = parallel_chain.invoke({<br>    &quot;topic&quot;: &quot;AI&quot;<br>})<br>print(result)</pre><pre>Output:<br><br>{<br>    &quot;tweet&quot;: &quot;...&quot;,<br>    &quot;linkedin&quot;: &quot;...&quot;<br>}</pre><p>Each key corresponds to one Runnable.</p><h3>💡 Note 3</h3><p>Every Runnable receives the <strong>same input</strong>.</p><pre>{<br>    &quot;topic&quot;:&quot;AI&quot;<br>}<br></pre><p>LangChain automatically distributes the input to every Runnable inside RunnableParallel.</p><h3>💡 Note 4</h3><p>Each branch can be a complete pipeline in itself.</p><p>For example:</p><pre>RunnableSequence(<br>    prompt,<br>    model,<br>    parser<br>)</pre><p>This means you can build <strong>complex parallel workflows</strong>, not just single model calls.</p><h3>💡 Note 5</h3><p>You can even mix different Runnable types.</p><p>Example:</p><pre>RunnableParallel({ <br>    &quot;summary&quot;: summary_chain,<br>    &quot;translation&quot;: translation_chain,<br>    &quot;keywords&quot;: keyword_chain,<br>    &quot;sentiment&quot;: sentiment_chain<br>})</pre><p>All four chains will execute simultaneously.</p><h3>RunnablePassthrough</h3><p>Normally, every Runnable in LangChain <strong>transforms</strong> its input before passing it to the next step.</p><p>However, sometimes we want to <strong>keep the original output unchanged</strong> while also performing additional operations on it.</p><p>That’s exactly what <strong>RunnablePassthrough</strong> does.</p><p>It simply forwards the input <strong>without modifying it</strong>.</p><p>Think of it as a transparent pipe that lets the data pass through unchanged.</p><h4>Why Do We Need RunnablePassthrough?</h4><p>Imagine you’ve generated a joke using an LLM.</p><p>Now you want to:</p><ul><li>Display the original joke to the user ✅</li><li>Generate an explanation of the joke ✅</li></ul><p>Without RunnablePassthroughThe original joke would be replaced by the explanation.</p><p>RunnablePassthrough allows us to preserve the original joke while another Runnable processes it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-SIa6C8OO8dSl9TlKndvvw.png" /><figcaption>WorkFlow Runnables PassThrough</figcaption></figure><pre>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint<br>from dotenv import load_dotenv<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnableSequence, RunnablePassthrough, RunnableParallel<br><br>load_dotenv()<br><br><br>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;Qwen/Qwen2.5-7B-Instruct&quot;,<br>    task=&quot;text-generation&quot;<br>)<br><br>model = ChatHuggingFace(llm=llm)<br><br>prompt1 = PromptTemplate(<br>    template=&#39;Write a joke about {topic}&#39;,<br>    input_variables=[&#39;topic&#39;]<br>)<br><br><br>parser = StrOutputParser()<br><br>prompt2 = PromptTemplate(<br>    template=&#39;Explain the following joke - {text}&#39;,<br>    input_variables=[&#39;text&#39;]<br>)<br><br>joke_gen_chain = RunnableSequence(prompt1, model, parser)<br><br>parallel_chain = RunnableParallel({<br>    &#39;joke&#39;: RunnablePassthrough(),<br>    &#39;explanation&#39;: RunnableSequence(prompt2, model, parser)<br>})<br><br>final_chain = RunnableSequence(joke_gen_chain, parallel_chain)<br><br>print(final_chain.invoke({&#39;topic&#39;:&#39;cricket&#39;}))</pre><h3>💡 Note 1</h3><p>RunnablePassthrough Performs <strong>no processing</strong>. It simply returns the input exactly as it received it.</p><h3>💡 Note 2</h3><p>Without RunnablePassthroughYou would only receive the explanation. The original joke would not be available in the final output.</p><h3>💡 Note 3</h3><p>RunnablePassthrough is commonly used with RunnableParallel to preserve intermediate results while additional computations are performed.</p><h3>💡 Note 4</h3><p>You can think of it as creating a copy of the data for one branch while allowing another branch to transform it.</p><h3>RunnableLambda</h3><p>While LangChain provides built-in Runnables such as PromptTemplate, Chat Models, and Output Parsers, there are situations where you want to execute your own Python function as part of an LCEL pipeline.</p><p>However, a normal Python function cannot be directly connected to other LangChain components.</p><p>That’s where <strong>RunnableLambda</strong> comes in.</p><p>RunnableLambda wraps a regular Python function and converts it into a Runnable, allowing it to work seamlessly with other LangChain components.</p><h4>Why Do We Need RunnableLambda?</h4><p>Imagine you’ve generated a joke using an LLM.</p><p>Now you also want to calculate:</p><ul><li>Total number of words</li><li>Reading time</li><li>Character count</li><li>Sentiment score</li></ul><p>These are simple Python operations, not LLM tasks.</p><p>Instead of calling them separately, RunnableLambda allows you to integrate them directly into your LangChain workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3XErD3bklxX86tFDKYyAA.png" /><figcaption>WorkFlow Runnables Lambda</figcaption></figure><pre>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint<br>from dotenv import load_dotenv<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnableSequence, RunnableParallel, RunnablePassthrough, RunnableLambda<br><br>load_dotenv()<br><br><br>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;Qwen/Qwen2.5-7B-Instruct&quot;,<br>    task=&quot;text-generation&quot;<br>)<br><br>model = ChatHuggingFace(llm=llm)<br><br>def word_count(text):<br>    return len(text.split())<br><br>prompt = PromptTemplate(<br>    template=&#39;Write a joke about {topic}&#39;,<br>    input_variables=[&#39;topic&#39;]<br>)<br><br><br><br>parser = StrOutputParser()<br><br>joke_gen_chain = RunnableSequence(prompt, model, parser)<br><br>parallel_chain = RunnableParallel({<br>    &#39;joke&#39;: RunnablePassthrough(),<br>    &#39;word_count&#39;: RunnableLambda(word_count)<br>})<br><br>final_chain = RunnableSequence(joke_gen_chain, parallel_chain)<br><br>result = final_chain.invoke({&#39;topic&#39;:&#39;AI&#39;})<br><br>final_result = &quot;&quot;&quot;{} \n word count - {}&quot;&quot;&quot;.format(result[&#39;joke&#39;], result[&#39;word_count&#39;])<br><br>print(final_result)</pre><h3>💡 Note 1</h3><p>RunnableLambda is used to integrate <strong>custom Python logic</strong> into an LCEL pipeline.</p><h3>💡 Note 2</h3><p>Without RunnableLambda, you would need to execute the Python function <strong>outside</strong> the LangChain workflow. With RunnableLambda, everything stays inside one pipeline.</p><h3>💡 Note 3</h3><p>RunnableLambda can wrap <strong>any callable</strong>. It doesn’t have to be related to AI.</p><p>Example: RunnableLambda(my_function)</p><h3>💡 Note 4</h3><p>RunnableLambda is perfect for lightweight computations.</p><p>Examples include:</p><ul><li>Word count</li><li>Character count</li><li>Date formatting</li><li>JSON manipulation</li><li>Mathematical calculations</li><li>Data cleaning</li><li>Text preprocessing</li></ul><h3>💡 Note 5</h3><p>Avoid placing heavy LLM calls inside RunnableLambda. It is designed for <strong>custom business logic</strong>, not as a replacement for language models.</p><h3>RunnableBranch</h3><p>Not every AI workflow follows the same execution path. Sometimes, the next step depends on the output generated in the previous step.</p><p>For example:</p><ul><li>If a report is too long, summarize it.</li><li>If customer feedback is negative, escalate it to support.</li><li>If an email is spam, move it to the spam folder.</li><li>If the sentiment is positive, generate a thank-you response.</li></ul><p>In such scenarios, we need <strong>conditional execution</strong>.</p><p>That’s where <strong>RunnableBranch</strong> comes in.</p><p>RunnableBranch evaluates one or more conditions and executes <strong>only the Runnable whose condition evaluates to </strong><strong>True</strong>.</p><p>Unlike RunnableParallel, which executes <strong>all</strong> branches simultaneously, RunnableBranch executes <strong>only one branch</strong>.</p><h4>Why Do We Need RunnableBranch?</h4><p>Imagine you’re generating a report about a topic. Sometimes the report may be short. Sometimes it may contain hundreds of words.</p><p>Instead of summarizing every report, it would be better to summarize <strong>only when necessary</strong>.</p><p>This makes the workflow more intelligent and efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4HRmgUaqjMDvjiRYYqPgw.png" /><figcaption>WorkFlow Runnable Branch</figcaption></figure><pre>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint<br>from dotenv import load_dotenv<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnableSequence, RunnableBranch, RunnablePassthrough, RunnableLambda<br><br>load_dotenv()<br><br><br>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;Qwen/Qwen2.5-7B-Instruct&quot;,<br>    task=&quot;text-generation&quot;<br>)<br><br>model = ChatHuggingFace(llm=llm)<br><br>prompt1 = PromptTemplate(<br>    template=&#39;Write a detailed report on {topic}&#39;,<br>    input_variables=[&#39;topic&#39;]<br>)<br><br>prompt2 = PromptTemplate(<br>    template=&#39;Summarize the following text \n {text}&#39;,<br>    input_variables=[&#39;text&#39;]<br>)<br><br><br>parser = StrOutputParser()<br><br>report_gen_chain = prompt1 | model | parser<br><br>branch_chain = RunnableBranch(<br>    (lambda x: len(x.split())&gt;300, prompt2 | model | parser),<br>    RunnablePassthrough()<br>)<br><br>final_chain = RunnableSequence(report_gen_chain, branch_chain)<br><br>print(final_chain.invoke({&#39;topic&#39;:&#39;Russia vs Ukraine&#39;}))</pre><h3>💡 Note 1</h3><p>Unlike RunnableParallel, RunnableBranch Executes <strong>only one branch</strong>.</p><h3>💡 Note 2</h3><p>The first condition that evaluates to <strong>True</strong> is selected. Remaining branches are ignored.</p><h3>💡 Note 3</h3><p>The <strong>last Runnable</strong> acts as the <strong>default branch</strong>. <em>RunnablePassthrough()</em></p><p>It executes only if none of the previous conditions match.</p><h3>💡 Note 4</h3><p>You can define multiple conditions.</p><p>Example:</p><pre>RunnableBranch(<br>    (<br>        lambda x: x &gt; 1000,<br>        chain_1<br>    ),<br>    (<br>        lambda x: x &gt; 500,<br>        chain_2<br>    ),<br>    (<br>        lambda x: x &gt; 100,<br>        chain_3<br>    ),<br>    RunnablePassthrough()<br>)</pre><p>LangChain checks them <strong>from top to bottom</strong> and executes the <strong>first matching branch</strong>.</p><h3>💡 Note 5</h3><p>RunnableBranch is ideal when different inputs require different processing paths, allowing your AI workflow to make intelligent decisions instead of following a fixed sequence.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8CfqCv4PVNLxiA-GdkZVrg.png" /></figure><p>Runnables are the foundation of the <strong>LangChain Expression Language (LCEL)</strong> and play a crucial role in building modular, reusable, and scalable AI applications. Instead of treating prompts, models, output parsers, and custom functions as separate components, Runnables provide a common interface that allows them to work together seamlessly.</p><p>Understanding these Runnable primitives will make it much easier to design flexible AI workflows, whether you’re building chatbots, content generation tools, Retrieval-Augmented Generation (RAG) systems, or intelligent AI agents.</p><p>As you continue your LangChain journey, you’ll notice that almost every advanced feature — from Chains and Agents to Retrievers and LangGraph — is built on top of the Runnable interface. Mastering Runnables is therefore an essential step toward developing production-ready LLM applications.</p><p>In the next article, we’ll explore <strong>Document Loaders</strong> in LangChain and learn how to load data from PDFs, Word documents, HTML pages, Markdown files, CSVs, and other sources before preparing them for Retrieval-Augmented Generation (RAG) and other AI applications.</p><p><strong>Code Repository: </strong><a href="https://github.com/Atul245/LangChain-for-developers">https://github.com/Atul245/LangChain-for-developers</a></p><p>If you found this article helpful, consider:<br>⭐ Starring the repository<br>🍴 Forking the repository<br>👤 Following me for more content on LangChain, Generative AI, and AI Engineering</p><p><strong>Connect with me on LinkedIn:</strong> <a href="https://www.linkedin.com/in/atulkumar8/">https://www.linkedin.com/in/atulkumar8/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bde67a3eb645" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ LangChain Series #4: Chains Explained — Building AI Workflows with LCEL]]></title>
            <link>https://pub.towardsai.net/langchain-series-4-chains-explained-building-ai-workflows-with-lcel-1d4f125ea740?source=rss-8073e9223796------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d4f125ea740</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[writing-prompts]]></category>
            <category><![CDATA[runnable]]></category>
            <dc:creator><![CDATA[Atul Kumar]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 22:01:00 GMT</pubDate>
            <atom:updated>2026-07-03T22:01:00.972Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CKshhA-xruC_hxHgLsh5NQ.png" /></figure><p>This is the fourth article in my LangChain learning series. In the previous article, we explored prompts and learned how to communicate effectively with language models. Now it’s time to connect those components into complete AI workflows. In this article, we’ll explore Chains in LangChain and learn how to build Simple, Sequential, Parallel, and Conditional Chains using the LangChain Expression Language (LCEL). Through practical Python examples, you’ll understand how these chain patterns simplify the development of scalable, maintainable AI applications.</p><h3>1. Introduction</h3><p>In the previous article, we learned how to create prompts using PromptTemplate, ChatPromptTemplate, and Output Parsers.</p><p>But a real AI application doesn’t stop after sending a single prompt to an LLM.</p><p>Most applications involve multiple steps:</p><ul><li>Generate content</li><li>Summarize it</li><li>Translate it</li><li>Extract structured data</li><li>Route it based on the result</li></ul><p>This is exactly what <strong>Chains</strong> helps us accomplish.</p><p>A Chain connects multiple LangChain components into a single executable workflow.</p><h3>What is a Chain?</h3><p>A Chain is a sequence of connected components where the output of one component becomes the input of the next.</p><p>Instead of manually calling every component, LangChain lets us connect them using the <strong>LangChain Expression Language (LCEL)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3apNy_u4brBtLZxwBs3AKQ.png" /><figcaption>Simple Visulaization</figcaption></figure><h3>Why Use Chains?</h3><p>Without chains:</p><pre>prompt.invoke()<br>model.invoke()<br>parser.invoke()</pre><p>We manually call every component.</p><p>With chains:</p><pre>chain = prompt | model | parser</pre><p>One line executes the entire workflow.</p><p>Benefits:</p><ul><li>Cleaner code</li><li>Better readability</li><li>Easy debugging</li><li>Reusable pipelines</li><li>Seamless LangChain integration</li></ul><h3>LangChain Expression Language (LCEL)</h3><p>LCEL introduces the | operator.</p><p>Instead of writing nested function calls, we compose pipelines.</p><pre>chain = prompt | model | parser</pre><p>Each component automatically passes its output to the next component.</p><p>This makes AI workflows easier to build and maintain.</p><h3>Simple Chain</h3><p>A Simple Chain is the most basic LangChain workflow. It connects a prompt, an LLM, and an output parser into a single pipeline. The output of one component automatically becomes the input of the next.</p><pre>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint<br>from dotenv import load_dotenv<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br><br># Load environment variables<br>load_dotenv()<br><br># Prompt template<br>prompt = PromptTemplate(<br>    template=&quot;Generate 5 interesting facts about {topic}&quot;,<br>    input_variables=[&quot;topic&quot;]<br>)<br><br># Load Hugging Face model<br>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;Qwen/Qwen2.5-7B-Instruct&quot;,<br>    task=&quot;text-generation&quot;<br>)<br><br>model = ChatHuggingFace(llm=llm)<br><br># Convert AIMessage -&gt; String<br>parser = StrOutputParser()<br><br># Build the chain<br>chain = prompt | model | parser<br><br># Execute<br>result = chain.invoke({<br>    &quot;topic&quot;: &quot;cricket&quot;<br>})<br><br>print(result)<br><br># Visualize chain<br>chain.get_graph().print_ascii()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTCIkmV-quMrNBrTzkTjdw.png" /><figcaption>WorkFlow_SimpleChain</figcaption></figure><h3>Sequential Chain</h3><p>A <strong>Sequential Chain</strong> is a workflow where the <strong>output of one chain becomes the input of the next chain</strong>. Unlike a Simple Chain, which performs only one task, a Sequential Chain breaks a complex problem into multiple steps, with each step depending on the previous one.</p><p>For example, instead of asking an LLM to generate a report and summarize it in a single prompt, we can split the task into two stages:</p><ol><li>Generate a detailed report.</li><li>Summarize the generated report.</li></ol><p>This approach makes the workflow more modular, reusable, and easier to maintain.</p><pre>from dotenv import load_dotenv<br><br>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br><br>load_dotenv()<br><br># ---------------------------------------<br># Load Hugging Face Model<br># ---------------------------------------<br><br>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;meta-llama/Llama-3.1-8B-Instruct&quot;,<br>    task=&quot;text-generation&quot;<br>)<br><br>model = ChatHuggingFace(llm=llm)<br><br># ---------------------------------------<br># Output Parser<br># ---------------------------------------<br><br>parser = StrOutputParser()<br><br># ---------------------------------------<br># Prompt 1<br># Generate a Detailed Report<br># ---------------------------------------<br><br>report_prompt = PromptTemplate(<br>    template=&quot;&quot;&quot;<br>Write a detailed report about {topic}.<br><br>Include:<br>- Introduction<br>- Working Principle<br>- Advantages<br>- Applications<br>- Conclusion<br>&quot;&quot;&quot;,<br>    input_variables=[&quot;topic&quot;]<br>)<br><br># ---------------------------------------<br># Prompt 2<br># Summarize the Report<br># ---------------------------------------<br><br>summary_prompt = PromptTemplate(<br>    template=&quot;&quot;&quot;<br>Summarize the following report in 5 concise bullet points.<br><br>Report:<br>{report}<br>&quot;&quot;&quot;,<br>    input_variables=[&quot;report&quot;]<br>)<br><br># ---------------------------------------<br># Sequential Chain<br># ---------------------------------------<br><br>chain = (<br>    report_prompt<br>    | model<br>    | parser<br>    | {&quot;report&quot;: lambda x: x}<br>    | summary_prompt<br>    | model<br>    | parser<br>)<br><br># ---------------------------------------<br># Execute Chain<br># ---------------------------------------<br><br>result = chain.invoke({<br>    &quot;topic&quot;: &quot;Retrieval-Augmented Generation (RAG)&quot;<br>})<br><br>print(result)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HcQ41ykcT4OCWDxVK-H3dw.png" /><figcaption>WorkFlow_SequentialChain</figcaption></figure><h3>Parallel Chain</h3><p>A <strong>Parallel Chain</strong> is a workflow where <strong>multiple chains execute simultaneously on the same input</strong>, instead of running one after another.</p><p>Unlike a Sequential Chain, where each step waits for the previous one to finish, a Parallel Chain performs independent tasks at the same time. This reduces execution time and allows you to generate multiple outputs from the same input.</p><h4>When Should You Use a Parallel Chain?</h4><p>Use a Parallel Chain when multiple tasks:</p><ul><li>Use the <strong>same input</strong></li><li>Are <strong>independent</strong> of each other</li><li>Can execute simultaneously</li></ul><h4>Examples</h4><ul><li>Generate <strong>Notes</strong> and <strong>Quiz</strong> from a document</li><li>Translate text into multiple languages</li><li>Extract keywords and summarize simultaneously</li><li>Generate a blog title and social media caption together</li></ul><pre>from dotenv import load_dotenv<br>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnableParallel<br><br>load_dotenv()<br><br># -------------------------------<br># Load Hugging Face Model<br># -------------------------------<br><br>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;Qwen/Qwen2.5-7B-Instruct&quot;,<br>    task=&quot;text-generation&quot;<br>)<br><br>model = ChatHuggingFace(llm=llm)<br><br>parser = StrOutputParser()<br><br># -------------------------------<br># Prompt 1: Generate Notes<br># -------------------------------<br><br>notes_prompt = PromptTemplate(<br>    template=&quot;&quot;&quot;<br>Generate concise study notes about the following topic.<br><br>Topic:<br>{topic}<br>&quot;&quot;&quot;,<br>    input_variables=[&quot;topic&quot;]<br>)<br><br># -------------------------------<br># Prompt 2: Generate Quiz<br># -------------------------------<br><br>quiz_prompt = PromptTemplate(<br>    template=&quot;&quot;&quot;<br>Generate five multiple-choice questions about the following topic.<br><br>Topic:<br>{topic}<br>&quot;&quot;&quot;,<br>    input_variables=[&quot;topic&quot;]<br>)<br><br># -------------------------------<br># Create Parallel Chain<br># -------------------------------<br><br>parallel_chain = RunnableParallel({<br><br>    &quot;Notes&quot;:<br>        notes_prompt<br>        | model<br>        | parser,<br><br>    &quot;Quiz&quot;:<br>        quiz_prompt<br>        | model<br>        | parser<br>})<br><br># -------------------------------<br># Execute<br># -------------------------------<br><br>result = parallel_chain.invoke({<br>    &quot;topic&quot;: &quot;LangChain&quot;<br>})<br><br>print(&quot;========== NOTES ==========\n&quot;)<br>print(result[&quot;Notes&quot;])<br><br>print(&quot;\n========== QUIZ ==========\n&quot;)<br>print(result[&quot;Quiz&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MzFQnpEbTIPgglUREEbjTg.png" /><figcaption>WorkFlow_ParallelChain</figcaption></figure><h3>Conditional Chain</h3><p>A <strong>Conditional Chain</strong> is a workflow where the <strong>next chain is chosen based on a condition or decision</strong>.</p><p>Unlike a Sequential Chain, which always follows the same execution path, a Conditional Chain dynamically decides which branch to execute depending on the output of a previous step.</p><p>For example, imagine you’re building a customer support system. When a customer submits feedback, the application first analyzes the sentiment. If the sentiment is <strong>positive</strong>, it sends a thank-you response. If it’s <strong>negative</strong>, it forwards the complaint to customer support.</p><p>Instead of executing every chain, LangChain runs <strong>only the branch whose condition is satisfied</strong>.</p><h4>When Should You Use a Conditional Chain?</h4><p>Use a Conditional Chain whenever your application needs to <strong>make decisions</strong> before choosing the next action.</p><p>Examples include:</p><ul><li>Customer support routing</li><li>Email classification</li><li>Sentiment analysis</li><li>Fraud detection</li><li>Content moderation</li><li>AI decision-making systems</li></ul><pre>from dotenv import load_dotenv<br>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnableBranch<br><br>load_dotenv()<br><br># ------------------------------------<br># Load Model<br># ------------------------------------<br><br>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;Qwen/Qwen2.5-7B-Instruct&quot;,<br>    task=&quot;text-generation&quot;<br>)<br><br>model = ChatHuggingFace(llm=llm)<br><br>parser = StrOutputParser()<br><br># ------------------------------------<br># Prompt for Positive Feedback<br># ------------------------------------<br><br>positive_prompt = PromptTemplate(<br>    template=&quot;&quot;&quot;<br>Write a polite thank-you email for the following positive customer feedback.<br><br>Feedback:<br>{feedback}<br>&quot;&quot;&quot;,<br>    input_variables=[&quot;feedback&quot;]<br>)<br><br># ------------------------------------<br># Prompt for Negative Feedback<br># ------------------------------------<br><br>negative_prompt = PromptTemplate(<br>    template=&quot;&quot;&quot;<br>Write an apology email and inform the customer that the issue has been forwarded to customer support.<br><br>Feedback:<br>{feedback}<br>&quot;&quot;&quot;,<br>    input_variables=[&quot;feedback&quot;]<br>)<br><br># ------------------------------------<br># Create Conditional Chain<br># ------------------------------------<br><br>chain = RunnableBranch(<br><br>    (<br>        lambda x: &quot;good&quot; in x[&quot;feedback&quot;].lower()<br>               or &quot;excellent&quot; in x[&quot;feedback&quot;].lower()<br>               or &quot;amazing&quot; in x[&quot;feedback&quot;].lower(),<br><br>        positive_prompt | model | parser<br>    ),<br><br>    negative_prompt | model | parser<br>)<br><br># ------------------------------------<br># Execute<br># ------------------------------------<br><br>result = chain.invoke({<br>    &quot;feedback&quot;:<br>    &quot;The service was excellent and your support team was amazing.&quot;<br>})<br><br>print(result)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_odF1uYncnrmiIKE1tHqA.png" /><figcaption>WorkFlow_ConditionalChain</figcaption></figure><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lHNLhy2CsLI0HNcyYkRlHA.png" /></figure><p>Chains are the backbone of LangChain applications.</p><p>Instead of manually managing prompts, models, and parsers, LCEL allows us to connect components into reusable AI workflows using a simple pipeline syntax.</p><p>By understanding <strong>Simple</strong>, <strong>Sequential</strong>, <strong>Parallel</strong>, and <strong>Conditional</strong> Chains, you can build applications ranging from basic chatbots to sophisticated AI systems with multiple decision paths.</p><p>In the next article, we’ll explore <strong>Runnables in LangChain</strong> and learn how the Runnable interface powers LCEL through composition, parallel execution, branching, and reusable AI workflows.</p><p><strong>Code Repository: </strong><a href="https://github.com/Atul245/LangChain-for-developers">https://github.com/Atul245/LangChain-for-developers</a></p><p>If you found this article helpful, consider:<br>⭐ Starring the repository<br>🍴 Forking the repository<br>👤 Following me for more content on LangChain, Generative AI, and AI Engineering</p><p><strong>Connect with me on LinkedIn:</strong> <a href="https://www.linkedin.com/in/atulkumar8/">https://www.linkedin.com/in/atulkumar8/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d4f125ea740" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/langchain-series-4-chains-explained-building-ai-workflows-with-lcel-1d4f125ea740">🚀 LangChain Series #4: Chains Explained — Building AI Workflows with LCEL</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ LangChain Series #3: Prompts Explained — Prompt Templates, Chat Prompts, Dynamic Prompting…]]></title>
            <link>https://pub.towardsai.net/langchain-series-3-prompts-explained-prompt-templates-chat-prompts-dynamic-prompting-fd1411b3e986?source=rss-8073e9223796------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd1411b3e986</guid>
            <category><![CDATA[writing-prompts]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[prompt-template]]></category>
            <dc:creator><![CDATA[Atul Kumar]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 17:01:03 GMT</pubDate>
            <atom:updated>2026-06-12T17:01:03.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWBmXAVAKCp5MbMqR5OD2A.png" /></figure><h3>🚀 LangChain Series #3: Prompts Explained — Prompt Templates, Chat Prompts, Dynamic Prompting, Structured Outputs, and Output Parsers</h3><h4>Prompts are the foundation of every LLM application.</h4><p>No matter how powerful a model is, the quality of its output depends heavily on the instructions you provide.</p><p>In LangChain, prompts are much more than simple strings. They allow developers to dynamically generate instructions, manage conversations, inject chat history, and even enforce structured outputs.</p><h3>What are Prompts?</h3><p>A prompt is an instruction, question, or input given to a model to guide its response.</p><p>For example:</p><pre>Explain what a Transformer model is.<br>              or<br>Summarize the Attention Is All You Need paper.</pre><p>The model uses this prompt as context to generate an output.</p><h3>Static vs Dynamic Prompts:</h3><p>One of the first concepts to understand is the difference between static and dynamic prompting.</p><h4>Static Prompts:</h4><p>Static prompts use hardcoded instructions. Only the user input changes while the prompt structure remains the same.</p><p>Example:</p><pre>user_input = &quot;Attention Is All You Need&quot;</pre><pre>prompt = f&quot;Summarize this topic: {user_input}&quot;</pre><p>Generated prompt:</p><pre>Summarize this topic: Attention Is All You Need</pre><p><strong><em>Why is it called Static?</em></strong></p><p>Because the structure never changes.</p><pre>Summarize this topic:</pre><p>will always remain the same.</p><p><strong><em>Limitations of Static Prompts: </em></strong>While simple, static prompts have several drawbacks:</p><ul><li>Difficult to reuse</li><li>No validation</li><li>Harder to maintain</li><li>Doesn’t integrate well with LangChain workflows</li></ul><p>This is where Prompt Templates become useful.</p><h4>Dynamic Prompts:</h4><p>Dynamic prompts generate instructions at runtime. Instead of hardcoding values, placeholders are used and filled dynamically.</p><p>Example:</p><pre>Explain the research paper {paper}<br>in a {style} style<br>with a {length} explanation.</pre><p>Generated prompt:</p><pre>Explain the research paper Attention Is All You Need<br>in a Beginner-Friendly style<br>with a Long explanation.</pre><p>The prompt changes based on user selections.</p><h3>Prompt Templates</h3><p>LangChain provides PromptTemplate to create reusable dynamic prompts.</p><pre>from langchain_core.prompts import PromptTemplate<br><br>template = PromptTemplate(<br>    input_variables=[<br>        &quot;paper&quot;,<br>        &quot;style&quot;,<br>        &quot;length&quot;,<br>        &quot;style_instruction&quot;<br>    ],<br>    validate_template=True,<br>    template=&quot;&quot;&quot;<br>Please summarize the research paper titled &quot;{paper}&quot;<br><br>Explanation Style: {style}<br>Explanation Length: {length}<br><br>Style Guidelines:<br>{style_instruction}<br>&quot;&quot;&quot;<br>)</pre><h3>Why Use PromptTemplate Instead of f-Strings?</h3><h4>1. Reusability</h4><p>Create once and use many times.</p><h4>2. Variable Validation</h4><p>PromptTemplate checks missing variables.</p><pre>validate_template=True</pre><p>helps catch mistakes early.</p><h4>3. Better LangChain Integration</h4><p>Prompt Templates work seamlessly with:</p><ul><li>Chains</li><li>Agents</li><li>Memory</li><li>LCEL</li></ul><h4>4. Easier Maintenance</h4><p>Updating a single template updates your entire application.</p><h3>Generating Prompts Dynamically</h3><p>The template can be populated using:</p><pre>final_prompt = template.invoke({<br>    &quot;paper&quot;: paper_input,<br>    &quot;style&quot;: style_input,<br>    &quot;length&quot;: length_input,<br>    &quot;style_instruction&quot;: style_instructions[style_input]<br>})</pre><p>This creates a customized prompt based on user selections.</p><h3>Chat Models and Messages</h3><p>Traditional LLMs accept plain text:</p><pre>Input<br> ↓<br>String<br> ↓<br>Output</pre><p>Chat Models work differently.</p><p>They accept a sequence of messages.</p><pre>System Message<br>Human Message<br>AI Message</pre><p>and return an AI response.</p><h3>Message Types in LangChain</h3><p>LangChain provides three primary message types.</p><pre>from langchain_core.messages import (<br>    SystemMessage,<br>    HumanMessage,<br>    AIMessage<br>)</pre><h4>System Message:</h4><p>Defines the model’s behavior.</p><pre>SystemMessage(<br>    content=&quot;You are a concise AI assistant.&quot;<br>)</pre><h4>Human Message:</h4><p>Represents user input.</p><pre>HumanMessage(<br>    content=&quot;Tell me about LangChain.&quot;<br>)</pre><h4>AI Message:</h4><p>Stores previous responses.</p><pre>AIMessage(<br>    content=response.content<br>)</pre><h3>ChatPromptTemplate</h3><p>ChatPromptTemplate helps create dynamic prompts for chat models.</p><p>Example from our project:</p><pre>from langchain_core.prompts import ChatPromptTemplate<br><br>chat_template = ChatPromptTemplate([<br>    (&#39;system&#39;, &#39;You are a helpful {domain} expert&#39;),<br>    (&#39;human&#39;, &#39;Explain in simple terms what is {topic}&#39;)<br>])<br>prompt = chat_template.invoke({<br>    &#39;domain&#39;: &#39;machine learning&#39;,<br>    &#39;topic&#39;: &#39;diffusion models&#39;<br>})</pre><h3>Why Use ChatPromptTemplate?</h3><p>Instead of managing message objects manually, we can generate them dynamically.</p><p><strong><em>Benefits:</em></strong></p><ul><li>Cleaner code</li><li>Better readability</li><li>Easy variable substitution</li></ul><h3>Message Placeholders</h3><p>Real chatbots need conversation history.</p><p>LangChain solves this using: <strong><em>MessagesPlaceholder</em></strong></p><p>Example:</p><pre>from langchain_core.prompts import ChatPromptTemplate,MessagesPlaceholder<br><br><br>chat_template = ChatPromptTemplate([<br>    (&#39;system&#39;, &#39;You are a helpful customer support agent&#39;),<br>    MessagesPlaceholder(<br>        variable_name=&#39;chat_history&#39;<br>    ),<br>    (&#39;human&#39;, &#39;{query}&#39;)<br>])<br></pre><h4>Why Message Placeholders?</h4><p>They allow dynamic insertion of:</p><ul><li>Chat history</li><li>Previous interactions</li><li>Context memory</li></ul><p>without manually rebuilding prompts every time.</p><p><strong>This becomes extremely useful in:</strong> Chatbots, Agents, Customer Support Systems</p><h3>Structured Outputs and Output Parsers in LangChain</h3><p>So far, our models have returned plain text responses.</p><p>Example:</p><pre>The sentiment of the review is positive.</pre><p>While this is easy for humans to read, it is difficult for applications to process programmatically.</p><p>Imagine building:</p><ul><li>A Review Analyzer</li><li>A Resume Parser</li><li>A Customer Support Bot</li><li>A Data Extraction System</li></ul><p>Instead of plain text, we often need structured data like:</p><pre>{<br>    &quot;sentiment&quot;: &quot;positive&quot;,<br>    &quot;summary&quot;: &quot;The product received favorable feedback.&quot;<br>}</pre><p>This is where Structured Outputs and Output Parsers become useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-GYD_Z0EN53RyyZMCNprg.png" /></figure><h4>Structured Outputs:</h4><p>Structured Outputs allow LLMs to return data in predefined formats.</p><p>Instead of generating free-form text, we define a schema that the model should follow.</p><pre>    User Input<br>       ↓<br>      LLM<br>       ↓<br>Structured Response</pre><p>LangChain supports multiple ways to define these structures.</p><h4><strong><em>Which Schema Type Should You Use?</em></strong></h4><p><strong><em>TypedDict: </em></strong>Use TypedDict when:-</p><ul><li>You only need type hints.</li><li>You don’t need validation.</li><li>You trust the model output.</li></ul><p>Example:</p><pre>from typing import TypedDict<br><br>class Person(TypedDict):<br>    name: str<br>    age: int</pre><p><strong><em>Why TypedDict Has No Validation</em></strong></p><p>Consider:</p><pre>person = {<br>    &quot;name&quot;: &quot;Bob&quot;,<br>    &quot;age&quot;: &quot;25&quot;<br>}</pre><p>Even though age should be an integer, TypedDict will not raise an error.</p><p>This is because TypedDict provides type hints but does not validate data.</p><p><strong><em>Pydantic Models: </em></strong>Use Pydantic when:-</p><ul><li>Validation is required.</li><li>Default values are needed.</li><li>Automatic type conversion is useful.</li></ul><p>Example:</p><pre>from pydantic import BaseModel<br><br>class Student(BaseModel):<br>    name: str<br>    age: int = 18</pre><p><strong><em>Why Use Pydantic?</em></strong></p><ol><li><strong>Strict Schema Enforcement:</strong> Ensures the response follows a predefined structure.</li><li><strong>Type Safety:</strong> Automatically converts values into correct Python types.</li><li><strong>Validation:</strong> Detects missing or invalid fields.</li><li><strong>LangChain Integration:</strong> Works seamlessly with structured outputs and output parsers.</li></ol><p><strong><em>JSON Schema: </em></strong>Another popular approach is JSON Schema.</p><p>Example:</p><pre>{<br>  &quot;title&quot;: &quot;student&quot;,<br>  &quot;type&quot;: &quot;object&quot;,<br>  &quot;properties&quot;: {<br>    &quot;name&quot;: &quot;string&quot;,<br>    &quot;age&quot;: &quot;integer&quot;<br>  },<br>  &quot;required&quot;: [&quot;name&quot;]<br>}</pre><p><strong><em>When Should You Use JSON Schema?</em></strong></p><ul><li>You don’t want Python-specific dependencies.</li><li>You need a standard schema format.</li><li>You want interoperability across systems.</li></ul><h4>Output Parsers:</h4><p>What if the model cannot generate structured output natively?</p><p>This is where Output Parsers come in.</p><p>Output Parsers convert raw LLM responses into structured formats.</p><pre>LLM Output<br>     ↓<br>Output Parser<br>     ↓<br>Structured Data</pre><p>LangChain provides multiple output parsers.</p><p><strong><em>String Output Parser: </em></strong>The simplest parser. It converts model responses into plain strings.</p><p>Example:</p><pre>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint<br>from dotenv import load_dotenv<br>from langchain_core.prompts import PromptTemplate<br><br>load_dotenv()<br><br>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;google/gemma-2-2b-it&quot;,<br>    task=&quot;text-generation&quot;<br>)<br><br>model = ChatHuggingFace(llm=llm)<br><br># 1st prompt -&gt; detailed report<br>template1 = PromptTemplate(<br>    template=&#39;Write a detailed report on {topic}&#39;,<br>    input_variables=[&#39;topic&#39;]<br>)<br><br># 2nd prompt -&gt; summary<br>template2 = PromptTemplate(<br>    template=&#39;Write a 5 line summary on the following text. /n {text}&#39;,<br>    input_variables=[&#39;text&#39;]<br>)<br><br>prompt1 = template1.invoke({&#39;topic&#39;:&#39;black hole&#39;})<br><br>result = model.invoke(prompt1)<br><br>prompt2 = template2.invoke({&#39;text&#39;:result.content})<br><br>result1 = model.invoke(prompt2)<br><br>print(result1.content)</pre><p>This parser is commonly used inside chains.</p><p><strong><em>JSON Output Parser: </em></strong>JSON Output Parser converts responses into JSON objects.</p><p>Example:</p><pre>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint<br>from dotenv import load_dotenv<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import JsonOutputParser<br><br>load_dotenv()<br><br>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;Qwen/Qwen2.5-7B-Instruct&quot;,<br>    task=&quot;text-generation&quot;<br>)<br><br>model = ChatHuggingFace(llm=llm)<br><br>json_parser = JsonOutputParser()<br><br>template = PromptTemplate(<br>    template=&#39;Give me 5 facts about {topic} \n {format_instruction}&#39;,<br>    input_variables=[&#39;topic&#39;],<br>    partial_variables={&#39;format_instruction&#39;: json_parser.get_format_instructions()}<br>)<br><br># prompt = template.format()<br># model_output = model.invoke(prompt)<br># final_result = json_parser.parse(model_output.content)<br><br>chain = template | model | json_parser<br><br>chain_result = chain.invoke({&#39;topic&#39;: &#39;Origami&#39;})<br><br><br>print(chain_result)</pre><p>The parser automatically injects formatting instructions into the prompt.</p><p><strong><em>Why Use JsonOutputParser?</em></strong></p><ul><li>Converts output into JSON.</li><li>Easier programmatic access.</li><li>Works with models lacking native structured output support.</li></ul><p><strong><em>Structured Output Parser: </em></strong>StructuredOutputParser allows us to define required fields explicitly.</p><p>Example:</p><pre>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint<br>from dotenv import load_dotenv<br>from langchain_core.prompts import PromptTemplate<br>from langchain_classic.output_parsers.structured import StructuredOutputParser, ResponseSchema<br><br>load_dotenv()<br><br>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;Qwen/Qwen2.5-7B-Instruct&quot;,<br>    task=&quot;text-generation&quot;<br>)<br><br>model = ChatHuggingFace(llm=llm)<br><br>response_schema = [<br>    ResponseSchema(name=&quot;fact1&quot;, description=&quot;The first fact about the topic&quot;), <br>    ResponseSchema(name=&quot;fact2&quot;, description=&quot;The second fact about the topic&quot;),<br>    ResponseSchema(name=&quot;fact3&quot;, description=&quot;The third fact about the topic&quot;),<br>    ResponseSchema(name=&quot;fact4&quot;, description=&quot;The fourth fact about the topic&quot;),    <br>    ResponseSchema(name=&quot;fact5&quot;, description=&quot;The fifth fact about the topic&quot;)<br>]<br><br>parser = StructuredOutputParser.from_response_schemas(response_schema)<br><br>template = PromptTemplate(<br>    template=&#39;Give me 5 facts about {topic} \n {format_instruction}&#39;,<br>    input_variables=[&#39;topic&#39;],<br>    partial_variables={&#39;format_instruction&#39;: parser.get_format_instructions()}<br>)<br><br>chain = template | model | parser<br><br>chain_result = chain.invoke({&#39;topic&#39;: &#39;Origami&#39;})<br><br>print(chain_result)</pre><p><strong><em>Pydantic Output Parser: </em></strong>PydanticOutputParser combines structure and validation.</p><p>Example:</p><pre>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint<br>from dotenv import load_dotenv<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import PydanticOutputParser<br>from pydantic import BaseModel, Field<br><br>load_dotenv()<br><br>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;Qwen/Qwen2.5-7B-Instruct&quot;,<br>    task=&quot;text-generation&quot;<br>)<br><br>model = ChatHuggingFace(llm=llm)<br><br>class Person(BaseModel):<br><br>    name: str = Field(description=&#39;Name of the person&#39;)<br>    age: int = Field(gt=18, description=&#39;Age of the person&#39;)<br>    city: str = Field(description=&#39;Name of the city the person belongs to&#39;)<br><br>parser = PydanticOutputParser(pydantic_object=Person)<br><br>template = PromptTemplate(<br>    template=&#39;Generate the name, age and city of a fictional {place} person \n {format_instruction}&#39;,<br>    input_variables=[&#39;place&#39;],<br>    partial_variables={&#39;format_instruction&#39;:parser.get_format_instructions()}<br>)<br><br>chain = template | model | parser<br><br>final_result = chain.invoke({&#39;place&#39;:&#39;sri lankan&#39;})<br><br>print(final_result)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Girv3Ir2Vv4MWX926XVHPg.png" /></figure><h3>Conclusion</h3><p>Structured outputs make LLM responses predictable and easier to integrate into applications.</p><p>LangChain provides multiple approaches:</p><ul><li>TypedDict for lightweight schemas</li><li>Pydantic for validation and type safety</li><li>JSON Schema for standard schema definitions</li><li>Output Parsers for models that cannot generate structured outputs natively</li></ul><p>Understanding these tools is essential when building reliable AI applications that need structured, machine-readable data rather than free-form text.</p><p>In the next article, we’ll dive into Chains in LangChain and learn how to combine prompts, models, and output parsers into powerful end-to-end AI pipelines using LCEL.</p><p><strong>Code Repository: </strong><a href="https://github.com/Atul245/LangChain-for-developers">https://github.com/Atul245/LangChain-for-developers</a></p><p>If you found this article helpful, consider:<br>⭐ Starring the repository<br>🍴 Forking the repository<br>👤 Following me for more content on LangChain, Generative AI, and AI Engineering</p><p><strong>Connect with me on LinkedIn:</strong> <a href="https://www.linkedin.com/in/atulkumar8/">https://www.linkedin.com/in/atulkumar8/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd1411b3e986" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/langchain-series-3-prompts-explained-prompt-templates-chat-prompts-dynamic-prompting-fd1411b3e986">🚀 LangChain Series #3: Prompts Explained — Prompt Templates, Chat Prompts, Dynamic Prompting…</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ LangChain Series #2: Models Explained — LLMs, Chat Models, and Embeddings with Practical…]]></title>
            <link>https://pub.towardsai.net/langchain-series-2-models-explained-llms-chat-models-and-embeddings-with-practical-501e1715e5bb?source=rss-8073e9223796------2</link>
            <guid isPermaLink="false">https://medium.com/p/501e1715e5bb</guid>
            <category><![CDATA[embedding-model]]></category>
            <category><![CDATA[semantic-search]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[langchain-models]]></category>
            <dc:creator><![CDATA[Atul Kumar]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 04:48:34 GMT</pubDate>
            <atom:updated>2026-06-11T06:16:56.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pm45AHqS19P2cPhDmVgURQ.png" /></figure><h3>🚀 <strong>LangChain Series #2: Models Explained — LLMs, Chat Models, and Embeddings with Practical Examples</strong></h3><h3>Introduction</h3><p>When people start learning LangChain, they often think a “model” simply means ChatGPT or Gemini.</p><p>In reality, LangChain provides a unified interface for working with different types of AI models from multiple providers such as OpenAI, Google, Anthropic, and Hugging Face.</p><p>Without LangChain, switching between providers would require rewriting API calls and adapting to different response formats. LangChain solves this problem by offering a consistent abstraction layer over various models.</p><h3>What are Models in LangChain?</h3><p>Models are the core interfaces through which we interact with AI models. It is one of the core building blocks of a LangChain application.</p><p>Models take input, process it, and generate meaningful output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SyVBSm70zBGYWf8jkbmUmg.png" /><figcaption>Types Of Models</figcaption></figure><h4>Language Model:</h4><p>Language Models are AI systems designed to understand, generate, and process natural language.</p><p><strong><em>Examples: </em></strong>GPT-4, Claude, Gemini, and Llama</p><p><strong><em>These models are primarily used in:</em></strong> Chatbots, Content Generation, Coding Assistants, and AI Agents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_VD5pxX3PZ6NqEjkW3c2Q.png" /></figure><h4>Embedding Model:</h4><p>An embedding model converts text into a list of numbers( <em>a vector</em>) that captures the meaning of the text. This places <strong><em>semantically similar</em></strong> text close together in vector space</p><pre>&quot;Tokyo is the capital of Japan.&quot; -----&gt; [0.234, -0.129, 0.845, ...]<br>        (Text)                                (Vector</pre><p>These vectors allow machines to understand semantic similarity.</p><p><strong><em>Embedding Models are heavily used in: </em></strong>Semantic Search, Recommendation Systems, RAG Applications, Vector Databases</p><h3>Language Model</h3><h4>What are LLMs?</h4><p>General-purpose models that are used for raw text generation. They take a string (plain text) and return a string (plain text). These are old traditional models and are not used much now.</p><pre>Input:  &quot;What is the capital of Japan?&quot;<br>Output: Tokyo is the capital of Japan.</pre><ol><li><strong><em>Using OpenAI LLM: </em></strong>The following code uses OpenAI’s traditional completion model.</li></ol><p>Input:</p><pre>from langchain_openai import OpenAI<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>llm = OpenAI(model=&quot;gpt-3.5-turbo-instruct&quot;)<br><br>result = llm.invoke(&quot;What is the capital of Japan?&quot;)<br><br>print(result)</pre><p><strong><em>Explanation:</em></strong></p><ol><li>OpenAI() creates an LLM object.</li><li>invoke() sends a text prompt.</li><li>The model returns plain text.</li></ol><p>Output:</p><pre>Tokyo is the capital of Japan.</pre><h4>What are Chat Models?</h4><p>Language models that are specialized for conversational tasks. They take a sequence of messages as input and return chat messages as output <em>( as opposed to using plain text). </em>These are traditionally newer models and are used more in comparison to the LLMs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVTh-_C9pcY4TL5lci-QYw.png" /></figure><p><strong>Chat Models understand roles such as:</strong> System, User, Assistant</p><p><strong>This makes them ideal for: </strong>Chatbots, AI Assistants, Agents, Customer Support Systems</p><ol><li><strong><em>OpenAI Chat Model: </em></strong>The following example uses GPT-4 through LangChain.</li></ol><pre>from langchain_openai import ChatOpenAI<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>model = ChatOpenAI(<br>    model=&quot;gpt-4&quot;,<br>    temperature=0.9<br>)<br><br>result = model.invoke(<br>    &quot;What is the capital of Japan?&quot;<br>)<br><br>print(result.content)</pre><p><strong>Understanding Temperature: </strong>Temperature controls randomness.</p><pre>0.0 → Deterministic<br>0.5 → Balanced<br>1.0 → Creative</pre><p>Lower values produce predictable outputs while higher values generate more diverse responses.</p><p><strong><em>2. Google Gemini Chat Model: </em></strong>LangChain provides a unified interface for Google’s Gemini models.</p><pre>from langchain_google_genai import ChatGoogleGenerativeAI<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>model = ChatGoogleGenerativeAI(<br>    model=&#39;gemini-1.5-pro&#39;<br>)<br><br>result = model.invoke(<br>    &#39;What is the capital of Japan?&#39;<br>)<br><br>print(result.content)</pre><p><strong>Explanation</strong></p><p>Even though the provider changed from OpenAI to Google, the interface remains almost identical.</p><p><strong><em>This is one of the biggest advantages of LangChain.</em></strong></p><p><strong><em>3. Anthropic Claude Chat Model: </em></strong>Claude can be integrated in the same way.</p><pre>from langchain_anthropic import ChatAnthropic<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>model = ChatAnthropic(<br>    model=&#39;claude-3-5-sonnet-20241022&#39;<br>)<br><br>result = model.invoke(<br>    &#39;What is the capital of Japan?&#39;<br>)<br><br>print(result.content)</pre><p><em>Notice that only the provider changes while the LangChain workflow remains the same.</em></p><p>4. <strong><em>Hugging Face API Model</em></strong></p><pre>from huggingface_hub import InferenceClient<br>from dotenv import load_dotenv<br>import os<br><br>load_dotenv()<br><br>client = InferenceClient(<br>    api_key=os.getenv(&quot;HUGGINGFACEHUB_API_TOKEN&quot;)<br>)<br><br>result = client.chat_completion(<br>    model=&quot;meta-llama/Llama-3.1-8B-Instruct&quot;,<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: &quot;What is the capital of Japan?&quot;<br>        }<br>    ]<br>)<br><br>print(<br>    result.choices[0].message.content<br>)</pre><p><strong>Explanation</strong></p><p>Here we use Meta’s Llama model through Hugging Face’s hosted inference API.</p><p>5. <strong>Running Hugging Face Locally</strong></p><p>Instead of paying for APIs, you can run open-source models on your own machine</p><pre>from langchain_huggingface import (<br>    ChatHuggingFace,<br>    HuggingFacePipeline<br>)<br><br>llm = HuggingFacePipeline.from_model_id(<br>    model_id=&#39;TinyLlama/TinyLlama-1.1B-Chat-v1.0&#39;,<br>    task=&#39;text-generation&#39;,<br>    pipeline_kwargs={<br>        &quot;temperature&quot;: 0.5,<br>        &quot;max_new_tokens&quot;: 100<br>    }<br>)<br><br>model = ChatHuggingFace(llm=llm)<br><br>result = model.invoke(<br>    &quot;What is the capital of Japan?&quot;<br>)<br><br>print(result.content)</pre><p><strong><em>Why Run Locally?</em></strong></p><ul><li>Better privacy</li><li>No API cost</li><li>Full control over the model</li></ul><h3>Embedding Models</h3><p>While Language Models generate text, Embedding Models generate vectors.</p><ol><li><strong><em>OpenAI Embedding Model: </em></strong>Embedding a query using OpenAI.</li></ol><pre>from langchain_openai import OpenAIEmbeddings<br><br>embedding = OpenAIEmbeddings(<br>    model=&#39;text-embedding-3-large&#39;,<br>    dimensions=32<br>)<br><br>result = embedding.embed_query(<br>    &quot;Tokyo is the capital of Japan.&quot;<br>)<br><br>print(result)</pre><pre>output: [0.12, -0.43, 0.89, ...]</pre><p>2. <strong><em>Embedding Multiple Documents: </em></strong>We can embed multiple documents simultaneously</p><pre>from langchain_openai import OpenAIEmbeddings<br><br>embedding = OpenAIEmbeddings(<br>    model=&#39;text-embedding-3-large&#39;,<br>    dimensions=32<br>)<br><br>documents = [<br>    &quot;Tokyo is the capital of Japan.&quot;,<br>    &quot;Osaka is the second largest city in Japan.&quot;,<br>    &quot;Japan is famous for its technology and culture.&quot;<br>]<br><br>result = embedding.embed_documents(<br>    documents<br>)<br><br>print(result)</pre><p><strong><em>3. Hugging Face Embeddings: </em></strong>Open-source embeddings can also be generated locally.</p><pre>from langchain_huggingface import HuggingFaceEmbeddings<br><br>embedding = HuggingFaceEmbeddings(<br>    model_name=&#39;sentence-transformers/all-MiniLM-L6-v2&#39;<br>)<br><br>documents = [<br>    &quot;Tokyo is the capital of Japan.&quot;<br>    &quot;Osaka is the second-largest city in Japan.&quot;<br>    &quot;Japan is famous for its technology and culture.&quot;<br>]<br><br>result = embedding.embed_documents(documents)<br><br>print(result)</pre><h3>LLM vs Chat Model vs Embedding Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRZcIFhDaRlLRCd3xxAwKw.png" /></figure><h3>Real-World Example: Finding the Most Relevant Document Using Embeddings</h3><p>One of the most powerful applications of Embedding Models is <strong>Semantic Search</strong>.</p><p>Unlike traditional keyword search, semantic search focuses on the meaning of the text rather than exact word matches.</p><p>Let’s see this in action.</p><pre>from langchain_openai import OpenAIEmbeddings<br>from dotenv import load_dotenv<br>from sklearn.metrics.pairwise import cosine_similarity<br><br>load_dotenv()<br><br>embedding = OpenAIEmbeddings(<br>    model=&#39;text-embedding-3-large&#39;,<br>    dimensions=300<br>)<br><br>documents = [<br>    &quot;LangChain helps developers build applications powered by large language models.&quot;,<br>    &quot;RAG improves LLM responses by retrieving relevant information from external documents.&quot;,<br>    &quot;Vector databases store embeddings and enable semantic search.&quot;,<br>]<br><br>query = &quot;How does RAG help AI applications?&quot;<br><br>doc_embeddings = embedding.embed_documents(documents)<br>query_embedding = embedding.embed_query(query)<br><br>scores = cosine_similarity(<br>    [query_embedding],<br>    doc_embeddings<br>)[0]<br><br>index, score = sorted(<br>    list(enumerate(scores)),<br>    key=lambda x: x[1]<br>)[-1]<br><br>print(&quot;Query:&quot;, query)<br>print(&quot;Most Relevant Document:&quot;)<br>print(documents[index])<br>print(&quot;Similarity Score:&quot;, score)</pre><p><strong><em>Step 1: Convert Documents into Vectors: </em></strong>The embedding model transforms each document into a numerical representation called a vector.</p><pre>&quot;LangChain helps developers build applications powered by large language models.&quot;<br>      ↓<br>[0.42, -0.18, 0.67, ...]<br><br>&quot;RAG improves LLM responses by retrieving relevant information from external documents.&quot;<br>      ↓<br>[0.31, 0.54, -0.22, ...]<br><br>&quot;Vector databases store embeddings and enable semantic search.&quot;<br>      ↓<br>[0.76, -0.09, 0.44, ...]</pre><p>These vectors capture the semantic meaning of the text rather than just individual keywords.</p><p><strong><em>Step 2: Convert the Query into a Vector: </em></strong>Suppose the user asks:</p><pre>How does RAG help AI applications?</pre><p>The query is also converted into a vector using the same embedding model.</p><pre>Query<br>   ↓<br>Embedding Model<br>   ↓<br>Query Vector</pre><p>Now both the documents and the query exist in the same vector space, allowing us to compare their meanings mathematically.</p><p><strong><em>Step 3: Calculate Similarity: </em></strong>We use Cosine Similarity to measure how closely the query vector matches each document vector.</p><pre>scores = cosine_similarity(<br>    [query_embedding],<br>    doc_embeddings<br>)[0]</pre><p>A higher similarity score indicates that the document is more relevant to the query.</p><h4>Expected Output:</h4><pre>Query: How does RAG help AI applications?</pre><pre>Most Relevant Document:<br>RAG improves LLM responses by retrieving relevant information from external documents.</pre><pre>Similarity Score: 0.92</pre><p>The exact similarity score may vary depending on the embedding model used.</p><h3>Why This is Powerful</h3><p>Notice that the query is:</p><pre>How does RAG help AI applications?</pre><p>while the document contains:</p><pre>RAG improves LLM responses by retrieving relevant information from external documents.</pre><p>The query does not exactly match the document text, yet the embedding model understands that both are discussing the same concept: how RAG enhances the performance of language models by providing relevant external knowledge.</p><p>Traditional keyword-based search relies heavily on exact word matches, whereas embeddings capture the underlying meaning of the text. This allows semantic search systems to retrieve relevant information even when different wording is used.</p><p>This ability to understand meaning rather than exact keywords is what makes embeddings the foundation of modern RAG systems, AI search engines, recommendation systems, and intelligent knowledge retrieval applications.</p><h3>Conclusion</h3><p>Models are the foundation of every LangChain application.</p><ul><li><strong>LLMs</strong> generate text from text.</li><li><strong>Chat Models</strong> power conversational AI systems.</li><li><strong>Embedding Models</strong> convert text into vectors for semantic understanding.</li></ul><p>Together, these models enable the creation of chatbots, AI assistants, semantic search engines, and Retrieval-Augmented Generation (RAG) applications.</p><p>In the next article, we’ll explore <strong>Prompts in LangChain</strong> and learn how to control model behavior using Prompt Templates, Chat Prompts, and Dynamic Prompt Engineering.</p><p><strong>Code Repository: </strong><a href="https://github.com/Atul245/LangChain-for-developers">https://github.com/Atul245/LangChain-for-developers</a></p><p>If you found this article helpful, consider:<br>⭐ Starring the repository<br>🍴 Forking the repository<br>👤 Following me for more content on LangChain, Generative AI, and AI Engineering</p><p><strong>Connect with me on LinkedIn: </strong><a href="https://www.linkedin.com/in/atulkumar8/">https://www.linkedin.com/in/atulkumar8/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=501e1715e5bb" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/langchain-series-2-models-explained-llms-chat-models-and-embeddings-with-practical-501e1715e5bb">🚀 LangChain Series #2: Models Explained — LLMs, Chat Models, and Embeddings with Practical…</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Explained: Images, Containers, Dockerfiles, Docker Hub, and Docker Compose]]></title>
            <link>https://pub.towardsai.net/docker-explained-images-containers-dockerfiles-docker-hub-and-docker-compose-7a74fd2185be?source=rss-8073e9223796------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a74fd2185be</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <dc:creator><![CDATA[Atul Kumar]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 07:49:00 GMT</pubDate>
            <atom:updated>2026-06-09T05:15:05.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpV_LPo7GAcJbil2SADZHA.png" /></figure><h3>Why do we need Docker?</h3><p>Imagine you’re a chef who has created the perfect cake recipe. You want your friends to bake the same cake, but each friend has a different kitchen, equipment, and ingredients.</p><p>As a result, the cake may not turn out exactly the way you intended.</p><p>Software developers face a very similar problem. An application that works perfectly on one machine may fail on another because of differences in:</p><ul><li>Operating systems</li><li>Installed software</li><li>Dependency versions</li><li>Environment configurations</li></ul><p>This often leads to the infamous phrase:</p><blockquote><em>“It works on my machine.”</em></blockquote><p>Docker solves this problem by packaging an application together with all of its dependencies and configurations into a portable unit called a <strong>container</strong>.</p><p>Instead of sharing only the code, developers can share the entire environment required to run that code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j4G-Q8eyoHv_Mm86mG1TMA.png" /></figure><h4><strong>Understanding Docker Through an Apartment Analogy</strong></h4><p>To understand Docker better, let’s compare <strong>Virtual Machines</strong> and <strong>Containers</strong>.</p><p><strong><em>Virtual Machines: </em></strong>Think of Virtual Machines as separate apartments.</p><p>Each apartment has:</p><ul><li>Its own kitchen</li><li>Its own living room</li><li>Its own utilities</li></ul><p>This provides strong isolation but consumes a lot of resources.</p><p><strong><em>Containers: </em></strong>Containers are more like rooms in a shared apartment.</p><p>Each room is isolated, but everyone shares the same kitchen (the host operating system).</p><p>This makes containers:</p><ul><li>Lightweight</li><li>Faster to start</li><li>More resource-efficient</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_idezmR2hUfN3oCMHP_Djg.png" /></figure><h3><strong>What is a Docker Image?</strong></h3><p>An image is like a snapshot of a virtual operating system (OS) that contains all the necessary files and configurations to run an application.</p><p>It includes:</p><ul><li>Application code</li><li>Runtime</li><li>Libraries</li><li>Dependencies</li><li>Configuration files</li></ul><p>Think of an image as a recipe that can be used repeatedly to create identical containers.</p><p>💡<strong><em>Key Point: </em></strong>An image is <strong>read-only</strong> and serves as a <strong>Blueprint</strong>.</p><h3>What is a Docker Container?</h3><p>A container is a running instance of an image. It encapsulates the application and its dependencies, isolating it from the host system.</p><p>A container contains:</p><ul><li>The application</li><li>Required dependencies</li><li>Runtime environment</li></ul><p>Because containers are isolated, they behave consistently across different systems.</p><p>💡<strong><em>Key Point:</em></strong> Container is a <strong>Running Application</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmjSgwigHv-k-qMWzDrCkg.png" /></figure><h3>Common Docker Commands</h3><h4><strong><em>Starting and Stopping Containers</em></strong></h4><pre>docker start &lt;container_id&gt; <br>docker stop &lt;container_id&gt;</pre><p>These commands start and stop existing containers.</p><h4><strong><em>Accessing a Running Container</em></strong></h4><pre>docker exec -it &lt;container_id&gt; sh</pre><p><strong><em>Explanation:</em></strong></p><ul><li>exec executes a command inside a running container.</li><li>-i keeps STDIN open.</li><li>-t allocates a terminal.</li><li>sh Opens a shell session.</li></ul><p>This allows you to inspect and interact with the container.</p><h3>Understanding Port Mapping</h3><p>Port mapping allows accessing services running inside a Docker container from the host system.</p><p><strong><em>Example</em></strong></p><pre>docker run -it -p 8000:9000 my_web_app</pre><h4>What Happens?</h4><ul><li>Port <strong>8000</strong> on your machine</li><li>Maps to port <strong>9000</strong> inside the container</li></ul><p>When you visit:</p><pre>http://localhost:8000</pre><p>Docker forwards the request to port 9000 inside the container.</p><h3>Dockerfile: The Recipe for Your Container</h3><p>Picture a Dockerfile as a recipe for building your container. Each instruction adds a new “ingredient” or step to the recipe, creating a layer in the final image. These layers act like building blocks, with subsequent layers depending on the ones below.</p><h4>Docker Layers</h4><p>Each Dockerfile instruction creates a separate layer.</p><pre>Layer 5  Application Code<br>Layer 4  npm install<br>Layer 3  Copy Files<br>Layer 2  Install Node.js<br>Layer 1  Ubuntu Base Image</pre><p>These layers are stacked together to form the final image.</p><h4>Benefits</h4><ul><li>Faster builds</li><li>Efficient storage</li><li>Layer caching</li></ul><p>When one layer changes, Docker rebuilds only that layer and the layers above it.</p><h3>Dockerfile Example for a Node.js Application</h3><pre>#This instruction pulls the latest Ubuntu base image from the Docker Hub registry and creates a new layer.<br>FROM ubuntu:<br><br>RUN apt-get update:<br>RUN apt-get install -y curl:<br>RUN curl -sL https://deb.nodesource.com/setup_18.x | bash -:<br>RUN apt-get upgrade -y:<br><br>RUN apt-get install -y nodejs:<br><br>#Copies the files from the host machine to the current working directory inside the container, creating a new layer.<br>COPY package.json package.json:<br>COPY package-lock.json package-lock.json:<br>COPY main.js main.js:<br><br>#Installs the project dependencies defined in package.json inside the container.<br>RUN npm install:<br><br>#Specifies the command to run when the container starts.<br>ENTRYPOINT [ &quot;node&quot;, &quot;main.js&quot; ]:</pre><h3>Efficient Docker Caching</h3><p>Think of caching as remembering parts of your recipe you’ve already made. By placing stable instructions (like installing system packages) earlier in your Dockerfile, Docker can “remember” them and skip rebuilding those steps if they haven’t changed. This makes building your container image much faster, like not having to re-chop vegetables every time you cook the same dish.</p><p>Efficient caching in Docker involves structuring your Dockerfile to prioritize stable, less frequently changing instructions first. By doing so, Docker can reuse cached layers for unchanged instructions during subsequent builds, minimizing redundant execution and speeding up the build process.</p><h4>Ordering Instructions:</h4><ul><li>Prioritize less frequently changing instructions before those that change more often.</li><li>Commands like package installations (apt-get install) should come before copying application files or running npm install.</li><li>In the provided Dockerfile, instructions like FROM, RUN apt-get update, and RUN apt-get install are less likely to change frequently and benefit from caching.</li></ul><h4>Leveraging Cache:</h4><ul><li>Docker caches each instruction’s result as a separate layer.</li><li>Properly ordered instructions allow Docker to reuse cached layers for unchanged instructions, avoiding redundant execution during subsequent builds.</li></ul><p>Here’s an optimized version of the Dockerfile we made earlier:</p><pre>FROM ubuntu<br><br># Install system dependencies<br>RUN apt-get update \<br>    &amp;&amp; apt-get install -y \<br>       curl \<br>       nodejs \<br>    &amp;&amp; curl -sL https://deb.nodesource.com/setup_18.x | bash - \<br>    &amp;&amp; apt-get upgrade -y \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br># Copy application files<br>COPY package.json package-lock.json main.js /app/<br><br># Install application dependencies<br>RUN npm install<br><br># Set entry point<br>ENTRYPOINT [ &quot;node&quot;, &quot;/app/main.js&quot; ]</pre><h3>Publishing Image to Docker Hub</h3><p>Docker Hub is a cloud registry used to store and share Docker images.</p><h4>Creating a Repository on Docker Hub</h4><ol><li>Go to the <a href="https://hub.docker.com/">Docker Hub website</a> and log in to your account.</li><li>Click on the “Create Repository” button.</li><li>Choose a name for your repository and configure any other settings as needed.</li><li>Click on the “Create” button to create the repository.</li></ol><h4>Building an Image with Username/Reponame</h4><ol><li>First, ensure that you’re logged in to Docker Hub on your local machine using the docker login command:</li></ol><pre>docker login</pre><p>2. Then, navigate to the directory containing your Dockerfile and build your image using the docker build command:</p><pre>#Replace username with your Docker Hub username and reponame with the name of the repository<br> docker build -t username/reponame.</pre><h4>Pushing Image to Docker Hub</h4><ol><li>Once the image is built, you can push it to Docker Hub using the docker push command:</li></ol><pre># Again, replace username with your Docker Hub username and reponame with the name of the repository.<br> docker push username/reponame</pre><h4>Docker Compose</h4><p>Docker Compose simplifies the process of managing multiple Docker applications by allowing you to define all the necessary components in a single YAML file. This file typically includes information such as which Docker images to use for each service, the networking configuration between containers, and any volumes required for data persistence.</p><p><strong><em>For example,</em></strong> let’s say you have a web application that consists of a frontend service using a Node.js image and a backend service using a Python image. With Docker Compose, you can specify these services along with their dependencies, environment variables, and any other configurations in a docker-compose.yml file. Then, with a single command (docker-compose up), Docker Compose will create and start all the necessary containers based on your specifications.</p><h4>Example Docker Compose File</h4><pre>version: &#39;3&#39;</pre><pre>services:</pre><pre>  frontend:<br>    build: ./frontend</pre><pre>    ports:<br>      - &quot;3000:3000&quot;</pre><pre>    depends_on:<br>      - backend</pre><pre>    environment:<br>      - NODE_ENV=production<br>      - API_URL=http://backend:5000</pre><pre>  backend:<br>    image: postgres:latest</pre><pre>    ports:<br>      - &quot;5432:5432&quot;</pre><pre>    environment:<br>      - POSTGRES_USER=myuser<br>      - POSTGRES_PASSWORD=mypassword<br>      - POSTGRES_DB=mydatabase</pre><h4>Running Docker Compose</h4><p>Start all services:</p><pre>docker compose up</pre><p>Run in detached mode:</p><pre>docker compose up -d</pre><p>Stop all services:</p><pre>docker compose down</pre><p>With a single command, Docker Compose creates networks, starts containers, and manages communication between services.</p><h3>📝Key Takeaways</h3><p>✅ Docker eliminates the “<strong>works on my machine</strong>” problem.</p><p>✅ Images act as templates for containers.</p><p>✅ Containers provide isolated and consistent environments.</p><p>✅ Dockerfiles define how images are built.</p><p>✅ Layer caching makes image builds faster.</p><p>✅ Docker Hub allows sharing images worldwide.</p><p>✅ Docker Compose simplifies multi-container applications.</p><p>Docker has become one of the most important tools in modern software development. Whether you’re building web applications, deploying microservices, or working with AI projects, learning Docker is a skill that will save countless hours and make your applications more portable, scalable, and reliable.</p><p>If you found this article helpful, consider following me for more such content</p><p><strong>Connect with me on LinkedIn: </strong><a href="https://www.linkedin.com/in/atulkumar8/">https://www.linkedin.com/in/atulkumar8/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a74fd2185be" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/docker-explained-images-containers-dockerfiles-docker-hub-and-docker-compose-7a74fd2185be">Docker Explained: Images, Containers, Dockerfiles, Docker Hub, and Docker Compose</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transfer Learning: Why Train From Scratch When Someone Has Already Done the Hard Work?]]></title>
            <link>https://atulkumar8.medium.com/transfer-learning-why-train-from-scratch-when-someone-has-already-done-the-hard-work-f220cf60b686?source=rss-8073e9223796------2</link>
            <guid isPermaLink="false">https://medium.com/p/f220cf60b686</guid>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Atul Kumar]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 17:35:27 GMT</pubDate>
            <atom:updated>2026-06-06T17:35:27.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnJejNNlp4QVF1nRVOUvuw.png" /></figure><p>Imagine you want to build an image classification model that can distinguish between cats and dogs, or perhaps mobile phones and tablets.</p><p>The first thought that comes to mind is:</p><p>“Why not train my own neural network?”</p><p>Sounds simple, right?</p><p>Not quite.</p><h4>The Problem with Training Your Own Model</h4><ol><li><strong><em>Models Are Data Hungry:</em></strong></li></ol><p>Deep learning models require huge amounts of labeled data.</p><p>Suppose you want to classify:</p><ul><li>Cats vs Dogs</li><li>Cars vs Bikes</li><li>Mobile vs Tablet</li></ul><p>You might need thousands or even millions of images.</p><p>And the worst part?</p><p>Every image must be labeled manually.</p><p>This process is:</p><ul><li>Expensive</li><li>Time-consuming</li><li>Labor-intensive</li></ul><p><strong><em>2. Training takes a long time:</em></strong></p><p>Even if you have enough data, training a deep neural network from scratch can take:</p><ul><li>Hours</li><li>Days</li><li>Sometimes weeks</li></ul><p>Depending on the model size and available hardware.</p><p>So the question becomes:</p><p><strong><em>Do we really need to start from zero every time?</em></strong></p><h4>The Solution: Transfer Learning</h4><p>Instead of building everything from scratch, we can use a model that has already learned (<strong><em>PreTrained model</em></strong>) useful visual features from a massive dataset.</p><p>This approach is called <strong>Transfer Learning</strong>.</p><p>Transfer Learning is a machine learning technique where knowledge gained while solving one problem is reused to solve another related problem.</p><p>🤔Think of it like this:</p><p>You first learn how to ride a bicycle.</p><p>While learning, you acquire knowledge about:</p><ul><li>Balancing</li><li>Steering</li><li>Controlling motion</li></ul><p>Later, when you learn to ride a motorcycle, you don’t start from zero.</p><p>You transfer the knowledge you gained from cycling and build upon it.</p><p>Neural networks work in a very similar way.</p><p><strong>Why Pretrained Models Exist ?</strong></p><p>Researchers have already trained powerful models on enormous datasets such as ImageNet.</p><p>ImageNet contains millions of images belonging to thousands of categories.</p><p>During training, these models learn useful visual patterns that can be reused across many tasks.</p><p>Examples of pretrained models include:</p><ul><li>VGG16</li><li>VGG19</li><li>ResNet</li><li>Inception</li><li>MobileNet</li><li>EfficientNet</li></ul><p>Instead of training a new model, we can leverage the knowledge already stored in these networks.</p><p><strong>What Does a CNN Actually Learn?</strong></p><p>A Convolutional Neural Network (CNN) learns features in stages.</p><p><strong><em>Early Layers: </em></strong>The first few layers learn simple patterns such as:</p><ul><li>Edges</li><li>Lines</li><li>Corners</li><li>Basic textures</li></ul><p><strong><em>Middle Layers: </em></strong>As we move deeper into the network, the model learns:</p><ul><li>Shapes</li><li>Curves</li><li>Object parts</li></ul><p><strong><em>Deep Layers: </em></strong>The deepest layers learn complex concepts such as:</p><ul><li>Faces</li><li>Wheels</li><li>Animals</li><li>Entire objects</li></ul><p>Eventually, these learned features are converted into a feature vector that is passed to fully connected layers for classification.</p><p>This hierarchical learning is the reason transfer learning works so well.</p><h4>How does Transfer Learning work under the hood?</h4><p>Let’s take VGG16 as an example.</p><p>A typical CNN consists of:</p><ol><li>Convolutional Layers (Feature Extractor)</li><li>Fully Connected Layers (Classifier)</li></ol><p>The convolutional layers learn useful visual features, while the fully connected layers perform the final classification.</p><p>Instead of training everything again, we reuse the convolutional part and modify only the classification part.</p><p>This saves both time and computational resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZjVrG-_PFblFVhrzi3Rkfw.png" /></figure><h4>Why Do We Freeze Layers?</h4><p>One important concept in transfer learning is <strong>freezing layers</strong>.</p><p>When we freeze a layer:</p><ul><li>Its weights remain unchanged.</li><li>Backpropagation does not update those weights.</li><li>Previously learned knowledge is preserved.</li></ul><p><strong><em>Why is this useful?</em></strong></p><p>Because the knowledge learned during training is stored inside the network weights.</p><p>If we unnecessarily retrain all layers, we risk destroying that valuable knowledge.</p><p>In simple terms: <strong>Freeze the knowledge, train only what is necessary.</strong></p><h4><strong>Ways of doing Transfer Learning:</strong></h4><p>1. <strong><em>Feature Extraction: </em></strong>This is the simplest form of transfer learning.</p><p><strong>W<em>hat We Do</em></strong></p><ul><li>Keep the convolutional base frozen.</li><li>Remove the original classifier.</li><li>Add our own fully connected layers.</li><li>Train only the newly added layers.</li></ul><p><strong><em>When Should You Use It?</em></strong></p><p>When your dataset is similar to the dataset on which the pretrained model was trained.</p><p>For example:</p><ul><li>Cat vs Dog</li><li>Horse vs Cow</li><li>Apple vs Orange</li></ul><p>The pretrained model already knows how to detect useful visual features, so we simply reuse them.</p><p><strong><em>Advantages</em></strong></p><ul><li>Faster training</li><li>Less data required</li><li>Lower computational cost</li></ul><p><strong><em>2. Fine-Tuning: </em></strong>Sometimes our dataset is very different from the original dataset.</p><p>For example:</p><p>A pretrained model may have learned common everyday objects, but we want to classify:</p><ul><li>Medical X-rays</li><li>Satellite imagery</li><li>Industrial defects</li></ul><p>In such cases, feature extraction alone may not be enough.</p><p><strong><em>What We Do</em></strong></p><ul><li>Keep most convolutional layers frozen.</li><li>Unfreeze the last few convolutional layers.</li><li>Train them along with the new classifier.</li></ul><p>This allows the network to adapt its learned features to the new task.</p><p><strong><em>When Should You Use It?</em></strong></p><ul><li>Your dataset differs significantly from the original dataset.</li><li>You have a reasonable amount of training data.</li><li>You need higher accuracy.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXQQS4FmIRLoZ6getIoF6g.png" /></figure><p><strong>💡Key Insights: <em>“Why teach a model to recognize edges, shapes, and textures from scratch when millions of images have already taught another model those lessons?”</em></strong></p><p><strong><em>“The next time you’re about to train a model from scratch, ask yourself: Does my model really need to learn everything again, or can it build on what another model already knows?”</em></strong></p><p>If you found this article helpful, consider following me for more content on Machine Learning, Deep Learning, Computer Vision, and AI.</p><p><strong>Connect with me on LinkedIn: </strong><a href="https://www.linkedin.com/in/atulkumar8/">https://www.linkedin.com/in/atulkumar8/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f220cf60b686" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ LangChain Series #1: Understanding Models, Prompts, Chains, Memory, Indexes, and Agents]]></title>
            <link>https://pub.towardsai.net/langchain-explained-understanding-models-prompts-chains-memory-indexes-and-agents-bad18256bceb?source=rss-8073e9223796------2</link>
            <guid isPermaLink="false">https://medium.com/p/bad18256bceb</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Atul Kumar]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 06:07:41 GMT</pubDate>
            <atom:updated>2026-06-11T06:16:05.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1XqwcxRy04lZnW1_no8Avg.png" /></figure><p>Large Language Models (LLMs) such as GPT, Gemini, and Claude have made it easier than ever to build intelligent applications. However, developing production-ready AI systems often requires much more than simply calling an API.</p><p>This is where LangChain comes in</p><p>In this article, we’ll explore the core components of LangChain and understand why they are important.</p><h3>Introduction to Langchain :</h3><p>LangChain is an open-source framework that simplifies the development of applications powered by Large Language Models. It provides a collection of components that help developers connect LLMs with external data, memory, tools, and workflows.</p><h3>Benefits of LangChain:</h3><h4>1. Model Agnostic</h4><p>LangChain provides a unified interface for different LLM providers such as OpenAI, Gemini, and Claude. This makes it easier to switch models without rewriting large portions of code.</p><h4>2. Reusable Prompt Templates</h4><p>Instead of hardcoding prompts, developers can create dynamic and reusable prompt templates, improving maintainability and scalability.</p><h4>3. Simplified AI Workflows</h4><p>Chains allow multiple operations to be connected, making complex workflows easier to build and manage.</p><h4>4. Context-Aware Applications</h4><p>Memory enables applications to remember previous interactions, creating more natural and personalized user experiences.</p><h4>5. Efficient Knowledge Retrieval</h4><p>Indexes and vector databases allow applications to retrieve relevant information from large datasets, improving response accuracy.</p><h4>6. Autonomous Decision Making</h4><p>Agents can dynamically decide which tools or actions to use, enabling the development of intelligent AI systems.</p><h4>7. Faster Development</h4><p>LangChain provides ready-to-use components, reducing development time and allowing developers to focus on application logic rather than infrastructure.</p><h3>What Can We Build Using LangChain?</h3><h4>1. AI Chatbots</h4><p>Build conversational assistants capable of answering questions and maintaining context throughout a conversation.</p><h4>2. Customer Support Systems</h4><p>Create intelligent support agents that can access company knowledge bases and provide accurate responses.</p><h4>3. Retrieval-Augmented Generation (RAG) Applications</h4><p>Build systems that retrieve information from documents and use LLMs to generate context-aware answers.</p><h4>4. Document Question-Answering Systems</h4><p>Allow users to upload PDFs, research papers, or reports and ask questions about their contents.</p><h4>5. AI Agents</h4><p>Develop autonomous agents that can use tools, APIs, databases, and search engines to complete tasks.</p><h4>6. Personal AI Assistants</h4><p>Create assistants that manage schedules, answer questions, summarize information, and perform actions on behalf of users.</p><h4>7. Content Generation Tools</h4><p>Generate blogs, social media posts, emails, reports, and marketing content automatically.</p><h4>8. Recommendation Systems</h4><p>Use embeddings and semantic search to recommend products, articles, courses, or videos.</p><h4>9. Research Assistants</h4><p>Build AI systems that search, summarize, and analyze information from multiple sources.</p><h4>10. Multi-Agent Systems</h4><p>Create multiple specialized agents that collaborate to solve complex problems and automate workflows.</p><h3>Components Of LangChain:-</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0trxD6ZtKU3NoD0MQAiYw.png" /><figcaption>LangChain Components</figcaption></figure><h3>1. Models</h3><p>Models are the core interfaces through which we interact with AI models. It is one of the core building blocks of a LangChain application.</p><p><strong><em>Problem:</em></strong><br> Different AI providers, such as Anthropic, OpenAI, and Google Gemini, use different SDKs and API formats. If you write code directly for one provider, switching to another often requires changing significant parts of your code.</p><p><strong><em>Solution:</em></strong><br> LangChain’s Model abstraction provides a common interface for interacting with different LLMs. Instead of writing provider-specific code, we write against LangChain’s standardized API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9aBLd2jQcco_dQIAGWrBQA.png" /><figcaption>Models In LangChain</figcaption></figure><h3><strong>2. Prompts</strong></h3><p>A Prompt is the fundamental text input or instruction provided to a Large Language Model (LLM).</p><p><strong><em>Problem:</em></strong></p><p>LLMs perform best when prompts are well — structured properly. But hardcoding prompts every time can lead to:</p><ul><li>Repeated code</li><li>Inconsistent outputs</li><li>Difficult maintenance</li></ul><p><strong><em>Solution:</em></strong></p><p>The Prompt component in LangChain provides reusable and dynamic templates that insert user inputs into predefined instructions before sending them to the model.</p><p><strong><em>Prompting Techniques:</em></strong></p><ol><li><strong>Dynamic Prompting:</strong> Prompt changes based on user input or variable.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rqopJxNPUthMSc6ckod-eQ.png" /><figcaption>Example of Dynamic Prompting</figcaption></figure><p><strong>Use Case: </strong>Personalised responses, Chatbots, AI Applications.</p><p><strong>2. Role-Based Prompting: </strong>Assign a role or persona to the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMWrUNo1qe7Ndrt1T7hHyw.png" /><figcaption>Example of Role based Prompting</figcaption></figure><p><strong>Use Case: </strong>Expert Advice, Tutoring, Coding Assistance.</p><p>3. <strong>Few-Shot Prompting: </strong>It provides an example so the model learns the desired pattern and generates the desired output for a new input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fegUeeNXuCm3pqUkC5NASw.png" /><figcaption>Example of Few-Shot Prompting</figcaption></figure><p><strong>Use Case: </strong>Classification, Extraction, Formatting Tasks.</p><h3>3. Chains</h3><p>A Chain in LangChain connects individual components like prompts, LLMs, and output parsers into a seamless, automated workflow.</p><p>Let Say,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLifs-uIyL4hbBsJqyoMFw.png" /><figcaption>NLP Pipeline</figcaption></figure><p>We can represent the flow using pipelines; if not, we have to manually take the output of one and push it as input to another</p><p><strong><em>Problem:</em></strong></p><p>Many GenAI applications require multiple steps, not just a single Large Language Model (LLM) call. Without chains, we would have had to manually connect all the steps.</p><p><strong><em>Solution:</em></strong></p><p>Chains connect multiple LangChain components into a single workflow, in which the output of one component becomes the input to the next.</p><p><strong>Types of Chains:</strong></p><ol><li><em>Sequential Chain:</em> Steps executed one after another.</li><li><em>Parallel Chain: </em>Multiple tasks run simultaneously.</li><li><em>RAG Chain: </em>Most common in Industry( Chat with PDF, Company Knowledge base)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUmqYOk42dEro1-PRDayow.png" /><figcaption>Types Of Chains</figcaption></figure><h3><strong>4. Memory</strong></h3><p><strong><em>Problem:</em></strong></p><p>By Default, “<strong>LLM API calls are stateless</strong>” means they do not remember previous conversations.</p><p><strong><em>Solution:</em></strong></p><p>Memory stores conversation history or important information and automatically provides it to the LLM when needed.</p><p><strong>How Memory Works?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thgReTeBU5cNyMN0MvDPNw.png" /><figcaption>Working of Memory</figcaption></figure><p><strong>Types of Memory:</strong></p><ol><li><strong>Conversation Buffer Memory:</strong> Stores the entire conversation. Simple, but becomes large over time. <em>Best for short conversations and prototyping.</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tOD9dPn9LdJo8tyWo8SFNA.png" /><figcaption>Conversation Buffer Memory</figcaption></figure><p>2. C<strong>onversation Buffer Window Memory: </strong>Limit memory to only the last K messages. <em>Best for maintaining the recent conversational context while keeping the token usage predictable and preventing the context window from </em><strong><em>overflowing.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYxd1jnO3VIrh6dW0WAMUw.png" /></figure><p><strong>3. Summarize Based Memory: </strong>Periodically summarize older chat segments to keep a condensed memory footprint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HF4_zEcJCLB-3p7OHVYQTQ.png" /></figure><p><strong>4. Custom Memory: </strong>For advanced use cases, we can store specialized state, e.g., <em>the user&#39;s preference or key facts about them, in a common memory class</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPzZv5qIQjMBpsJ0-s4f-w.png" /></figure><p><strong><em>💡Key Takeaway: </em></strong><em>Choose the right memory type based on your use case, conversation length, and token limit to build an efficient and context-aware AI application.</em></p><h3><strong>5. Indexes</strong></h3><p>Indexes in LangChain connect your application to external Knowledge, such as PDFs, websites, or databases.</p><p><strong><em>Problem:</em></strong></p><p>LLM has a limited context window and can not directly search through thousands of documents, PDFs, websites, and databases efficiently.</p><p><strong><em>Solution:</em></strong></p><p>Indexes organize and structure data so that relevant information can be found quickly and provided to the LLM when needed.</p><p><strong>Components of Index:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrPsprwaAvrzJvMK3ZO7oQ.png" /><figcaption>Index Components</figcaption></figure><ol><li><strong>Data Loader: </strong>Load data from different sources.</li><li><strong>Text Splitter:</strong> Large documents are broken into smaller chunks.</li></ol><pre>10 pages pdf ---- convert to -----&gt;   10 chunks (1chunk/page)<br><br>Why?<br>  -LLM context Limit.<br>  -Better reterival accuracy.</pre><p>3. <strong>Embedding Model: </strong>Convert text into vectors <em>(numerical representation), and </em>these vectors capture the semantic meaning of that text.</p><pre>&quot;MACHINE LEARNING&quot; ----&gt;  [0.23,0.81,0.45,...]<br>  ( TEXT)                    (Vector)</pre><p><strong>Retrieval Flow:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obH3uqgbvvB9ANd6pBtwgg.png" /><figcaption>Retrieval flow</figcaption></figure><h3><strong>6. Agents</strong></h3><p><strong><em>Problem:</em></strong></p><p>A normal LLM or chain follows a fixed workflow</p><pre>Example: <br><br>User Question ---&gt; Prompt ---&gt; LLM ---&gt; Answer<br><br>But What if  AI needs to --<br>1. Search the web<br>2. Query a Database<br>3. Call an API<br><br>We do not always know beforehand which tool will be needed</pre><p><strong><em>Solution:</em></strong></p><p>An Agent is an AI system that has the capabilities of reasoning, deciding, and choosing the appropriate tool to complete a task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NFbGZIfJQs1ebm0cjM95g.png" /><figcaption>Chain VS Agent</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1PPq_WfK-g8ktKOITw-T7w.png" /></figure><h3><strong>Final Thoughts:</strong></h3><p>LangChain has become one of the most popular frameworks in the Generative AI ecosystem because it simplifies the process of building intelligent applications. By providing components such as Models, Prompts, Chains, Memory, Indexes, and Agents, it enables developers to move beyond simple chatbot interactions and create powerful real-world AI solutions.</p><p>Understanding these core components is the first step toward building advanced applications such as AI assistants, RAG systems, and autonomous agents. As the AI landscape continues to evolve, frameworks like LangChain will play an important role in helping developers create scalable and production-ready AI systems.</p><p>Thank you for reading! If you found this article helpful, consider sharing it and following me on Medium for more content on Generative AI and Machine Learning.</p><p><strong>Code Repository: </strong><a href="https://github.com/Atul245/LangChain-for-developers">https://github.com/Atul245/LangChain-for-developers</a></p><p>If you found this article helpful, consider:<br>⭐ Starring the repository<br>🍴 Forking the repository<br>👤 Following me for more content on LangChain, Generative AI, and AI Engineering</p><p><strong>Connect with me on LinkedIn: </strong><a href="https://www.linkedin.com/in/atulkumar8/">https://www.linkedin.com/in/atulkumar8/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bad18256bceb" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/langchain-explained-understanding-models-prompts-chains-memory-indexes-and-agents-bad18256bceb">🚀 LangChain Series #1: Understanding Models, Prompts, Chains, Memory, Indexes, and Agents</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>