<?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 Vamshi Krishna Ginna on Medium]]></title>
        <description><![CDATA[Stories by Vamshi Krishna Ginna on Medium]]></description>
        <link>https://medium.com/@vamshiginna1606?source=rss-5482f97f8048------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7euNl7jAWVfj0nVRe9aAAg.png</url>
            <title>Stories by Vamshi Krishna Ginna on Medium</title>
            <link>https://medium.com/@vamshiginna1606?source=rss-5482f97f8048------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 14:49:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vamshiginna1606/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[LangGraph 101: Build Your First Agentic AI Workflow (Step-by-Step for Beginners)]]></title>
            <link>https://medium.com/@vamshiginna1606/langgraph-101-build-your-first-agentic-ai-workflow-step-by-step-for-beginners-b9a1a0cec59a?source=rss-5482f97f8048------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9a1a0cec59a</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Vamshi Krishna Ginna]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 06:46:15 GMT</pubDate>
            <atom:updated>2025-06-08T06:46:15.001Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Why LangGraph Is the Future of Agentic AI</h3><p>Have you ever felt stuck building GenAI apps with LangChain because everything flows in a straight line — input → LLM → output?<br> It works for toy examples. But what if your app needs to:</p><ul><li>Make decisions mid-flow?</li><li>Use tools conditionally based on user intent?</li><li>Loop back, retry, or remember previous steps?</li></ul><blockquote>That’s where <strong>LangGraph</strong> comes in.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*qSMgg3rxDpSevHHtrgsWMw.png" /></figure><p><em>If you’re interested, here’s a fascinating blog that explores the evolution of AI agents — you might find it worth a read. </em><a href="https://medium.com/@vamshiginna1606/from-counting-sheep-to-autonomous-agents-how-stats-ml-and-gpt-led-us-to-autonomous-ai-agents-238d99ed89e3"><em>From Counting Sheep to Autonomous Agents</em></a></p><h4>1.1. What is LangGraph?</h4><p>Think of LangGraph as <strong>your AI workflow’s control center</strong> — a graph-based framework that helps you build smarter, stateful agents with memory, branching, and loops.</p><p>🔧 Instead of chaining steps, you create a <strong>graph</strong> where:</p><ul><li>Each <strong>node</strong> is a task (e.g., ask a question, call a tool, summarize a doc)</li><li>Each <strong>edge</strong> decides what happens next</li><li>The <strong>state</strong> travels through this graph and evolves at every step</li><li><strong>Loops and branches </strong>are dynamic decision-making paths</li></ul><blockquote>LangGraph makes your agents not just react — but think, adapt, and evolve.</blockquote><p>If you’re someone who’s already built simple GenAI apps using LangChain and OpenAI, this blog is your next step toward building <strong>agentic AI workflows</strong> that actually feel smart.</p><p>Whether you want to build:</p><ul><li>A customer support bot that looks things up and responds based on user mood</li><li>An AI tutor that adapts its teaching style</li><li>Or a research assistant that can branch into different tasks</li></ul><p>LangGraph is the tool you’ve been waiting for.</p><h4>1.2. New to LangChain or GenAI Apps?</h4><p>Before diving into LangGraph, I highly recommend checking out these beginner-friendly crash courses:</p><ul><li>🧠 <a href="https://medium.com/@vamshiginna1606/langchain-crash-course-part-1-build-powerful-llm-apps-from-scratch-eba24b75b55c"><strong>LangChain Crash Course — Part 1: Build Powerful LLM Apps from Scratch</strong></a><br> Learn the basics of chains, prompts, tools, memory, and outputs.</li><li>📄<strong> </strong><a href="https://medium.com/@vamshiginna1606/langchain-crash-course-part-2-build-your-first-rag-app-24908b14d337"><strong>LangChain Crash Course — Part 2: Build Your First RAG App</strong></a><br> Build an end-to-end retrieval-augmented generation pipeline.</li></ul><p>These will give you a solid foundation so you can confidently dive into graph-based logic with LangGraph.</p><h3>2. LangGraph Demystified — Core Concepts Explained Simply</h3><p>So what exactly is <strong>LangGraph</strong>, and why does it matter?</p><p>Let’s break it down with <strong>zero jargon</strong> and real-world parallels so even if you’re new to graphs or agents, this will just click.</p><h4>2.1. Imagine Building an AI Workflow Like a Flowchart</h4><p>Most LLM apps (like the ones you build with LangChain) work like a <strong>pipeline</strong>:</p><pre>Input → LLM → Output</pre><p>But real-world AI workflows need more than that:</p><ul><li>Retry logic</li><li>Branching decisions</li><li>Memory of past steps</li><li>Tool usage</li></ul><p>LangGraph lets you <strong>build all of this using a graph</strong> — like a <strong>flowchart</strong>, but for LLMs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*uWrFGX9KWc6lg952RkjHpA.png" /></figure><h4>2.2. The 4 Core Concepts of LangGraph</h4><p>Let’s go over the building blocks:</p><h4>1️⃣ Node = A Task</h4><p>Each node in LangGraph is just a function. It performs one step — like calling an LLM, retrieving a document, or using a tool.</p><p>📦Example:</p><pre>def generate_answer(state: dict):<br>    response = llm.invoke(f&quot;Answer this: {state[&#39;question&#39;]}&quot;)<br>    return {&quot;answer&quot;: response}</pre><p>You register this as a node:</p><pre>builder.add_node(&quot;generate&quot;, generate_answer)</pre><h4>2️⃣ Edge = What Comes Next?</h4><p>Edges are connections between nodes — they tell LangGraph <strong>what to do after a node finishes</strong>.</p><p>📦Example:</p><pre>builder.add_edge(&quot;retrieve&quot;, &quot;generate&quot;)</pre><p>You can also have <strong>conditional edges</strong> that branch based on logic (like if/else):</p><pre>builder.add_conditional_edges(&quot;decide&quot;, decide_fn, {<br>  &quot;yes&quot;: &quot;tool_a&quot;,<br>  &quot;no&quot;: &quot;tool_b&quot;<br>})</pre><h4>3️⃣ State = The Shared Memory</h4><p>LangGraph passes around a <strong>state dictionary</strong> that stores all context.</p><p>📦Example:</p><pre>{<br>  &quot;question&quot;: &quot;What&#39;s the weather?&quot;,<br>  &quot;docs&quot;: &quot;...&quot;,<br>  &quot;answer&quot;: &quot;It&#39;s sunny!&quot;<br>}</pre><p>Every node <strong>reads from and writes to</strong> this shared state.</p><h4>4️⃣ StateGraph &amp; Invoke = Run the Flow</h4><p>You use StateGraph to define your logic, then .compile() to finalize the graph, and finally .invoke(input) to run it.</p><p>📦 Example:</p><pre>graph = builder.compile()<br>graph.invoke({&quot;question&quot;: &quot;What&#39;s Python?&quot;})</pre><p>That’s it! LangGraph handles the flow through your nodes like magic 🪄</p><h3>3. Setting Up Your First LangGraph Project</h3><p>Now that you understand the basics, let’s build your <strong>first real LangGraph app</strong> — step by step.</p><p>We’ll create a simple <strong>question-answering agent</strong> that:</p><ol><li>Takes a user question</li><li>Optionally retrieves some docs</li><li>Uses an LLM to generate an answer</li></ol><h4>Step 1: Create Your Project Folder</h4><p>In your terminal:</p><pre>mkdir my-langgraph-agent<br>cd my-langgraph-agent</pre><h4>Step 2: Install Required Packages</h4><p>Make sure you’re in your Conda env (langgraph_env), then:</p><pre>pip install langgraph langchain-openai python-dotenv</pre><h4>Step 3: Create Your .env File</h4><p>Inside your folder, add a file named .env with your OpenAI key. You can also use any other open source LLM models available with free API keys.</p><pre>OPENAI_API_KEY=sk-...</pre><p>🔗 <em>Need help?</em><br> 📘 <a href="https://medium.com/@vamshiginna1606/api-key-setup-for-openai-groq-and-langsmith-in-your-projects-edf745e9507c">API Key Setup for OpenAI</a></p><h4>Step 4: Define Your State</h4><p>LangGraph passes state between all steps. Let’s define it as a basic Python dict for now:</p><pre># state<br>from typing import TypedDict<br><br>class GraphState(TypedDict):<br>    question: str<br>    answer: str</pre><h4>Step 5: Add Your Nodes (Functions)</h4><p>Each node is just a function that takes in the state and returns updated keys.</p><pre># nodes<br>from langchain_openai import ChatOpenAI<br><br>llm = ChatOpenAI(model=&quot;gpt-4&quot;)<br><br><br>def generate(state: dict) -&gt; dict:<br>    question = state[&quot;question&quot;]<br>    response = llm.invoke(f&quot;Answer the following: {question}&quot;)<br>    return {&quot;answer&quot;: response.content}</pre><h4>Step 6: Build the Graph</h4><p>Now let’s wire it all together.</p><pre># app<br>from langgraph.graph import StateGraph<br><br>builder = StateGraph(GraphState)<br>builder.add_node(&quot;generate&quot;, generate)<br>builder.set_entry_point(&quot;generate&quot;)<br><br><br>graph = builder.compile()<br><br>output = graph.invoke({&quot;question&quot;: &quot;What is LangGraph?&quot;})<br>print(output)</pre><h4>Output</h4><p>Your terminal should print something like:</p><pre>{&#39;question&#39;: &#39;What is LangGraph?&#39;, &#39;answer&#39;: &#39;LangGraph is...&#39;}</pre><p>Boom 💥 You just built your first LangGraph-powered AI flow!</p><h3>4. Hands-On — Add Tools, Decisions &amp; Branches</h3><p>So far, your LangGraph had a single node: generate. Now let’s make it smarter by:</p><ol><li>Adding a <strong>tool</strong> (e.g., get_weather)</li><li>Introducing a <strong>decision node</strong></li><li>Creating <strong>conditional edges</strong> to choose between paths</li></ol><h4>Step 1: Add a Simple Tool</h4><p>Let’s say our agent can answer general questions or fetch weather if asked. <a href="https://medium.com/@vamshiginna1606/langchain-tools-5-langchain-tools-every-llm-developer-should-know-ad698f06dcb5"><em>Learn more about tools here</em></a><em>.</em></p><pre>from langchain.tools import tool<br><br>@tool<br>def get_weather(location: str) -&gt; str:<br>    &quot;&quot;&quot;Get the weather for a given location.&quot;&quot;&quot;<br>    return f&quot;The weather in {location} is sunny ☀️&quot;</pre><p>You’ll also need to define this tool in your graph:</p><pre>tools = [get_weather]</pre><h4>Step 2: Add a Nodes</h4><p>This function will check if the question is about the weather or not.</p><pre>from langchain_openai import ChatOpenAI<br><br>llm = ChatOpenAI(model=&quot;gpt-4&quot;)<br><br>def decide_topic(state: dict) -&gt; str:<br>    question = state[&quot;question&quot;].lower()<br>    return &quot;weather&quot; if &quot;weather&quot; in question else &quot;general&quot;<br>    <br>def use_weather_tool(state: dict) -&gt; dict:<br>    return {&quot;answer&quot;: get_weather.invoke(&quot;Paris&quot;)}<br><br>def generate(state: dict) -&gt; dict:<br>    question = state[&quot;question&quot;]<br>    response = llm.invoke(f&quot;Answer: {question}&quot;)<br>    return {&quot;answer&quot;: response.content}</pre><h4>Step 3: Update Graph with Branching</h4><pre>from langgraph.graph import StateGraph, END<br><br>builder = StateGraph(dict)<br><br>builder.add_node(&quot;decide&quot;, lambda x: x)  # Acts as passthrough<br>builder.add_node(&quot;weather&quot;, use_weather_tool)<br>builder.add_node(&quot;generate&quot;, generate)<br><br>builder.set_entry_point(&quot;decide&quot;)<br><br>builder.add_conditional_edges(<br>    &quot;decide&quot;,<br>    decide_topic,<br>    {<br>        &quot;weather&quot;: &quot;weather&quot;,<br>        &quot;general&quot;: &quot;generate&quot;<br>    }<br>)<br><br>builder.add_edge(&quot;weather&quot;, END)<br>builder.add_edge(&quot;generate&quot;, END)<br><br>graph = builder.compile()</pre><h4>4. Try It Out</h4><pre>print(graph.invoke({&quot;question&quot;: &quot;What&#39;s the weather in Paris?&quot;})[&quot;answer&quot;])<br>print(graph.invoke({&quot;question&quot;: &quot;Explain LangGraph in simple words.&quot;})[&quot;answer&quot;])</pre><p>You’ll see:</p><ul><li>For weather questions: &quot;The weather in Paris is sunny ☀️&quot;</li><li>For general ones: LLM-generated answer</li></ul><h4>Why This Matters</h4><p>Traditional LangChain flows struggle with <strong>dynamic behavior</strong> like:</p><ul><li>“Use this tool <strong>only if</strong> needed”</li><li>“Try A, else try B”</li><li>“Loop until the user is satisfied”</li></ul><p>LangGraph lets you express all of that clearly with <strong>branches and loops</strong>.</p><h3>5. Conclusion &amp; What’s Next</h3><p>Congratulations! 🎉 You’ve just built your <strong>first LangGraph-powered agentic AI workflow</strong> — going from a single-function GenAI app to a branching, decision-making, LLM-driven graph.</p><h4>5.1. Let’s Recap What You’ve Learned:</h4><ul><li><strong>LangGraph</strong> is a graph-based framework for building advanced LLM workflows.</li><li>You now understand core concepts like <strong>nodes</strong>, <strong>edges</strong>, <strong>state</strong>, and <strong>invoke</strong>.</li><li>You built a working app that: Routes questions, Uses tools, Responds intelligently</li></ul><p>This is a major step up from traditional LangChain chains — you’re no longer just calling an LLM, you’re building workflows that feel more <strong>agentic, adaptive, and scalable</strong>.</p><h4>5.2. Coming Up Next…</h4><p>This was just the beginning. In future posts, we’ll explore:</p><ul><li><strong>Adding persistent memory</strong> for multi-turn conversations</li><li><strong>LangGraph + RAG</strong>: combining structured logic with document retrieval</li><li><strong>Multi-agent collaboration</strong>: building agent teams with shared goals</li></ul><h4>Got Feedback or Questions?</h4><p>I’d love to hear your thoughts!<br> Did something confuse you? Want a specific tutorial next? Just drop a comment on the blog or connect with me:</p><p>🔗 <a href="https://medium.com/@vamshiginna1606">Follow me on Medium</a><br> 🤝 <a href="https://www.linkedin.com/in/vamshikrishnaginna/">Connect on LinkedIn</a></p><p>Let’s keep building agentic apps together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9a1a0cec59a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain Tools: 5 Tools Every LLM Developer Should Know]]></title>
            <link>https://medium.com/@vamshiginna1606/langchain-tools-5-langchain-tools-every-llm-developer-should-know-ad698f06dcb5?source=rss-5482f97f8048------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad698f06dcb5</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[langchain-tools]]></category>
            <dc:creator><![CDATA[Vamshi Krishna Ginna]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 05:25:19 GMT</pubDate>
            <atom:updated>2025-06-07T05:28:34.786Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. What are LangChain Tools?</h3><p>Large Language Models (LLMs) are impressive, but out of the box, they can’t <em>act</em> — they can only <em>respond</em> based on pre-trained data. That’s where <strong>LangChain Tools</strong> step in.</p><p>LangChain Tools empower LLMs to <strong>interact with the real world</strong> by connecting to APIs, performing calculations, browsing the web, and more. Think of them as “plugins” that allow the LLM to:</p><ul><li>Search the internet for real-time news</li><li>Run Python code for calculations or data processing</li><li>Call external REST APIs (e.g., weather, finance, sports)</li><li>Query databases or fetch documents</li><li>Use chains of tools for more complex workflows</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*79VuX9_58DK-JXaW" /></figure><p>This makes LangChain not just a framework for chaining prompts — but a powerful <strong>agentic platform</strong> for building intelligent, autonomous applications.</p><blockquote><strong>New to LangChain?</strong><br> Don’t worry — I’ve got you covered! Start with these beginner-friendly blogs before diving into tools:</blockquote><ol><li><a href="https://medium.com/@vamshiginna1606/langchain-crash-course-part-1-build-powerful-llm-apps-from-scratch-eba24b75b55c">LangChain Crash Course Part 1 — Build Powerful LLM Apps from Scratch</a></li><li><a href="https://medium.com/@vamshiginna1606/langchain-crash-course-part-2-build-your-first-rag-app-24908b14d337">LangChain Crash Course Part 2 — Build Your First RAG App</a></li></ol><h3>2. The Top 5 LangChain Tools You Should Know</h3><p>LangChain offers dozens of built-in tools, but here are <strong>5 must-know tools</strong> that will instantly level up your LLM-powered applications.</p><h4>1. RequestsTool — Call Any API with Ease</h4><p>This tool allows your LLM to interact with <strong>any RESTful API</strong>. Want to fetch stock prices, weather, or sports scores? Just pass the URL and headers — and boom!</p><blockquote><em>✅ Use Case: Pull live stock price or real-time traffic updates.</em></blockquote><pre>from langchain_community.agent_toolkits.openapi.toolkit import RequestsToolkit<br>from langchain_community.utilities.requests import TextRequestsWrapper<br><br># Permissions are narrowly-scoped: only public JSONPlaceholder API, no auth, no custom headers<br>toolkit = RequestsToolkit(<br>    requests_wrapper=TextRequestsWrapper(headers={}),<br>    allow_dangerous_requests=ALLOW_DANGEROUS_REQUEST,<br>)<br><br># View available tools<br>tools = toolkit.get_tools()<br>print(tools)<br><br># Use the GET tool to fetch posts from JSONPlaceholder<br>get_tool = [tool for tool in tools if tool.name == &quot;requests_get&quot;][0]<br>result = get_tool.run({&quot;url&quot;: &quot;https://jsonplaceholder.typicode.com/posts?_limit=2&quot;})<br>print(result)<br><br>###########################################################################<br>#Output<br># [RequestsGetTool(requests_wrapper=TextRequestsWrapper(headers={}, aiosession=None, auth=None, response_content_type=&#39;text&#39;, verify=True), allow_dangerous_requests=True), RequestsPostTool(requests_wrapper=TextRequestsWrapper(headers={}, aiosession=None, auth=None, response_content_type=&#39;text&#39;, verify=True), allow_dangerous_requests=True), RequestsPatchTool(requests_wrapper=TextRequestsWrapper(headers={}, aiosession=None, auth=None, response_content_type=&#39;text&#39;, verify=True), allow_dangerous_requests=True), RequestsPutTool(requests_wrapper=TextRequestsWrapper(headers={}, aiosession=None, auth=None, response_content_type=&#39;text&#39;, verify=True), allow_dangerous_requests=True), RequestsDeleteTool(requests_wrapper=TextRequestsWrapper(headers={}, aiosession=None, auth=None, response_content_type=&#39;text&#39;, verify=True), allow_dangerous_requests=True)] <br>#[<br># {<br>#   &quot;userId&quot;: 1,<br>#   &quot;id&quot;: 1,<br>#   &quot;title&quot;: &quot;sunt aut facere repellat provident occaecati excepturi optio reprehenderit&quot;,<br>#   &quot;body&quot;: &quot;quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto&quot;<br>#  },<br>#  {<br>#    &quot;userId&quot;: 1,<br>#    &quot;id&quot;: 2,<br>#    &quot;title&quot;: &quot;qui est esse&quot;,<br>#    &quot;body&quot;: &quot;est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla&quot;<br>#  }<br>#]<br></pre><h4>2. WikipediaAPIWrapper — Get Clean, Structured Facts Fast</h4><p>Query Wikipedia directly from your LLM. Instead of hallucinating facts, your model can now rely on structured and verifiable information.</p><blockquote><em>✅ Use Case: Answer “What happened in the 2025 RCB vs CSK match?” with historical context.</em></blockquote><pre>from langchain_community.tools import WikipediaQueryRun<br>from langchain_community.utilities import WikipediaAPIWrapper<br><br>api_wrapper = WikipediaAPIWrapper(top_k_results=5, doc_content_chars_max=1000)<br><br>wikipedia = WikipediaQueryRun(api_wrapper=api_wrapper)<br><br>wikipedia.run(&quot;Virat Kohli&quot;)<br><br># Output: &#39;Page: Virat Kohli\nSummary: Virat Kohli (born 5 November 1988) is an Indian international cricketer who plays ODI cricket for the national team and is a former captain in all formats. He is a right-handed batsman and occasional right-arm medium pace bowler. Considered one of the greatest all-format batsmen in the history of cricket, he is called the King, the Chase Master, and the Run Machine for his skills, records and ability to lead his team to victory. Kohli is the highest run-scorer in the Indian Premier League, third in T20I, third in ODI, and third in international cricket. He has the most ODI centuries and second-most centuries in international cricket. Kohli is also the most successful Test captain of India with back-to-back Test mace wins and most victories in his tenure. He is the only batter to earn 900 rating points in all three formats.\nKohli was the captain of the 2008 U19 World Cup winning team and was a crucial member of the teams that won 2011 ODI World Cup, 2013 Champ&#39;</pre><h4>3. SerpAPIWrapper — Real-Time Web Search via Google</h4><p>Need current news, tweets, or live updates? This tool integrates with Google via SerpAPI and gives your LLM the power to <em>see the web</em>.</p><blockquote><em>✅ Use Case: Get breaking news about the June 2025 stampede or current trending topics.</em></blockquote><pre>from langchain_community.utilities import SerpAPIWrapper<br><br>search = SerpAPIWrapper()<br><br>params = {<br>    &quot;engine&quot;: &quot;bing&quot;,<br>    &quot;gl&quot;: &quot;us&quot;,<br>    &quot;hl&quot;: &quot;en&quot;,<br>}<br>search = SerpAPIWrapper(params=params)<br><br>search.run(&quot;Who won the IPL 2025?&quot;)<br><br>#Output: &#39;Royal Challengers Bengaluru&#39; </pre><h4>4. PythonREPLTool — Let Your LLM Think Mathematically</h4><p>This tool gives your model a virtual Python terminal to execute code and return results — perfect for math, logic, or even data parsing.</p><blockquote><em>✅ Use Case: Calculate batting averages or convert timezones on the fly.</em></blockquote><pre>from langchain_core.tools import Tool<br>from langchain_experimental.utilities import PythonREPL<br><br>python_repl = PythonREPL()<br><br>python_repl.run(&quot;print(1+1)&quot;)<br><br>#Output:<br>#Python REPL can execute arbitrary code. Use with caution.<br>#&#39;2\n&#39;</pre><h4>5. Toolkits (e.g., NewsAPI, OpenWeatherMap) — Domain-Specific Power</h4><p>LangChain offers out-of-the-box integrations with APIs like OpenWeather, NewsAPI, and more — enabling your LLM to become a domain-specific agent.</p><blockquote><em>✅ Use Case: Summarize current weather across cities or list top headlines from trusted sources.</em></blockquote><pre><br>from langchain_community.utilities import OpenWeatherMapAPIWrapper<br><br>weather = OpenWeatherMapAPIWrapper()<br><br>weather_data = weather.run(&quot;London,GB&quot;)<br>print(weather_data)<br><br>#Output: <br>#In London,GB, the current weather is as follows:<br>#Detailed status: overcast clouds<br>#Wind speed: 4.12 m/s, direction: 10°<br>#Humidity: 51%<br>#Temperature: <br>  #- Current: 12.82°C<br>  #- High: 13.98°C<br>  #- Low: 12.01°C<br>  #- Feels like: 11.49°C<br>#Rain: {}<br>#Heat index: None <br>#Cloud cover: 100%</pre><p>Explore more tools on <a href="https://python.langchain.com/docs/integrations/tools/">Langchain Tools</a></p><h3>3: Hands-On — Fetching Real-World Info with LangChain Tools</h3><p>LangChain Tools become powerful when applied to real-world tasks. Let’s use the <strong>SerpAPIWrapper</strong> to pull real-time information about two trending topics:</p><ul><li>🏏 <strong>RCB’s latest match highlights</strong></li><li>🚨 <strong>Recent stampede incident (June 2025)</strong></li></ul><p>This hands-on demo shows how an LLM can act like a research assistant — pulling and summarizing news as it happens.</p><h4>What You Need</h4><ul><li>A free <a href="https://serpapi.com/">SerpAPI</a> key</li><li>langchain and langchain_community installed</li><li>openai or compatible LLM for agent setup</li></ul><h4>Code Snippet: Real-Time Search with SerpAPIWrapper</h4><pre>from langchain.agents import initialize_agent, Tool<br>from langchain_community.tools import SerpAPIWrapper<br>from langchain.chat_models import ChatOpenAI<br><br># Step 1: Configure SerpAPI tool<br>search = SerpAPIWrapper()  # Make sure SERPAPI_API_KEY is set in your .env<br># Step 2: Register the tool<br>tools = [<br>    Tool(<br>        name=&quot;News Search&quot;,<br>        func=search.run,<br>        description=&quot;Use for searching live news and updates via Google&quot;<br>    )<br>]<br># Step 3: Initialize the agent<br>llm = ChatOpenAI(temperature=0)<br>agent = initialize_agent(tools, llm, agent=&quot;zero-shot-react-description&quot;)<br># Step 4: Ask real-world questions<br>query_1 = &quot;What happened in the latest RCB match in IPL 2025?&quot;<br>query_2 = &quot;Tell me about the June 2025 stampede incident in India.&quot;<br>print(agent.run(query_1))<br>print(agent.run(query_2))</pre><pre><br>RCB won the latest match in IPL 2025 by 6 runs.<br>The June 2025 stampede incident in India occurred outside the M Chinnaswamy Stadium during celebrations, resulting in 11 deaths and over 30 injuries. The franchise involved pledged financial support to the families of the victims, and several individuals were detained in connection with the incident.</pre><blockquote>🔍 The LLM will now search Google (via SerpAPI), summarize top headlines, and present the latest updates as if it were reading the news for you.</blockquote><h4>Why This Matters</h4><p>This example shows how LLMs can go beyond just “talking” — they can <em>act</em> as live agents, pulling verified, real-time data to power intelligent apps.</p><h3>4. When to Use Which Tool?</h3><p>LangChain offers a wide variety of tools, but choosing the right one depends on <strong>what kind of information</strong> you need and <strong>how fast or accurate</strong> it needs to be. Here’s a quick breakdown to help you decide</p><h4>Tool Decision Matrix</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCmCVOafy7Piw_r-2mbE2A.png" /></figure><h4>Real-World Example: Building an IPL Match Analyzer</h4><p>Imagine you’re building a mini assistant to analyze IPL 2025 matches:</p><ul><li>Use SerpAPIWrapper to fetch <strong>match summaries</strong></li><li>Use PythonREPLTool to <strong>calculate strike rates or averages</strong></li><li>Use RequestsTool to <strong>pull player stats from CricAPI</strong></li><li>Use WikipediaAPIWrapper to <strong>compare teams&#39; historical performance</strong></li></ul><p>Each tool acts like a skill you’re giving your LLM — the better you match the tool to the task, the smarter your app becomes.</p><h3>5. Learn More &amp; Build More</h3><p>If today’s hands-on demo got you excited, there’s a whole world of LangChain Tools waiting for you. Whether you’re building an AI news agent, a stock market dashboard, or an on-demand weather assistant — the possibilities are endless.</p><h4>Explore More Tools Here:</h4><p><a href="https://python.langchain.com/docs/integrations/tools/">LangChain Tool Integrations — Official Docs</a></p><p>This documentation is your treasure map. You’ll find tools for:</p><ul><li>Databases (SQL, MongoDB)</li><li>File systems (CSV, PDFs)</li><li>APIs (News, Weather, GitHub)</li><li>Search (Google, DuckDuckGo, Wikipedia)</li><li>Utilities (PythonREPL, Calculator, Terminal)</li></ul><h4>Bonus: Build Your Own Custom Tool</h4><p>LangChain lets you create your <strong>own tools</strong> by wrapping any Python function. This means you can integrate LLMs into <em>your</em> APIs, business logic, or data pipelines seamlessly.</p><pre>from langchain.agents import Tool<br><br>def get_discounted_price(price, discount):<br>    return price - (price * discount / 100)<br><br>custom_tool = Tool(<br>    name=&quot;Discount Calculator&quot;,<br>    func=lambda q: get_discounted_price(100, 15),  # Just an example<br>    description=&quot;Calculates discounted price given original price and discount rate&quot;<br>)</pre><h3>🚀 Keep Learning With My Blogs</h3><p>To master LangChain from beginner to advanced, follow my ongoing crash course:</p><ul><li>🧠 <a href="https://medium.com/@vamshiginna1606/langchain-crash-course-part-1-build-powerful-llm-apps-from-scratch-eba24b75b55c">Part 1: Build Powerful LLM Apps from Scratch</a></li><li>🛠️ <a href="https://medium.com/@vamshiginna1606/langchain-crash-course-part-2-build-your-first-rag-app-24908b14d337">Part 2: Build Your First RAG App</a></li></ul><blockquote>I publish a new hands-on blogs every week — so follow me on <a href="https://medium.com/@vamshiginna1606">Medium</a> and let’s build cool stuff together!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad698f06dcb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Search at Scale: Cloud vs. Local DBs: Build a RAG App with Pinecone, LangChain & OpenAI]]></title>
            <link>https://medium.com/@vamshiginna1606/vector-search-at-scale-cloud-vs-local-dbs-build-a-rag-app-with-pinecone-langchain-openai-778faf513db4?source=rss-5482f97f8048------2</link>
            <guid isPermaLink="false">https://medium.com/p/778faf513db4</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pinecone]]></category>
            <dc:creator><![CDATA[Vamshi Krishna Ginna]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 06:08:38 GMT</pubDate>
            <atom:updated>2025-06-01T06:08:38.874Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction: The Search Problem LLMs Can’t Solve Alone</h3><p>Large Language Models (LLMs) like GPT-4 can reason, write, and summarize — but they can’t <strong>remember</strong>. They don’t have persistent memory or context beyond a few thousand tokens. That’s where <strong>vector databases</strong> come in.</p><p>When you convert data (text, image, audio) into embeddings — a high-dimensional representation — LLMs can <strong>retrieve</strong> semantically similar content. This process powers <strong>RAG (Retrieval-Augmented Generation)</strong> and makes AI smarter, faster, and context-aware.</p><p>But here’s the catch:</p><blockquote><em>Not all vector databases are created equal. Some are built for rapid prototyping. Others are built for the cloud.</em></blockquote><p>Some (like FAISS or Chroma) are great for <strong>local dev</strong>, while others (like Pinecone or Weaviate) are battle-tested for <strong>production</strong> with cloud APIs, scaling, filtering, and hybrid search.</p><p>In this blog, you’ll learn:</p><ul><li>☁️ Cloud-hosted vs. local vector DBs: Which is right for you?</li><li>⚡ KNN vs. ANN: How retrieval strategies impact speed and accuracy</li><li>🧠 Why real-world LLM apps demand scalable, multimodal search</li><li>🛠️ Hands-on: Build a semantic search + RAG app using <strong>Pinecone + OpenAI + LangChain</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lH7CbHxHHzr2qHHX" /></figure><h3>2. Cloud vs. Local Vector Databases: What’s the Difference?</h3><p>When it comes to storing and querying vector embeddings, one of the first decisions you’ll make is <strong>where</strong> to run your database:<br> 🔹 <strong>Locally</strong> on your machine or server<br> 🔹 <strong>In the cloud</strong> with a managed API</p><p>Both approaches have pros and cons — let’s break them down.</p><h4>2.1. Deployment Matrix</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*YHz69bfKP7d2XsgqZG3XYw.png" /></figure><p>🧠 <strong>Insight</strong>:</p><ul><li><strong>Pinecone</strong> is cloud-native and built for scale but has <strong>no local deployment</strong> option.</li><li><strong>FAISS/Chroma</strong> are ideal for quick local testing but lack enterprise features like horizontal scaling or distributed indexing.</li><li><strong>Qdrant</strong> and <strong>Weaviate</strong> offer the best of both worlds — local testing and cloud deployment with production-level performance.</li></ul><h4>2.2. Trade-offs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PsEE31rXDliSDRi5sl9z9A.png" /></figure><h4>2.3. When to Use What?</h4><p><strong>Use Local DBs (FAISS, Chroma):</strong></p><ul><li>In Jupyter notebooks or dev environments</li><li>When cost is a constraint</li><li>For fast experimentation</li></ul><p><strong>Use Cloud DBs (Pinecone, Weaviate, Qdrant):</strong></p><ul><li>For RAG apps in production</li><li>When handling millions of embeddings</li><li>When you need multi-user access, uptime SLAs, and secure APIs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hp4ramMYcv7Hs2x2D2ep8g.png" /><figcaption>source: <a href="https://superlinked.com/vector-db-comparison">https://superlinked.com/vector-db-comparison</a></figcaption></figure><h3>3. KNN vs. ANN: Speed vs. Precision in Vector Retrieval</h3><p>Once your data is embedded into vectors and stored in a database, the next step is <strong>retrieving similar vectors</strong>. But how should the database decide which vectors are “closest”?</p><p>This is where two core search strategies come into play:</p><h4>3.1. The Basics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*yMr-YASsr7ZZYXjqNRmTdA.png" /></figure><h4>3.2. KNN: Precise, but Costly</h4><ul><li>Exhaustively compares the query vector to <strong>all</strong> stored vectors.</li><li>Delivers the most <strong>accurate</strong> results.</li><li>Becomes slow and memory-intensive as dataset grows.</li><li><strong>Suitable for</strong>: Small datasets, Academic work, Situations where accuracy is critical</li></ul><h4>3.3. ANN: Speed Meets Scale</h4><ul><li>Uses smart indexing techniques like <strong>HNSW</strong>, <strong>IVF</strong>, or <strong>PQ</strong>.</li><li>Returns results that are <em>very close</em> — but not mathematically perfect.</li><li>Scales to millions of embeddings with <strong>minimal latency</strong>.</li><li><strong>Suitable for:</strong> Real-time applications, Semantic search at scale Any production-grade vector DB (Pinecone, Weaviate, etc.)</li></ul><h4>3.4. Quick Analogy:</h4><p>Imagine finding the 5 people closest to you in a stadium:</p><ul><li><strong>KNN</strong> = check every single person.</li><li><strong>ANN</strong> = check every person in your section and return the closest.</li></ul><p><strong>Takeaway:</strong></p><blockquote><em>If you’re building a serious AI application, </em><strong><em>ANN is the default</em></strong><em> — it’s how most modern vector DBs achieve real-time speed without compromising too much on quality.</em></blockquote><h3>4. Real-World LLM Use Cases Need More Than Just Text</h3><p>In today’s AI landscape, information isn’t limited to plain text. Real applications need to work with:</p><ul><li>📝 Text (emails, docs)</li><li>🖼️ Images (screenshots, scanned forms)</li><li>🔊 Audio (calls, voice notes)</li><li>🎥 Video (recordings, tutorials)</li><li>📊 Tables (spreadsheets, PDFs)</li></ul><p>To support these, we need databases that understand <strong>multimodal inputs</strong> — and store them efficiently in <strong>vector form</strong>.</p><h4>4.1. Multimodal Embedding Flow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*3ibEgG1MAAa9TJ-Tupzyvw.png" /></figure><p>📌 <em>Tables can also be summarized to plain text before embedding.</em></p><h4>4.2. Use Case Examples</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*OONU_1VpB7eP8XxJSiwLFw.png" /></figure><p>These aren’t future ideas — they’re being built today using tools like <strong>LangChain</strong>, <strong>Pinecone</strong>, and <strong>OpenAI</strong>.</p><h3>💡 Core Insight:</h3><blockquote><em>“The real magic isn’t in how we </em><strong><em>create</em></strong><em> embeddings… it’s in how vector databases </em><strong><em>organize, index, and retrieve</em></strong><em> them for scalable AI workflows.”</em></blockquote><p>This is what separates powerful cloud-hosted DBs like <strong>Weaviate</strong>, <strong>Qdrant</strong>, and <strong>Pinecone</strong> from local prototypes like FAISS and Chroma.</p><h3>5. Hands-On: Build a Semantic Search + RAG App with Pinecone &amp; LangChain</h3><p>Now that we’ve explored the theory, let’s get our hands dirty.</p><p>In this section, you’ll:</p><ul><li>Generate vector embeddings using OpenAI</li><li>Store them in Pinecone (cloud vector DB)</li><li>Query similar content</li><li>Build a simple RAG (Retrieval-Augmented Generation) pipeline</li></ul><h4>Step 1: Create a Pinecone Account &amp; API Key</h4><ol><li>Go to <a href="https://www.pinecone.io/">https://www.pinecone.io</a></li><li>Sign up and navigate to <strong>API Keys</strong></li><li>Copy your key and keep it safe — we’ll load it in .env</li></ol><pre>OPENAI_API_KEY=sk-xxxxxxxxxxxxx<br>PINECONE_API_KEY=xxxxxxxxxxxxx</pre><h4>Step 2: Install Dependencies</h4><pre>pip install langchain-openai langchain-pinecone pinecone-client python-dotenv</pre><h4>Step 3: Code Walkthrough</h4><pre># Load environment variables<br>import os<br>from dotenv import load_dotenv<br>load_dotenv()<br><br># 🔗 Initialize OpenAI Embeddings<br>from langchain_openai import OpenAIEmbeddings<br><br>embeddings = OpenAIEmbeddings(model=&quot;text-embedding-3-large&quot;)<br>dimensions = len(embeddings.embed_query(&quot;Hello world!&quot;))<br><br>print(f&quot;Embedding Dimensions: {dimensions}&quot;) #3072thon</pre><pre># Initialize Pinecone Client<br>from pinecone import Pinecone, ServerlessSpec<br>pc = Pinecone(api_key=os.getenv(&quot;PINECONE_API_KEY&quot;))<br><br>index_name = &quot;semantic-search-demo&quot;<br><br># Create index if it doesn&#39;t exist<br>if not pc.has_index(index_name):<br>    pc.create_index(<br>        name=index_name,<br>        dimension=dimensions,<br>        metric=&quot;cosine&quot;,<br>        spec=ServerlessSpec(cloud=&quot;aws&quot;, region=&quot;us-east-1&quot;)<br>    )<br><br>index = pc.Index(index_name)</pre><pre># Create LangChain Vector Store<br>from langchain_pinecone import PineconeVectorStore<br>vector_store = PineconeVectorStore(index=index, embedding=embeddings)</pre><pre># 📄 Create Sample Documents<br>from langchain_core.documents import Document<br>from uuid import uuid4<br><br>docs = [<br>    Document(page_content=&quot;The best pancakes are made with buttermilk and love.&quot;, metadata={&quot;type&quot;: &quot;food&quot;}),<br>    Document(page_content=&quot;Sushi spots are trending this summer in NYC.&quot;, metadata={&quot;type&quot;: &quot;review&quot;}),<br>    Document(page_content=&quot;Apple launched a new chip with record-breaking battery life.&quot;, metadata={&quot;type&quot;: &quot;tech&quot;}),<br>]<br><br>ids = [str(uuid4()) for _ in docs]<br>vector_store.add_documents(documents=docs, ids=ids)<br></pre><blockquote><em>✅ </em><strong><em>Check your Pinecone dashboard!</em></strong><em><br> You’ll now see the </em><em>semantic-search-demo index populated with vectors.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izoy4RHa1ANSQmRLcdBhYg.png" /></figure><h4>Step 4: Run Semantic Search</h4><pre>query = &quot;Which places serve good sushi?&quot;<br>results = vector_store.similarity_search(query, k=2)<br><br><br>print(&quot;Semantic Search Results:&quot;)<br>for doc in results:<br>    print(f&quot;- {doc.page_content}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-u694529LGp6AOoPGHEWQ.png" /><figcaption>output</figcaption></figure><h4>Step 5: Add an LLM for RAG</h4><pre>from langchain.chains import RetrievalQA<br>from langchain_openai import ChatOpenAI<br><br><br>llm = ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0)<br>rag_chain = RetrievalQA.from_chain_type(<br>    llm=llm,<br>    retriever=vector_store.as_retriever()<br>)<br><br><br>response = rag_chain.run(&quot;Tell me about breakfast foods.&quot;)<br>print(response)<br><br>#output<br>#Breakfast foods vary widely across different cultures, but some popular options include pancakes, which are often made with ingredients like buttermilk for added flavor and texture. Other common breakfast foods include eggs, bacon, cereal, toast, and pastries. In some cultures, breakfast might include rice, beans, or even soup. The key to a great breakfast often lies in the quality of the ingredients and the care put into preparation.</pre><h4>Recap</h4><p>You just built a <strong>semantic search engine + RAG system</strong> using:</p><ul><li>OpenAI Embeddings</li><li>Pinecone for indexing</li><li>LangChain for orchestration</li></ul><p>You can expand this by embedding full documents, PDFs, product data, or resumes — and scaling this to production in minutes.</p><h3>6. Conclusion: The Power of Search Starts with Vectors</h3><p>If you’ve made it this far — congrats! You’ve just built a production-ready semantic search + RAG application using Pinecone, OpenAI, and LangChain.</p><p>In the era of LLMs and multimodal data, vector databases are no longer optional — they’re foundational. Whether you’re powering an AI assistant, a document Q&amp;A tool, or a personalized recommendation system, <strong>your choice of vector database matters</strong>.</p><blockquote><em>The real value lies not just in embedding — but in how you </em><strong><em>store, scale, and search</em></strong><em> those embeddings.</em></blockquote><h4>6.1. What’s Next?</h4><p>If you’re excited to keep building, here are some <strong>highly recommended next reads</strong> from my blog collection:</p><h4>6.2. Core Building Blocks</h4><ul><li><a href="https://medium.com/@vamshiginna1606/vector-embeddings-from-zero-to-hero-with-python-langchain-f5c56e6816cc"><strong>Vector Embeddings: From Zero to Hero (with Python &amp; LangChain)</strong></a><br> Learn all the theory + hands-on tricks to master embeddings.</li><li><a href="https://medium.com/@vamshiginna1606/langchain-crash-course-part-1-build-powerful-llm-apps-from-scratch-eba24b75b55c"><strong>LangChain Crash Course — Part 1: Build Powerful LLM Apps from Scratch</strong></a><br> A complete beginner’s guide to LangChain components.</li><li><a href="https://medium.com/@vamshiginna1606/langchain-crash-course-part-2-build-your-first-rag-app-24908b14d337"><strong>LangChain Crash Course — Part 2: Build Your First RAG App</strong></a><br> End-to-end guide to building your first retrieval-augmented app.</li></ul><p>Thank you for reading!</p><p>If this helped you, feel free to share it and tag me on <a href="https://www.linkedin.com/in/vamshikrishnaginna/">LinkedIn </a>or <a href="https://medium.com/@vamshiginna1606">Medium</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=778faf513db4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Embeddings: From Zero to Hero (with Python & LangChain)]]></title>
            <link>https://medium.com/@vamshiginna1606/vector-embeddings-from-zero-to-hero-with-python-langchain-f5c56e6816cc?source=rss-5482f97f8048------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5c56e6816cc</guid>
            <category><![CDATA[embedding-model]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[vector-embeddings]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Vamshi Krishna Ginna]]></dc:creator>
            <pubDate>Sat, 31 May 2025 06:57:14 GMT</pubDate>
            <atom:updated>2025-05-31T06:57:50.004Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>In today’s AI-driven world, machines need more than just raw text — they need understanding. That’s where <strong>vector embeddings</strong> come in. These powerful numerical representations transform words, sentences, and even full documents into high-dimensional vectors that capture meaning, context, and relationships.</p><p>Whether you’re building a <strong>semantic search engine</strong>, a <strong>recommendation system</strong>, or a <strong>chatbot that actually gets you</strong>, embeddings are the foundation. They allow AI models to measure similarity, detect nuance, and connect ideas in ways traditional databases simply can’t.</p><blockquote><strong>Think of embeddings as the bridge between human language and machine reasoning.</strong></blockquote><p>This blog takes you from the <strong>absolute basics</strong> of embeddings to building a <strong>hands-on LangChain-powered assistant</strong> using Python. We’ll explore:</p><ul><li>How embeddings work</li><li>Where they’re used</li><li>The difference between traditional and vector databases</li><li>And how to use tools like <strong>OpenAI</strong>, <strong>HuggingFace</strong>, <strong>FAISS</strong>, and <strong>LangChain</strong> to bring it all together.</li></ul><p>📌 <strong>Bonus:</strong> If you’re new to LangChain or curious about building a complete Retrieval-Augmented Generation (RAG) app, check out my previous post: <a href="https://medium.com/@vamshiginna1606/langchain-crash-course-part-2-build-your-first-rag-app-24908b14d337">LangChain Crash Course — Part 2: Build Your First RAG App</a></p><p>Let’s dive in and demystify embeddings — from zero to hero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*gKq85CDJr0zJ50oN" /></figure><h3>2. NLP Prerequisites</h3><p>Before diving deep into vector embeddings, it’s essential to understand a few key NLP concepts that form the foundation of how text is processed and understood by machines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*nvFxQ3-lGWh-pKs_" /></figure><h4>2.1. Tokenization</h4><p>Tokenization breaks down a sentence or document into smaller units called tokens — typically words or subwords.</p><pre>from nltk.tokenize import word_tokenize<br>text = &quot;Vector embeddings are powerful!&quot;<br>tokens = word_tokenize(text)<br>print(tokens)</pre><p>Output:</p><pre>[&#39;Vector&#39;, &#39;embeddings&#39;, &#39;are&#39;, &#39;powerful&#39;, &#39;!&#39;]</pre><h4>2.2. Stopwords</h4><p>Stopwords are common words like “and”, “the”, “is” that carry minimal meaning and are often removed in preprocessing.</p><pre>from nltk.corpus import stopwords<br>stop_words = set(stopwords.words(&#39;english&#39;))<br>filtered_tokens = [w for w in tokens if w.lower() not in stop_words]<br>print(filtered_tokens)<br></pre><p>Output:</p><pre>[&#39;Vector&#39;, &#39;embeddings&#39;, &#39;powerful&#39;, &#39;!&#39;]</pre><h4>2.3. Lemmatization</h4><p>Lemmatization reduces words to their base form using context and vocabulary.</p><pre>from nltk.stem import WordNetLemmatizer<br>lemmatizer = WordNetLemmatizer()<br>print(lemmatizer.lemmatize(&quot;running&quot;))</pre><h4>2.4. Bag of Words (BoW)</h4><p>A simple model that represents text as a vector of word counts.</p><pre>from sklearn.feature_extraction.text import CountVectorizer<br>corpus = [&quot;Embeddings convert text into vectors.&quot;, &quot;Vectors can be compared mathematically.&quot;]<br>vectorizer = CountVectorizer()<br>print(vectorizer.fit_transform(corpus).toarray())<br></pre><p>Output:</p><pre>[[0 0 0 1 1 1 0 1 1]<br> [1 1 1 0 0 0 1 0 1]]</pre><h4>2.5. TF-IDF (Term Frequency-Inverse Document Frequency)</h4><p>Weights words based on how important they are to a document in a corpus.</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer<br>vectorizer = TfidfVectorizer()<br>print(vectorizer.fit_transform(corpus).toarray())</pre><p>Output:</p><pre>[[0.         0.         0.         0.47107781 0.47107781 0.47107781<br>  0.         0.47107781 0.33517574]<br> [0.47107781 0.47107781 0.47107781 0.         0.         0.<br>  0.47107781 0.         0.33517574]]</pre><h4>2.6. Word2Vec (Intro)</h4><p>Word2Vec learns word associations from large text corpora, producing meaningful word embeddings.</p><pre>from gensim.models import Word2Vec<br>sentences = [[&quot;vector&quot;, &quot;embeddings&quot;, &quot;are&quot;, &quot;useful&quot;]]<br>model = Word2Vec(sentences, min_count=1)<br>print(model.wv[&quot;vector&quot;])</pre><p>These foundational tools will help you understand how raw text evolves into structured numerical representations — setting the stage for deeper embedding concepts.</p><h3>3. From Text to Vectors</h3><p>At the heart of modern NLP lies a simple idea: <strong>convert text into numbers</strong>. Why? Because machines don’t understand words — they understand <strong>vectors</strong> (i.e., arrays of numbers). That’s where embeddings step in.</p><h4>3.1. Main Goal of Embeddings</h4><p>Transform natural language into a <strong>dense vector representation</strong> that captures the meaning and context of the input.</p><h4>3.2. One-Hot Encoding: The Old School Way</h4><p>Before embeddings, we used <strong>one-hot encoding</strong>. It represents each word as a binary vector with only one ‘1’ and the rest ‘0s’.</p><p>Example:</p><pre># Vocabulary: [&quot;king&quot;, &quot;queen&quot;, &quot;man&quot;, &quot;woman&quot;]<br># &quot;king&quot; → [1, 0, 0, 0]</pre><p><strong>Limitations:</strong></p><ul><li>Doesn’t capture any relationship between words</li><li>Results in high-dimensional sparse vectors</li></ul><h4>3.3. Embeddings: The Modern Way</h4><p>Instead of binary vectors, <strong>embeddings assign each word a dense, fixed-length vector</strong>. These vectors are learned from data and capture semantic relationships.</p><p>Example:</p><pre># &quot;king&quot; → [0.25, 0.78, -0.39, ...]  (typically 300–3072 dimensions)</pre><p>These embeddings enable <strong>semantic arithmetic</strong>:</p><ul><li>king - man + woman ≈ queen</li></ul><h4>3.4. Same Length, Different Texts</h4><p>One of the most powerful things about embeddings is that <strong>any sentence, no matter how long, gets converted to a vector of the same length</strong>. The length is determined by the model (e.g., 384 for MiniLM, 3072 for OpenAI’s text-embedding-3-large).</p><h4>3.5. Why It Matters</h4><p>This transformation lets us:</p><ul><li>Measure <strong>similarity</strong> between texts using cosine distance</li><li>Build <strong>search engines</strong> and <strong>recommendation systems</strong></li><li>Feed meaningful inputs into deep learning models</li></ul><h3>4. Types of Embeddings</h3><p>Not all embeddings are created equal. Depending on the task, different types of embeddings help represent language at varying levels of granularity.</p><h4>4.1. Word Embeddings</h4><p>Each word is mapped to a unique vector. Captures meaning based on usage across a large corpus.</p><ul><li>Common Models: <strong>Word2Vec</strong>, <strong>GloVe</strong>, <strong>FastText</strong></li><li>Good for: Analogy tasks, sentiment analysis</li><li>Limitation: Same vector for the word “bank” (river bank vs. money bank)</li></ul><pre>from gensim.models import Word2Vec<br>sentences = [[&quot;king&quot;, &quot;queen&quot;, &quot;man&quot;, &quot;woman&quot;]]<br>model = Word2Vec(sentences, min_count=1)<br>print(model.wv[&quot;king&quot;])</pre><h4>4.2. Sentence Embeddings</h4><p>Encodes entire sentences into a single vector that captures overall meaning.</p><ul><li>Common Models: <strong>SBERT</strong>, <strong>Universal Sentence Encoder</strong></li><li>Good for: Semantic search, duplicate detection</li><li>Advantage: Handles word order, punctuation, and meaning</li></ul><pre>from sentence_transformers import SentenceTransformer<br>model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;)<br>print(model.encode(&quot;Vector embeddings are powerful.&quot;))</pre><h4>4.3. Document Embeddings</h4><p>Goes beyond sentences to capture the context of a full document.</p><ul><li>Common Models: <strong>Doc2Vec</strong>, <strong>DPR (Dense Passage Retriever)</strong></li><li>Good for: Large-scale document similarity, classification</li></ul><h4>4.5. Multimodal Embeddings</h4><p>Maps images, audio, and text into the same vector space.</p><ul><li>Used in: <strong>CLIP</strong>, <strong>DALL·E</strong>, <strong>Flamingo</strong></li><li>Good for: Cross-modal search (e.g., image captioning, visual Q&amp;A)</li></ul><p>Each type of embedding plays a role in solving different real-world problems. Next, let’s get our hands dirty with a <strong>hands-on demo using LangChain and OpenAI embeddings</strong>.</p><h3>5. LangChain Embeddings (Hands-on with OpenAI &amp; Hugging Face)</h3><p>Let’s get practical! We’ll use <strong>LangChain</strong>, a framework that makes working with LLMs and vector stores incredibly simple. First, we’ll generate embeddings using <strong>OpenAI</strong> and <strong>Hugging Face</strong>, then compare them.</p><h4>5.1. Setup Environment</h4><p>Install dependencies and load your environment variables.</p><pre>pip install langchain-openai langchain-huggingface python-dotenv</pre><pre>import os<br>from dotenv import load_dotenv<br>load_dotenv()  # Load API keys from .env</pre><blockquote>Follow this guide to generate API keys: <a href="https://medium.com/@vamshiginna1606/api-key-setup-for-openai-groq-and-langsmith-in-your-projects-edf745e9507c">How to Set Up OpenAI, Groq, and LangSmith API Keys</a></blockquote><h4>5.2. OpenAI Embeddings with LangChain</h4><pre>from langchain_openai import OpenAIEmbeddings<br><br>embeddings = OpenAIEmbeddings(model=&quot;text-embedding-3-large&quot;)<br>text = &quot;This is a blog post on vector embeddings.&quot;<br>embeddings_result = embeddings.embed_query(text)<br><br>print(f&quot;Length: {len(embeddings_result)}&quot;)<br>print(f&quot;Type: {type(embeddings_result)}&quot;)</pre><p>Output:</p><pre>Length: 3072<br>Type: &lt;class &#39;list&#39;&gt;</pre><ul><li>Same vector length for any input text</li><li>Perfect for semantic search or vector similarity</li></ul><h4>5.3. Dimension Reduction (Optional)</h4><p>You can reduce dimensions using LangChain’s built-in config:</p><pre>embeddings = OpenAIEmbeddings(model=&quot;text-embedding-3-large&quot;, dimensions=1024)</pre><p>You’ll lose some granularity, but it helps with storage and speed.</p><h4>5.4. Hugging Face Embeddings (Open Source)</h4><p>You can create a free account on Hugging Face and generate a new access key under settings and include that key in your .env file as <em>HF_TOKEN=hf_vCixxxxxxxxxxxxxxxxxxxxx</em></p><pre>from langchain_huggingface import HuggingFaceEmbeddings<br><br>embeddings = HuggingFaceEmbeddings(model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)<br>text = &quot;This is a blog post on vector embeddings.&quot;<br>embeddings_result = embeddings.embed_query(text)<br><br>print(f&quot;Length: {len(embeddings_result)}&quot;)</pre><ul><li>Output: 384-dimensional vector</li><li>Free to use, great for local testing</li><li>Good balance of speed and quality</li></ul><h3>6. Understanding Embedding Vector Properties</h3><p>Now that we’ve generated embeddings using LangChain, let’s unpack what these vectors actually mean and how they’re used in real-world applications.</p><h4>6.1. Fixed Length, High Dimensions</h4><p>Each model generates a vector of a <strong>fixed length</strong> regardless of input length:</p><ul><li>OpenAI (text-embedding-3-large) → 3072 dimensions</li><li>Hugging Face (MiniLM-L6-v2) → 384 dimensions</li></ul><p>This uniformity allows easy comparison and storage of diverse text inputs.</p><h4>6.2. Embeddings as Feature Representations</h4><p>Each element in the vector can be thought of as representing a <strong>latent feature</strong> of the text — like tone, topic, syntax, or sentiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*Jw4-wiq53fZsdZQ9" /></figure><pre>print(type(embeddings_result))  # &lt;class &#39;list&#39;&gt;<br>print(len(embeddings_result))   # 3072 or 384</pre><p>These features are learned from vast datasets and compressed into a space where similar meanings are <strong>closer together</strong>.</p><h4>6.3. Dimensionality Reduction (Optional but Useful)</h4><p>To improve speed and efficiency (e.g., on mobile or in-memory apps), you can reduce the vector dimensions without much loss in accuracy.</p><pre>embeddings = OpenAIEmbeddings(model=&quot;text-embedding-3-large&quot;, dimensions=1024)</pre><blockquote>Tip: This is useful when comparing vectors from different models or embedding multiple sentences in a lightweight application.</blockquote><h4>6.4. Use Case: Semantic Comparison</h4><p>You can now apply similarity metrics to compare how close two vectors are:</p><pre>from sklearn.metrics.pairwise import cosine_similarity<br>from sklearn.metrics.pairwise import euclidean_distances<br><br>documents = [<br>    &quot;What is the capital of USA?&quot;,<br>    &quot;Who is the president of USA?&quot;,<br>    &quot;Who is the Prime Minister of India?&quot;,<br>]<br><br>my_query = &quot;Narendra Modi is the Prime Minister of India.&quot;<br>query_embedding = embeddings.embed_query(my_query<br><br>documents_embeddings = embeddings.embed_documents(documents)<br><br>cosine_similarity([query_embedding], documents_embeddings)<br><br>#output: array([[0.13519943, 0.28759853, 0.729995  ]])<br><br>euclidean_distances([query_embedding], documents_embeddings)<br>#output: array([[1.31514299, 1.19365109, 0.73485375]])<br></pre><ul><li><strong>Cosine Similarity</strong> → Measures angle (good for text)</li><li><strong>Euclidean Distance</strong> → Measures absolute distance (less common in NLP)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*y7dlnXhXjhT3WO2t9ZyRFg.png" /></figure><p>Next up: we’ll explore the <strong>difference between vector databases and traditional databases</strong>, and why you need a specialized system to handle embeddings efficiently.</p><h3>7. Vector Databases vs SQL/NoSQL Databases</h3><p>Traditional databases (SQL or NoSQL) are great at storing and retrieving structured data like numbers, strings, and relationships. But when it comes to <strong>semantic search or similarity search</strong>, they fall short.</p><p>That’s where <strong>Vector Databases</strong> come in.</p><h4>7.1. Traditional Databases</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*9uHb_WLiciKZSVrITLAmfA.png" /></figure><p>These systems store <strong>structured</strong> or <strong>semi-structured</strong> data using tables or JSON-like documents. But they can’t perform vector similarity operations like cosine similarity natively.</p><h4>7.2. Vector Databases</h4><p>Vector DBs store <strong>embeddings</strong> and allow efficient <strong>nearest-neighbor search</strong>. They are optimized for:</p><ul><li><strong>Semantic search</strong></li><li><strong>Recommendation engines</strong></li><li><strong>Clustering and anomaly detection</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*YIiAq2A7fOtZEjsKel5Z1Q.png" /></figure><h4>7.3. Why Use a Vector DB?</h4><ol><li><strong>Fast Similarity Search</strong><br> Use approximate nearest neighbor (ANN) algorithms like HNSW or IVF for millisecond-level retrieval.</li><li><strong>Metadata Filtering</strong><br> Combine similarity with filters like price range, category, tags, etc.</li><li><strong>Scalable &amp; Distributed</strong><br> Cloud vector DBs scale to millions of records.</li></ol><h3>8. Indexing &amp; Similarity Search in Vector Databases</h3><p>Vector search isn’t just about comparing every vector to every other one — that would be too slow. Instead, vector databases use <strong>indexing</strong> techniques to make similarity search lightning-fast and scalable.</p><h4>8.1. What Is a Vector Index?</h4><p>An <strong>index</strong> is a data structure that enables fast search over a collection of vectors. Without it, every search would require comparing a query to every item in the database (O(n) time).</p><h4>8.2. Types of Vector Indexes</h4><h4>8.2.1 Flat Index (Brute Force)</h4><ul><li>Checks similarity against every stored vector</li><li>Accurate, but slow for large datasets</li><li>Best for small datasets or testing</li></ul><pre># FAISS flat index<br>import faiss<br>index = faiss.IndexFlatL2(384)  # For 384-dimensional vectors<br>index.add(embedding_matrix)</pre><h4>8.2.2. HNSW (Hierarchical Navigable Small World)</h4><ul><li>Graph-based structure</li><li>Very fast and scalable</li><li>️ Slightly approximate, but high accuracy</li></ul><blockquote><em>Used in Weaviate, Qdrant, and FAISS with </em><em>IndexHNSWFlat</em></blockquote><h4>8.2.3. IVF (Inverted File Index)</h4><ul><li>Clusters vectors into groups (like k-means)</li><li>First searches in a few clusters</li><li>Faster, but needs training and tuning</li></ul><blockquote><em>Used in FAISS with </em><em>IndexIVFFlat</em></blockquote><h4>8.4. Similarity Metrics</h4><ul><li><strong>Cosine Similarity</strong> → Best for text</li><li><strong>Euclidean Distance</strong> → Good for spatial data</li><li><strong>Dot Product</strong> → Used in some deep learning models</li></ul><pre>from sklearn.metrics.pairwise import cosine_similarity<br>cosine_similarity([query_vector], [doc_vector])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*fTP9DL_OKynWzteATPiBVw.png" /></figure><p>Next up, let’s implement a <strong>simple FAISS-powered search system</strong></p><h3>9. Mini Project: Semantic Search using LangChain + OpenAI + FAISS</h3><p>Let’s build a <strong>search interface</strong> where a user types a query, and the app returns the most semantically similar sentence from a small dataset using embeddings and FAISS.</p><p>This mini-project shows how to:</p><ol><li>Convert text into embeddings using OpenAI via LangChain</li><li>Store them in a FAISS vector index</li><li>Perform a similarity search</li></ol><h4>Step 1: Setup</h4><p>Install required libraries:</p><pre>pip install langchain faiss-cpu openai python-dotenv</pre><p>Set up your .env:</p><pre>OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxx</pre><h4>Step 2: Import and Load API Key</h4><pre>import os<br>from dotenv import load_dotenv<br>from langchain_openai import OpenAIEmbeddings<br><br>load_dotenv()<br>embeddings = OpenAIEmbeddings(model=&quot;text-embedding-3-large&quot;)</pre><h4>Step 3: Create Your Corpus</h4><pre>documents = [<br>    &quot;Artificial Intelligence is the simulation of human intelligence by machines.&quot;,<br>    &quot;Machine learning is a field of AI that uses statistical techniques.&quot;,<br>    &quot;Embeddings convert natural language to numerical vectors.&quot;,<br>    &quot;OpenAI develops powerful language models like GPT-4.&quot;,<br>    &quot;FAISS is a library for efficient similarity search and clustering of dense vectors.&quot;<br>]</pre><h4>Step 4: Generate Embeddings</h4><pre><br>#Use either one of the below<br><br>#simple approach <br>embedded_docs = [embeddings.embed_query(doc) for doc in documents]<br><br>#Optimal approach<br>#embedded_docs= embeddings.embed_documents(documents)</pre><h4>Step 5: Store in FAISS and Query</h4><pre># Import FAISS library for efficient similarity search and clustering of dense vectors<br>import faiss<br><br># Import FAISS vector store implementation from LangChain community<br>from langchain_community.vectorstores import FAISS<br><br># Import in-memory document store for storing documents alongside their embeddings<br>from langchain_community.docstore.in_memory import InMemoryDocstore<br><br>#length of the embedding vector<br>embedding_dim = len(embeddings.embed_query(&quot;hello world&quot;))<br><br># Create a new FAISS index for L2 (Euclidean) distance with the specified embedding dimension<br>faiss_index = faiss.IndexFlatL2(embedding_dim)<br><br># Create a FAISS vector store using the specified embedding function, FAISS index, and in-memory docstore.<br># This will allow efficient similarity search over embedded documents.<br>FAISS_vector_store = FAISS(<br>    embedding_function=embeddings,<br>    index=faiss_index,<br>    docstore=InMemoryDocstore(),<br>    index_to_docstore_id={},<br>)</pre><p>Now, embed the user query and perform a search:</p><pre>FAISS_vector_store.add_texts(documents)<br><br># Perform a similarity search in the FAISS vector store.<br># This will return the top 2 most similar documents to the query &quot;What is the future of AI?&quot;<br>results = FAISS_vector_store.similarity_search(<br>    &quot;What is FAISS used for?&quot;,<br>    k=2<br>)</pre><h4>6. Output Example</h4><pre>Best Match: FAISS is a library for efficient similarity search and clustering of dense vectors.</pre><p>With less than 50 lines of code, you’ve built a fully functional semantic search system!</p><h3>10. Use Cases &amp; Applications of Embeddings</h3><p>Embeddings are not just a buzzword — they power some of the most useful features in modern AI systems. Here are some practical, real-world applications:</p><h4>1. Semantic Search</h4><p>Search results based on <strong>meaning</strong>, not exact keywords.</p><p><strong>Example:</strong></p><ul><li>Query: “How to build neural networks?”</li><li>Matches: “Guide to deep learning architectures” instead of only exact keyword hits.</li></ul><h4>2. Recommendation Systems</h4><p>Find similar items, products, or content by comparing embedding vectors.</p><p><strong>Example:</strong></p><ul><li>Users who viewed this article also liked…</li><li>Movie, book, or product similarity</li></ul><h4>3. Chatbots &amp; RAG Applications</h4><p>Use vector search to retrieve the most relevant context for large language models (LLMs).</p><p><strong>Example:</strong></p><ul><li>LangChain’s Retrieval-Augmented Generation (RAG)</li><li>Customer support bots that pull from internal docs</li></ul><h4>4. Text Clustering &amp; Classification</h4><p>Group similar texts (e.g., reviews, tickets, tweets) without explicit labels.</p><p><strong>Example</strong>:</p><ul><li>Grouping feedback into themes</li><li>Spam vs. not spam</li></ul><h4>5. Anomaly Detection</h4><p>Identify data points that deviate from the norm using vector distance.</p><p><strong>Example:</strong></p><ul><li>Fraud detection</li><li>Outlier reviews or sensor readings</li></ul><h4>6. Personalization</h4><p>Use embeddings to personalize user feeds, content recommendations, or search results.</p><p><strong>Example:</strong></p><ul><li>Tailored course recommendations</li><li>Adaptive learning platforms</li></ul><h3>Conclusion &amp; Further Resources</h3><p>We’ve come a long way in this journey — from understanding what embeddings are to building a working semantic search system using OpenAI and LangChain.</p><h4>Recap</h4><ul><li>Embeddings convert text into meaningful numerical vectors.</li><li>They power everything from search engines and recommendation systems to LLM-based apps.</li><li>LangChain and FAISS make it easy to generate, store, and search embeddings efficiently.</li></ul><p>Whether you’re building a chatbot, smart search engine, or your next AI side project — <strong>embeddings are your foundation</strong>.</p><h4>Resources to Go Deeper</h4><p>🔗 <strong>Blog: LangChain Crash Course — Part 2: Build Your First RAG App</strong><br> <a href="https://medium.com/@vamshiginna1606/langchain-crash-course-part-2-build-your-first-rag-app-24908b14d337">Read it here</a></p><p>📚 <strong>LangChain Docs</strong>:<br> <a href="https://docs.langchain.com/">https://docs.langchain.com</a></p><p>📖 <strong>OpenAI Embedding API</strong>:<br> <a href="https://platform.openai.com/docs/guides/embeddings">https://platform.openai.com/docs/guides/embeddings</a></p><p>🧠 <strong>FAISS by Meta</strong>:<br> <a href="https://github.com/facebookresearch/faiss">https://github.com/facebookresearch/faiss</a></p><p>🆓 <strong>Hugging Face Embedding Models</strong>:<br> <a href="https://huggingface.co/sentence-transformers">https://huggingface.co/sentence-transformers</a></p><p>Thank you for reading!<br> If this helped you, feel free to share it and tag me on <a href="https://www.linkedin.com/in/vamshikrishnaginna/">LinkedIn </a>or <a href="https://medium.com/@vamshiginna1606">Medium</a>.<br> Happy embedding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5c56e6816cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain Crash Course — Part 2: Build Your First RAG App]]></title>
            <link>https://medium.com/@vamshiginna1606/langchain-crash-course-part-2-build-your-first-rag-app-24908b14d337?source=rss-5482f97f8048------2</link>
            <guid isPermaLink="false">https://medium.com/p/24908b14d337</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Vamshi Krishna Ginna]]></dc:creator>
            <pubDate>Sun, 25 May 2025 06:02:59 GMT</pubDate>
            <atom:updated>2025-05-25T06:02:59.132Z</atom:updated>
            <content:encoded><![CDATA[<h3>LangChain Crash Course — Part 2: Build Your First RAG App</h3><h3>1. Introduction: What is RAG (Retrieval-Augmented Generation)?</h3><p>Large Language Models (LLMs) like GPT-4 are incredibly powerful — but they have limitations. They don’t “know” your private data, they can hallucinate, and their training data is static. That’s where <strong>Retrieval-Augmented Generation (RAG)</strong> steps in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*izuEH_uV5X7dmUzj.jpg" /><figcaption>Image Source: <a href="https://d2908q01vomqb2.cloudfront.net/f1f836cb4ea6efb2a0b1b99f41ad8b103eff4b59/2024/06/06/ML-16629-rag-architecture-1.jpg">AWS Machine Learning Blog</a></figcaption></figure><h3>1.2. Motivation Behind RAG</h3><p>Imagine asking GPT-4:</p><blockquote><em>“Summarize my company’s internal strategy doc.”</em></blockquote><p>LLMs can’t help unless they’ve seen that document before. But with RAG, you can <strong>fetch relevant content</strong> (your own data!) and feed it to the model <em>on-the-fly</em> — like giving it a custom memory.</p><p>RAG helps you:</p><ul><li>Inject up-to-date, domain-specific knowledge</li><li>avoid hallucinations from model guesswork</li><li>Keep models lightweight while enabling deeper knowledHow LLMs + Context = Better Answers</li></ul><p>RAG is the backbone of many AI-powered apps — from PDF Q&amp;A bots and internal search tools to legal assistants and chatbots over private data.</p><h3>1.3. RAG vs Prompt Engineering vs Fine-Tuning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*ecINx6tAWVYFhmgSz0CDqw.png" /></figure><blockquote><em>🧠 </em><strong><em>RAG combines the flexibility of prompting with the specificity of fine-tuning — without retraining.</em></strong></blockquote><p>Learn the <a href="https://medium.com/@vamshiginna1606/langchain-crash-course-part-1-build-powerful-llm-apps-from-scratch-eba24b75b55c"><strong><em>LangChain Crash Course Part-1 — Build Powerful LLM Apps from Scratch</em></strong></a>, if you are just getting started.</p><h3>2. Document Loaders: Feeding Your LLM the Right Data</h3><p>To enable RAG, the first step is to <strong>load documents</strong> into LangChain from a variety of sources — text files, web pages, PDFs, databases, Notion, and more. These documents are then chunked, embedded, and stored for retrieval.</p><p>LangChain provides a wide range of <strong>document loaders</strong> that handle different formats, extract text, and capture metadata.</p><h3>2.1. Load a Simple Text File</h3><p>Let’s start with the most basic: loading a plain text file.</p><pre># Import the TextLoader class from langchain_community for loading text files<br>from langchain_community.document_loaders import TextLoader<br><br># Load a local .txt file using TextLoader<br>loader = TextLoader(&quot;speech.txt&quot;)<br><br># Load the document(s) from the file<br>text_document = loader.load()<br><br># Print the number of documents loaded<br>print(f&quot;Number of documents loaded: {len(text_document)}&quot;)<br><br># Iterate through each document and print a preview of its content and metadata<br>for doc in text_document:<br>    print(f&quot;Document content: {doc.page_content[:100]}...&quot;)  # Print first 100 characters<br>    print(f&quot;Metadata: {doc.metadata}&quot;)  # Shows filename and path</pre><p>You’ll get a list of Document objects, each containing the page_content and optional metadata.</p><h3>2.2. Load Web Pages with WebBaseLoader (another example)</h3><p>Want to load content from the internet? Use the WebBaseLoader, which supports BeautifulSoup for parsing HTML.</p><pre>from langchain_community.document_loaders import WebBaseLoader<br>import bs4<br><br># Initialize a WebBaseLoader to load and parse the Wikipedia page on Artificial Intelligence.<br># The bs_kwargs argument uses BeautifulSoup&#39;s SoupStrainer to only parse elements with the specified classes.<br>loader = WebBaseLoader(<br>    web_path=(&quot;https://en.wikipedia.org/wiki/Artificial_intelligence&quot;,),<br>    bs_kwargs=dict(parse_only=bs4.SoupStrainer(class_=(&quot;mw-heading mw-heading3&quot;, &quot;mw-default-size&quot;)))<br>)<br><br># Load the documents from the web page using the loader<br>docs = loader.load()<br><br># Print the number of documents loaded from the web page<br>print(f&quot;Loaded {len(docs)} web-based documents.&quot;)</pre><p>This is great for scraping structured articles or blog content dynamically into your RAG system.</p><h3>2.3. Other Popular Document Loaders</h3><p>LangChain supports dozens of sources. Some popular ones include:</p><ul><li><strong>PDFs</strong>: PyPDFLoader, PDFMinerLoader</li><li><strong>Notion</strong>: NotionDBLoader, NotionDirectoryLoader</li><li><strong>CSV</strong>: CSVLoader, UnstructuredCSVLoader</li><li><strong>Google Drive / Docs</strong>: GDriveLoader, GDocsLoader</li><li><strong>Markdown / HTML</strong>: UnstructuredMarkdownLoader, BSHTMLLoader</li></ul><p>Explore the full list of loaders here:<br> 👉 <a href="https://python.langchain.com/docs/integrations/document_loaders/">https://python.langchain.com/docs/integrations/document_loaders/</a></p><p>Next, we’ll learn how to <strong>split these documents into smaller chunks</strong> using LangChain’s TextSplitter—a key step before embedding and storing in a vector database.</p><h3>3. Text Splitters: Prepping Documents for the LLM Brain</h3><p>Once your documents are loaded, the next step is <strong>splitting</strong> them into smaller, digestible chunks. Why? Because LLMs have context length limits, and feeding them large documents at once isn’t practical or efficient.</p><p>This process is called <strong>chunking</strong> — breaking documents into smaller overlapping sections so that each chunk carries meaningful information on its own.</p><h3>Key Concepts</h3><ul><li><strong>Chunk Size</strong>: How many characters (or tokens) each chunk contains. Larger chunks give more context, but can hit token limits.</li><li><strong>Chunk Overlap</strong>: How much content is repeated between chunks. Useful to maintain continuity, especially at chunk boundaries.</li></ul><blockquote><em>🧠 Best practice: Keep </em><em>chunk_size between </em><strong><em>300–1000</em></strong><em> and </em><em>chunk_overlap between </em><strong><em>10–20%</em></strong><em> of the chunk size.</em></blockquote><h3>3.1. Recursive Character Splitter (Recommended)</h3><p>This is the <strong>default and recommended splitter</strong> for unstructured text.</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter<br><br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=200)<br>split_docs = text_splitter.split_documents(pdf_document)</pre><h4>How It Works:</h4><ul><li><strong>Splitting logic</strong>: It tries to split the document using a list of characters in priority: [&quot;\n\n&quot;, &quot;\n&quot;, &quot; &quot;, &quot;&quot;] This means it first tries to split by paragraphs, then by lines, then by spaces, and finally character-by-character as a last resort.</li><li><strong>Chunk size is measured by</strong>: number of characters.</li><li><strong>Goal</strong>: Keep semantically related pieces (like paragraphs and sentences) together as long as possible.</li></ul><pre>print(f&quot;Generated {len(split_docs)} chunks&quot;)<br>for chunk in split_docs[:2]:<br>    print(chunk.page_content[:200])</pre><h3>3.2. Structured Data? Try Recursive JSON Splitter</h3><p>LangChain also supports structured splitting for formats like nested JSON (e.g., chat logs, product catalogs).</p><pre>from langchain_text_splitters import RecursiveJsonSplitter<br><br>json_splitter = RecursiveJsonSplitter(max_chunk_size=300)<br>json_chunks = json_splitter.split_json(json_data)<br><br>print(f&quot;Total JSON chunks: {len(json_chunks)}&quot;)</pre><p>LangChain provides a wide range of text splitters for specific file types and formats — Markdown, CSV, HTML, JSON, and more.<br> 🔗 Dive deeper: <a href="https://python.langchain.com/docs/concepts/text_splitters/">https://python.langchain.com/docs/concepts/text_splitters/</a></p><p>Next up: Let’s convert these chunks into <strong>vector embeddings</strong> and store them in a vector database for fast semantic search.</p><h3>4. Embeddings &amp; Vector Stores: Giving AI a Memory</h3><p>Once documents are split into meaningful chunks, the next step is to <strong>convert them into vector embeddings</strong> — numerical representations that capture the <em>semantic meaning</em> of each chunk.</p><p>These embeddings are then stored in a <strong>vector database</strong> like <strong>FAISS</strong>, <strong>Chroma</strong>, or <strong>Pinecone</strong>, allowing you to retrieve the most relevant chunks based on a user’s query.</p><p><strong><em>Note: You can refer this blog to gather and setup the required env vars: </em></strong><a href="http://API Key Setup for OpenAI, Groq, and Langsmith in Your Projects"><strong><em>API Key Setup for OpenAI, Groq, and Langsmith in Your Projects</em></strong></a></p><h3>4.1. What Are Embeddings?</h3><p>Embeddings are high-dimensional vectors (lists of numbers) generated by models like OpenAI’s text-embedding-3-small. These vectors allow semantic similarity comparisons between questions and documents.</p><blockquote><em>Example: “What is AI?” will be close in vector space to “Definition of artificial intelligence.”</em></blockquote><h3>4.2. Generate Embeddings with OpenAI</h3><p>Since your environment is configured with a valid OPENAI_API_KEY, you can use this out of the box:</p><pre># Import the OpenAIEmbeddings class from langchain_openai<br>from langchain_openai import OpenAIEmbeddings<br><br># Initialize the OpenAIEmbeddings model for generating text embeddings<br>embedding_model = OpenAIEmbeddings()</pre><p>Then embed the split documents like this:</p><pre>from langchain.vectorstores import FAISS<br><br># Create a FAISS vector store (index) from the split PDF document chunks<br># This will embed each chunk using the embedding_model and store them for efficient similarity search<br>vectorstore = FAISS.from_documents(split_docs, embedding_model)</pre><p>Now your vector store is ready to retrieve the most relevant chunks for any query.</p><h3>4.3. Query the Vector Store</h3><pre>query = &quot;What is the purpose of the speech?&quot;<br>docs = vectorstore.similarity_search(query, k=3)<br><br>for i, doc in enumerate(docs):<br>    print(f&quot;\nTop Match {i+1}:\n{doc.page_content[:200]}...&quot;)</pre><p>This will return the top k chunks that are semantically closest to the user’s query using cosine similarity.</p><h3>4.4. Popular Vector Store Options</h3><p>Vector StoreNotes<strong>FAISS</strong>Fast and free for local development <strong>Chroma </strong>Python-native, fast, easy to use <strong>Pinecone </strong>Scalable, production-ready cloud option <strong>Weaviate / Qdrant</strong>Great for hybrid search (metadata + vector)</p><p><strong>Want to dive deeper?</strong> <a href="https://python.langchain.com/docs/modules/data_connection/vectorstores/">https://python.langchain.com/docs/modules/data_connection/vectorstores/</a></p><h3>5. Semantic Search (Retrievers): Finding What Matters</h3><p>Now that your documents are embedded and stored in a vector database, it’s time to <strong>retrieve the most relevant chunks</strong> based on user input. This process is known as <strong>semantic search</strong>, and it’s what makes Retrieval-Augmented Generation (RAG) so powerful.</p><p>LangChain uses <strong>retrievers</strong> to abstract this logic.</p><h3>5.1. What is a Retriever?</h3><p>A <strong>retriever</strong> is a wrapper around your vector store (like FAISS or Chroma) that provides a standard interface to search for relevant document chunks.</p><p>It helps answer:</p><blockquote><em>“Which pieces of my data are most relevant to the current query?”</em></blockquote><h3>5.2. Create a Retriever from Your Vector Store</h3><p>If you’re using FAISS:</p><pre># Create a retriever from the FAISS vectorstore using similarity search with top 3 results<br>retriever = vectorstore.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;: 3})</pre><p>You can now use this retriever directly:</p><pre><br># Retrieve the most relevant documents for the given query<br>docs = retriever.get_relevant_documents(&quot;What was the speaker&#39;s main message?&quot;)<br><br># Print the first 200 characters of each retrieved document<br>for i, doc in enumerate(docs):<br>    print(f&quot;\nRetrieved Doc {i+1}:\n{doc.page_content[:200]}...&quot;)</pre><h3>5.3. Search Types in LangChain</h3><p>Search TypeDescriptionsimilarityDefault — uses cosine similaritymmrMaximum marginal relevance — promotes diversitysimilarity_score_thresholdOnly returns documents above a certain score</p><p>You can tune your retrieval method depending on your use case: <strong>focus vs. diversity</strong>.</p><h3>🧠 Bonus: Metadata Filtering</h3><p>You can filter retrieved documents by metadata:</p><pre>retriever = vectorstore.as_retriever(<br>    search_kwargs={&quot;k&quot;: 5, &quot;filter&quot;: {&quot;source&quot;: &quot;speech.txt&quot;}}<br>)</pre><p>This is great for applications with mixed data types (e.g., PDFs, websites, notes).</p><p>📚 <strong>Want to go deeper into retrievers?</strong><br> 🔗 <a href="https://python.langchain.com/docs/integrations/retrievers/">LangChain Retriever Integrations</a></p><h3>6. Summarization / Chain on Retrieved Docs</h3><p>You’ve successfully retrieved the most relevant pieces of information — now it’s time to <strong>process those chunks with an LLM</strong> to generate answers, insights, or summaries.</p><p>LangChain provides several <strong>document chain types</strong> to help you structure this interaction.</p><h3>6.1. Use Case: “Read and respond intelligently to these documents”</h3><p>This is the core of a <strong>RAG pipeline</strong>:</p><blockquote><strong><em>Retrieve relevant context → Pass to LLM → Generate final output</em></strong></blockquote><h3>6.2. Types of Document Chains</h3><p>LangChain offers three common patterns for chaining retrieved documents to a language model:</p><p>Chain TypeBest ForStuffDocumentsChainSmall docs that fit in a single promptMapReduceChainLarge docs that need chunk-level processing and combiningRefineDocumentsChainIterative refinement and updating answers</p><h3>6.3. Example: Use StuffDocumentsChain</h3><p><em>Note: Replace the query according to the content present in your speech.txt file</em></p><pre># Import necessary classes for prompt, LLM, and output parsing<br>from langchain.prompts import PromptTemplate<br>from langchain_openai import ChatOpenAI<br>from langchain_core.output_parsers import StrOutputParser<br><br># Step 1: Create the prompt template for Retrieval-Augmented Generation (RAG)<br>prompt = PromptTemplate.from_template(<br>    &quot;Given the context below, answer the user&#39;s question:\n\n{context}\n\nQuestion: {question}&quot;<br>)<br><br># Step 2: Initialize the ChatOpenAI LLM with the specified model<br>llm = ChatOpenAI(model=&quot;gpt-4o&quot;)<br><br># Step 3: Create an output parser to extract the string response from the LLM output<br>output_parser = StrOutputParser()<br><br># Step 4: Combine the prompt, LLM, and output parser into a runnable chain<br>chain_with_parser = prompt | llm | output_parser<br><br># Step 5: Prepare the context by joining the content of the retrieved documents<br>context = &quot;\n\n&quot;.join(doc.page_content for doc in docs)<br><br># Step 6: Invoke the chain with the context and the user&#39;s question<br>response = chain_with_parser.invoke({<br>    &quot;context&quot;: context,<br>    &quot;question&quot;: &quot;What is the main argument of the speech?&quot;<br>})<br><br># Print the response from the LLM<br>print(response)</pre><p>This simple chain takes all retrieved documents, stuffs them into a single prompt, and lets the LLM respond.</p><p>Now that your RAG pipeline is functional from <strong>Load → Chunk → Embed → Retrieve → Answer</strong>, it’s time to <strong>combine everything into a cohesive app</strong>.</p><p>Let’s build a working <strong>RAG demo!</strong></p><h3>7. Putting It All Together: Build a Basic RAG App</h3><p>Let’s connect all the pieces you’ve learned — document loading, chunking, embedding, retrieval, and summarization — into a single working <strong>Retrieval-Augmented Generation (RAG) application</strong>.</p><p>This will be a simple, modular pipeline to answer questions from a local text document or webpage using OpenAI and LangChain.</p><h3>7.1. What We’ll Build</h3><p>A <strong>Q&amp;A system</strong> that:</p><ol><li>Loads a document (speech.txt)</li><li>Splits it into chunks</li><li>Converts chunks into vector embeddings</li><li>Stores them in a FAISS vector store</li><li>Retrieves relevant chunks based on a user query</li><li>Feeds those chunks to an LLM to generate an answer</li></ol><h3>7.2. Final Integrated Code</h3><pre><br># Retrieval-Augmented Generation (RAG) Full Pipeline Example<br><br># 1. Load the text document<br>from langchain_community.document_loaders import TextLoader<br>loader = TextLoader(&quot;speech.txt&quot;)<br>documents = loader.load()<br>print(f&quot;Loaded {len(documents)} document(s).&quot;)<br>for doc in documents:<br>    print(f&quot;Preview: {doc.page_content[:100]}...&quot;)  # Show first 100 chars<br><br><br><br># 2. Split the document into chunks<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)<br>split_docs = text_splitter.split_documents(documents)<br>print(f&quot;Split into {len(split_docs)} chunks.&quot;)<br><br><br><br># 3. Create embeddings and vector store<br>from langchain_openai import OpenAIEmbeddings<br>from langchain.vectorstores import FAISS<br>embedding_model = OpenAIEmbeddings()<br>vectorstore = FAISS.from_documents(split_docs, embedding_model)<br>print(&quot;Vector store created.&quot;)<br><br><br><br># 4. Create a retriever for similarity search<br>retriever = vectorstore.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;: 3})<br><br><br><br># 5. Retrieve relevant chunks for a query<br>query = &quot;What was the main message of the speech?&quot;<br>retrieved_docs = retriever.get_relevant_documents(query)<br>print(f&quot;Retrieved {len(retrieved_docs)} relevant document(s):&quot;)<br>for i, doc in enumerate(retrieved_docs):<br>    print(f&quot;\nChunk {i+1} preview:\n{doc.page_content[:200]}...&quot;)<br><br><br><br># 6. Set up the prompt and LLM for answer generation<br>from langchain.prompts import PromptTemplate<br>from langchain_openai import ChatOpenAI<br>from langchain_core.output_parsers import StrOutputParser<br><br>prompt = PromptTemplate.from_template(<br>    &quot;Given the context below, answer the user&#39;s question:\n\n{context}\n\nQuestion: {question}&quot;<br>)<br>llm = ChatOpenAI(model=&quot;gpt-4o&quot;)<br>output_parser = StrOutputParser()<br><br><br><br># 7. Prepare the context and run the RAG chain<br>context = &quot;\n\n&quot;.join(doc.page_content for doc in retrieved_docs)<br>chain_with_parser = prompt | llm | output_parser<br><br>response = chain_with_parser.invoke({<br>    &quot;context&quot;: context,<br>    &quot;question&quot;: query<br>})<br><br>print(&quot;\nFinal Answer:&quot;)<br>print(response)<br></pre><h3>7.3. Output Example (will based on your content on speech.txt)</h3><pre>Final Answer:<br>The speech emphasized unity, resilience, and a collective vision for national progress.</pre><p>This is your <strong>basic working RAG app</strong> — a complete loop from unstructured data to structured answers using LangChain.</p><h3>8. Conclusion: You’ve Built Your First RAG App with LangChain!</h3><p>Congratulations! 🎉 In this second part of the crash course, you’ve gone beyond basic LLM usage and built a fully functional <strong>Retrieval-Augmented Generation (RAG)</strong> pipeline using LangChain and OpenAI.</p><p>Here’s a quick recap of what you accomplished:</p><p>✅ Loaded documents from text and web sources<br> ✅ Split them into context-aware chunks<br> ✅ Generated vector embeddings using OpenAI<br> ✅ Stored and searched them via a vector database (FAISS)<br> ✅ Retrieved relevant context and used LLMs to answer queries<br> ✅ Built a modular, scalable RAG app end-to-end</p><p><strong>Missed Part 1?</strong> Start here:<br> 👉 <a href="https://medium.com/@vamshiginna1606/langchain-crash-course-part-1-build-powerful-llm-apps-from-scratch-eba24b75b55c">LangChain Crash Course — Part 1</a></p><p><strong>Explore loaders, splitters, and retrievers further</strong>:<br> 📂<a href="https://python.langchain.com/docs/integrations/document_loaders/"> Document Loader</a>s<br> ✂️<a href="https://python.langchain.com/docs/concepts/text_splitters/"> Text Splitter</a>s<br> 🔍<a href="https://python.langchain.com/docs/integrations/retrievers/"> Retriever</a>s</p><p>Thanks for following along. Feel free to share your RAG apps and tag me on LinkedIn!</p><p>👉 <a href="https://www.linkedin.com/in/vamshikrishnaginna/">Let’s Connect</a><br> 🚀 Keep building. Keep learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24908b14d337" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain Crash Course Part-1 — Build Powerful LLM Apps from Scratch]]></title>
            <link>https://medium.com/@vamshiginna1606/langchain-crash-course-part-1-build-powerful-llm-apps-from-scratch-eba24b75b55c?source=rss-5482f97f8048------2</link>
            <guid isPermaLink="false">https://medium.com/p/eba24b75b55c</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[genarative-ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Vamshi Krishna Ginna]]></dc:creator>
            <pubDate>Sat, 24 May 2025 06:15:32 GMT</pubDate>
            <atom:updated>2025-05-24T06:15:32.240Z</atom:updated>
            <content:encoded><![CDATA[<h3>LangChain Crash Course Part-1 — Build Powerful LLM Apps from Scratch</h3><h3>1. Introduction: Why LangChain?</h3><p>The explosion of large language models (LLMs) like GPT-4 and Claude has opened doors to building intelligent apps — from AI assistants to code generators and research bots. But there’s a catch: working directly with these models is messy. You juggle prompts, manage memory, call APIs, and stitch tools together manually.</p><p>That’s where <strong>LangChain</strong> comes in.</p><p>LangChain is a <strong>framework designed to streamline LLM app development</strong>. Think of it as the “backend SDK” for language-based applications. It abstracts away the plumbing — prompt management, tool usage, memory handling, and chaining tasks — so you can focus on <em>what</em> your app should do, not <em>how</em> it does it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*XWsBjgG4ymzW-PtC" /></figure><h3>⚡ Why LangChain?</h3><ul><li><strong>Modularity:</strong> Combine LLMs with tools, APIs, databases, and memory modules like LEGO blocks.</li><li><strong>Ease of Prototyping:</strong> Build and test ideas quickly with LLMChain, AgentExecutor, and PromptTemplates.</li><li><strong>Production Ready:</strong> Integrates with tracing tools like <strong>LangSmith</strong> and supports OpenAI, Claude, Groq, and more.</li><li><strong>Future-Proof:</strong> Supports agentic workflows, retrieval-augmented generation (RAG), and tool-using agents.</li></ul><p>Whether you’re building a chatbot, data analyst, email summarizer, or autonomous agent — LangChain gives you the building blocks to go from idea 💡 to app faster than ever.</p><h3>2. Environment Setup</h3><p>Before we dive into building awesome apps, let’s set up your playground. You’ll need Python, a virtual environment, and API keys to get started with LangChain.</p><h3>2.1. Create a Virtual Environment</h3><p>Open your terminal and run:</p><pre>python -m venv langchain_env<br>source langchain_env/bin/activate  # On Windows: langchain_env\\Scripts\\activate</pre><p>This keeps dependencies isolated and clean. Learn more about virtual environment here: <a href="https://medium.com/@vamshiginna1606/conda-commands-you-should-know-create-manage-activate-python-environments-like-a-pro-7d67e427af65"><strong><em>Conda Commands You Should Know: Create, Manage &amp; Activate Python Environments Like a Pro</em></strong></a></p><h3>2.2. Create requirements.txt</h3><p>Copy the below into a requirements.txt file:</p><pre>langchain<br>langchain-openai<br>langchain-groq<br>langchain-community<br>langchain-core<br>pydantic<br>python-dotenv</pre><p>Now install all at once:</p><pre>pip install -r requirements.txt</pre><h3>2.3. Set Up API Keys with .env</h3><p>Create a .env file in your root directory with the following:</p><pre>OPENAI_API_KEY=sk-...<br>GROQ_API_KEY=gsk-...<br>LANGCHAIN_API_KEY=lsv2-...edw</pre><p>Learn more about how to gather API keys here: <a href="https://medium.com/@vamshiginna1606/api-key-setup-for-openai-groq-and-langsmith-in-your-projects-edf745e9507c"><strong><em>API Key Setup for OpenAI, Groq, and Langsmith in Your Projects</em></strong></a></p><blockquote><em>Use </em><a href="https://pypi.org/project/python-dotenv/"><em>python-dotenv</em></a><em> to load these into your app securely</em></blockquote><h3>2.4. Test Your Setup</h3><p>Let’s create an file langchain_crash_course.ipynb</p><pre>import os #import os for environment variables<br>from dotenv import load_dotenv #to load the environment variables from .env file<br><br>load_dotenv()<br><br><br>#now how to use the environment variables so that keys are loaded from .env file to this environment<br># os.environ[&#39;MY_ENV_VAR&#39;] = os.getenv(&#39;MY_ENV_VAR&#39;, &#39;default_value&#39;)<br><br>os.environ[&#39;GROQ_API_KEY&#39;] = os.getenv(&#39;GROQ_API_KEY&#39;)    # you can also direct assign API key here if you want<br>os.environ[&#39;OPENAI_API_KEY&#39;] = os.getenv(&#39;OPENAI_API_KEY&#39;)<br><br>##Langsmith tracking and tracing<br>os.environ[&#39;LANG_SMITH_API_KEY&#39;] = os.getenv(&#39;LANG_SMITH_API_KEY&#39;)<br>os.environ[&#39;LANGCHAIN_PROJECT&#39;] = os.getenv(&#39;LANGCHAIN_PROJECT&#39;, &#39;Agentic2.0&#39;)<br><br>## Another key is given my langchain<br>os.environ[&quot;LANGCHAIN_TRACING_V2&quot;]=&quot;true&quot;  # enables LangChain&#39;s Tracing V2, a feature designed to help developers debug<br><br></pre><pre>from langchain_openai import ChatOpenAI<br><br>llm = ChatOpenAI()<br>llm.invoke(&quot;Hello, world!&quot;)</pre><p>If you see a response something like below , you’re all set!</p><pre>AIMessage(content=&#39;Hello! How can I assist you today?&#39;, additional_kwargs={&#39;refusal&#39;: None}, response_metadata={&#39;token_usage&#39;: {&#39;completion_tokens&#39;: 9, &#39;prompt_tokens&#39;: 11, &#39;total_tokens&#39;: 20, &#39;completion_tokens_details&#39;: {&#39;accepted_prediction_tokens&#39;: 0, &#39;audio_tokens&#39;: 0, &#39;reasoning_tokens&#39;: 0, &#39;rejected_prediction_tokens&#39;: 0}, &#39;prompt_tokens_details&#39;: {&#39;audio_tokens&#39;: 0, &#39;cached_tokens&#39;: 0}}, &#39;model_name&#39;: &#39;gpt-3.5-turbo-0125&#39;, &#39;system_fingerprint&#39;: None, &#39;id&#39;: &#39;chatcmpl-Baa6mm1iOXiU5XYRFTyw49Ceqhpsg&#39;, &#39;service_tier&#39;: &#39;default&#39;, &#39;finish_reason&#39;: &#39;stop&#39;, &#39;logprobs&#39;: None}, id=&#39;run--b0ec067e-e343-46e6-ad3e-590fc0cb2067-0&#39;, usage_metadata={&#39;input_tokens&#39;: 11, &#39;output_tokens&#39;: 9, &#39;total_tokens&#39;: 20, &#39;input_token_details&#39;: {&#39;audio&#39;: 0, &#39;cache_read&#39;: 0}, &#39;output_token_details&#39;: {&#39;audio&#39;: 0, &#39;reasoning&#39;: 0}})</pre><p>Next, we’ll explore LangChain’s <strong>core building blocks</strong> — Chains, Tools, Agents, and more. Ready to build? Let’s go!</p><h3>3. LangChain Core Concepts</h3><p>LangChain is powerful because it breaks complex LLM applications into small, composable pieces. Here are the essential building blocks every beginner should know:</p><h3>3.1. Chains</h3><p>Chains are the simplest unit in LangChain. A <strong>Chain</strong> connects inputs → LLM → outputs.</p><ul><li>Most common: LLMChain</li><li>Uses a PromptTemplate to format input and send it to an LLM.</li></ul><pre><br>from langchain_openai import ChatOpenAI # this is like a wrapper for OpenAI&#39;s API to call any openai models<br>from langchain_core.prompts import ChatPromptTemplate # Importing ChatPromptTemplate to create a prompt template for the chat model<br><br><br># Initialize the ChatOpenAI model with your desired parameters<br>llm= ChatOpenAI(model=&quot;gpt-4o&quot;)<br><br>prompt = ChatPromptTemplate.from_messages(<br>    [<br>        (&quot;system&quot;, &quot;You are an expert AI Engineer. Answer the question to the best of your ability.&quot;), # System message to set the context for the AI<br>        (&quot;user&quot;, &quot;{input}&quot;), # Human message to take the user&#39;s question as input<br>    ]<br>)<br><br><br># we have prompt and model, now we can combine them to create a chain<br><br># normal chaining<br><br>chain = prompt | model  # This combines the prompt and model to create a chain<br><br>chain<br><br>#order of execution is important here: prompt -&gt; model -&gt; response<br><br># there are also something called output prasers, which are used to parse the output of the model<br><br><br>chain.invoke({&quot;input&quot;: &quot;What capital of France?&quot;})  # Invoking the chain with a question (without output parser)</pre><h3>3.2. Prompt Templates</h3><p>PromptTemplates are reusable text templates that insert variables. Learn more about prompt templates <a href="https://python.langchain.com/docs/concepts/prompt_templates/">here</a>.</p><pre>from langchain_core.prompts import PromptTemplate<br><br>prompt_template = PromptTemplate.from_template(&quot;Tell me a joke about {topic}&quot;)<br><br>prompt_template.invoke({&quot;topic&quot;: &quot;cats&quot;})</pre><p>You can think of them as the “UI” between your app and the LLM.</p><h3>3.3. Tools</h3><p>LangChain allows LLMs to use tools like calculators, web search, file readers, or custom APIs.</p><pre>from langchain.tools import Tool<br><br>tools = [<br>    Tool(<br>        name=&quot;Calculator&quot;,<br>        func=lambda x: eval(x),<br>        description=&quot;Useful for solving math problems&quot;<br>    )<br>]</pre><p>These tools make your agents more powerful and capable.</p><h3>3.4. Agents</h3><p>Agents are LLMs that decide <strong>what action to take</strong> and <strong>which tool to use</strong>.</p><ul><li>Think of them as dynamic task solvers.</li><li>Example: You ask, “What’s the weather in Paris and convert to Fahrenheit?” — the agent figures out it needs to use a weather API + calculator.</li></ul><pre>from langchain.agents import initialize_agent, AgentType<br><br>agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION)</pre><h3>3.5. Memory</h3><p>Chains and agents can remember previous inputs. This is useful for <strong>conversational agents</strong>.</p><pre>from langchain.memory import ConversationBufferMemory<br>memory = ConversationBufferMemory()</pre><p>Memory helps simulate dialogue and keep context across turns.</p><h3>3. 6. Output Parsers</h3><p>LLMs often return verbose or unstructured text. <strong>Output parsers</strong> help extract exactly what you need (like a number, JSON, or structured string).</p><h4>Example: Parsing JSON</h4><pre>from langchain_core.output_parsers import JsonOutputParser<br>from langchain_core.prompts import PromptTemplate<br><br>output_parser = JsonOutputParser()<br>print(&quot;Instructions:&quot;, output_parser.get_format_instructions())<br><br>prompt = PromptTemplate(<br>    template=&quot;Answer the user question:\n{format_instructions}\n{query}&quot;,<br>    input_variables=[&quot;query&quot;],<br>    partial_variables={&quot;format_instructions&quot;: output_parser.get_format_instructions()},<br>)</pre><p>Parsers are powerful when you want reliable, machine-readable outputs — especially useful for structured tasks or chaining steps together.</p><p>These core ideas — <strong>Chains</strong>, <strong>Prompts</strong>, <strong>Agents</strong>, <strong>Tools</strong>, and <strong>Memory</strong> — are all you need to start building real-world AI apps.</p><p>Next, let’s build your <strong>first working chain</strong> with OpenAI and LangChain! 🔥</p><h3>5. Getting Your First Chain Working</h3><p>Let’s put all the pieces together and build your first LangChain-powered app — a simple “Hello World” that talks to OpenAI’s LLM.</p><h3>What You’ll Use</h3><p>As seen in the previous section, LangChain apps are built using three core components:</p><ol><li><strong>PromptTemplate</strong> — to format the user input</li><li><strong>LLM</strong> — like OpenAI, to generate responses</li><li><strong>OutputParser</strong> — to clean up or structure the output</li></ol><p>Let’s wire these up! Data flows in this order Prompt --&gt; llm --&gt; output parser</p><h3>👋 Hello World with LLMChain and OpenAI</h3><pre>from langchain.prompts import PromptTemplate<br>from langchain_openai import ChatOpenAI<br>from langchain_core.output_parsers import StrOutputParser<br><br><br># Step 1: Create the prompt<br>prompt = PromptTemplate.from_template(&quot;Answer the question: {input}&quot;)<br><br><br># Step 2: Load the LLM<br>llm =ChatOpenAI(model=&quot;gpt-4o&quot;)<br><br><br># Step 3: Create the output parser<br>output_parser = StrOutputParser()<br><br><br># Step 4: Combine into a chain<br>chain_with_parser = prompt | llm | output_parser<br><br># Step 5: Call the chain<br>response = chain_with_parser.invoke({&quot;input&quot;: &quot;What is the capital of France?&quot;})<br>print(response)  # Output: Paris<br></pre><pre>The capital of France is Paris.</pre><p>🎉 Congrats! You’ve just built your first functional LangChain app that answers questions using OpenAI.</p><p>This is the <strong>minimum viable LangChain app</strong> — easy to extend, easy to debug, and built for experimentation.</p><h3>6. Bonus: Using Pydantic with LangChain</h3><p>As your LangChain apps grow in complexity, you’ll want more structured, reliable outputs from your LLMs. That’s where <strong>Pydantic</strong> comes in.</p><p>Pydantic is a Python library used to define and validate data models with type hints. In LangChain, it allows us to <strong>enforce structured outputs</strong> — like returning a dictionary with specific fields (e.g., name, answer, confidence) instead of a blob of text.</p><blockquote><em>🔗 </em><strong><em>New to Pydantic?</em></strong><em><br> Check out this hands-on beginner blog to get started:<br> 👉 </em><a href="https://medium.com/@vamshiginna1606/ultimate-crash-course-build-smarter-python-apps-with-pydantic-f05d4316b579"><em>Ultimate Crash Course: Build Smarter Python Apps with Pydantic</em></a></blockquote><h3>Why Pydantic in AI Agent Development?</h3><ul><li><strong>Clarity:</strong> Define exactly what the output structure should be.</li><li><strong>Validation:</strong> Auto-checks model outputs (e.g., type, nulls, constraints).</li><li><strong>Typed Interaction:</strong> Helps downstream tools and agents work reliably with structured data.</li><li><strong>Safety:</strong> Prevents hallucinations or unexpected formats from breaking your chain.</li></ul><h3>Example: Generate a Joke with Structure</h3><p>Below is a code shows how to define a structured output for a joke using Pydantic with LangChain:</p><pre>from pydantic import BaseModel, Field<br>from langchain_core.output_parsers import JsonOutputParser<br>from langchain_core.prompts import PromptTemplate<br>from langchain_openai import ChatOpenAI<br><br># Load model<br>model = ChatOpenAI(temperature=0)<br><br># Step 1: Define structured data model<br>class Joke(BaseModel):<br>    setup: str = Field(description=&quot;question to set up a joke&quot;)<br>    punchline: str = Field(description=&quot;answer to resolve the joke&quot;)<br><br># Step 2: Define query<br>joke_query = &quot;Tell me a joke.&quot;<br><br># Step 3: Create a parser with the model<br>parser = JsonOutputParser(pydantic_object=Joke)<br><br># Step 4: Create a prompt with parser instructions<br>prompt = PromptTemplate(<br>    template=&quot;Answer the user query.\n{format_instructions}\n{query}\n&quot;,<br>    input_variables=[&quot;query&quot;],<br>    partial_variables={&quot;format_instructions&quot;: parser.get_format_instructions()},<br>)<br><br><br># Step 5: Build the chain<br>chain = prompt | model | parser<br><br><br># Step 6: Run it<br>response = chain.invoke({&quot;query&quot;: joke_query})<br>print(response)</pre><p>This will output a structured response like:</p><pre>{<br>  &quot;setup&quot;: &quot;Why did the chicken go to the seance?&quot;,<br>  &quot;punchline&quot;: &quot;To talk to the other side!&quot;<br>}</pre><p>Using Pydantic in LangChain not only adds <strong>robustness</strong> but also opens doors to safely integrating agents, APIs, and automation at scale.</p><p>In next blog, we’ll explore how to use <strong>Tools and Agents</strong> together for building more intelligent AI apps. 🧠⚙️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eba24b75b55c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Key Setup for OpenAI, Groq, and Langsmith in Your Projects]]></title>
            <link>https://medium.com/@vamshiginna1606/api-key-setup-for-openai-groq-and-langsmith-in-your-projects-edf745e9507c?source=rss-5482f97f8048------2</link>
            <guid isPermaLink="false">https://medium.com/p/edf745e9507c</guid>
            <category><![CDATA[api-key]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[groq]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Vamshi Krishna Ginna]]></dc:creator>
            <pubDate>Sat, 24 May 2025 04:52:28 GMT</pubDate>
            <atom:updated>2025-05-24T04:52:28.420Z</atom:updated>
            <content:encoded><![CDATA[<p>Want to build AI-powered apps using OpenAI, Groq, or Langsmith? It all starts with getting your API keys and configuring your environment correctly. This blog walks you through the process step-by-step — perfect for beginners!</p><h3>📁 Step 1: Create a .env File</h3><p>Before integrating any API, create a .env file in your project root. This helps securely store your API keys.</p><pre># .env file<br>LANG_SMITH_API_KEY=lsv2_pt_f87xxxxxxxxxxxxxxxxxxxxxxxx<br>GROQ_API_KEY=gsk_vW0kaSf1RKyxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>OPENAI_API_KEY=sk-proj-Jtyxzxxxxxxxxxxxxxxxxxxxxxxxxxxx</pre><h3>Step 2: Get Your Groq API Key</h3><ol><li>Visit <a href="https://console.groq.com/keys">Groq Console</a> and <strong>sign up/login</strong>.</li><li>Click on <strong>Create API Key</strong>.</li><li>Enter a project name (e.g., “My Test Project”).</li><li>Copy the key and paste it in your .env as <em>GROQ_API_KEY=gsk_vW0kaSf1RKyxxxxxxxxxxxxxxxxxxxxxxxxxxx</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3M6wS9BpYYUKetGHt7wCQ.png" /><figcaption>Screenshots of Groq API key creation</figcaption></figure><h3>Step 3: Get Your Langsmith API Key</h3><ol><li>Go to <a href="https://www.langchain.com/langsmith">Langsmith</a> and sign in with Google.</li><li>Navigate to <strong>Settings &gt; API Keys</strong>.</li><li>Create a key under your chosen project name.</li><li>Copy the key and add it to your .env as <em>LANG_SMITH_API_KEY=lsv2_pt_f87xxxxxxxxxxxxxxxxxxxxxxxx</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T80bdbwtcUzL4HPNUX6jgQ.png" /><figcaption>Screenshots of langsmith and langchain key creation</figcaption></figure><h3>Step 4: Get Your OpenAI API Key</h3><ol><li>Go to <a href="https://platform.openai.com/settings/organization/api-keys">OpenAI API Keys</a> (this is NOT chatgpt.com)</li><li>Create an account (note: a <strong>minimum $5 balance</strong> is required).</li><li>Generate your key and save it to the .env file as <em>OPENAI_API_KEY=sk-proj-Jtyxzxxxxxxxxxxxxxxxxxxxxxxxxxxx</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npqVKIOqDoZ25DDMv-W2jg.png" /><figcaption>Screenshots of Open AI API key creation</figcaption></figure><h3>✅ Final Step: Use Your .env Securely</h3><p>Once added, load the keys into your app using environment variable libraries like dotenv in Node.js or python-dotenv in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/0*iPH6OPopZUzy72Vu" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bI3-eaVNMVkqY7O6HtcwOQ.png" /></figure><p><strong>Pro Tip:</strong> Never upload your .env file to GitHub. Always add it to .gitignore.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edf745e9507c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ultimate Crash Course: Build Smarter Python Apps with Pydantic]]></title>
            <link>https://medium.com/@vamshiginna1606/ultimate-crash-course-build-smarter-python-apps-with-pydantic-f05d4316b579?source=rss-5482f97f8048------2</link>
            <guid isPermaLink="false">https://medium.com/p/f05d4316b579</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[pydantic]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-validation]]></category>
            <dc:creator><![CDATA[Vamshi Krishna Ginna]]></dc:creator>
            <pubDate>Sun, 18 May 2025 06:17:45 GMT</pubDate>
            <atom:updated>2025-05-18T06:17:45.692Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>If you’ve ever built an API, passed data between AI agents, or simply wanted your Python code to stop breaking because of a bad input — you need to meet <strong>Pydantic</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*3mpXhtOlGnrUW6OW" /></figure><p>Pydantic is a powerful data parsing and validation library that makes type-safe code <strong>easy and elegant</strong>. It underpins FastAPI (one of the fastest-growing web frameworks) and is becoming the go-to tool for AI developers working on <strong>Agentic AI</strong> apps — where validating structured data is a non-negotiable.</p><blockquote>⚡ Bonus: Pydantic is written in Rust under the hood — it’s not just elegant, it’s <strong>blazing fast</strong>.</blockquote><p>In this crash course, we’ll go beyond reading — you’ll code alongside the examples. By the end, you’ll not only understand Pydantic, but also see how it quietly powers AI agents, APIs, and smart data pipelines behind the scenes.</p><h3>What You’ll Learn</h3><p>In this crash course, we’ll cover:</p><ol><li>Introduction</li><li><strong>Normal Class vs @dataclass vs BaseModel</strong> — Why Pydantic stands out</li><li><strong>Type Hinting in Python</strong> — The backbone of data validation</li><li><strong>Your First Pydantic Model</strong> — Install, build, and validate</li><li><strong>Field-Based Validation</strong> — Enforcing constraints the clean way</li><li><strong>Nested Models</strong> — Modeling real-world, structured data</li><li><strong>Pydantic with FastAPI</strong> — Powering APIs with smart schemas</li><li><strong>Pydantic Utilities (v2)</strong> — Clean JSON, dicts, and safe parsing</li><li><strong>Challenge Assignment</strong> — Build a chatbot response model</li><li><strong>Conclusion</strong> — What’s next on your learning path?</li></ol><h3>2. Normal Class vs @dataclass vs BaseModel (Pydantic)</h3><p>Let’s kick things off with a core comparison: <strong>How do you structure data in Python, and what’s the Pydantic advantage?</strong></p><h3>2.1. The Classic Python Class</h3><pre>class User:<br>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age<br><br>u = User(&quot;Alice&quot;, 30)</pre><p>✅ ️Simple?<br> ❌ But — no type checking, no default serialization, and if someone passes age=&quot;thirty&quot;… no errors!</p><h3>2.2. Enter @dataclass</h3><p>Python 3.7 introduced @dataclass to reduce boilerplate.</p><pre>from dataclasses import dataclass<br><br>@dataclass<br>class User:<br>    name: str<br>    age: int<br><br>u = User(&quot;Alice&quot;, 30)<br>print(u)</pre><p>✅ Less boilerplate<br> ❌ But still: no automatic type validation, no built-in serialization</p><h3>2.3. Meet <em>pydantic.BaseModel</em></h3><pre>from pydantic import BaseModel<br><br>class User(BaseModel):<br>    name: str<br>    age: int<br><br>u = User(name=&quot;Alice&quot;, age=30)<br>print(u)</pre><p>✅ Clean<br>✅ Type-safe (throws error if age=&quot;thirty&quot;)<br>✅ Easily serializable (.dict(), .json())<br>✅ Auto-casting (age=&quot;30&quot; will be converted to int)</p><blockquote>💡 This is why <strong>Pydantic is perfect for Agentic AI</strong>: when an AI agent sends or receives JSON data, you want to <strong>validate and clean that data instantly</strong> — without dozens of if conditions.</blockquote><h3>2.4. Let’s Break It and See What Happens</h3><p>Try this:</p><pre>u = User(name=&quot;Alice&quot;, age=&quot;thirty&quot;)</pre><p>With BaseModel, you get:</p><pre>ValidationError: 1 validation error for User<br>age<br>  value is not a valid integer (type=type_error.integer)</pre><p>With a normal class? It silently fails or causes downstream bugs.</p><h3>3. Type Hinting in Python — The Foundation</h3><p>Before Pydantic can do its magic, it needs a map — and that’s what type hints are. They tell Pydantic (and your IDE!) what types of data to expect.</p><p>Let’s look at the basics:</p><pre>name: str         # expects a string<br>age: int          # expects an integer<br>score: float      # expects a float<br>is_active: bool   # expects True or False</pre><p>Now try:</p><pre>from typing import Optional, List<br><br>bio: Optional[str]        # can be a string or None<br>tags: List[str]           # a list of strings</pre><p>Type hints <strong>don’t enforce anything by themselves</strong>, but Pydantic uses them to validate your data <strong>at runtime</strong>.</p><blockquote><strong>Why it matters for Agentic AI:</strong><br> With type-hinted data models, LLM agents can <strong>reliably exchange structured data</strong> in multi-agent environments. This reduces hallucinations and miscommunication between agents — imagine one agent expecting a float and getting a string.</blockquote><h3>4. Your First Pydantic Model</h3><p>Let’s get our hands dirty. First, install Pydantic:</p><pre>pip install pydantic</pre><p>Now try your first model:</p><pre>from pydantic import BaseModel<br><br>class User(BaseModel):<br>    name: str<br>    age: int<br><br>u = User(name=&quot;Alice&quot;, age=30)<br>print(u)<br>print(u.model_dump())</pre><p>It prints a clean object and a serializable dictionary — perfect for APIs or AI tools that exchange JSON.</p><pre>name=&#39;Alice&#39; age=30<br>{&#39;name&#39;: &#39;Alice&#39;, &#39;age&#39;: 30}</pre><p><strong>Imagine this in AI:</strong><br>Validating a user profile input for a chatbot? Pydantic does it in <em>one line</em> — no more nested if checks or fragile regexes.</p><p>Now try:</p><pre>User(name=&quot;Alice&quot;, age=&quot;30&quot;)</pre><p>✅ Still works — Pydantic automatically casts types when it can.</p><p>But now try:</p><pre>User(name=&quot;Alice&quot;, age=&quot;thirty&quot;)</pre><p>You’ll get a helpful ValidationError. That’s <strong>defensive programming done right</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QF1su9Ky1FYY_KdMtmuEzQ.png" /></figure><h3>5. Validation Made Easy With Fields</h3><p>Sometimes, you don’t need full-blown validation logic — just a clean way to set <strong>constraints and metadata</strong> on your fields. That’s where Field(...) shines.</p><p>Pydantic’s Field() lets you:</p><ul><li>Enforce basic rules like min/max values</li><li>Set defaults</li><li>Add helpful descriptions</li><li>Define regex patterns</li></ul><h3>Example 1: User Input Constraints</h3><pre>from pydantic import BaseModel, Field<br><br>class User(BaseModel):<br>    username: str = Field(..., min_length=3, max_length=15, description=&quot;Username must be between 3 and 15 characters&quot;)<br>    age: int = Field(..., gt=0, lt=120, description=&quot;Age must be between 1 and 119&quot;)</pre><p>Try User(username=&quot;ab&quot;, age=150) — it fails with meaningful errors.</p><h3>Example 2: Feedback Form</h3><pre>from typing import Optional<br><br>class Feedback(BaseModel):<br>    rating: int = Field(..., ge=1, le=5, description=&quot;Rating from 1 (worst) to 5 (best)&quot;)<br>    comment: Optional[str] = Field(None, max_length=200)</pre><p>You now have:</p><ul><li>A required rating that must be 1 to 5</li><li>An optional comment with a max character limit</li></ul><blockquote><strong>Agentic AI Insight:</strong><br>In multi-agent workflows, fields like these define <strong>tight interfaces</strong> between agents. For example, one agent might expect a rating score or limited-length response — Pydantic ensures that those expectations are always met before processing continues.</blockquote><h3>6. Nested Models and Reusability</h3><p>What if your data has layers?</p><p>With Pydantic, you can compose models like LEGO blocks:</p><pre>class Address(BaseModel):<br>    city: str<br>    zip_code: str<br><br>class User(BaseModel):<br>    name: str<br>    address: Address</pre><p>You can now do:</p><pre>User(name=&quot;Alice&quot;, address={&quot;city&quot;: &quot;NYC&quot;, &quot;zip_code&quot;: &quot;10001&quot;})</pre><p>It automatically parses and validates nested dictionaries. You can even reuse Address in multiple models.</p><blockquote><em>🤝 </em><strong><em>Agentic AI Tip</em></strong><em>:<br> When passing outputs between agents, nested Pydantic models let you build </em><strong><em>clean interfaces</em></strong><em> that agents can understand. No more worrying about missing keys or wrong formats — each piece of the structure is validated before it’s used.</em></blockquote><h3>7. Pydantic with FastAPI</h3><p><strong>FastAPI</strong> is one of the most popular Python web frameworks right now — and <strong>Pydantic is the engine behind its speed and reliability</strong>. Every time you define a request body or response model in FastAPI, you’re using Pydantic behind the scenes.</p><p>Here’s how it works:</p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel<br><br>app = FastAPI()<br><br>class Item(BaseModel):<br>    name: str<br>    price: float<br><br>@app.post(&quot;/items/&quot;)<br>async def create_item(item: Item):<br>    return {&quot;message&quot;: &quot;Item received!&quot;, &quot;data&quot;: item}</pre><p>FastAPI will:</p><ul><li>Automatically parse and validate the request body as an Item</li><li>Generate interactive docs (/docs) using the schema from Pydantic</li><li>Return a clean JSON response — also powered by Pydantic</li></ul><blockquote><strong>AI API Use Case:</strong><br> Many AI-powered apps — like chatbots, vector database wrappers, and tool-based reasoning systems — expose APIs using FastAPI + Pydantic. This combo ensures <strong>fast, secure, and schema-driven data handling</strong>, especially when interacting with external LLMs or agents.</blockquote><h3>8. Handy Pydantic Utilities</h3><p>Pydantic isn’t just about validation — it also gives you clean tools to work with structured data. These come in handy when converting between JSON, dictionaries, or even untrusted inputs (hello, LLMs).</p><h3>.model_dump()</h3><p>Use this to convert your model into a plain Python dict:</p><pre>user = User(name=&quot;Alice&quot;, age=30)<br>print(user.model_dump())</pre><p>You can customize the output with:</p><pre>user.model_dump(exclude_unset=True)  # Only include fields that were set explicitly</pre><h3>.model_dump_json()</h3><p>This gives you a JSON string from the model:</p><pre>print(user.model_dump_json())</pre><p>Optional parameters let you customize formatting or exclude fields.</p><h3>User.model_validate(obj)</h3><p>This is now the preferred way to validate and parse raw data:</p><pre>raw_data = {&quot;name&quot;: &quot;Bob&quot;, &quot;age&quot;: &quot;35&quot;}  # age will be coerced to int<br>user = User.model_validate(raw_data)</pre><blockquote><strong>Agentic AI Tip:</strong><br> These updated utilities are essential when handling <strong>structured LLM outputs</strong> or tool responses. Use model_validate() to parse them safely, and model_dump() or model_dump_json() to send structured data to other agents, APIs, or frontends</blockquote><h3>9. Challenge: Build a Pydantic Model for an AI Chatbot’s Response</h3><p>Let’s put your skills to the test with a real-world task!</p><h3>The Scenario:</h3><p>You’re building an AI chatbot that responds with:</p><ul><li>A message (string)</li><li>A confidence score (float between 0 and 1)</li><li>A list of suggested follow-up questions (optional)</li></ul><h3>Your Task:</h3><p>Create a Pydantic model that validates this response, enforces rules, and sets reasonable defaults.</p><p>Example:</p><pre>from pydantic import BaseModel, Field<br>from typing import Optional, List<br><br>class ChatbotResponse(BaseModel):<br>    message: str = Field(..., description=&quot;The main reply from the AI&quot;)<br>    confidence: float = Field(..., ge=0, le=1, description=&quot;Confidence score between 0 and 1&quot;)<br>    follow_ups: Optional[List[str]] = Field(default=None, description=&quot;Suggested follow-up questions&quot;)</pre><p>Now test it with different data. Try passing invalid types or missing fields. Tweak it to make it your own.</p><blockquote>Bonus: Add a timestamp or chatbot version field if you want to simulate more realistic scenarios!</blockquote><h3>10. Conclusion</h3><p>Congrats! You’ve completed a hands-on crash course in Pydantic — one of the most powerful and intuitive tools for working with structured data in Python.</p><p>Let’s recap what you’ve learned:</p><ul><li>How Pydantic compares with normal classes and @dataclass</li><li>The power of type hints and how they enable runtime validation</li><li>How to use Field() for constraints and documentation</li><li>How Pydantic powers FastAPI and AI-based APIs</li><li>Best practices for working with Pydantic v2</li><li>How to model AI agent responses with real-world structure</li></ul><p>Whether you’re building an LLM-based app, a web API, or just want safer Python code, Pydantic makes your data <strong>clear</strong>, <strong>validated</strong>, and <strong>ready for production</strong>.</p><blockquote>✨ Next steps? Try integrating what you’ve learned into a FastAPI app or LangChain agent. Trust me — future you will thank you.</blockquote><p>Learn more at <a href="https://docs.pydantic.dev/latest/">https://docs.pydantic.dev/latest/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f05d4316b579" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Broken APIs to Bulletproof AI Agents: How Pydantic Saves Your Stack]]></title>
            <link>https://medium.com/@vamshiginna1606/from-broken-apis-to-bulletproof-ai-agents-how-pydantic-saves-your-stack-0895a63bafd5?source=rss-5482f97f8048------2</link>
            <guid isPermaLink="false">https://medium.com/p/0895a63bafd5</guid>
            <category><![CDATA[pydantic]]></category>
            <category><![CDATA[ｐｙｔｈｏｎ]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Vamshi Krishna Ginna]]></dc:creator>
            <pubDate>Sat, 17 May 2025 18:22:10 GMT</pubDate>
            <atom:updated>2025-05-17T18:22:10.189Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Pydantic?</h3><p><strong>Pydantic</strong> is a Python library that makes <strong>data validation and parsing</strong> not just easy, but elegant. It lets you define schemas using Python’s type hints and automatically validates, converts, and parses data at runtime.</p><p>Think of it as your <strong>data safety net</strong> — catching errors before they crash your app.</p><pre>from pydantic import BaseModel<br><br>class User(BaseModel):<br>    name: str<br>    age: int<br>    email: str</pre><p>If you pass a dictionary with a string for age, Pydantic will auto-convert it. If something’s missing or malformed? It throws a structured error.</p><h3>Core Features</h3><ul><li>Type conversion &amp; validation</li><li>Auto-completion in IDEs (thanks to type hints)</li><li>Custom data validation</li><li>Nested models &amp; complex data types</li><li>Serialization: .json() &amp; .dict() methods</li><li>Performance — built with dataclasses + cython-level speed</li></ul><h3>What Problem Does It Solve?</h3><p>Before Pydantic, developers manually validated every piece of input:</p><pre>if &#39;age&#39; in data and isinstance(data[&#39;age&#39;], int):<br>    ...</pre><p>This bloated code, introduced bugs, and made maintenance painful.</p><p>Pydantic solves this by:</p><ul><li>Ensuring <strong>clean data boundaries</strong> between external inputs and internal logic.</li><li>Reducing <strong>boilerplate validation logic.</strong></li><li>Improving <strong>developer confidence and speed</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*AVYa8-joosWYNR9G" /></figure><h3>Pydantic + FastAPI = 🔥</h3><p>FastAPI uses Pydantic models for:</p><ul><li><strong>Request validation</strong></li><li><strong>Response formatting</strong></li><li><strong>Data documentation</strong> (auto-generates Swagger docs!)</li></ul><pre>from fastapi import FastAPI<br>from pydantic import BaseModel<br><br>class Item(BaseModel):<br>    name: str<br>    price: float<br>app = FastAPI()<br>@app.post(&quot;/items/&quot;)<br>def create_item(item: Item):<br>    return item</pre><p>If the request is invalid, FastAPI + Pydantic return structured errors — no manual checks required.</p><h3>Pydantic in Gen AI &amp; Agentic AI Applications</h3><p>In generative AI apps, especially with <strong>LLMs and agents</strong>, data flows between multiple tools:</p><ul><li>User → API</li><li>API → LLM → Vector DB</li><li>LLM → Agent tools → Output</li></ul><p>Pydantic is the <strong>glue</strong> that ensures safe, consistent, structured data flow.</p><h3>Where It’s Useful:</h3><ul><li>Defining <strong>prompt templates</strong> and inputs</li><li>Structuring LLM outputs (e.g., JSON → Pydantic models)</li><li>Validating tool configurations and agent inputs</li><li>Interfacing with APIs (input validation + response schemas)</li></ul><pre>class SearchToolInput(BaseModel):<br>    query: str<br>    top_k: int</pre><p>Even when using OpenAI function-calling, Pydantic helps generate valid function signatures and response types.</p><h3>Final Thoughts: The Future is Typed</h3><p>Whether you’re building a simple API or an advanced AI agent, <strong>structured data handling is non-negotiable</strong>.</p><p>Pydantic doesn’t just help — it supercharges your development.</p><p>It’s the quiet powerhouse behind FastAPI’s speed and the unsung hero in complex AI pipelines.</p><p>If you’re working with LLMs, multi-agent systems, or any Gen AI toolchain — it’s time you learned Pydantic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0895a63bafd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Counting Sheep to Autonomous Agents: How Stats, ML, and GPT Led Us to Autonomous AI Agents]]></title>
            <link>https://medium.com/@vamshiginna1606/from-counting-sheep-to-autonomous-agents-how-stats-ml-and-gpt-led-us-to-autonomous-ai-agents-238d99ed89e3?source=rss-5482f97f8048------2</link>
            <guid isPermaLink="false">https://medium.com/p/238d99ed89e3</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vamshi Krishna Ginna]]></dc:creator>
            <pubDate>Sat, 17 May 2025 05:44:19 GMT</pubDate>
            <atom:updated>2025-05-17T18:10:55.612Z</atom:updated>
            <content:encoded><![CDATA[<p>Let me take you on a journey — one that started with statisticians tallying up crop yields and has led us to machines that can design, build, and deploy software. Yeah, it’s that wild.</p><p>AI didn’t just <em>happen</em>. It evolved — through decades of trial, innovation, and paradigm shifts. And today, we stand at the edge of something extraordinary: <strong>Agentic AI</strong>. But to appreciate where we’re headed, we need to look at where we’ve been.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*UZnmWuwL7tggvz0r" /></figure><h3>1. The Statistical Era: Simpler Times, Simpler Mode</h3><p>Picture this: It’s the early 1900s. A scientist is poring over a dusty ledger filled with rainfall data and harvest yields. Their goal? Find out if more rain means more crops.</p><p>That’s it. That was<strong> “data science.”</strong></p><p>Statistical tools like <strong>linear regression</strong> became the gold standard — clean, interpretable, and rooted in mathematics. These models gave us a taste of what was possible: discovering relationships, making predictions, understanding the world a little better.</p><p>But the world didn’t stay simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*kicFDCEhNjy6271QAspSlQ.png" /></figure><h3>2. Traditional Machine Learning: Let the Machines Do the Thinking</h3><p>Fast forward to the late 90s and early 2000s. Computing power had taken off, and so did our ambitions. We moved from observing data to <strong>training machines</strong> to find patterns themselves.</p><p>Enter traditional ML — algorithms like <strong>decision trees</strong>, <strong>SVMs</strong>, and <strong>random forests</strong>. They could look at structured data (think: spreadsheets) and learn which features mattered.</p><p>Imagine predicting house prices using square footage, neighborhood, and number of bathrooms. Machines were now uncovering patterns that statisticians once found manually. It was efficient, scalable… to a point.</p><p>But they still needed structured, labeled data — and the real world is anything but tidy.</p><h3>3. The Big Data Explosion: Drinking from the Firehose</h3><p>Then came 2007. Facebook, YouTube, Instagram. E-commerce. Sensors. Smartphones. Suddenly, we weren’t dealing with spreadsheets anymore. We had <strong>terabytes of images, videos, clicks, chats</strong> — pouring in by the second.</p><p>And traditional ML? It choked.</p><p>Models couldn’t keep up. They hit a ceiling — accuracy plateaued, scalability became a nightmare, and our hunger for insight far outpaced what the tools could handle.</p><p>So we looked to biology.</p><h3>4. Deep Learning: Thinking Like a Brain</h3><p>This was the game-changer.</p><p>We borrowed from neuroscience and built <strong>neural networks</strong>. These deep learning models could process raw, unstructured data — images, text, audio — and actually <em>get better</em> the more data you gave them.</p><ul><li><strong>CNNs</strong> transformed image recognition.</li><li><strong>RNNs</strong> and <strong>LSTMs</strong> brought us voice assistants and sequential text understanding.</li><li>And then came <strong>Transformers</strong> — the game changer.</li></ul><p>The 2017 paper, <em>“Attention is All You Need,”</em> didn’t just suggest a better architecture — it <strong>redefined the future</strong> of AI. Transformers enabled models like <strong>BERT</strong>, <strong>GPT</strong>, and <strong>BART</strong> to not just recognize patterns, but to understand and <strong>generate</strong> language with context and coherence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*fsa3n9ziRCNHBuZa" /></figure><h3>5. Generative AI: Machines That Create</h3><p>This is where the magic got real.</p><p>With models like <strong>GPT-3</strong> and <strong>GPT-4</strong>, machines didn’t just understand — they began to <strong>create</strong>. They could:</p><ul><li>Write essays,</li><li>Generate functional code,</li><li>Summarize lengthy legal documents,</li><li>Even compose poetry (sometimes surprisingly well).</li></ul><p>We went from:</p><blockquote><em>“Classify this email”<br> to:<br> “Write the entire email for me.”</em></blockquote><p>But even these state-of-the-art models had limitations. They couldn’t <strong>fetch real-time information</strong>, <strong>take action</strong>, or <strong>adapt on the fly</strong>. They were brilliant conversationalists — but passive ones.</p><p>The next frontier? Giving them <strong>agency</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P2HCgTOrE0DLuzJo" /></figure><h3>6. The Rise of Agentic AI: From Assistants to Autonomous Agents</h3><p>Let me put it simply:</p><p><strong>Agentic AI is the next frontier.</strong> It’s no longer just about responding to prompts — it’s about planning, executing, and learning from outcomes.</p><p>Think of an AI that doesn’t just answer a question, but:</p><ul><li>Breaks a big task into subtasks</li><li>Chooses the best tools to get things done</li><li>Uses memory and context to stay on track</li><li>Loops through trial and error until it gets it right</li></ul><p>It’s like hiring a junior employee who <em>never</em> gets tired, forgets, or needs coffee.</p><h3>7. Real-World Example: An AI Software Engineer?</h3><p>Imagine this: you tell an agent, “Build me a web app that tracks expenses.”</p><p>Here’s what it does:</p><ul><li>Reads the requirements</li><li>Generates user stories</li><li>Designs the system architecture</li><li>Writes backend and frontend code</li><li>Runs tests</li><li>Deploys the app</li><li>Fixes bugs when they pop up</li></ul><p>And you? You just review, tweak, and steer.</p><p>This isn’t science fiction. It’s already happening in early-stage tools like Devin, AutoGPT, and others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TGB3evNpHRZzAdhS" /><figcaption>source : <a href="https://github.com/shubhamprajapati7748/sdlc-copilot/blob/main/workflow.png">https://github.com/shubhamprajapati7748/sdlc-copilot/blob/main/workflow.png</a></figcaption></figure><h3>8. Plugging Into the World: Tools Make the Agent</h3><p>The magic happens when these agents <strong>use external tools</strong>.</p><ul><li>Need the latest research? Call the ArXiv API.</li><li>Need to fact-check something? Hit Wikipedia or a search engine.</li><li>Want memory? Use vector databases like Pinecone or Chroma.</li></ul><p>Think of these tools like plugins in an IDE — they expand what the agent can do, and more importantly, make sure it doesn’t hallucinate or guess.</p><p>This is where power meets precision.</p><h3>9. Final Thoughts: Welcome to the Age of Intelligence</h3><p>From statisticians counting crops to agents writing production code, we’ve come a long way.</p><p>We’re not just building tools anymore — we’re building <strong>systems that can reason, act, and evolve</strong>. We’re entering an age where software builds software, with humans in the loop but not holding the wheel the whole time.</p><p>Agentic AI isn’t a trend. It’s the next era of intelligence. And we’re just getting started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*gF-oM6ycSrLfIsRJJT1kLw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=238d99ed89e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>