<?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 DFashimpaur on Medium]]></title>
        <description><![CDATA[Stories by DFashimpaur on Medium]]></description>
        <link>https://medium.com/@dfashimpaur?source=rss-aa539dd0073------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-lVEfvemW7JM2LDT.jpg</url>
            <title>Stories by DFashimpaur on Medium</title>
            <link>https://medium.com/@dfashimpaur?source=rss-aa539dd0073------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:58:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dfashimpaur/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[Building a Simple AI Agent in Python]]></title>
            <link>https://medium.com/@dfashimpaur/building-a-simple-ai-agent-in-python-34a5fc6ff5cf?source=rss-aa539dd0073------2</link>
            <guid isPermaLink="false">https://medium.com/p/34a5fc6ff5cf</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[DFashimpaur]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 19:00:50 GMT</pubDate>
            <atom:updated>2025-11-18T19:00:50.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y-2sYFaAPuYms5xk0jNjIw.png" /><figcaption>Building a Simple AI Agent in Python with LangChain and Claude</figcaption></figure><h4>A hands-on, engineering-focused walkthrough for Python developers using LangChain, Claude, and Pydantic for structured LLM workflows.</h4><h3>Why This Matters</h3><p>Modern AI development increasingly relies on small, composable building blocks — agents, tools, models, and data flows that can be orchestrated like any other part of a software system. For Python engineers, understanding how to structure these components is now just as essential as mastering asynchronous programming or writing clean class hierarchies.</p><p>This article provides a practical, engineer-first guide to building a simple AI agent using <strong>Python</strong>, <strong>LangChain</strong>, and <strong>Anthropic’s Claude models</strong>. The goal is to show <em>how the pieces fit together</em>, why each part exists, and what patterns are used in real-world AI engineering — without unnecessary abstraction or hype.</p><h3>Prerequisites</h3><p>To follow along, readers should be comfortable with:</p><ul><li>Python 3.8–3.12</li><li>Virtual environments (venv, pipenv, or similar)</li><li>Basic knowledge of how LLM APIs work</li><li>Running scripts from the command line</li></ul><p>The example uses the Claude API, but the overall structure applies broadly to LLMs.</p><h3>Obtaining an API Key</h3><p>An API key is required to run the code. For Claude, navigate to the Anthropic console, open the <strong>API Keys</strong> section, and create a new key. Store it securely and never commit it to source control.</p><p>Create a .env file in your project directory and add:</p><pre>ANTHROPIC_API_KEY=&quot;&lt;your_key_here&gt;&quot;</pre><p>This allows the script to load your key at runtime via python-dotenv.</p><h3>Project Structure</h3><p>Set up your project directory and initialize a few basic files:</p><pre>AI_Agent/<br>├── __init__.py<br>├── .env<br>└── ai_agent.py</pre><p>__init__.py simply marks the directory as a Python package. All logic will go into ai_agent.py.</p><p>Install the required libraries:</p><pre>python-dotenv<br>langchain<br>langchain-anthropic<br>langchain-community<br>langchain-openai<br>langchain-core<br>wikipedia<br>pydantic</pre><h3>Writing the Agent</h3><p>Start with imports:</p><pre>import textwrap<br>import sys<br><br>from dotenv import load_dotenv<br>from langchain_anthropic import ChatAnthropic<br>from langchain_core.output_parsers import PydanticOutputParser<br>from langchain_core.prompts import ChatPromptTemplate<br>from pydantic import BaseModel, Field</pre><p>dotenv is used for secure key management, LangChain handles structured prompts and model interaction, and pydantic is used to define a strongly typed response schema.</p><p>Load environment variables:</p><pre>load_dotenv()</pre><h3>Defining a Structured Output Model</h3><p>A key engineering practice in LLM work is enforcing structured output. Pydantic makes this clean and explicit:</p><pre>class ResearchResponse(BaseModel):<br>    topic: str = Field(..., description=&quot;The topic of the research paper&quot;)<br>    summary: str = Field(..., description=&quot;A summary of the research paper&quot;)<br>    sources: list[str] = Field(..., description=&quot;A list of sources used in the research paper&quot;)<br>    tools_used: list[str] = Field(..., description=&quot;A list of tools used in the research paper&quot;)</pre><p>This schema serves as the contract for what the LLM must produce.</p><p>Create a model instance:</p><pre>llm = ChatAnthropic(<br>    model_name=&quot;claude-sonnet-4-5-20250929&quot;,<br>    temperature=0,<br>    timeout=None,<br>    max_retries=2<br>)</pre><p>Any Claude model may be substituted.</p><h3>Creating the Prompt and Parser</h3><p>Define the parser:</p><pre>parser = PydanticOutputParser(pydantic_object=ResearchResponse)</pre><p>Create the system prompt with a placeholder for automatic format instructions:</p><pre>SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are a research assistant that will help generate a research paper.<br>Answer the user query and use necessary tools.<br>Wrap the output of this format and provide no other text<br>{format_instructions}<br>&quot;&quot;&quot;</pre><p>Build the ChatPromptTemplate:</p><pre>prompt = ChatPromptTemplate([<br>    (&quot;system&quot;, SYSTEM_PROMPT),<br>    (&quot;user&quot;, &quot;{question}&quot;),<br>]).partial(format_instructions=parser.get_format_instructions())</pre><p>partial() injects the schema as JSON, instructing the LLM exactly how to shape its output.</p><h3>The LangChain Execution Pipeline</h3><p>LangChain uses operator overloading to construct pipelines:</p><pre>chain = prompt | llm | parser</pre><p>This creates a single callable object that:</p><ol><li>Renders the prompt</li><li>Sends it to the model</li><li>Parses the response into a ResearchResponse instance</li></ol><p>This is one of LangChain’s cleanest abstractions.</p><h3>Helper Function for Output Formatting</h3><pre>def pretty_print_wrapped(label: str, text: str, width: int = 120):<br>    indent = f&quot;{label}: &quot;<br>    print(<br>        textwrap.fill(<br>            text,<br>            width=width,<br>            initial_indent=indent,<br>            subsequent_indent=&quot; &quot; * len(indent)<br>        )<br>    )<br>    print()</pre><p>This ensures consistent and readable console output.</p><h3>Main Execution Logic</h3><pre>if __name__ == &quot;__main__&quot;:<br>    default_question = (<br>        &quot;How much wood could a woodchuck chuck if a woodchuck could chuck wood?&quot;<br>    )<br>    max_width = 120<br>    <br>    question = &quot; &quot;.join(sys.argv[1:]) if len(sys.argv) &gt; 1 else default_question<br>    pretty_print_wrapped(&quot;Original Question&quot;, question, width=max_width)<br>    output: ResearchResponse = chain.invoke({&quot;question&quot;: question})<br>    for field_name, field_value in output.model_dump().items():<br>        label = field_name.replace(&quot;_&quot;, &quot; &quot;).title()<br>        if isinstance(field_value, list):<br>            field_value = f&#39;[{&quot;, &quot;.join(field_value)}]&#39;<br>        pretty_print_wrapped(label, field_value, width=max_width)   </pre><p>This script accepts a CLI argument or falls back to a default question.</p><p>Run with pipenv:</p><pre>pipenv run -m ai_agent</pre><p>Or specify a question:</p><pre>pipenv run -m ai_agent &quot;Why is the sky blue&quot;</pre><h3>Closing Thoughts</h3><p>This example demonstrates a clean, composable pattern for building AI agents in Python using LangChain. By combining structured output with a well-defined prompt pipeline, engineers can enforce predictable behavior while retaining the flexibility of modern LLM models. The same architectural approach scales naturally to more advanced workflows such as tool calling, multi-step reasoning, and retrieval-augmented pipelines.</p><p>As LLM ecosystems continue to evolve, strong typing, explicit contracts, and maintainable abstractions will remain essential skills for Python engineers building reliable AI-driven systems.</p><h3>🙌 If You Made It This Far…</h3><p>If you found this article helpful, please give it a clap to let me know it resonated with you! 👏</p><p>And don’t keep it to yourself — share it with others who might benefit from learning clean, Pythonic approaches to AI solutions.</p><p>Your support helps me create more content like this and keeps the Python community thriving. Thank you!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*oSgHk-EZrDGkhPrqCu9viQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34a5fc6ff5cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of List Slicing: Writing Better Algorithms In Python]]></title>
            <link>https://medium.com/@dfashimpaur/writing-algorithms-in-python-d852d70759dc?source=rss-aa539dd0073------2</link>
            <guid isPermaLink="false">https://medium.com/p/d852d70759dc</guid>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[DFashimpaur]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 19:37:58 GMT</pubDate>
            <atom:updated>2025-11-10T21:47:12.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCkxpd4Wv6JLosinQY4Pnw.jpeg" /></figure><h3>🧩 The Power of List Slicing: Writing Better Algorithms In Python</h3><h4>A simple rotation problem shows how Python slicing can turn loops into one-liners.</h4><h3><strong>🔍 The Problem</strong></h3><p>You’re given an array (or list) of integers and an integer `K`. The task is to <strong>rotate</strong> the list to the right by `K` positions — that is, move the last `K` elements to the front while keeping the order.</p><pre>A = [1, 2, 3, 4, 5]<br>K = 3<br><br># After rotating 3 times, the result should be:<br><br>result = [3, 4, 5, 1, 2]</pre><p>Each rotation shifts the elements to the right, wrapping the last element to the start of the list.</p><p>This can be seen in the following illustration:</p><pre>[1, 2, 3, 4, 5] --&gt; [5, 1, 2, 3, 4]<br>[5, 1, 2, 3, 4] --&gt; [4, 5, 1, 2, 3]<br>[4, 5, 1, 2, 3] --&gt; [3, 4, 5, 1, 2]</pre><h3>🔰 The Intuitive (but Inefficient) Way</h3><p>The way most people start is to use a for loop.</p><pre>def rotate_list(integer_list: list[int], steps: int) -&gt; list[int]:<br>    for _ in range(steps):<br>        integer_list = [integer_list[-1]] + integer_list[:-1]<br>    return integer_list</pre><p><strong>Time Complexity</strong></p><ul><li>Each rotation (integer_list = [integer_list[-1]] + integer_list[:-1]) copies the whole list</li><li>Each time a copy operation happens, it is O(N), where N is the length of the list</li><li>Since it is performed ‘steps’ times, the total time complexity becomes O(steps x N)</li></ul><p>If integer_list is large, this quickly becomes inefficient. Rotating a list of 100 elements 100 times takes 10,000 operations.</p><p><strong>Space Complexity</strong></p><ul><li>Each iteration of the for loop creates a new integer list of size N.</li><li>Since the previous list is discarded after each step, the extra memory used at any one time is proportional to the list length, and therefore the Space Complexity is O(N).</li></ul><h3>🐍 Slice-Based Rotation (the optimized one-liner):</h3><pre>def rotate_list(integer_list: list[int], steps: int) -&gt; list[int]:<br>    if not integer_list:<br>        return integer_list<br><br>    n = len(integer_list)<br>    steps = steps % n<br>    if steps == 0:<br>        return integer_list<br>    <br>    return integer_list[-steps:] + integer_list[:-steps]</pre><p><strong>What The Modulo (%) Operator Provides</strong></p><ul><li>If the length of integer_list is larger than the list size, it then normalizes it. An integer_list with a length of 10 and a steps value of 11, the result will be the same as a steps value of 1.</li><li>If the result of the modulo operation returns 0, the effect of the rotation is identical to the original list, and therefore, the response is the original list.</li></ul><p><strong>Time Complexity</strong></p><ul><li>Each slice (integer_list[-steps:] and integer_list[:-steps]) creates a copy of a portion of the list</li><li>Both slices together touch each element once, so the slicing operation is O(N).</li><li>Concatenation (+) of the two slices is also O(N), because it creates a new list</li></ul><p>This leaves a total time cost for the slicing approach is O(N) with respect to the input size. This is the best possible Time Complexity for a full-array rotation since every element must move once.</p><p><strong>Space Complexity</strong></p><p>Because the expression (integer_list[-steps:] + integer_list[:-steps]) creates a new list of all elements contained in integer_list. It needs space for a full copy, making the Space Complexity O(N).</p><p><strong>Why This Slicing Approach Works</strong></p><ul><li>integer_list[=steps:] grabs the last number of steps elements</li><li>integer_list[:-steps] grabs all the elements before the steps index</li><li>Combining them both (+) effectively rotates the list the required number of steps</li></ul><p>Because slicing is handled internally by Python, it is both cleaner and faster.</p><h3>🧪 Example Runs</h3><pre>&gt;&gt;&gt; rotate_list([3, 8, 9, 7, 6], 3)<br>[9, 7, 6, 3, 8]<br><br>&gt;&gt;&gt; rotate_list([0, 0, 0], 1)<br>[0, 0, 0]<br><br>&gt;&gt;&gt; rotate_list([1, 2, 3, 4], 4)<br>[1, 2, 3, 4]</pre><h3>⚙️ Why This Matters</h3><p>The same slicing pattern shows up across Python codebases — not just for<br> rotations, but for reordering sequences, cyclic buffers, and even text<br> transformations. Understanding slicing makes your code shorter, faster, and<br> easier to reason about.</p><p>In production, this approach is:</p><ul><li><strong>Readable:</strong> clear intent at a glance</li><li><strong>Safe:</strong> handles edge cases cleanly</li><li><strong>Performant:</strong> O(N) time, O(N) space</li></ul><h3>💡 Lessons Beyond This Problem</h3><p>This isn’t just about rotation. It is about <strong>thinking</strong> in slices. It can be used in many cases where a less efficient approach may be taken.</p><pre>wordlist = [&#39;Medium&#39;, &#39;article&#39;, &#39;This&#39;, &#39;is&#39;, &#39;my&#39;]<br>print(&#39; &#39;.join([[wordlist[-3:]] + wordlist[:-3])<br># prints &#39;This is my Medium article&#39;</pre><p>Try implementing this approach by adding a direction flag to support left-rotation while still keeping the logic compact and simple.</p><h3>🏁 Final Thoughts</h3><p>Simple problems like this remind us why Python is such a joy to write. One clear expression can replace a page full of procedural logic.</p><p>Master slicing, and you will not only write shorter code — you will write clearer code.</p><h3>🙌 If You Made It This Far…</h3><p>If you found this article helpful, please <strong>give it a clap</strong> to let me know it resonated with you! 👏</p><p>And don’t keep it to yourself — <strong>share it with others</strong> who might benefit from learning clean, Pythonic approaches to algorithm problems.</p><p>Your support helps me create more content like this and keeps the Python community thriving. Thank you!</p><blockquote>✨ “Beautiful is better than ugly… Simple is better than complex”<br> — The Zen of Python</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*oSgHk-EZrDGkhPrqCu9viQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d852d70759dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>