<?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 Leo Capuano on Medium]]></title>
        <description><![CDATA[Stories by Leo Capuano on Medium]]></description>
        <link>https://medium.com/@leocapvano?source=rss-ea7232bc95eb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FoiIo5rK5vAy8LwHWMhK2A.jpeg</url>
            <title>Stories by Leo Capuano on Medium</title>
            <link>https://medium.com/@leocapvano?source=rss-ea7232bc95eb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:00:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leocapvano/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[AWS AgentCore is awesome]]></title>
            <link>https://medium.com/@leocapvano/aws-agentcore-is-awesome-ac9be7561a70?source=rss-ea7232bc95eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac9be7561a70</guid>
            <category><![CDATA[amazon-bedrock-agentcore]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Leo Capuano]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 22:09:20 GMT</pubDate>
            <atom:updated>2026-01-05T22:09:20.996Z</atom:updated>
            <content:encoded><![CDATA[<p>I was experimenting with AWS AgentCore lately. I wanted to see how easy and powerful it is to write, deploy and connect a simple agent in production so I decided to take one of my latest projects (Telegram Bot powered by a LangGraph agent) and deploy it to AgentCore.</p><p>The starting point is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AtxTrzKx7DTWGo8l" /></figure><p>old architecture</p><p>what is it?</p><p>It is a Telegram Bot that is deployed on AWS in a fully serverless style. How does it works in just a few words?</p><ol><li>The user opens a bot’s chat on Telegram</li><li>Telegram sends this request to an exposed API Gateway (protected by IP CIDR whitelist)</li><li>API Gateway invokes a Lambda that implements a simple LangGraph agent</li><li>The response is sent back to Telegram servers which sends a message in the user’s chat</li></ol><h3>The idea</h3><p>Reading AgentCore’s documentation it is clear that this technology allows you to create an isolated runtime that can host your agents and execute them in an isolated environment; so my idea was to add an AgentCore Runtime component after the Lambda function that can execute my agent logic. Let’s see how easy it is!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wH4AXaR_mUa1xdDW" /></figure><p>new architecture</p><h3>Strands Agents</h3><p>Strands Agents is an open source SDK that allows you to create agents (like LangGraph, ADK, CrewAI, etc.); for this new agent I will use this SDK as it is very easy to set up a simple and running agent.</p><p>If you want to explore more: <a href="https://strandsagents.com/latest/">https://strandsagents.com/latest/</a></p><h3>The agent’s code</h3><p>AgentCore is just the infrastructure that runs our agent, the code has to be written by us, and to allow AgentCore to invoke our agent we need to respect a contract (well documented on AWS’s doc). Here is a basic example of an agent written using Strands Agents SDK and that exposes the HTTP endpoints required by AgentCore Runtime:</p><pre># agent.py file</pre><pre>from fastapi import FastAPI, HTTPException<br>from pydantic import BaseModel<br>from typing import Dict, Any<br>from datetime import datetime<br>from strands import Agent<br>from strands.models.openai import OpenAIModel<br>import logging<br>from strands.agent.conversation_manager import SlidingWindowConversationManager</pre><pre># Create a conversation manager with custom window size<br>conversation_manager = SlidingWindowConversationManager(<br>    window_size=10,<br>    should_truncate_results=True,<br>)</pre><pre>logging.getLogger(&quot;strands&quot;).setLevel(logging.INFO)<br>logger = logging.getLogger(&quot;strands&quot;)<br>logger.addHandler(logging.StreamHandler())</pre><pre>app = FastAPI(title=&quot;Strands Agent Server&quot;, version=&quot;1.0.0&quot;)</pre><pre>openai_model = OpenAIModel(<br>    model_id=&quot;o3-mini-2025-01-31&quot;,<br>    client_args={&quot;api_key&quot;: &quot;...&quot;}, # do not hardcode key here<br>    # params={&quot;temperature&quot;: 0.2},<br>)<br>agent = Agent(model=openai_model, conversation_manager=conversation_manager)<br></pre><pre>class InvocationRequest(BaseModel):<br>    input: Dict[str, Any]<br></pre><pre>class InvocationResponse(BaseModel):<br>    output: Dict[str, Any]<br></pre><pre>@app.post(&quot;/invocations&quot;, response_model=InvocationResponse)<br>async def invoke_agent(request: InvocationRequest):<br>    logger.info(f&quot;Received new request: {str(request.input)}&quot;)<br>    try:<br>        user_message = request.input.get(&quot;prompt&quot;, &quot;&quot;)<br>        if not user_message:<br>            logger.error(&quot;Prompt not provided in input!&quot;)<br>            raise HTTPException(<br>                status_code=400,<br>                detail=&quot;No prompt found in input. Please provide a &#39;prompt&#39; key in the input.&quot;,<br>            )</pre><pre>        result = agent(user_message)<br>        response = {<br>            &quot;message&quot;: result.message,<br>            &quot;timestamp&quot;: datetime.utcnow().isoformat(),<br>        }</pre><pre>        return InvocationResponse(output=response)</pre><pre>    except Exception as e:<br>        logger.exception(&quot;Internal server error while processing request&quot;)<br>        raise HTTPException(<br>            status_code=500, detail=f&quot;Agent processing failed: {str(e)}&quot;<br>        )<br></pre><pre>@app.get(&quot;/ping&quot;)<br>async def ping():<br>    return {&quot;status&quot;: &quot;healthy&quot;}<br></pre><pre>if __name__ == &quot;__main__&quot;:<br>    import uvicorn<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8080)</pre><p>as you can see AgentCore Runtime requires the endpoints /invocations and /ping to be defined as it uses them to invoke and health-check our agent respectively.</p><h3>Create docker image</h3><p>AgentCore Runtime has many deployment modes, my favourite one is through docker. Basically we need to build a docker image, push it to a registry (ECR in our case) and then AgentCore automatically pulls and uses it.</p><p>A very simple Dockerfile for the above agent will be:</p><pre>FROM python:3.14.2-slim<br>WORKDIR /app<br>COPY requirements.txt requirements.txt<br>RUN pip install -r requirements.txt<br>COPY agent.py agent.py<br>EXPOSE 8080</pre><pre># Run application<br>CMD [&quot;uvicorn&quot;, &quot;agent:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8080&quot;]</pre><p>One important note to deploy our agent is that AgentCore Runtime runs the agent’s container in a MicroVM with AWS Graviton processors for cost and efficiency purposes; this means that our image has to be built for ARM64 platform.</p><p>Ok done, we just need to build the image and push it to ECR:</p><pre>docker buildx create --use</pre><pre># Authenticate Docker to Amazon ECR<br>aws ecr get-login-password --region &lt;region&gt; | docker login --username AWS --password-stdin &lt;accountID&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com</pre><pre># Build and push the image (ARM64)<br>docker buildx build \<br>  --platform linux/arm64 \<br>  -t &lt;accountID&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com:latest \<br>  --push .</pre><h3>Deploy AgentCore Runtime</h3><p>Deploy an AgentCore Runtime means run a command in AWS CLI:</p><pre>aws bedrock-agentcore-control create-agent-runtime --agent-runtime-name &quot;AGENT_RUNTIME_NAME&quot; --agent-runtime-artifact containerConfiguration={containerUri=ACCOUNT_ID.dkr.ecr.REGION.amazonaws.com/IMAGE_NAME:IMAGE_TAG} --role-arn AGENT_EXECUTION_ROLE_ARN --network-configuration networkMode=PUBLIC --region $AWS_REGION</pre><p>Note that you also need to create an AgentCore execution role that is simply an IAM role that gives your agent permission to operate; if you read the AWS’s doc you can find a basic AgentCore execution role to start using it:</p><pre>{<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Action&quot;: [<br>                &quot;ecr:BatchGetImage&quot;,<br>                &quot;ecr:GetDownloadUrlForLayer&quot;<br>            ],<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: [<br>                &quot;&lt;your ECR&gt;&quot;<br>            ],<br>            &quot;Sid&quot;: &quot;ECRImageAccess&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;ecr:GetAuthorizationToken&quot;<br>            ],<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Sid&quot;: &quot;ECRTokenAccess&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;logs:DescribeLogStreams&quot;,<br>                &quot;logs:CreateLogGroup&quot;<br>            ],<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: [<br>                &quot;&lt;your cw&gt;&quot;<br>            ]<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;logs:DescribeLogGroups&quot;<br>            ],<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: [<br>                &quot;&lt;your cw&gt;&quot;<br>            ]<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;logs:CreateLogStream&quot;,<br>                &quot;logs:PutLogEvents&quot;<br>            ],<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: [<br>                &quot;&lt;your cw&gt;&quot;<br>            ]<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;xray:PutTraceSegments&quot;,<br>                &quot;xray:PutTelemetryRecords&quot;,<br>                &quot;xray:GetSamplingRules&quot;,<br>                &quot;xray:GetSamplingTargets&quot;<br>            ],<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: [<br>                &quot;*&quot;<br>            ]<br>        },<br>        {<br>            &quot;Action&quot;: &quot;cloudwatch:PutMetricData&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;cloudwatch:namespace&quot;: &quot;bedrock-agentcore&quot;<br>                }<br>            },<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;bedrock-agentcore:GetWorkloadAccessToken&quot;,<br>                &quot;bedrock-agentcore:GetWorkloadAccessTokenForJWT&quot;,<br>                &quot;bedrock-agentcore:GetWorkloadAccessTokenForUserId&quot;<br>            ],<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:bedrock-agentcore:&lt;region&gt;:&lt;accountid&gt;:workload-identity-directory/default&quot;,<br>                &quot;arn:aws:bedrock-agentcore:&lt;region&gt;:&lt;accountid&gt;:workload-identity-directory/default/workload-identity/&lt;agent_name&gt;-*&quot;<br>            ],<br>            &quot;Sid&quot;: &quot;GetAgentAccessToken&quot;<br>        }<br>    ],<br>    &quot;Version&quot;: &quot;2012-10-17&quot;<br>}</pre><h3>Connect the agent</h3><p>The last step was to invoke my new agent running on AgentCore Runtime from my old Lambda function (that is now a wrapper). Here is the code to do it:</p><pre>agent_core_client = boto3.client(&quot;bedrock-agentcore&quot;, region_name=&quot;...&quot;)</pre><pre>response = agent_core_client.invoke_agent_runtime(<br>        agentRuntimeArn=AGENTCORE_RUNTIME_ARN,<br>        runtimeSessionId=session_id,  # Must be 33+ chars<br>        payload=payload,<br>        qualifier=&quot;DEFAULT&quot;, # the default alias<br>    )</pre><pre>response_body = response[&quot;response&quot;].read()<br>response_data = json.loads(response_body)</pre><pre>print(f&quot;AgentCore Response: {response_data}&quot;)</pre><p>Done 🙂</p><h3>Technical notes</h3><p>How does AgentCore Runtime work? Every time you invoke your agent with a session_id, AgentCore creates a new MicroVM that will host your code and executes your agent (if you pass a session_id that is bound to a MicroVM that already exists, AgentCore will re-use that running agent).</p><p>This session management is configurable at creation time by adding “ — lifecycle-configuration idleRuntimeSessionTimeout=&lt;seconds&gt;”; this means that you can specify the number of seconds that AgentCore will keep you MicroVM running if it is Idle (not used).</p><p>The benefit? You have complete session isolation. In my Telegram bot for example, the session_id is a combination of Telegram user ID and chat ID, so that for every user and chat, I can deploy an isolated MicroVM and the agent has access to the conversation history out of the box!</p><h3>Conclusions</h3><p>AgentCore is full of features with this short article, I wanted to show how easy it is to get started and deploy a simple agent using AgentCore Runtime. The key takeaway is that you get access to AWS’s operational excellence, security, and stability when running agents in a production environment.</p><p>You can explore more on AgentCore on the official AWS’s documentation (AgentCore Identity, Memory, Gateway, Observability, Tools, etc.)</p><p><a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/what-is-bedrock-agentcore.html">https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/what-is-bedrock-agentcore.html</a></p><p>Hope you liked it, happy deploy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac9be7561a70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentic code execution]]></title>
            <link>https://medium.com/@leocapvano/agentic-code-execution-564b030bab84?source=rss-ea7232bc95eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/564b030bab84</guid>
            <category><![CDATA[ai-tool-calling]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Leo Capuano]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 15:31:45 GMT</pubDate>
            <atom:updated>2025-12-08T15:31:45.897Z</atom:updated>
            <content:encoded><![CDATA[<h3>Agentic Code Execution: optimise agentic workflows</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hA_VhxFGnN7mDCWb" /><figcaption>Photo by <a href="https://unsplash.com/@agk42?utm_source=medium&amp;utm_medium=referral">Alex Knight</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Context</h3><p>When building AI agents today, the core design challenge is crafting an efficient workflow around one key element: <strong>tools</strong>.</p><p>Tools allow a model to interact with external systems, perform tasks, and retrieve information. Recently the ecosystem has matured rapidly, and we now have <strong>two main paradigms</strong> for enabling tool usage:</p><ol><li><strong>Function Tool Calling</strong> — The model selects a function, fills in structured arguments, and receives structured results.</li><li><strong>MCP (Model Context Protocol)</strong> — A protocol-based abstraction that allows models to interact with tools in a more declarative and standardized way.</li></ol><p>Both are powerful, but each inherit a foundational limitation: <strong>tools are static</strong>.</p><p>They must be defined in advance with fixed arguments, fixed internal logic, and fixed return types.</p><p>This rigidity becomes problematic as agents become more capable, multi-step, and autonomous.</p><h3>The Problem</h3><h3>1. Tools are inherently static</h3><p>A Python function used as a tool might look like:</p><pre>def resize_image(path: str, width: int, height: int) -&gt; str:<br>    ...</pre><p>This function has:</p><ul><li><strong>Fixed arguments</strong></li><li><strong>Fixed internal code</strong></li><li><strong>Fixed return value format</strong></li></ul><p>If the model wants to:</p><ul><li>Resize an image <em>and</em> crop it</li><li>Resize it using a different algorithm</li><li>Resize multiple images in parallel</li><li>Produce additional metadata</li></ul><p>…it simply <em>cannot</em>, unless the developer <strong>modifies the function</strong>. This means tool design is a bottleneck for agent intelligence.</p><h3>2. Too many tools = too many tokens</h3><p>Every tool definition is injected into the model’s context window.</p><p>If you create dozens of tools, you automatically:</p><ul><li>Inflate the base prompt</li><li>Increase latency</li><li>Increase token cost</li><li>Increase the chance of model confusion</li></ul><p>AI engineers often try to compress functionality using <strong>feature flags</strong>:</p><pre>def file_manager(path: str, delete: bool = False, read: bool = False, write: bool = False):<br>    ...</pre><p>But this quickly becomes unwieldy:</p><ul><li>Argument lists grow large</li><li>Internal code becomes complex</li><li>Models make more mistakes filling arguments</li><li>The tool becomes unclear and harder to maintain</li></ul><h3>3. Intermediate results consume tokens</h3><p>Each tool call returns data that the model must read and interpret.</p><p>For multi-step reasoning, intermediate data may flood the context and waste tokens.</p><p>Example:</p><ol><li>A tool call returns a JSON list of 10,000 items</li><li>That list is returned → 10,000 JSON items go into the context</li><li>The model passes this list to a subsequent tool call → 10,000 JSON items go into the context</li><li>Second tool call produces another list of 5,000 items → 5,000 JSON items go into the context</li><li>and so on …</li></ol><p>You pay for all of it.</p><h3>The Solution — Exec: Dynamic Code Tools</h3><p>Instead of exposing <em>static functions</em>, expose <strong>a single tool</strong> that simply executes arbitrary code generated by the model.</p><h3>Example API</h3><pre>def execute_python(code: str) -&gt; str:<br>    exec(code, globals()) # exec() will execute python code inside a string variable</pre><h3>Model usage</h3><pre>{<br>  &quot;tool&quot;: &quot;execute_python&quot;,<br>  &quot;code&quot;: &quot;<br>		files = [f for f in os.listdir(&#39;.&#39;) if f.endswith(&#39;.log&#39;)]<br>		files = files[:50]<br>		print(&#39;\\\\n&#39;.join(files))<br>	&quot;<br>}</pre><p>Now your tool collapses dozens of predefined functions into <strong>one universal interface</strong>.</p><h3>Advantages</h3><ul><li>Infinite flexibility</li><li>No predefined arguments needed</li><li>No complex branching logic</li><li>The agent controls its own workflow</li><li>Can dynamically generate bespoke code per task</li><li>Significant reduction in token usage for tool definitions</li></ul><h3>But there’s a big issue</h3><p><strong>Security.</strong></p><p>Executing model-generated Python inside your main interpreter is dangerous:</p><ul><li>os.remove(&quot;/&quot;)</li><li>exfiltration of files</li><li>infinite loops</li><li>memory exhaustion</li><li>environment modification</li></ul><p>Unless executed inside a hardened sandbox, exec is unsafe.</p><h3>The Solution — Subprocess Sandboxing</h3><p>A safer approach is executing model-generated code inside a <strong>subprocess</strong> with strict isolation.</p><h3>Example implementation</h3><pre>import subprocess<br>import tempfile<br>import sys<br><br>def run_python_subprocess(code: str) -&gt; str:<br>    with tempfile.NamedTemporaryFile(suffix=&quot;.py&quot;, delete=False) as f:<br>        f.write(code.encode())<br>        path = f.name<br>    <br>    result = subprocess.run(<br>        [sys.executable, path],<br>        capture_output=True,<br>        text=True,<br>        timeout=5,<br>        cwd=&quot;/tmp&quot;<br>    )<br>    return result.stdout or result.stderr</pre><h3>Why subprocess is safer</h3><ul><li>Interpreter runs in a separate process</li><li>OS-level limitations possible:</li><li>seccomp</li><li>cgroups</li><li>AppArmor / SELinux</li><li>CPU, memory, and timeout limits</li><li>Can run inside a throwaway container</li><li>Isolated filesystem access</li></ul><h3>Example usage</h3><pre>{<br>  &quot;tool&quot;: &quot;run_python_subprocess&quot;,<br>  &quot;code&quot;: &quot;<br>		import json, glob, os<br>                images = glob.glob(&#39;*.png&#39;)<br>                result = [{&#39;file&#39;: f, &#39;size&#39;: os.path.getsize(f)} for f in images]<br>                print(json.dumps(result))<br> &quot;<br>}</pre><p>This allows:</p><ul><li>dynamic logic</li><li>multi-step pipelines</li><li>data processing</li><li>arbitrary algorithms</li></ul><p>…all with <strong>one flexible tool</strong>.</p><p>Alongside subprocess sandboxing (which isn’t 100% safe as implemented above), you can use other techniques such as running Python in isolated mode (python -I), preventing dangerous imports by overriding builtins.__import__, adding timeout protection, containerization, and more.</p><p>Do not use this code in production — it’s written only to showcase an approach you can use to overcome some limitations of traditional tool calling.</p><h3>Practical Use Cases</h3><h3>1. Data Transformation Tools</h3><p>Agents write custom logic to generate CSVs, JSON, XML, XLSX, etc.</p><h3>2. CodeAssist / CodeMode</h3><p>Agents write and execute code as part of their reasoning loop.</p><h3>3. Autonomous Engineering Agents</h3><p>Agents can:</p><ul><li>explore environments</li><li>run tests</li><li>build artifacts</li><li>parse data</li></ul><p>without predefined static functions.</p><h3>References</h3><p>If you want to explore more about agentic code execution, the topic is evolving rapidly, consider reading more:</p><ul><li><a href="https://www.anthropic.com/engineering/code-execution-with-mcp">Anthropic — <em>Code Execution with MCP</em></a></li><li><a href="https://blog.cloudflare.com/code-mode/">Cloudflare — <em>Code Mode</em></a></li></ul><h3>Conclusions</h3><p>Traditional function-based tools limit the flexibility and intelligence of agents.</p><p>As workflows grow more complex, static tool definitions become a bottleneck and increase token usage.</p><p><strong>Agentic code execution</strong> — where the model writes and executes its own code — provides a solution:</p><ul><li>One tool replaces dozens</li><li>Token usage decreases</li><li>Workflows become adaptive</li><li>Developers write less boilerplate</li><li>Agents gain full expressive power</li></ul><p>exec enables this paradigm, while subprocess makes it practical and safe.</p><p>Modern agent architectures are shifting from “functions with arguments” to <strong>dynamic code execution tools</strong>, enabling the next generation of powerful agentic systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=564b030bab84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS GUI for Localstack]]></title>
            <link>https://medium.com/@leocapvano/aws-gui-for-localstack-507d4b09d47b?source=rss-ea7232bc95eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/507d4b09d47b</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-secrets-manager]]></category>
            <category><![CDATA[localstack]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Leo Capuano]]></dc:creator>
            <pubDate>Sat, 18 Jan 2025 10:46:07 GMT</pubDate>
            <atom:updated>2025-01-18T10:46:07.918Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simplify Your Local AWS Workflow with a GUI for Localstack</h3><p>Managing Amazon S3 and AWS Secrets Manager on <strong>Localstack</strong> just got easier with a Python-based graphical user interface (GUI). Whether you’re developing or testing AWS services locally, this tool simplifies your workflow with a user-friendly interface for managing S3 buckets and SecretsManager secrets.</p><p>Let’s explore this project, its features, and how you can get started quickly.</p><p>GitHub link: <a href="https://github.com/leo-capvano/Localstack-GUI/tree/main">https://github.com/leo-capvano/Localstack-GUI/tree/main</a></p><h3>What Is Localstack?</h3><p><strong>Localstack</strong> is a fully functional local AWS cloud stack. It enables developers to run and test AWS services such as <strong>S3 </strong>and <strong>Secrets Manager</strong> on their own local environment by emulating those services in a local docker container.</p><p>However, interacting with Localstack typically involves using the AWS CLI or SDK, which can be daunting for some users.</p><p>This GUI provides an intuitive and efficient way to perform common AWS operations without diving deep into the command line.</p><h3>Key Features of Localstack GUI</h3><h3>S3 Management Made Easy</h3><p>Managing S3 buckets and objects can be tedious, but with this GUI, you can:</p><ul><li><strong>Create Buckets</strong>: Spin up new S3 buckets locally with a click.</li><li><strong>List Buckets</strong>: View all the buckets you’ve created on your Localstack instance.</li><li><strong>Delete Buckets</strong>: Clean up unused buckets.</li><li><strong>Add Objects</strong>: Upload files directly into any bucket with ease.</li><li><strong>List Objects</strong>: See all files stored within a bucket in an organized format.</li><li><strong>View Object Details</strong>: Get metadata and other object-specific details.</li><li><strong>Remove Objects</strong>: Delete files from your buckets.</li><li><strong>Download Objects</strong>: Save files from Localstack buckets to your local system.</li><li><strong>Change Endpoint URL</strong>: Quickly update the Localstack endpoint if needed.</li></ul><h3>Secrets Manager at Your Fingertips</h3><p>AWS Secrets Manager helps securely store and access sensitive information like API keys. The GUI supports:</p><ul><li><strong>Create Secrets</strong>: Add new secrets.</li><li><strong>List Secrets</strong>: View all stored secrets in a structured list.</li><li><strong>Delete Secrets</strong>: Remove outdated or unnecessary secrets.</li><li><strong>View Secret Details</strong>: Check metadata and configuration details of each secret.</li><li><strong>View Secret Value</strong>: Securely access the values of your stored secrets.</li><li><strong>Change Endpoint URL</strong>: Update the Secrets Manager endpoint as per your configuration.</li></ul><h3>Why Use This GUI?</h3><ol><li><strong>Simplified Workflow</strong>: Perform complex AWS tasks without navigating through a command line.</li><li><strong>User-Friendly</strong>: The interface is designed to make managing buckets and secrets intuitive, even for beginners.</li><li><strong>Local Development</strong>: No need to connect to AWS — everything works with Localstack.</li><li><strong>Time-Saving</strong>: Focus on building and testing your applications while the GUI takes care of AWS operations.</li></ol><h3>Getting Started</h3><p>Here’s how you can set up the GUI and get started.</p><h3>System Requirements</h3><ul><li><strong>Docker &amp; Docker-Compose</strong>: Ensure these are installed on your machine.</li></ul><h3>Set Up Localstack</h3><p>First, run a Localstack container:</p><pre>cd localstack_gui/res  <br>docker-compose -f docker-compose-localstack.yml up -d  <br>docker ps  # Verify the container is running</pre><h3>Run the GUI</h3><p>You can interact with the application in two ways:</p><p><strong>Executable File</strong><br>An .exe file is available for quick execution:</p><p>cd localstack_gui/dist run.exe # Start the GUI</p><p><em>(Tip: You can add the executable file to your PATH for easier access.)</em></p><p>The .exe file will run for you a Streamlit web application reachable through your browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*zJFfFKTNLFFIMQ5Y0Fvi0w.png" /></figure><h3>Feature Showcase</h3><h3>Run Localstack container first</h3><p>We provided a docker-compose file inside the project at <em>res/docker-compose-localstack.yml</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*Hi4Wuw_1p3RGUfRdKK3BQQ.png" /></figure><p>Check your Localstack container is running using <em>docker ps</em> command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPxz65iqM5yg6xRlWI1wXQ.png" /></figure><h3>S3 Interface</h3><p>Create a new S3 bucket called <em>my-bucket </em>and upload a file with an object prefix <em>files/</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AcgGTLVOAwq0NZin39hPVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8-Gsg6hBwhEF3duzqKd-w.png" /><figcaption>Upload file dialog</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-orFowdE69p37boTSuvcA.png" /><figcaption>Bucket content after file upload</figcaption></figure><h3>Secrets Manager</h3><p>Create a new secret named <em>my-secret</em> with a secret value of <em>my-secret-value:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xkcl2MpWmAWg2fQ5N-W-cQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*efwrZATFrP1Ea67nTO2SIA.png" /><figcaption>Localstack SecretsManager after creating our secret, with all the possibile secret operations</figcaption></figure><h3>Contributing</h3><p>This is an open-source project, and contributions are welcome! Whether you’re fixing bugs, enhancing features, or adding new ones, your help is greatly appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=507d4b09d47b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Fine-Tuning with OpenAI]]></title>
            <link>https://medium.com/@leocapvano/llm-fine-tuning-with-openai-31e527893cb9?source=rss-ea7232bc95eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/31e527893cb9</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Leo Capuano]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 18:07:44 GMT</pubDate>
            <atom:updated>2024-11-21T18:07:44.641Z</atom:updated>
            <content:encoded><![CDATA[<p>This post explains what is LLM fine tuning and shows a simple example to quickly get started with your first LLM fine-tuning using OpenAI’s platform.</p><p>We will refer to <a href="https://github.com/leo-capvano/llm-fine-tuning-openai">llm-fine-tuning-openai</a> project to explain some concepts and show a real example of a fine-tuning task.</p><h3>What is Fine Tuning?</h3><p>Fine-tuning is a procedure that improves LLM models available through the API; it enhances the response quality, make you save cost by reducing tokens with shorter prompts and reduces the generation’s latency.</p><p>OpenAI’s text generation models are pre-trained on extensive datasets, enabling them to handle a variety of tasks. To guide the models effectively, prompts often include instructions and a few examples, a technique known as “<strong>few-shot learning</strong>” which demonstrates the desired task directly within the input.</p><p>Here’s an example of <strong>few-shot learning</strong> to teach a model how to format movie reviews:</p><p><strong>Prompt:</strong><br><em>“Format the movie reviews as follows:<br>Review: [Your thoughts on the movie]<br>Rating: [Stars out of 5]</em></p><p><em>Examples:</em></p><ol><li><em>Review:</em><strong><em> </em></strong><em>The movie was visually stunning and emotionally gripping. A masterpiece.<br>Rating: ⭐⭐⭐⭐⭐</em></li><li><em>Review: The plot was predictable, but the acting was decent.<br>Rating: ⭐⭐⭐</em></li></ol><p><strong>Completion:</strong><br><em>The action scenes were thrilling, but the pacing was slow.<br>Rating: ⭐⭐⭐⭐</em></p><p><strong>The few-shot examples help the model learn the pattern and structure of the desired output, so it can apply the format to new inputs effectively.</strong></p><p><strong>Fine-tuning </strong>takes few-shot learning to the next level by training models on significantly more examples than a prompt can include. This leads to better performance across a wider range of tasks.</p><p>Once fine-tuned, the model requires fewer (or any) examples in the prompt, reducing costs and enabling faster, more efficient responses.</p><p>Here are the 3 steps to fine-tune an LLM:</p><ol><li>Prepare training data</li><li>Train a model using training data</li><li>Use your fine-tuned LLM</li></ol><h3>Prepare Training Data</h3><p>To train a model effectively, you need a diverse dataset of example conversations that mirror the type of interactions you expect in production.</p><p>These examples should follow the <a href="https://platform.openai.com/docs/api-reference/chat/create"><strong>Chat Completions API format</strong></a>, consisting of a list of messages where each message includes a <strong>role</strong> (e.g., system, user, assistant), <strong>content</strong>, and optionally a <strong>name</strong>.</p><p>For example let’s create a training dataset that contains request and responses for a product support chatbot:</p><pre>{&quot;messages&quot;: [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Eva is a product support chatbot for a product named Galaxy ZPhone 12&quot;}, {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;How can I reset my Galaxy ZPhone 12?&quot;}, {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;To reset your Galaxy ZPhone 12, go to Settings &gt; System &gt; Z12Reset options, and choose &#39;Reset this phone :)&#39; Don’t forget to back up your data first!&quot;}]}<br>{&quot;messages&quot;: [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Eva is a product support chatbot for a product named Galaxy ZPhone 12&quot;}, {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;What’s the warranty period for the Galaxy ZPhone 12?&quot;}, {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;The Galaxy ZPhone 12 comes with a 33-year warranty starting from the purchase date. Keep your receipt handy for warranty claims.&quot;}]}<br>{&quot;messages&quot;: [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Eva is a product support chatbot for a product named Galaxy ZPhone 12&quot;}, {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;My Galaxy ZPhone 12 isn’t charging. What should I do?&quot;}, {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;First, try using a different charger and cable to rule out accessory issues. If it’s still not charging, visit our nearest ZService center for assistance, they will replace your battery for free.&quot;}]}</pre><p>(you need to add <em>at least 10 </em>of these rows to the fine-tuning training dataset in order to start a fine-tuning job)</p><p>In this case we are training our LLM to generate responses about a dummy Galaxy ZPhone 12 …</p><h3>Train a model using training data</h3><p>Once you have created the training dataset file, it has to be uploaded the the OpenAI’s storage through the <a href="https://platform.openai.com/docs/api-reference/files/create">Files API</a>; it will later be used by the fine-tuning job.</p><p>The following code defines 3 functions:</p><ol><li><em>upload_training_file </em>uploads a given file (under the res/ folder) to OpenAI’s storage</li><li><em>create_training_job </em>creates a new fine-tuning job that will use the previously uploaded file to re-train our model</li></ol><pre>import os<br>from openai import OpenAI<br><br>client = OpenAI()<br><br>def create_training_job(training_file: str, model: str):<br>    return client.fine_tuning.jobs.create(<br>        training_file=training_file,<br>        model=model<br>    )<br><br>def upload_training_file(training_file_name: str):<br>    with open(os.path.join(&quot;res&quot;, training_file_name), &quot;rb&quot;) as training_data_file:<br>        return client.files.create(file=training_data_file, purpose=&quot;fine-tune&quot;)</pre><p>We can use those 2 functions to create a procedure that <strong>uploads a training file </strong>and then <strong>starts a fine-tuning job:</strong></p><pre>import time<br><br>from svc.training_svc import upload_training_file, create_training_job, training_job_status<br><br>BASE_MODEL = &quot;gpt-4o-2024-08-06&quot;<br><br>def main():<br>    print(&quot;This is your OpenAI fine-tuning pipeline.&quot;)<br>    training_file_name = input(&quot;Choose the training file name. It must be placed into the res/ folder -&gt; &quot;)<br>    training_file = upload_training_file(training_file_name)<br>    prompt = input(&quot;A new Fine-Tuning job will be created. Do you confirm? [y/N] -&gt; &quot;)<br>    if prompt.lower() == &quot;y&quot;:<br>        job = create_training_job(training_file.id, BASE_MODEL)<br>        start_time = time.time()<br>        while training_job_status(job.id).fine_tuned_model is None:<br>            time.sleep(5)<br>            print(<br>                f&quot;The fine tuning job is in progress, wait until it finishes ... {int(time.time() - start_time)}s elapsed&quot;)<br>        print(f&quot;Fine Tuning completed, your custom model id is: {training_job_status(job.id).fine_tuned_model}&quot;)</pre><p>This script will:</p><ol><li>ask for the filename of the training data to upload</li><li>uploads training data to OpenAI’s storage</li><li>starts a new fine-tuning job using <strong><em>gpt-4o </em></strong>model</li></ol><p>At the end of the execution you will be able to see the training data file uploaded into OpenAI’s storage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zAOG4AWO3Dm4XW6jn2QIiw.png" /><figcaption>training data file in OpenAI’s storage</figcaption></figure><p>And a fine-tuning job being executed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFmySHU8QlB85XCkR-jynA.png" /><figcaption>list of many fine-tuning jobs inside the OpenAI’s console</figcaption></figure><p>from this view we have to extract the <strong><em>Output model</em></strong> field, as this value represents the name of our new <strong>fine-tuned LLM.</strong></p><p>For each fine-tuning job it’s possible to see some training metrics; this is useful to evaluate the quality of the training process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*6IMrA2Mwt88f9EX9aueydw.png" /></figure><h3>Use your fine-tuned LLM</h3><p>Once your job is finished, the model should be ready for inference use immediately. However, in some cases, it may take a few minutes for the model to fully load and handle requests. If you encounter timeouts or cannot find the model name, it’s likely still loading. Simply wait a few minutes and try again.</p><p>As mentioned above, the most important output of our job is the <strong><em>Output model </em></strong>field; this is the name of our new fine-tuned LLM that we can use with the <em>LLM chat API.</em></p><p>This code will show you how to use a fine-tuned model:</p><pre>from svc.llm_svc import ask_model<br><br>EXIT_KEYWORD = &quot;bye&quot;<br><br># send user question to the LLM (function in the snippet below)<br>def ask(user_input):<br>    for chunk in ask_model(user_input=user_input):<br>        yield chunk<br><br>def main():<br>    print(&quot;Eva: Hello! I am Eva, your chatbot :). Type &#39;bye&#39; to exit.&quot;)<br>    while True:<br>        user_input = input(&quot;\n\nYou: &quot;)<br>        if user_input.lower() == EXIT_KEYWORD:<br>            print(&quot;Chatbot: Goodbye! Have a great day!&quot;)<br>            break<br><br>        print(&quot;\nEva: &quot;)<br>        for chunk in ask(user_input):<br>            print(chunk, end=&#39;&#39;, flush=True)</pre><pre>from openai import OpenAI<br><br>client = OpenAI()<br><br># this is the name of the fine-tuned model<br>MODEL = &quot;ft:gpt-4o-2024-08-06:personal::AVlKXZY3&quot;<br><br># generate responses in streaming mode and send<br># each chunk to the console output<br>def ask_model(user_input: str):<br>    completion = client.chat.completions.create(<br>        model=MODEL,<br>        messages=[<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a product support chatbot for the ZPhone 12&quot;},<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input}<br>        ],<br>        stream=True<br>    )<br>    for chunk in completion:<br>        yield chunk.choices[0].delta.content</pre><p>This script:</p><ul><li>loops through a user input that will have a conversation with an LLM until it writes “bye” into the prompt</li><li>queries the fine-tuned LLM</li><li>streams the response and shows each chunk to the console</li></ul><h3>Conclusions</h3><p>In this post, we’ve explored the concept of fine-tuning Large Language Models (LLMs) and demonstrated how to quickly get started using OpenAI’s platform.</p><p>Fine-tuning allows you to enhance the performance of pre-trained models by tailoring them to your specific use cases, reducing token costs, and improving response latency.</p><p>We provided a step-by-step guide, from preparing training data to deploying and using your fine-tuned model, with examples and code snippets for clarity. By following these steps, you can customize LLMs like GPT to meet the unique needs of your application, ensuring higher-quality outputs and a better user experience.</p><p>Fine-tuning is a powerful tool to unlock the full potential of LLMs for production-grade tasks.</p><p>Consider a contribution to my GitHub project: <a href="https://github.com/leo-capvano/llm-fine-tuning-openai">https://github.com/leo-capvano/llm-fine-tuning-openai</a></p><p>:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31e527893cb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[S.O.L.I.D. Principles Cheat Sheet]]></title>
            <link>https://medium.com/@leocapvano/s-o-l-i-d-principles-cheat-sheet-ab5e0b4f1dbb?source=rss-ea7232bc95eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab5e0b4f1dbb</guid>
            <category><![CDATA[design-pattern-in-python]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[objectorientedprogramming]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <dc:creator><![CDATA[Leo Capuano]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 16:18:26 GMT</pubDate>
            <atom:updated>2024-07-05T16:20:41.405Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sU3g5Fqt3yl_L4As" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Emile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the world of software development, writing clean, maintainable, and scalable code is crucial. The SOLID principles, introduced by <strong>Robert C. Martin</strong>, offer a powerful toolkit for achieving these goals. These principles provide a foundation for designing robust object-oriented software.</p><p>In this guide, we will explore each SOLID principle with practical Java examples. Whether you’re a seasoned developer or just starting your Java journey, understanding and applying these principles will enhance the quality of your code.</p><h3>What are SOLID Principles?</h3><p>SOLID is an acronym that represents five core principles of object-oriented design:</p><ol><li><strong>S</strong>ingle Responsibility Principle (SRP)</li><li><strong>O</strong>pen/Closed Principle (OCP)</li><li><strong>L</strong>iskov Substitution Principle (LSP)</li><li><strong>I</strong>nterface Segregation Principle (ISP)</li><li><strong>D</strong>ependency Inversion Principle (DIP)</li></ol><h4>1. Single Responsibility Principle</h4><blockquote>A class should have only have one job or responsibility.</blockquote><p>Following SRP makes your code easier to understand and maintain. When a class has only one responsibility, changes to that class are less likely to impact other parts of your system.</p><p><strong>Java Example:</strong></p><p>Consider a class that handles both employee details and payroll calculations. This violates SRP because it has more than one responsibility (<em>changes in employee details logic can introduce regressions in the payroll logic</em>).</p><pre>// Violation of SRP<br>public class Employee {<br>    private String name;<br>    private String position;<br>    <br>    public void calculatePay() {<br>        // Salary calculation logic<br>    }<br>    <br>    public void saveEmployee() {<br>        // Database saving logic<br>    }<br>}<br><br>// Following SRP<br>public class Employee {<br>    private String name;<br>    private String position;<br>    <br>    // Employee related attributes and methods<br>}<br><br>public class PayrollService {<br>    public void calculatePay(Employee employee) {<br>        // Salary calculation logic<br>    }<br>}<br><br>public class EmployeeRepository {<br>    public void saveEmployee(Employee employee) {<br>        // Database saving logic<br>    }<br>}</pre><h4>2. Open/Closed Principle (OCP)</h4><blockquote>Software entities (classes, modules, functions, …) should be open for extension but closed for modification.</blockquote><p>Modifying a Class’s behavior will impact every system that relies on that Class. By adhering to OCP, you can add new functionality without altering existing code, thereby reducing the risk of introducing bugs.</p><p><strong>Java Example:</strong></p><p>Imagine a shape drawing application where new shapes might be added over time. Instead of modifying the existing shape-drawing logic, we can extend the functionality by adding new classes.</p><pre>// Violation of OCP<br>public class ShapeDrawer {<br>    public void drawShape(String shapeType) {<br>        if (shapeType.equals(&quot;circle&quot;)) {<br>            // Draw circle<br>        } else if (shapeType.equals(&quot;rectangle&quot;)) {<br>            // Draw rectangle<br>        }<br>        // More shapes to be added here...<br>    }<br>}<br><br>// Following OCP<br>public interface Shape {<br>    void draw();<br>}<br><br>public class Circle implements Shape {<br>    @Override<br>    public void draw() {<br>        // Draw circle<br>    }<br>}<br><br>public class Rectangle implements Shape {<br>    @Override<br>    public void draw() {<br>        // Draw rectangle<br>    }<br>}<br><br>public class ShapeDrawer {<br>    public void drawShape(Shape shape) {<br>        shape.draw();<br>    }<br>}</pre><h4>3. Liskov Substitution Principle (LSP)</h4><blockquote>Let ‍ m() be a property provable about objects ‍ x of type T. Then ‍ m() should be true for objects ‍y of type S where S is a subtype of T.</blockquote><p>This means that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. LSP ensures that derived classes extend the base class without changing its behavior. This maintains the program’s integrity when substituting classes.</p><p><strong>Java Example:</strong></p><p>Suppose we have a class Bird and a subclass Penguin. Penguins can&#39;t fly, so they shouldn&#39;t be substitutable for Bird if the Bird class assumes that all birds can fly.</p><pre>// Violation of LSP<br>public class Bird {<br>    public void fly() {<br>        // Fly logic<br>    }<br>}<br><br>public class Penguin extends Bird {<br>    @Override<br>    public void fly() {<br>        throw new UnsupportedOperationException(&quot;Penguins can&#39;t fly&quot;);<br>    }<br>}<br><br>// Following LSP<br>public interface Flyable {<br>    void fly();<br>}<br><br>public class Bird implements Flyable {<br>    public void fly() {<br>        // Fly logic<br>    }<br>}<br><br>public class Penguin {<br>    // Penguins don&#39;t fly -&gt; not a flyable -&gt; no fly method<br>}</pre><h4>4. Interface Segregation Principle (ISP)</h4><blockquote>A client should not be forced to implement behaviors it doesn’t use. Instead of one large interface, we should have multiple smaller, specific interfaces.</blockquote><p>ISP prevents classes from being forced to implement methods they do not use, promoting a more cohesive and modular design.</p><p><strong>Java Example:</strong></p><p>Consider a multifunction printer interface that forces every printer to implement all functionalities, even if a particular printer does not support some of them.</p><pre>// Violation of ISP<br>public interface MultifunctionPrinter {<br>    void print();<br>    void scan();<br>    void fax();<br>}<br><br>public class BasicPrinter implements MultifunctionPrinter {<br>    @Override<br>    public void print() {<br>        // Print logic<br>    }<br><br>    @Override<br>    public void scan() {<br>        // UnsupportedOperationException: Basic printers can&#39;t scan<br>        throw new UnsupportedOperationException(&quot;Scan not supported&quot;);<br>    }<br><br>    @Override<br>    public void fax() {<br>        // UnsupportedOperationException: Basic printers can&#39;t fax<br>        throw new UnsupportedOperationException(&quot;Fax not supported&quot;);<br>    }<br>}<br><br>// Following ISP<br>public interface Printer {<br>    void print();<br>}<br><br>public interface Scanner {<br>    void scan();<br>}<br><br>public interface Fax {<br>    void fax();<br>}<br><br>public class BasicPrinter implements Printer {<br>    @Override<br>    public void print() {<br>        // Print logic<br>    }<br>}<br><br>public class AdvancedPrinter implements Printer, Scanner, Fax {<br>    @Override<br>    public void print() {<br>        // Print logic<br>    }<br><br>    @Override<br>    public void scan() {<br>        // Scan logic<br>    }<br><br>    @Override<br>    public void fax() {<br>        // Fax logic<br>    }<br>}</pre><h4>5. Dependency Inversion Principle (DIP)</h4><blockquote>High-level modules (class that knows what to do) should not depend on low-level modules (the class that knows how to do it). Both should depend on abstractions.</blockquote><blockquote>Abstractions should not depend on details. Details should depend on abstractions.</blockquote><p>DIP reduces the dependency on specific implementations, making your code more flexible and easier to maintain.</p><p>A Class doesn’t have to know the specific implementation of one of its dependency; rather, it only has to know the interface that allows to use the dependency.</p><p><strong>Java Example:</strong></p><p>Consider a high-level class ShoppingCart that depends on a low-level class PaypalPaymentProcessor.</p><pre>// Violation of DIP<br>public class ShoppingCart {<br>    private PaypalPaymentProcessor paymentProcessor;<br>    <br>    public ShoppingCart() {<br>        this.paymentProcessor = new PaypalPaymentProcessor();<br>    }<br>    <br>    public void checkout() {<br>        paymentProcessor.processPayment();<br>    }<br>}<br><br>public class PaypalPaymentProcessor {<br>    public void processPayment() {<br>        // PayPal payment processing logic<br>    }<br>}<br><br>// Following DIP<br>public interface PaymentProcessor {<br>    void processPayment();<br>}<br><br>public class PaypalPaymentProcessor implements PaymentProcessor {<br>    @Override<br>    public void processPayment() {<br>        // PayPal payment processing logic<br>    }<br>}<br><br>public class ShoppingCart {<br>    private PaymentProcessor paymentProcessor;<br>    <br>    public ShoppingCart(PaymentProcessor paymentProcessor) {<br>        this.paymentProcessor = paymentProcessor;<br>    }<br>    <br>    public void checkout() {<br>        paymentProcessor.processPayment();<br>    }<br>}</pre><h3>Conclusion</h3><p>The SOLID principles are a cornerstone of good software design. They help in creating systems that are easy to understand, maintain, and extend. By following these principles, OOP developers can build robust, flexible, and scalable applications.</p><p>Ciao!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab5e0b4f1dbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>