<?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 Samin Chandeepa (Adomic) on Medium]]></title>
        <description><![CDATA[Stories by Samin Chandeepa (Adomic) on Medium]]></description>
        <link>https://medium.com/@saminchandeepa?source=rss-20594cbd238------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xyDiupfg2SJuT1Y83AgTAw.png</url>
            <title>Stories by Samin Chandeepa (Adomic) on Medium</title>
            <link>https://medium.com/@saminchandeepa?source=rss-20594cbd238------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 16:55:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saminchandeepa/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[Transform Gemma3 into a Reasoning Model using GRPO: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@saminchandeepa/transform-gemma3-into-a-reasoning-model-using-grpo-a-step-by-step-guide-4e674eb791a4?source=rss-20594cbd238------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e674eb791a4</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[reasoning-model]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[grpo]]></category>
            <dc:creator><![CDATA[Samin Chandeepa (Adomic)]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 06:33:42 GMT</pubDate>
            <atom:updated>2026-02-22T06:33:42.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7-1P4uHJP7dAKLyokObvA.png" /></figure><p>In this article, we’ll walk through a complete notebook that fine‑tunes <strong>Gemma3 (1B)</strong> to become a reasoning model using <strong>GRPO (Group Relative Policy Optimization).</strong><br>We’ll cover everything from the goal and the <em>theory behind GRPO, to data preparation, reward function design, code walkthrough</em>, and finally a peek under the hood of how GRPO actually works.</p><p>By the end, you’ll have a solid understanding of how to apply reinforcement learning to teach a language model to think step by step and output answers in a structured format.<br>👉You can run the original notebook for free on Google Colab, the link is at the end.</p><h3>1. Goal</h3><p>We want to transform the pretrained Gemma3 1B instruction model into a model that can solve grade‑school math problems (from the GSM8K dataset) by:</p><ul><li><strong><em>Reasoning explicitly</em></strong><em>, the model should output its thought process between special tags like </em><em>&lt;start_working_out&gt; and </em><em>&lt;end_working_out&gt;.</em></li><li><em>Delivering the final answer inside </em><em>&lt;SOLUTION&gt; … &lt;/SOLUTION&gt; tags.</em></li><li><em>Getting the answer correct, the extracted answer should match the ground truth.</em></li></ul><p>This is achieved by <strong>reinforcement learning (RL) specifically GRPO, </strong>where we give the model rewards for correct formatting and correct answers. Over many training steps, the model learns to maximise these rewards, thereby learning to reason.</p><h3>2. Basics of GRPO and Data Preparation</h3><h4>What is GRPO?</h4><p>GRPO (Group Relative Policy Optimization) is a reinforcement learning algorithm designed specifically for fine‑tuning large language models. It belongs to the family of policy gradient methods, but unlike PPO (Proximal Policy Optimization), it does not require a separate value network (critic). Instead, it uses the group of responses generated for the same prompt to estimate a baseline, making it more memory‑efficient and simpler to implement.</p><h4>Why “Group Relative”?</h4><p>For each prompt, we generate multiple completions (a group) from the current policy. We then compute a reward for each completion. The advantage of a particular response is defined relative to the group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*-ADfKvO8uwrGKqh2DML9Sw.png" /></figure><p>This standardises the rewards: a response with above‑average reward gets a positive advantage, while a below‑average response gets a negative advantage. The magnitude tells us how much better or worse it is compared to the group.</p><h4>The Policy Gradient Loss</h4><p><strong>The policy is the language model itself</strong>, parameterised by <em>θ</em>. It defines a probability distribution over sequences given a prompt: <strong><em>pθ​(response∣prompt)</em></strong>. The goal is to increase the probability of responses with high advantage and decrease those with low advantage.</p><p>The loss function is the negative advantage‑weighted log‑probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*hrZvM8-ENlS1hqfov1P2zw.png" /></figure><p>This is exactly the REINFORCE loss, but with a baseline (the group mean) that reduces variance without needing a learned value function.</p><h4>KL Penalty to Prevent Drift</h4><p>To avoid the model straying too far from its original behaviour (which could cause catastrophic forgetting or loss of fluency), we add a KL divergence penalty. We keep a copy of the model before the update (the reference policy, often the initial model) and measure how much the new policy diverges from it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*EOb17Ygcd-CVyxLZPd2snA.png" /></figure><h4>How the Model is Updated</h4><ol><li><strong>Forward pass</strong>: For each response in the group, we compute its log‑probability under the current policy (by feeding the prompt + response into the model and summing the logits of the generated tokens).</li><li><strong>Reward &amp; advantage</strong>: The reward functions give us <em>ri</em>​; we then compute <em>μ</em>, <em>σ</em>, and the advantages.</li><li><strong>Loss computation</strong>: We combine the advantages with the log‑probabilities to get <em>L(PG)</em>​, add the KL penalty, and obtain the final scalar loss.</li><li><strong>Backpropagation</strong>: We compute gradients of the loss with respect to the model parameters <em>θ</em>.</li><li><strong>Optimizer step</strong>: An optimizer (e.g., AdamW) updates the parameters in the direction that reduces the loss.</li></ol><p>This process repeats for many prompts, gradually shaping the model to produce responses that yield higher rewards.</p><h4>Why GRPO Works Well for LLMs</h4><ul><li><strong>No critic network</strong>: Saves memory and computation, especially important for large models.</li><li><strong>Natural baseline</strong>: The group mean provides a stable, data‑driven baseline without additional training.</li><li><strong>Stability</strong>: The combination of advantage standardisation and KL penalty prevents large, destructive updates.Simplicity: The algorithm is straightforward to implement and debug.</li></ul><p>In the Hugging Face TRL library🙂, the GRPOTrainer automates all these steps, including batched generation, reward computation, advantage calculation, and loss backpropagation – but understanding the underlying mechanics helps you design better reward functions and debug training.</p><h3>Dataset: GSM8K</h3><p>We use the <a href="https://huggingface.co/datasets/openai/gsm8k">GSM8K dataset</a> (main split). Each example contains a math problem and an answer with a #### separator, e.g.:</p><pre>Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May?<br>#### 72</pre><p>We will extract the answer after the #### and keep the question.</p><h3>Creating the Prompt</h3><p>To guide the model’s output format, we define a system prompt:</p><pre>You are given a problem.<br>Think about the problem and provide your working out.<br>Place it between &lt;start_working_out&gt; and &lt;end_working_out&gt;.<br>Then, provide your solution between &lt;SOLUTION&gt;&lt;/SOLUTION&gt;</pre><p>For each example, we build a conversation:</p><pre>prompt = [<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_prompt},<br>    {&quot;role&quot;: &quot;user&quot;,   &quot;content&quot;: question}<br>]</pre><p>The model will then generate a response that should contain the reasoning tags and the solution tags.</p><h3>3. The Reward Functions</h3><p>Reinforcement learning needs a scalar reward signal. Here we combine four reward functions, each focusing on a different aspect of the desired output.</p><h4>a) match_format_exactly</h4><p>Rewards 3 points if the whole generated text matches the required format exactly: it must contain &lt;start_working_out&gt; … &lt;end_working_out&gt; followed by &lt;SOLUTION&gt; … &lt;/SOLUTION&gt; (allowing optional whitespace).<br>This encourages the model to adhere strictly to the output structure.</p><h4>b) match_format_approximately</h4><p>A softer reward that looks at the presence of each required tag.<br>We add +0.5 if a tag appears exactly once, and –0.5 if it appears more or less than once. This helps early in training when the model hasn’t yet learned the format.</p><h4>c) check_answer</h4><p>Extracts the text between &lt;SOLUTION&gt; and &lt;/SOLUTION&gt; and compares it with the true answer:</p><ul><li><em>Exact match → +3.0</em></li><li><em>Match after stripping whitespace → +1.5</em></li><li><em>If the extracted text can be converted to a number, we compute the ratio to the true answer:</em></li><li><em>Ratio in [0.9, 1.1] → +0.5</em></li><li><em>Ratio in [0.8, 1.2] → +0.25</em></li><li><em>Otherwise → –1.0 (penalty)</em></li><li><em>If extraction fails or conversion fails, we give 0 or a small penalty.</em></li></ul><h4>d) check_numbers</h4><p>A simpler numeric check: we extract numbers (using a regex that finds digits/decimal points) from the solution section and compare them as floats. If they match exactly → +1.5, otherwise 0.</p><p>All rewards are summed; the total reward is used in the GRPO advantage calculation.</p><h3>4. Code Explanation</h3><p>Let’s walk through the notebook step by step.</p><h4>4.1 Installation and Setup</h4><p>The notebook begins with installing Unsloth, vLLM, TRL, and other dependencies. Unsloth provides optimised patching for faster training.<br>If you run it on Colab, a special cell installs the correct versions for the T4 GPU.</p><h4>4.2 Loading the Model</h4><p>We load Gemma3 1B using FastModel.from_pretrained from Unsloth. We set a maximum sequence length of 1024 tokens and choose not to use 4‑bit quantisation for this notebook (so we train in 16‑bit LoRA).</p><pre>model, tokenizer = FastModel.from_pretrained(<br>    model_name = &quot;unsloth/gemma-3-1b-it&quot;,<br>    max_seq_length = 1024,<br>    load_in_4bit = False,<br>    load_in_8bit = False,<br>    full_finetuning = False,<br>)</pre><h4>4.3 Adding LoRA Adapters</h4><p>We apply LoRA (Low‑Rank Adaptation) to the language layers. This keeps the number of trainable parameters small (about 0.65% of the model), making training fast and memory‑efficient.</p><pre>model = FastModel.get_peft_model(<br>    model,<br>    finetune_language_layers = True,<br>    finetune_attention_modules = True,<br>    finetune_mlp_modules = True,<br>    r = 8,<br>    lora_alpha = 8,<br>    lora_dropout = 0,<br>)</pre><h4>4.4 Data Preparation</h4><p>We load the GSM8K training split and map it to our prompt format. We also create a function to extract the numeric answer:</p><pre>def extract_hash_answer(text):<br>    if &quot;####&quot; not in text: return None<br>    return text.split(&quot;####&quot;)[1].strip()</pre><p>Then we map the dataset:</p><pre>dataset = dataset.map(lambda x: {<br>    &quot;prompt&quot; : [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_prompt},<br>        {&quot;role&quot;: &quot;user&quot;,   &quot;content&quot;: x[&quot;question&quot;]},<br>    ],<br>    &quot;answer&quot;: extract_hash_answer(x[&quot;answer&quot;]),<br>})</pre><h4>4.5 Regular Expressions for Format Matching</h4><p>We define patterns to match the reasoning and solution tags:</p><pre>match_format = re.compile(<br>    rf&quot;^{reasoning_start}.+?{reasoning_end}.*?{solution_start}(.+?){solution_end}$&quot;,<br>    flags = re.MULTILINE | re.DOTALL<br>)</pre><p>A second regex extracts numbers inside the solution tags for numeric comparison:</p><pre>match_numbers = re.compile(rf&quot;{solution_start}.*?([\d\.]+)&quot;, flags=re.DOTALL)</pre><h4>4.6 Defining Reward Functions</h4><p>Each reward function is a Python function that takes completions (a list of generated responses) and optionally answer (the ground truth). They return a list of scores.<br>We already described them in Section 3. The notebook defines:</p><ul><li>match_format_exactly</li><li>match_format_approximately</li><li>check_answer</li><li>check_numbers</li></ul><h4>4.7 GRPO Training Configuration</h4><p>We use the GRPOConfig from the trl library:</p><pre>training_args = GRPOConfig(<br>    learning_rate = 5e-6,<br>    per_device_train_batch_size = 1,<br>    num_generations = 4,        # number of responses per prompt<br>    max_prompt_length = 256,<br>    max_completion_length = 768, # = max_seq_length - max_prompt_length<br>    max_steps = 50,<br>    ...<br>)</pre><p>Important parameters:</p><ul><li>num_generations: how many responses to sample for each prompt – this defines the group size for GRPO.</li><li>per_device_train_batch_size: must be a multiple of num_generations (here 1 is automatically adjusted to 4).</li></ul><h4>4.8 Training</h4><p>We instantiate a GRPOTrainer, passing the model, tokenizer, list of reward functions, training arguments, and the dataset.</p><pre>trainer = GRPOTrainer(<br>    model = model,<br>    processing_class = tokenizer,<br>    reward_funcs = [match_format_exactly, match_format_approximately,<br>                    check_answer, check_numbers],<br>    args = training_args,<br>    train_dataset = dataset,<br>)<br>trainer.train()</pre><p>During training, we see a progress bar and a table of metrics: reward, reward_std, completion_length, and the individual contributions of each reward function.<br>The notebook shows outputs at each step – you’ll notice the model gradually learning to insert the tags and eventually produce correct answers.</p><h3>5. Under the Hood: How GRPO Really Works (best section😍)</h3><p>The GRPOTrainer from the TRL library hides a lot of complexity. To understand what’s really happening, let’s look at a minimal custom training loop (provided as a reference). This will clarify the core GRPO algorithm.</p><h4>The Core Loop (simplified)</h4><pre>for step in range(steps):<br>    optimizer.zero_grad()<br>    example = math_data[step % len(math_data)]<br><br>    stats = compute_grpo_loss(<br>        model, tokenizer, example, device,<br>        num_rollouts=2, max_new_tokens=256, temperature=0.8, top_p=0.9<br>    )<br><br>    stats[&quot;loss_tensor&quot;].backward()<br>    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)<br>    optimizer.step()</pre><p>The magic happens inside compute_grpo_loss. Let’s break it down.</p><pre>def compute_grpo_loss(<br>    model,<br>    tokenizer,<br>    example,<br>    device,<br>    num_rollouts=2,<br>    max_new_tokens=256,<br>    temperature=0.8,<br>    top_p=0.9,<br>):<br>    assert num_rollouts &gt;= 2<br>    roll_logps, roll_rewards, samples = [], [], []<br>    prompt = render_prompt(example[&quot;problem&quot;])<br><br>    was_training = model.training<br>    model.eval()<br><br>    for _ in range(num_rollouts):<br>        # Stage 1: generate rollouts<br>        token_ids, prompt_len, text = sample_response(<br>            model=model,<br>            tokenizer=tokenizer,<br>            prompt=prompt,<br>            device=device,<br>            max_new_tokens=max_new_tokens,<br>            temperature=temperature,<br>            top_p=top_p,<br>        )<br>        # Stage 2: compute rewards<br>        reward = reward_rlvr(text, example[&quot;answer&quot;])<br>        <br>        # Stage 4: compute logprobs<br>        logp = sequence_logprob(model, token_ids, prompt_len)<br><br>        roll_logps.append(logp)<br>        roll_rewards.append(reward)<br>        samples.append(<br>            {<br>                &quot;text&quot;: text,<br>                &quot;reward&quot;: reward,<br>                &quot;gen_len&quot;: token_ids.numel() - prompt_len,<br>            }<br>        )<br><br>    if was_training:<br>        model.train()<br><br>    # Stage 2: collect all rewards<br>    rewards = torch.tensor(roll_rewards, device=device)<br><br>    # Stage 3: compute advantages<br>    advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-4)<br><br>    # Stage 4: collect all logprobs<br>    logps = torch.stack(roll_logps)<br><br>    # Stage 5: compute policy gradient loss<br>    pg_loss = -(advantages.detach() * logps).mean()<br>    loss = pg_loss  # In the next chapter we add a KL term here<br><br>    return {<br>        &quot;loss&quot;: loss.item(),<br>        &quot;pg_loss&quot;: pg_loss.item(),<br>        &quot;rewards&quot;: roll_rewards,<br>        &quot;advantages&quot;: advantages.detach().cpu().tolist(),<br>        &quot;samples&quot;: samples,<br>        &quot;loss_tensor&quot;: loss,<br>    }</pre><h4>Step‑by‑step inside compute_grpo_loss</h4><ol><li><strong>Generate multiple rollouts</strong><br>For the given prompt, we generate num_rollouts completions using the current model (with sampling). Each completion is decoded to text.</li><li><strong>Compute rewards</strong><br>For each completion, we apply the reward functions (like the ones we defined) to get a scalar reward.</li><li><strong>Calculate advantages</strong><br>We take the group of rewards and compute:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*ycL8zcUkO9r8A8R-XarfhQ.png" /></figure><p>This is the “group relative” part, the advantage tells us how much better or worse this response was compared to the others.</p><p><strong>4. Compute policy loss</strong><br>We need the log‑probabilities of the generated tokens under the current policy.<br>We re‑evaluate the model on the generated sequences (with the prompt as prefix) and collect the log‑probs of the generated tokens.<br>The loss is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*fjNBIwt8y6JFva4VoqaKRw.png" /></figure><p>This is the policy gradient loss, it pushes the model to increase the probability of responses that had positive advantage and decrease those with negative advantage.</p><p><strong>5. Add KL penalty</strong><br>To prevent the model from drifting too far, we often add a KL divergence term between the current policy and a reference policy (usually the model before the update). In TRL, this can be done with a separate reference model or with a built‑in penalty.</p><p><strong>6. Return loss</strong><br>The loss is backpropagated and the model is updated.</p><h4>Why use groups?</h4><p>By using multiple responses per prompt, we get a natural baseline (the group mean) without training a separate value network. This makes GRPO simpler and more stable than PPO, especially for LLMs where a value network would be as large as the policy itself.</p><h4>How TRL implements it</h4><p>TRL’s GRPOTrainer does all of this efficiently:</p><ul><li>It batches the generation of multiple completions.</li><li>It handles padding and masking so that the log‑probs can be computed in a single forward pass.</li><li>It applies the reward functions in a vectorised way.</li><li>It automatically computes advantages and the loss, including the KL penalty.</li></ul><p>The trainer also logs metrics for each reward component, making it easy to monitor training.</p><h3>6. Conclusion</h3><p>We have successfully fine‑tuned Gemma3 1B to become a reasoning model using GRPO. The model now outputs structured reasoning and a final answer, and it improves its accuracy on math problems through reinforcement learning.</p><p>This notebook is a great starting point for experimenting with:</p><ul><li>Longer training runs (increase max_steps)</li><li>Different datasets (e.g., other math datasets, logic puzzles)</li><li>Custom reward functions tailored to your task</li><li>Larger base models (Gemma3 4B, 12B, 27B)</li></ul><p>You can run the notebook yourself in Google Colab , just click the link below and press “Run all”:</p><p>👉 <a href="https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/HuggingFace_Course-Gemma3_(1B)-GRPO.ipynb">Open the Notebook on Colab</a></p><p>For more notebooks and examples, check out the <a href="https://github.com/unslothai/notebooks">Unsloth notebooks</a>❤️<a href="https://github.com/unslothai/notebooks"> repository</a>. If you want to dive deeper into building reasoning models from scratch, consider the book <a href="https://www.manning.com/books/build-a-reasoning-model-from-scratch">Build a Reasoning Model from Scratch</a>❤️ by <a href="https://www.manning.com/authors/sebastian-raschka">Sebastian Raschka</a> it provides a hands‑on, step‑by‑step guide to constructing your own reasoning systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e674eb791a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Reinforcement Learning into Agentic AI Systems]]></title>
            <link>https://medium.com/@saminchandeepa/integrating-reinforcement-learning-into-agentic-ai-systems-7b45d3d6883f?source=rss-20594cbd238------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b45d3d6883f</guid>
            <category><![CDATA[ai-ml-services]]></category>
            <category><![CDATA[lrs]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Samin Chandeepa (Adomic)]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 14:59:06 GMT</pubDate>
            <atom:updated>2026-01-22T14:59:06.202Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKUapchRvbqbdSCUVjK1mQ.png" /></figure><h3>Introduction</h3><p>Agentic AI systems represent a paradigm shift in artificial intelligence, where autonomous agents actively perceive, reason, and act within dynamic environments to achieve goals. Reinforcement Learning (RL) serves as the backbone for embedding decision-making capabilities into these agents, enabling them to learn optimal behaviors through trial-and-error interactions. This integration allows agents to adapt to uncertainties, such as fluctuating demand or supply disruptions in real-world scenarios. For instance, in supply chain management, an RL agent might optimize warehouse routing by learning from repeated simulations of inventory movements, maximizing throughput while minimizing delays.</p><p>This article delves into the technical integration of RL within agentic architectures, emphasizing implementation details for advanced ML engineers. We explore core components, from policy learning to multi-agent setups, while addressing practical challenges and real-world applications. Concepts are grounded in Markov Decision Processes (MDPs), where an agent observes state s∈S, takes action a∈A, receives reward r, and transitions to s′. In supply chain contexts, the state could include inventory levels, supplier statuses, and demand forecasts, with actions like ordering quantities or rerouting shipments.</p><h3>Agent Architectures</h3><p>Agentic systems typically adopt modular architectures to decouple perception, decision-making, and execution, facilitating scalability and maintenance. A baseline RL-integrated agent comprises:</p><ul><li><strong>Observation Module</strong>: Processes raw inputs (e.g., sensor data from warehouse scanners or ERP system logs) into a state representation. For high-dimensional inputs, use encoders like CNNs for visual inventory tracking or transformers for processing textual supplier reports.</li><li><strong>Policy Network</strong>: Parameterized by πθ(a∣s), often a neural network outputting action distributions, such as probabilistic reorder points in inventory control.</li><li><strong>Value Estimator</strong>: Optional critic Vϕ(s) or Qϕ(s,a) for bootstrapping in actor-critic methods, estimating long-term costs like holding fees.</li><li><strong>Memory Buffer</strong>: Stores trajectories for experience replay, allowing offline learning from historical supply data.</li></ul><p>In hierarchical architectures, RL operates at multiple levels: low-level controllers handle primitive actions (e.g., robot arm movements in packing via PPO), while high-level planners select sub-goals using model-based RL like Dreamer, such as deciding on supplier switches during shortages.</p><p>For example, in a supply chain agent for demand forecasting, the architecture might include a low-level RL module for real-time pricing adjustments and a high-level one for strategic sourcing. This modularity enables fine-tuning individual components without retraining the entire system.</p><p>Pseudocode for a basic agent skeleton:</p><pre>class RLAgent:<br>    def __init__(self, policy_net, value_net, replay_buffer):<br>        self.policy = policy_net  # e.g., ActorCriticNN for probabilistic actions<br>        self.value = value_net    # Critic for value estimation<br>        self.buffer = replay_buffer  # DQN-style buffer for supply chain trajectories<br><br>    def act(self, state):  # State: dict with inventory, demand, costs<br>        return self.policy.sample_action(state)  # Action: e.g., order quantity<br><br>    def update(self, batch):<br>        # Compute TD errors, policy gradients; e.g., using advantage estimation for cost minimization<br>        pass</pre><h3>Environment Interaction Loops</h3><p>The core of RL integration is the interaction loop, where agents collect data via rollouts. In agentic systems, this loop is asynchronous and persistent, often running in real-time environments like simulated supply chains (e.g., using AnyLogic or custom Gym wrappers for logistics).</p><p>Key loop structure:</p><ol><li>Observe state st (e.g., current stock levels and incoming orders).</li><li>Sample action at∼π(st) (e.g., allocate trucks to routes).</li><li>Execute at​, receive rt (e.g., reward based on on-time delivery), and transition to st+1​.</li><li>Store transition (st,at,rt,st+1)in buffer.</li><li>Periodically update policy via off-policy methods (e.g., DDPG for continuous routing decisions) or on-policy (e.g., A3C for parallel warehouse simulations).</li></ol><p>For scalability, use vectorized environments (e.g., via Ray or Stable Baselines3) to parallelize rollouts across multiple supply scenarios. In non-stationary environments like volatile markets, incorporate adaptive exploration like entropy bonuses in SAC to explore alternative suppliers.</p><p>Example: In a supply chain simulation for perishable goods logistics, the loop might simulate daily cycles where the agent learns to reroute shipments around weather disruptions, with rewards penalizing spoilage.</p><p>Pseudocode for interaction loop:</p><pre>def interaction_loop(agent, env, num_steps):  # Env: SupplyChainGym with states like stock, demand<br>    state = env.reset()  # Initial state: empty warehouse<br>    for t in range(num_steps):<br>        action = agent.act(state)  # e.g., ship 50 units to retailer A<br>        next_state, reward, done = env.step(action)  # Reward: -cost + revenue<br>        agent.buffer.add((state, action, reward, next_state, done))<br>        if done:  # End of episode, e.g., end of fiscal quarter<br>            state = env.reset()<br>        else:<br>            state = next_state<br>        if t % UPDATE_INTERVAL == 0:<br>            batch = agent.buffer.sample(BATCH_SIZE)<br>            agent.update(batch)  # Update to minimize supply delays</pre><h3>Policy Learning within Agents</h3><p>Policy learning optimizes π to maximize expected cumulative reward J(π)=Eπ[∑tγtrt]. In agentic systems, use proximal methods like PPO for stability, clipping gradients to prevent large updates that could disrupt ongoing operations.</p><p>For continuous actions (e.g., variable order quantities), employ deterministic policies (DDPG) or stochastic ones (SAC). Integration with agents involves hybrid learning: supervised pre-training on historical supply data followed by RL fine-tuning (e.g., via DQfD for initial inventory policies).</p><p>In transformer-based agents, policies can be autoregressive, generating sequences of actions like procurement plans conditioned on market history.</p><p>Example: For a supply chain agent managing vendor selection, the policy might learn to output probabilities over suppliers based on past reliability, using PPO to balance cost and risk.</p><p>Update rule example (PPO surrogate loss):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*vRc9yR8b0JGUwjztmIsjHQ.png" /></figure><h3>Reward Design for Long-Horizon Tasks</h3><p>Long-horizon tasks (e.g., annual supply planning) suffer from sparse rewards, like end-of-year profit metrics. Design strategies include:</p><ul><li><strong>Shaping</strong>: Add dense intermediates, e.g., potential-based shaping r′=r+γΦ(s′)−Φ(s), where Φ is a learned potential approximating future inventory stability.</li><li><strong>Curriculum Learning</strong>: Gradually increase horizon, starting with daily restocking before scaling to monthly forecasting.</li><li><strong>Intrinsic Rewards</strong>: Curiosity-driven, encouraging exploration of new sourcing routes.</li></ul><p>Example: In supply chain optimization for global distribution, rewards could shape towards minimizing lead times, with intrinsic bonuses for discovering efficient multi-modal transport (e.g., combining sea and air freight).</p><p>Implementation tip: Parameterize reward functions as neural networks, optimized via meta-RL (e.g., RL²) to adapt to changing tariffs.</p><h3>Memory and Planning Integration</h3><p>Agents require memory for non-Markovian environments, like supply chains with seasonal trends. Use LSTMs/GRUs in recurrent policies to retain historical demand patterns or external memory like Neural Turing Machines for storing supplier contracts.</p><p>Planning integrates via model-based RL: Learn dynamics model p(s′∣s,a) (e.g., predicting demand fluctuations), then simulate trajectories for MCTS or MPC to plan inventory buffers.</p><p>Example: In a warehouse agent, memory tracks past picking errors, while planning simulates peak-season loads to optimize layouts.</p><p>Pseudocode for model-based planning:</p><pre>def plan(agent, state, model, horizon):  # State: current supply levels<br>    trajectories = []<br>    for _ in range(N_SIMS):<br>        sim_state = state<br>        rollout = []<br>        for h in range(horizon):  # e.g., simulate next 30 days<br>            action = agent.policy.sample(sim_state)  # e.g., reorder from supplier B<br>            sim_next, reward = model.predict(sim_state, action)  # Predict stock after action<br>            rollout.append((sim_state, action, reward, sim_next))<br>            sim_state = sim_next<br>        trajectories.append(rollout)<br>    # Select best via value estimation, e.g., lowest total cost<br>    return best_action(trajectories)</pre><h3>Tool-Using Agents</h3><p>Tool-using agents extend action spaces with external APIs or tools (e.g., ERP queries for real-time stock or weather APIs for logistics). RL learns tool selection as discrete actions, such as querying a demand forecasting tool before ordering.</p><p>Architecture: Policy outputs tool ID and parameters (e.g., “query_inventory supplier=X”); environment executes and returns results like current stock.</p><p>Training: Use sparse rewards for end-to-end supply efficiency, with auxiliary losses for tool accuracy. In ReAct framework, interleave reasoning (e.g., “check delays”) and tool calls.</p><p>Example: A supply chain agent might use a tool to simulate tariff impacts, learning via RL when to invoke it for international sourcing decisions.</p><p>For implementation, embed tool embeddings in policy input to condition on tool availability.</p><h3>Multi-Agent Coordination</h3><p>In multi-agent systems (MAS), RL handles cooperation/competition via centralized training decentralized execution (CTDE, e.g., QMIX for coordinating warehouse robots).</p><p>Coordination via communication: Learn message-passing policies, e.g., agents sharing inventory statuses.</p><p>Example: In supply chain MAS, one agent optimizes procurement while another handles distribution; RL coordinates to minimize bottlenecks, using opponent modeling for supplier negotiations.</p><p>Challenges: Non-stationarity; mitigate with opponent modeling in competitive bidding scenarios.</p><p>Pseudocode for MARL update (independent PPO):</p><pre>def marl_update(agents, shared_buffer):  # Agents: procurement, logistics, etc.<br>    batch = shared_buffer.sample()<br>    for agent in agents:<br>        agent_loss = compute_ppo_loss(agent.policy, batch[agent.id])  # e.g., loss for synchronized deliveries<br>        agent.optimizer.step(agent_loss)</pre><h3>System-Level Design Patterns</h3><ul><li><strong>Modular Pipelines</strong>: Decouple RL components (e.g., via ROS for warehouse robotics integration).</li><li><strong>Hybrid Systems</strong>: RL for low-level control (e.g., forklift navigation), symbolic planning for high-level (e.g., annual budgeting).</li><li><strong>Scalable Infra</strong>: Use Kubernetes for distributed training on supply simulations; Ray for actor-based agents mimicking supply nodes.</li><li><strong>Monitoring</strong>: Track metrics like episodic return (total profit), entropy (decision diversity) for diagnostics in live deployments.</li></ul><h3>Training vs. Inference Separation</h3><p>Training: Offline/on-policy data collection from supply logs/simulations, gradient updates on GPUs/TPUs. Use sim-to-real transfer (e.g., domain randomization for varying demand patterns).</p><p>Inference: Freeze policy, deploy on edge devices (e.g., IoT in warehouses) with quantization for fast responses. For online adaptation, use lightweight updates like fine-tuning with PEFT on new supplier data.</p><p>Separation ensures safety: Train in sim to avoid real disruptions, infer in real with human overrides.</p><h3>Practical Challenges</h3><ul><li><strong>Stability</strong>: PPO clipping mitigates variance in volatile markets; use normalization layers for state scaling.</li><li><strong>Reward Hacking</strong>: Agents might overstock to game short-term rewards; align via inverse RL (infer true objectives from expert demos) or robust optimization (e.g., CVaR for worst-case shortages).</li><li><strong>Exploration</strong>: Balance with epsilon-greedy (random supplier trials), NoisyNets, or count-based methods. In high-dim spaces like global chains, use VAE for state novelty to explore untapped routes.</li></ul><p>Mitigation: Regularize with entropy to prevent premature convergence, monitor for mode collapse in routing policies.</p><h3>Real-World Agentic Use Cases</h3><ul><li><strong>Inventory Management</strong>: RL agents (e.g., PPO-based) optimize stock levels in e-commerce warehouses, learning from demand signals to reduce overstock; example: Amazon-like systems minimizing holding costs.</li><li><strong>Logistics Optimization</strong>: Use SAC for continuous route planning in freight; multi-agent setups coordinate trucks and drones for last-mile delivery, adapting to traffic via self-play.</li><li><strong>Supplier Selection</strong>: Model-based RL (e.g., Dreamer) simulates negotiations; LLM-RL hybrids reason over contracts and fine-tune policies for risk-averse choices.</li><li><strong>Demand Forecasting and Replenishment</strong>: Hierarchical RL agents predict and act on trends; example: In food supply, agents use tool-calling for weather data to adjust perishable orders.</li><li><strong>Sustainability in Supply Chains</strong>: RL optimizes for carbon footprints; agents learn eco-friendly routing with rewards shaped for emissions reduction, integrated with multi-agent coordination for fleet management.</li></ul><p>In summary, RL empowers agentic AI by providing adaptive decision-making in complex supply chains, but requires careful design to handle uncertainty. Implementation libraries like Stable Baselines3 or RLlib facilitate rapid prototyping for these scenarios.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b45d3d6883f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Deep Reinforcement Learning]]></title>
            <link>https://medium.com/@saminchandeepa/introduction-to-deep-reinforcement-learning-2cd45429cf1e?source=rss-20594cbd238------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cd45429cf1e</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[lrs]]></category>
            <category><![CDATA[aiml]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Samin Chandeepa (Adomic)]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 16:36:21 GMT</pubDate>
            <atom:updated>2025-09-30T17:16:51.696Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is Reinforcement Learning?</strong></h3><p>Reinforcement Learning (RL) is a branch of machine learning where an agent learns to make decisions by interacting with an environment. The core idea is that the agent learns through trial and error, receiving rewards (positive or negative) as feedback for its actions. This process mirrors how humans and animals learn from their experiences.</p><p>For example, consider a dog learning to fetch a ball. <strong><em>When the dog chases and retrieves the ball, it receives positive feedback (a treat or praise)</em></strong>, reinforcing the behavior. However, <strong><em>if the dog ignores the ball or runs off, it gets negative feedback (no treat or a gentle correction)</em></strong>, discouraging those actions. Through repeated attempts, the dog learns to associate fetching the ball with rewards, improving its behavior over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgYl02GgTXrxbYRV5dwjnw.png" /></figure><p>Formally, Reinforcement Learning is a framework for solving control tasks (decision problems) by creating agents that learn from the environment via interactions, using rewards as the sole feedback.</p><h3>The Reinforcement Learning Framework</h3><p>At the heart of RL is the RL process, which forms a loop involving states, actions, rewards, and next states. Here’s how it works:</p><ul><li>The agent receives an initial state <strong>S(0)</strong> from the environment (e.g. the first frame of a game).</li><li>Based on this state, the agent selects an action <strong>A(0)​</strong> (e.g. moving right).</li><li>The environment responds with a new state <strong>S(1)</strong>​ and a reward <strong>R(1)</strong> (e.g. +1 for progress).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BBSIQ4cJ4Xxu13u3.jpg" /></figure><p>This sequence continues, generating trajectories of states, actions, rewards, and next states. The agent’s objective is to <strong>maximize </strong>the expected cumulative reward, also known as the expected return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*01ROnPPFAqbgCVlyYF82jA.png" /></figure><p>This goal is rooted in the reward hypothesis: all objectives can be framed as maximizing the expected cumulative reward. Thus, the agent learns behaviors that lead to the highest possible rewards.</p><h3>Markov Decision Process (MDP)</h3><p>Most RL problems are formalized as Markov Decision Processes (MDPs), a mathematical framework consisting of:</p><ul><li>A set of states S.</li><li>A set of actions A.</li><li>A transition probability function P(St+1∣St,At) , defining the dynamics.</li><li>A reward function R(St,At,St+1).</li><li>A discount factor γ (gamma).</li></ul><p>The RL framework is often modeled as a Markov Decision Process (MDP), where the Markov Property applies: <strong>the agent only needs the current state to decide the next action, not the entire history.</strong> This simplifies decision-making in complex environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*hoc4tVPrpYsmzKeicWisOg.png" /></figure><p>That means the <strong>future state depends only on the current state and action</strong>, not on the full history.</p><h3>States and Observations</h3><p>States (or observations) represent the information the agent gets from the environment:</p><ul><li><strong>Fully Observed Environments</strong>: The agent receives a complete state (e.g. the entire chessboard in a chess game).</li><li><strong>Partially Observed Environments</strong>: The agent gets only partial information (e.g. a limited view in Super Mario Bros).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZK7WthkTbkBCFpkT7ZdKA.png" /></figure><p>In practice, “state” often refers to both, with distinctions made in specific implementations.</p><h3>Action Spaces</h3><p>Actions are what the agent can do in the environment, categorized into:</p><ul><li><strong>Discrete Action Spaces</strong>: Finite options (e.g. left, right, jump, crouch in Super Mario Bros).</li><li><strong>Continuous Action Spaces</strong>: Infinite possibilities (e.g. steering angles in a self-driving car).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJQwqgolAEWYfYJMEH_mFA.png" /></figure><p>The choice of action space influences the RL algorithm selected.</p><h3>Rewards and Discounting</h3><p>Rewards provide feedback on action quality. The cumulative reward is the sum of all future rewards, but to account for uncertainty, rewards are discounted using a discount factor γ (typically 0.95–0.99). <strong><em>Future rewards are multiplied by γ, where t is the time step, prioritizing nearer rewards.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*R7XVVQN2K36bqZxY4WgN2A.png" /></figure><p>For example, in a maze with cheese rewards, those farther away (near obstacles) are more heavily discounted due to higher risk.</p><h3>Types of Tasks in Reinforcement Learning</h3><p>RL problems are instantiated as tasks, which fall into two categories:</p><h3>Episodic Tasks</h3><p>These have a <strong><em>clear start and end </em></strong>(terminal state), forming an episode — a sequence of states, actions, rewards, and next states. For instance, a level in Super Mario Bros. starts at the beginning and ends upon completion or death.</p><h3>Continuing Tasks</h3><p>These have <strong><em>no terminal state and run indefinitely</em></strong>. An example is an automated stock trading agent, which operates continuously until stopped.</p><h3>The Exploration/Exploitation Trade-off</h3><p>A key challenge in RL is balancing exploration (trying new actions to learn about the environment) and exploitation (using known information to maximize rewards).</p><p>Imagine a forager searching for fruit in a forest. Nearby, there are small patches of berries yielding minor rewards (+1 for each handful). <strong>Farther away, there’s a tree with a large bounty of ripe fruit (+1000 reward), but the path is uncertain and requires navigating through dense underbrush.</strong> If the forager purely exploits the nearby berry patches, they might get stuck collecting small rewards, missing the abundant fruit tree. Exploration, however, involves venturing into unknown areas, risking time and energy with no immediate payoff, but potentially discovering the tree’s greater reward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7vzVdNxvICRFKS3HsBFdMQ.png" /></figure><p>This example highlights the trade-off: exploitation ensures consistent but suboptimal gains, while exploration opens the possibility of finding a much larger reward at the cost of short-term uncertainty.</p><h3>Two Main Approaches for Solving RL Problems</h3><p>To find the optimal behavior that maximizes expected rewards, RL uses two primary methods: policy-based and value-based.</p><h3>The Policy (π): The Agent’s Brain</h3><p>The policy is the function dictating the agent’s actions given a state essentially its decision-making strategy. The goal is to learn the optimal policy π.</p><p>Policies can be:</p><ul><li><strong>Deterministic</strong>: Always outputs the same action for a state.</li><li><strong>Stochastic</strong>: Outputs a probability distribution over actions.</li></ul><h3>Policy-Based Methods</h3><p>These directly learn the policy function, mapping states to actions or action probabilities. Training optimizes the policy to select reward-maximizing actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*JwZHYYe6aRKAg1PszKjCgw.png" /></figure><h3>Value-Based Methods</h3><p>These learn a value function estimating the expected return from each state. The policy then selects actions leading to higher-value states. For example, in a grid world, the agent moves toward states with increasing values to reach the goal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*Cgbzp-sEDaP2GhysLZuHFQ.png" /></figure><h3>The “Deep” in Deep Reinforcement Learning</h3><p>Deep Reinforcement Learning (Deep RL) integrates deep neural networks into RL to handle complex, high-dimensional problems. Traditional RL might use tables (e.g., Q-tables in Q-Learning) to store state-action values, but deep RL approximates these with neural networks.</p><p>For instance:</p><ul><li>In classic <strong>Q-Learning</strong>, a table maps states to action values.</li><li>In Deep Q-Learning, a <strong>neural network estimates these Q-values</strong>, enabling scalability to environments like video games with vast state spaces.</li></ul><p>This “deep” aspect allows RL to tackle real-world applications, from gaming to robotics, by leveraging the representation power of deep learning.</p><p>Deep RL builds on the foundations of RL, <strong><em>enhancing them with neural networks for more powerful and generalizable agents</em></strong>.</p><h3>Conclusion</h3><p>Deep Reinforcement Learning (Deep RL) combines the principles of reinforcement learning with the power of deep neural networks, enabling agents to solve complex, high-dimensional decision-making problems through trial-and-error interactions with an environment.Deep RL’s ability to handle vast state spaces, as seen in applications like AlphaGo and robotic control, marks it as a transformative approach in artificial intelligence.</p><p>📝 Download the beginner notes here [Part-1]: <a href="https://10x.adomicarts.com/resources">https://10x.adomicarts.com/resources</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cd45429cf1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Train a Custom CNN Model for Single Character OCR]]></title>
            <link>https://medium.com/@saminchandeepa/how-to-train-a-custom-cnn-model-for-single-character-ocr-3aca5eb67714?source=rss-20594cbd238------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aca5eb67714</guid>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[train-cnn]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ocr-model]]></category>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Samin Chandeepa (Adomic)]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 14:11:47 GMT</pubDate>
            <atom:updated>2025-09-16T14:14:15.316Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ug25HWFO6nhe72Rsp01qiA.png" /></figure><h3>Introduction</h3><p>Single character Optical Character Recognition (OCR) is a fundamental building block in the world of text recognition technology. It involves teaching a machine to identify and interpret individual letters, numbers, or symbols from images, much like how a human might glance at a single character and instantly recognize it.</p><p>This guide will walk you through building a Convolutional Neural Network (CNN) from scratch specifically tailored for this task. We’ll cover everything from data preparation to model deployment, making it accessible for beginners while providing depth for those with some experience. By the end, you’ll understand not just how to implement the model, but why each step matters in creating an accurate and robust OCR system.</p><p>This approach is ideal for scenarios like captcha solving, license plate digit recognition, or basic handwriting analysis. It’s also the stepping stone to more complex systems, such as multi-character OCR, where sequences of characters (like words or sentences) are recognized.</p><h3>What is Single Character OCR?</h3><p>At its core, single character OCR is about classifying an image containing just one character into its corresponding label. Unlike full-text OCR, which handles entire lines or paragraphs, this focuses on isolation — perfect for controlled environments where characters are segmented beforehand.</p><p>For example:</p><ul><li><em>An input image showing a bold ‘A’ might be classified as “A”.</em></li><li><em>A blurry photo of the digit ‘7’ could output “7”.</em></li><li><em>Even special symbols, like a question mark ‘?’, can be recognized as “?”.</em></li></ul><p>The challenge lies in handling variations: different fonts, sizes, rotations, noise, or lighting conditions. A good model must generalize beyond perfect images to real-world imperfections.</p><h3>Why CNNs are Perfect for Character Recognition</h3><p>CNNs are designed for image data, making them superior to traditional machine learning models for OCR. Here’s a deeper dive into why:</p><ol><li><strong>Local Feature Detection</strong>: CNNs use filters (small matrices) that slide over the image to spot local patterns, like the straight lines in ‘I’ or the curves in ‘S’. This mimics how our visual cortex processes edges and shapes.</li><li><strong>Translation Invariance</strong>: If a character is shifted left or right in the image, the CNN can still recognize it because pooling layers summarize features regardless of exact position.</li><li><strong>Hierarchical Learning</strong>: Early layers learn simple features (e.g., horizontal lines), while deeper layers combine them into complex ones (e.g., the loop in ‘9’). This builds a hierarchy of understanding.</li><li><strong>Parameter Sharing and Efficiency</strong>: The same filter is applied across the entire image, reducing the number of parameters compared to fully connected networks, which prevents overfitting and speeds up training.</li></ol><p>In contrast, a simple neural network without convolutions would treat the image as a flat array, losing spatial information and requiring massive datasets to perform well.</p><h3>Dataset Preparation</h3><p>Data is the lifeblood of any ML model. For single character OCR, you need a dataset of images labeled by character. Popular sources include EMNIST (for handwritten characters) or synthetic datasets generated with tools like Pillow in Python.</p><h3>Dataset Structure</h3><p>Organize your data hierarchically for easy loading:</p><p>dataset/<br>├── training_data/<br>│ ├── A/<br>│ │ ├── img_001.png<br>│ │ ├── img_002.png<br>│ │ └── …<br>│ ├── B/<br>│ │ ├── img_001.png<br>│ │ └── …<br>│ └── … (folders for all characters, e.g., 0–9, A-Z)<br>└── testing_data/<br> ├── A/<br> ├── B/<br> └── …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ejugE5bCMEAQlMBom5EDw.png" /><figcaption>Traing Dataset with labels (Numbers + Charactors)</figcaption></figure><p>This structure ensures each folder represents a class, making it straightforward to map images to labels. Aim for at least 100–500 images per character to avoid imbalance, which could bias the model toward common characters like ‘E’.</p><h3>Data Loading and Preprocessing</h3><p>Loading involves scanning directories and creating a DataFrame for easy manipulation. Preprocessing standardizes images: resizing to a fixed size (e.g., 32x32 pixels), converting to grayscale (since color isn’t needed for characters), and normalizing pixel values to [0,1] for faster convergence.</p><pre>def load_character_dataset(path):<br>    data = [(os.path.join(path, lbl, img), lbl) <br>            for lbl in os.listdir(path) <br>            if os.path.isdir(os.path.join(path, lbl)) <br>            for img in os.listdir(os.path.join(path, lbl))]<br>    return pd.DataFrame(data, columns=[&#39;image_path&#39;, &#39;label&#39;])<br><br>def create_character_mappings():<br>    chars = list(string.digits + string.ascii_uppercase)<br>    return ({c: i for i, c in enumerate(chars)},<br>            {i: c for i, c in enumerate(chars)},<br>            len(chars))<br><br>def preprocess_images(df, img_size=(32, 32)):<br>    images = []<br>    labels = []<br>    for _, row in df.iterrows():<br>        img = load_img(row[&#39;image_path&#39;], target_size=img_size, color_mode=&#39;grayscale&#39;)<br>        images.append(img_to_array(img) / 255.0)<br>        labels.append(char_to_int[row[&#39;label&#39;]])<br>    return np.array(images), np.array(labels)<br><br># Load dataset and preprocess<br>df = load_character_dataset(&#39;/path/to/training_data&#39;)<br>char_to_int, int_to_char, num_classes = create_character_mappings()<br>X_train, y_train = preprocess_images(df)</pre><p>Explanation: The mappings convert characters to integers for one-hot encoding later. Preprocessing ensures all images are uniform, reducing variance that could confuse the model. Grayscale simplifies computation since characters are shape-based.</p><h3>CNN Architecture Design</h3><p>A CNN stacks layers to process images progressively. Our design uses three convolutional blocks for feature extraction, followed by dense layers for classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yuqQpaySGFFjbQZ56Sa7xQ.png" /><figcaption><a href="https://poloclub.github.io/cnn-explainer/">layers inside CNN</a></figcaption></figure><h3>Building the CNN Model</h3><pre>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization<br>from tensorflow.keras.regularizers import l2<br><br>def create_single_char_cnn(input_shape=(32, 32, 1), num_classes=36):<br>    model = Sequential([<br>        Conv2D(32, (3, 3), activation=&#39;relu&#39;, input_shape=input_shape, kernel_regularizer=l2(0.001)),<br>        BatchNormalization(),<br>        MaxPooling2D((2, 2)),<br>        Dropout(0.25),<br>        <br>        Conv2D(64, (3, 3), activation=&#39;relu&#39;, kernel_regularizer=l2(0.001)),<br>        BatchNormalization(),<br>        MaxPooling2D((2, 2)),<br>        Dropout(0.25),<br>        <br>        Conv2D(128, (3, 3), activation=&#39;relu&#39;, kernel_regularizer=l2(0.001)),<br>        BatchNormalization(),<br>        Dropout(0.25),<br>        <br>        Flatten(),<br>        Dense(256, activation=&#39;relu&#39;, kernel_regularizer=l2(0.001)),<br>        Dropout(0.5),<br>        Dense(num_classes, activation=&#39;softmax&#39;)<br>    ])<br>    return model<br><br>model = create_single_char_cnn(num_classes=num_classes)<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*7QYf6HXQTl5JGYurqn52iw.png" /></figure><h3>Architecture Explanation</h3><p>The model processes a 32x32 grayscale image through layers that halve dimensions while increasing depth (channels):</p><ul><li><strong>Input (32x32x1)</strong>: Raw pixel data.</li><li><strong>Conv2D(32, 3x3)</strong>: Applies 32 filters to detect basic features; ReLU activation introduces non-linearity.</li><li><strong>BatchNorm</strong>: Normalizes activations to speed up training and reduce internal covariate shift.</li><li><strong>MaxPool(2x2)</strong>: Downsamples to 16x16x32, focusing on dominant features.</li><li><strong>Dropout(0.25)</strong>: Randomly drops neurons to prevent overfitting.</li><li>Similar blocks with 64 and 128 filters build complexity.</li><li><strong>Flatten</strong>: Converts 6x6x128 to a 4608-vector.</li><li><strong>Dense(256)</strong>: Combines features; dropout(0.5) for regularization.</li><li><strong>Output (softmax)</strong>: Probabilities over 36 classes (0–9, A-Z).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ApJ4I_q8KvDRf0iEa9-FCQ.png" /><figcaption>CNN feature maps during the layer states</figcaption></figure><p>This design balances depth (for learning) with regularization (for generalization). Deeper layers capture intricate patterns like the difference between ‘O’ and ‘Q’.</p><h3>Training Configuration</h3><p>Training optimizes the model using backpropagation. We use categorical cross-entropy loss for multi-class classification and Adam optimizer for adaptive learning rates.</p><h3>Data Preparation and Augmentation</h3><p>Split data for validation and augment to simulate variations.</p><pre># One-hot encode labels and split data<br>y_cat = to_categorical(y_train, num_classes)<br>X_tr, X_val, y_tr, y_val = train_test_split(X_train, y_cat, test_size=0.2, stratify=y_train, random_state=42)<br><br># Data augmentation<br>datagen = ImageDataGenerator(<br>    rotation_range=10, width_shift_range=0.1, height_shift_range=0.1,<br>    zoom_range=0.1, shear_range=0.1, fill_mode=&#39;nearest&#39;<br>)<br>datagen.fit(X_tr)</pre><p><strong>Data Augmendation</strong></p><p>Data augmentation is a technique used to artificially increase the size and diversity of a training dataset by applying random transformations such as rotations, shifts, flips, zooms, or color changes to existing images. This helps a model generalize better by exposing it to varied examples, reducing overfitting, and improving performance when tested on unseen data. It is especially useful in deep learning tasks like image classification, where collecting large amounts of labeled data can be challenging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*_QLU8d8c9YTjSUNI.png" /><figcaption>Data Augmentation</figcaption></figure><h3>Compilation and Training</h3><pre>from tensorflow.keras.optimizers import Adam<br>from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau<br><br>model.compile(optimizer=Adam(learning_rate=0.001), loss=&#39;categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br><br>callbacks = [EarlyStopping(monitor=&#39;val_loss&#39;, patience=10, restore_best_weights=True), ReduceLROnPlateau(monitor=&#39;val_loss&#39;, factor=0.5, patience=5, min_lr=1e-7)]<br><br>history = model.fit(datagen.flow(X_train_split, y_train_split, batch_size=32), epochs=50, validation_data=(X_val, y_val), callbacks=callbacks)</pre><p>Callbacks prevent overfitting: EarlyStopping halts if validation loss stalls, ReduceLROnPlateau lowers learning rate for fine-tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*_H9bB6kL5PKAj6IO_XQgZw.png" /><figcaption>Accuracy</figcaption></figure><h3>Training History and Evaluation</h3><p>Use plots to visualize progress and compute accuracy.</p><pre># Evaluate on test data<br>test_df = load_character_dataset(&#39;/path/to/testing_data&#39;)<br>X_test, y_test = preprocess_images(test_df)<br>y_test_cat = to_categorical(y_test, num_classes)<br><br>predictions = model.predict(X_test)<br>pred_classes = np.argmax(predictions, axis=1)<br><br>accuracy = np.mean(pred_classes == y_test)<br>print(f&quot;Test Accuracy: {accuracy:.4f}&quot;)</pre><h3>Making Predictions</h3><p>Deploy the model for inference.</p><pre>def predict_single_character(model, image_path, int_to_char):<br>    img = load_img(image_path, target_size=(32, 32), color_mode=&#39;grayscale&#39;)<br>    img_array = img_to_array(img) / 255.0<br>    img_array = np.expand_dims(img_array, axis=0)<br>    prediction = model.predict(img_array, verbose=0)<br>    predicted_class = np.argmax(prediction)<br>    confidence = prediction[0][predicted_class]<br>    return int_to_char[predicted_class], confidence</pre><p>This function processes a single image, returning the character and confidence score.</p><h3>Model Optimization Tips</h3><ul><li><strong>Hyperparameter Tuning</strong>: Experiment with learning rates using schedulers.</li><li><strong>Advanced Augmentation</strong>: Add brightness variations for diverse lighting.</li><li><strong>Deeper Architectures</strong>: Stack more conv layers for complex datasets.</li></ul><h3>Saving and Loading Models</h3><p>Save for reuse:</p><pre>model.save(&#39;single_char_ocr_model.h5&#39;)<br>import pickle<br>with open(&#39;char_mappings.pkl&#39;, &#39;wb&#39;) as f:<br>    pickle.dump({&#39;char_to_int&#39;: char_to_int, &#39;int_to_char&#39;: int_to_char, &#39;num_classes&#39;: num_classes}, f)</pre><p>Load similarly for production.</p><h3>Common Issues and Solutions</h3><p>When training CNN models, several common issues can arise.</p><p>Overfitting occurs when the model memorizes training data instead of learning general patterns, leading to poor test performance; this can be addressed by adding dropout layers, applying stronger regularization, or expanding the dataset through augmentation techniques such as rotations, shifts, and zooms.</p><p>On the other hand, underfitting happens when the model is too simple or trained for too few epochs, preventing it from capturing the underlying patterns in the data; increasing network depth, training longer, or relaxing excessive regularization can help.</p><p>Another frequent challenge is class imbalance, where certain classes dominate the dataset, biasing predictions toward them; solutions include weighting the loss function, resampling the dataset, or generating synthetic samples.</p><p>Finally, poor generalization may occur if the training data is too narrow, meaning the model struggles with unseen inputs; improving dataset diversity, using cross-validation, applying early stopping, or leveraging transfer learning are effective strategies to build more robust models</p><h3>Production Deployment</h3><p>Wrap in a class for easy use:</p><pre>class SingleCharOCR:<br>    def __init__(self, model_path, mappings_path):<br>        from tensorflow.keras.models import load_model<br>        import pickle<br>        self.model = load_model(model_path)<br>        with open(mappings_path, &#39;rb&#39;) as f:<br>            self.int_to_char = pickle.load(f)[&#39;int_to_char&#39;]<br>    <br>    def predict(self, image_path):<br>        # Preprocess and predict as above<br>        pass  # Implement as in predict_single_character</pre><h3>Conclusion</h3><p>This CNN for single character OCR demonstrates the power of deep learning in image classification. With quality data, thoughtful architecture, and iterative training, you can achieve high accuracy. This model paves the way for advanced OCR by handling individual characters reliably. Experiment, analyze errors, and scale up!</p><p>You can refer to the full code from here :<a href="https://www.kaggle.com/code/adomicarts/ocr-model">https://www.kaggle.com/code/adomicarts/ocr-model</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aca5eb67714" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Workflow Strategies in Google Agent Development Kit (ADK): Building Effective Multi-Agent…]]></title>
            <link>https://medium.com/@saminchandeepa/mastering-workflow-strategies-in-google-agent-development-kit-adk-building-effective-multi-agent-59dbfcfa325f?source=rss-20594cbd238------2</link>
            <guid isPermaLink="false">https://medium.com/p/59dbfcfa325f</guid>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[google-agent-development]]></category>
            <category><![CDATA[ai-agent-architecture]]></category>
            <dc:creator><![CDATA[Samin Chandeepa (Adomic)]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 09:19:02 GMT</pubDate>
            <atom:updated>2025-07-31T05:59:07.425Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Workflow Strategies in Google Agent Development Kit (ADK): Building Effective Multi-Agent Systems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5ufZKhefwoawy-ol.png" /><figcaption>Multi-Agent System(Source : <a href="https://google.github.io/adk-docs/agents/">ADK</a>)</figcaption></figure><h3>Introduction</h3><p>In the rapidly evolving landscape of artificial intelligence, the concept of a single, monolithic AI agent handling all tasks is increasingly being replaced by more sophisticated architectures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gmXiP0VZkmZV6P-lfbU2WA.png" /></figure><p>Enter Multi-Agent Systems (MAS). A multi-agent system is a collection of autonomous, interacting entities (agents) that collaborate or coordinate to achieve a common goal or solve complex problems that are beyond the capabilities of any single agent. This paradigm offers significant advantages in terms of modularity, scalability, and robustness, making it ideal for tackling intricate real-world challenges.</p><p>Google’s Agent Development Kit (ADK) provides a robust framework for building such sophisticated agentic applications. ADK simplifies the creation and management of multi-agent systems by offering core primitives and patterns that facilitate inter-agent communication, task orchestration, and hierarchical organization. By leveraging ADK, developers can move beyond single-agent solutions to construct highly specialized, reusable, and maintainable AI applications.</p><p>This article will delve into the intricacies of building multi-agent systems using Google ADK. We will explore the fundamental primitives ADK offers for agent composition, including agent hierarchy and various workflow agents. Furthermore, we will examine the crucial mechanisms for inter-agent communication and interaction. Finally, we will illustrate common multi-agent patterns with practical code examples, demonstrating how these patterns can be implemented effectively using ADK to solve diverse problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*VpQdvLrB_ZJlALAcKpMHxA.png" /></figure><h3>1. Core Primitives for Agent Composition in ADK</h3><p>ADK’s power in building multi-agent systems stems from its well-defined set of core primitives. These building blocks allow developers to structure, manage, and facilitate interactions within a complex agent ecosystem. Understanding these primitives is foundational to designing effective and scalable multi-agent solutions.</p><h3>1.1. Agent Hierarchy: Parent and Sub-Agents</h3><p>The concept of agent hierarchy is a cornerstone for organizing multi-agent systems within ADK. It establishes a clear parent-child relationship among agents, forming a tree-like structure that defines the scope and flow of operations. This hierarchical organization is crucial for managing complexity and enabling structured delegation of tasks.</p><p><strong>Establishing Hierarchy with sub_agents</strong></p><p>In ADK, you define this hierarchy by passing a list of agent instances to the sub_agents argument when initializing a parent agent. The framework automatically recognizes this relationship and sets the parent_agent attribute on each child agent during its initialization. This explicit linking ensures that the system understands the relationships between different agents.</p><p><strong>Single Parent Rule</strong></p><p>An important constraint within ADK’s agent hierarchy is the single parent rule: an agent instance can only be added as a sub-agent once. Attempting to assign a second parent will result in a ValueError. This rule ensures a clear and unambiguous hierarchical structure, preventing potential conflicts or circular dependencies.</p><p><strong>Importance in ADK</strong></p><p>This hierarchical structure is not merely for organizational purposes; it plays a vital role in how ADK functions. It defines the scope for Workflow Agents, which we will discuss shortly, and influences the potential targets for LLM-Driven Delegation. Developers can navigate this hierarchy using agent.parent_agent to access the parent of a given agent or agent.find_agent(name) to locate descendants within the tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*SHA4c66Ylki-kSXy9AqJkw.png" /></figure><p>Here’s a conceptual example demonstrating how to define an agent hierarchy in ADK:</p><pre>from google.adk.agents import LlmAgent, BaseAgent<br><br># Define individual agents<br>greeter = LlmAgent(name=&quot;Greeter&quot;, model=&quot;gemini-2.0-flash&quot;)<br>task_doer = BaseAgent(name=&quot;TaskExecutor&quot;) # Custom non-LLM agent<br><br># Create parent agent and assign children via sub_agents<br>coordinator = LlmAgent(<br>    name=&quot;Coordinator&quot;,<br>    model=&quot;gemini-2.0-flash&quot;,<br>    description=&quot;I coordinate greetings and tasks.&quot;,<br>    sub_agents=[ # Assign sub_agents here<br>        greeter,<br>        task_doer<br>    ]<br>)<br><br># Framework automatically sets:<br># assert greeter.parent_agent == coordinator<br># assert task_doer.parent_agent == coordinator</pre><h3>1.2. Workflow Agents as Orchestrators</h3><p>While BaseAgent instances perform specific tasks, ADK introduces specialized agents known as Workflow Agents that are designed to orchestrate the execution flow of their sub_agents. These agents do not perform tasks themselves but rather manage how and when their child agents are invoked, making them indispensable for building structured and predictable multi-agent workflows. ADK provides three primary types of workflow agents:</p><ul><li><strong><em>SequentialAgent</em></strong>: This agent executes its sub_agents one after another in the order they are listed. It’s ideal for pipelines where the output of one step feeds directly into the next. The SequentialAgent passes the same InvocationContext sequentially, allowing agents to easily pass results via shared state.</li></ul><pre>step1 = LlmAgent(name=&quot;Step1_Fetch&quot;, output_key=&quot;data&quot;) # Saves output to state[&#39;data&#39;]<br>step2 = LlmAgent(name=&quot;Step2_Process&quot;, instruction=&quot;Process data from {data}.&quot;)<br><br>pipeline = SequentialAgent(name=&quot;MyPipeline&quot;, sub_agents=[step1, step2])<br># When pipeline runs, Step2 can access the state[&#39;data&#39;] set by Step1.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYgNqpHIWM0PIOnxEM19iA.png" /></figure><ul><li><strong><em>ParallelAgent</em></strong>: In contrast to the SequentialAgent, the ParallelAgent executes its sub_agents concurrently. This is highly beneficial for tasks that can be performed independently, significantly speeding up overall execution time. While events from sub-agents may be interleaved, all parallel children access the same shared session.state, enabling them to read initial state and write results. It’s important to use distinct keys to avoid race conditions when writing to shared state.</li></ul><pre>fetch_weather = LlmAgent(name=&quot;WeatherFetcher&quot;, output_key=&quot;weather&quot;)<br>fetch_news = LlmAgent(name=&quot;NewsFetcher&quot;, output_key=&quot;news&quot;)<br><br>gatherer = ParallelAgent(name=&quot;InfoGatherer&quot;, sub_agents=[fetch_weather, fetch_news])<br># When gatherer runs, WeatherFetcher and NewsFetcher run concurrently.<br># A subsequent agent could read state[&#39;weather&#39;] and state[&#39;news&#39;].</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjs3keCxMABWfmV57d_BXA.png" /></figure><ul><li><strong><em>LoopAgent</em></strong>: The LoopAgent is designed for iterative processes, executing its sub_agents sequentially in a loop. This is useful for scenarios requiring repeated actions until a certain condition is met or a maximum number of iterations is reached. The loop terminates if the optional max_iterations is reached, or if any sub-agent returns an Event with escalate=True in its EventActions. The LoopAgent passes the same InvocationContext in each iteration, allowing state changes (e.g., counters, flags) to persist across loops.</li></ul><pre>class CheckCondition(BaseAgent): # Custom agent to check state<br>    async def _run_async_impl(self, ctx: InvocationContext) -&gt; AsyncGenerator[Event, None]:<br>        status = ctx.session.state.get(&quot;status&quot;, &quot;pending&quot;)<br>        is_done = (status == &quot;completed&quot;)<br>        yield Event(author=self.name, actions=EventActions(escalate=is_done)) # Escalate if done<br><br>process_step = LlmAgent(name=&quot;ProcessingStep&quot;) # Agent that might update state[&#39;status&#39;]<br><br>poller = LoopAgent(<br>    name=&quot;StatusPoller&quot;,<br>    max_iterations=10,<br>    sub_agents=[process_step, CheckCondition(name=&quot;Checker&quot;)]<br>)<br># When poller runs, it executes process_step then Checker repeatedly<br># until Checker escalates (state[&#39;status&#39;] == &#39;completed&#39;) or 10 iterations pass.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wyf-RP-FTJ7UH-_FJIXV4g.png" /></figure><h3>1.3. Interaction &amp; Communication Mechanisms</h3><p>For a multi-agent system to function effectively, agents must be able to exchange information and trigger actions in one another. ADK provides several mechanisms to facilitate this inter-agent communication:</p><p><strong><em>Shared Session State (session.state)</em></strong></p><p>This is the most fundamental way for agents operating within the same invocation to communicate passively. Agents share the same Session object via the InvocationContext, allowing one agent to write a value (e.g., context.state[‘data_key’] = processed_data) and a subsequent agent to read it (data = context.state.get(‘data_key’)). State changes are tracked via CallbackContext. The output_key property on LlmAgent automatically saves the agent’s final response text or structured output to the specified state key. This asynchronous, passive communication is ideal for pipelines orchestrated by SequentialAgent or for passing data across LoopAgent iterations.</p><pre>agent_A = LlmAgent(name=&quot;AgentA&quot;, instruction=&quot;Find the capital of France.&quot;, output_key=&quot;capital_city&quot;)<br>agent_B = LlmAgent(name=&quot;AgentB&quot;, instruction=&quot;Tell me about the city stored in {capital_city}.&quot;)<br><br>pipeline = SequentialAgent(name=&quot;CityInfo&quot;, sub_agents=[agent_A, agent_B])<br># AgentA runs, saves &quot;Paris&quot; to state[&#39;capital_city&#39;].<br># AgentB runs, its instruction processor reads state[&#39;capital_city&#39;] to get &quot;Paris&quot;.</pre><p><strong><em>LLM-Driven Delegation (Agent Transfer)</em></strong></p><p>ADK allows an LLM agent to dynamically transfer control to another agent within its hierarchy by emitting a special AgentTransfer event. This is particularly useful for building flexible, LLM-driven workflows where the LLM decides which specialized agent should handle a specific sub-task. The LLM agent includes a structured AgentTransfer object (e.g., as part of a ToolCode or StructuredOutput) specifying the target_agent_name and any input_data for the target agent. The target agent must be a sub-agent (direct or indirect) of the transferring agent. This mechanism enables dynamic routing, allows LLMs to leverage specialized agents, and promotes modularity.</p><pre>booking_agent = LlmAgent(name=&quot;Booker&quot;, description=&quot;Handles flight and hotel bookings.&quot;)<br>info_agent = LlmAgent(name=&quot;Info&quot;, description=&quot;Provides general information and answers questions.&quot;)<br><br>coordinator = LlmAgent(<br>    name=&quot;Coordinator&quot;,<br>    model=&quot;gemini-2.0-flash&quot;,<br>    instruction=&quot;You are an assistant. Delegate booking tasks to Booker and info requests to Info.&quot;,<br>    description=&quot;Main coordinator.&quot;,<br>    # AutoFlow is typically used implicitly here<br>    sub_agents=[booking_agent, info_agent]<br>)<br># If coordinator receives &quot;Book a flight&quot;, its LLM should generate:<br># FunctionCall(name=&#39;transfer_to_agent&#39;, args={&#39;agent_name&#39;: &#39;Booker&#39;})<br># ADK framework then routes execution to booking_agent.</pre><p><strong><em>Explicit Invocation (AgentTool)</em></strong></p><p>For more direct and programmatic control, agents can explicitly invoke other agents as if they were tools. This is ideal when a parent agent needs to directly call a sub-agent and process its output within its own execution flow, rather than transferring control. An AgentTool is created, wrapping the target agent. This AgentTool can then be used by an LLM agent (if configured as one of its tools) or directly invoked by a BaseAgent within its _run_async_impl method. The AgentTool handles passing input to the target agent and capturing its output. This provides fine-grained control, allows for complex agent interactions, and enables agents to act as services for others.</p><pre># Define a target agent (could be LlmAgent or custom BaseAgent)<br>class ImageGeneratorAgent(BaseAgent): # Example custom agent<br>    name: str = &quot;ImageGen&quot;<br>    description: str = &quot;Generates an image based on a prompt.&quot;<br>    # ... internal logic ...<br>    async def _run_async_impl(self, ctx): # Simplified run logic<br>        prompt = ctx.session.state.get(&quot;image_prompt&quot;, &quot;default prompt&quot;)<br>        # ... generate image bytes ...<br>        image_bytes = b&quot;...&quot;<br>        yield Event(author=self.name, content=types.Content(parts=[types.Part.from_bytes(image_bytes, &quot;image/png&quot;)]))<br><br>image_agent = ImageGeneratorAgent()<br>image_tool = agent_tool.AgentTool(agent=image_agent) # Wrap the agent<br><br># Parent agent uses the AgentTool<br>artist_agent = LlmAgent(<br>    name=&quot;Artist&quot;,<br>    model=&quot;gemini-2.0-flash&quot;,<br>    instruction=&quot;Create a prompt and use the ImageGen tool to generate the image.&quot;,<br>    tools=[image_tool] # Include the AgentTool<br>)<br># Artist LLM generates a prompt, then calls:<br># FunctionCall(name=&#39;ImageGen&#39;, args={&#39;image_prompt&#39;: &#39;a cat wearing a hat&#39;})<br># Framework calls image_tool.run_async(...), which runs ImageGeneratorAgent.<br># The resulting image Part is returned to the Artist agent as the tool result.</pre><h3>2. Common Multi-Agent Patterns using ADK Primitives</h3><p>ADK’s core primitives enable the implementation of various common multi-agent system patterns. Understanding these patterns is crucial for designing robust, efficient, and scalable agentic applications that can address a wide range of complex problems. Each pattern leverages specific ADK primitives to achieve its unique orchestration and communication goals.</p><h3>Coordinator/Dispatcher Pattern</h3><p>Description and Use Case: In this pattern, a central LlmAgent acts as a Coordinator, receiving incoming requests, interpreting their intent, and then intelligently delegating the task to one or more specialized sub_agents (Dispatchers). This delegation is typically achieved using LLM-Driven Delegation (AgentTransfer). This pattern is highly effective for routing user requests to the appropriate backend service or specialized agent, making it ideal for building conversational AI systems that can handle diverse user intents and seamlessly hand off tasks to the most suitable agent.</p><p>ADK Primitives Used: LlmAgent (as the Coordinator), AgentTransfer (for delegation), and BaseAgent (for the specialized Dispatchers).</p><p>Here’s a conceptual example of the Coordinator/Dispatcher pattern:</p><pre>from google.adk.agents import LlmAgent<br>from google.adk.structured_output import AgentTransfer, StructuredOutput<br><br># Specialized agents<br>email_sender = LlmAgent(name=&quot;EmailSender&quot;, instruction=&quot;Send an email.&quot;)<br>db_query_agent = LlmAgent(name=&quot;DBQueryAgent&quot;, instruction=&quot;Query the database.&quot;)<br><br># Coordinator agent<br>dispatcher = LlmAgent(<br>    name=&quot;RequestDispatcher&quot;,<br>    model=&quot;gemini-2.0-flash&quot;,<br>    instruction=&quot;&quot;&quot;You are a request dispatcher.<br>    Based on the user&#39;s request, decide which agent should handle it:<br>    &#39;EmailSender&#39; for email tasks, &#39;DBQueryAgent&#39; for database queries.<br>    Always respond with a StructuredOutput containing an AgentTransfer.<br>    &quot;&quot;&quot;,<br>    sub_agents=[email_sender, db_query_agent]<br>)<br><br># Example user request: &quot;Send a welcome email to new users.&quot;<br># LLM output: StructuredOutput(agent_transfer=AgentTransfer(target_agent_name=&quot;EmailSender&quot;, input_data={&quot;subject&quot;: &quot;Welcome&quot;, &quot;body&quot;: &quot;...&quot;}))</pre><h3>Sequential Pipeline Pattern</h3><p>Description and Use Case: This pattern involves breaking down a complex task into a series of sequential steps, where each step is handled by a dedicated agent. The crucial aspect is that the output of one agent serves as the input for the next, creating a clear, linear flow of data and processing. This pattern is widely applicable in data processing workflows (e.g., fetching data, parsing it, analyzing it, and then summarizing the results), multi-step content generation, or automated customer support flows where a series of predefined actions need to be executed in order.</p><p>ADK Primitives Used: SequentialAgent (as the orchestrator), LlmAgent or BaseAgent (for individual steps), and session.state (for passing data between agents).</p><p>Here’s a conceptual example of a sequential pipeline:</p><pre>from google.adk.agents import SequentialAgent, LlmAgent<br><br># Define agents for each step<br>data_fetcher = LlmAgent(name=&quot;DataFetcher&quot;, output_key=&quot;raw_data&quot;)<br>data_parser = LlmAgent(name=&quot;DataParser&quot;, instruction=&quot;Parse {raw_data}.&quot;, output_key=&quot;parsed_data&quot;)<br>data_analyzer = LlmAgent(name=&quot;DataAnalyzer&quot;, instruction=&quot;Analyze {parsed_data}.&quot;, output_key=&quot;analysis_results&quot;)<br><br># Create a sequential pipeline<br>pipeline = SequentialAgent(<br>    name=&quot;DataProcessingPipeline&quot;,<br>    sub_agents=[data_fetcher, data_parser, data_analyzer]<br>)<br><br># When pipeline runs:<br># 1. DataFetcher runs, saves raw data to state[&#39;raw_data&#39;].<br># 2. DataParser runs, reads state[&#39;raw_data&#39;], saves parsed data to state[&#39;parsed_data&#39;].<br># 3. DataAnalyzer runs, reads state[&#39;parsed_data&#39;], saves analysis to state[&#39;analysis_results&#39;].</pre><h3>Parallel Fan-Out/Gather Pattern</h3><p>Description and Use Case: The Parallel Fan-Out/Gather pattern is designed for scenarios where multiple sub-tasks can be executed concurrently. A central agent dispatches these sub-tasks to several agents in parallel (fan-out), and once all parallel tasks are complete, it gathers and synthesizes their individual results (gather). This pattern is highly effective for simultaneously fetching information from multiple sources, generating multiple creative variations (e.g., different design options), or running concurrent analyses to expedite processing. It significantly reduces the overall execution time for tasks that can be parallelized.</p><p>ADK Primitives Used: ParallelAgent (as the orchestrator), LlmAgent or BaseAgent (for the parallel sub-tasks), and session.state (for gathering results from the concurrently executing agents).</p><p>Here’s a conceptual example of the Parallel Fan-Out/Gather pattern:</p><pre>from google.adk.agents import ParallelAgent, LlmAgent<br><br># Define agents for parallel execution<br>stock_price_fetcher = LlmAgent(name=&quot;StockPriceFetcher&quot;, output_key=&quot;stock_data&quot;)<br>news_sentiment_analyzer = LlmAgent(name=&quot;NewsSentimentAnalyzer&quot;, output_key=&quot;news_sentiment&quot;)<br>social_media_monitor = LlmAgent(name=&quot;SocialMediaMonitor&quot;, output_key=&quot;social_data&quot;)<br><br># Create a parallel agent to run them concurrently<br>parallel_gatherer = ParallelAgent(<br>    name=&quot;MarketDataGatherer&quot;,<br>    sub_agents=[stock_price_fetcher, news_sentiment_analyzer, social_media_monitor]<br>)<br><br># A subsequent agent could then read state[&#39;stock_data&#39;], state[&#39;news_sentiment&#39;], and state[&#39;social_data&#39;]<br># to synthesize a comprehensive market overview.</pre><h3>Hierarchical Task Decomposition</h3><p>Description and Use Case: This pattern addresses complex problems by having a high-level agent break down the main problem into smaller, more manageable sub-problems. Each sub-problem is then delegated to a specialized sub-agent for resolution. This decomposition process can be recursive, allowing for the tackling of highly intricate tasks by progressively breaking them down into simpler components. It’s particularly useful in complex problem-solving, project management (where a large project is divided into smaller tasks), or multi-faceted content creation (e.g., an article broken into sections, each written by a different agent).</p><p>ADK Primitives Used: LlmAgent (as the parent agent for decomposition and delegation), AgentTransfer or AgentTool (for facilitating the delegation or invocation of sub-agents), and BaseAgent (for the specialized sub-agents that handle the decomposed tasks).</p><p>Here’s a conceptual example of Hierarchical Task Decomposition:</p><pre>from google.adk.agents import LlmAgent<br>from google.adk.structured_output import AgentTransfer, StructuredOutput<br><br># Define specialized agents for sub-tasks<br>content_writer = LlmAgent(name=&quot;ContentWriter&quot;, instruction=&quot;Write a section of the article.&quot;)<br>image_designer = LlmAgent(name=&quot;ImageDesigner&quot;, instruction=&quot;Design an image for the article.&quot;)<br><br># High-level project manager agent<br>project_manager = LlmAgent(<br>    name=&quot;ArticleProjectManager&quot;,<br>    model=&quot;gemini-2.0-flash&quot;,<br>    instruction=&quot;&quot;&quot;You are a project manager for article creation.<br>    Break down the article topic into sections and delegate writing to &#39;ContentWriter&#39;<br>    and image creation to &#39;ImageDesigner&#39;.<br>    Use AgentTransfer to delegate tasks.<br>    &quot;&quot;&quot;,<br>    sub_agents=[content_writer, image_designer]<br>)<br><br># Example: User asks for an article on &quot;AI in Healthcare&quot;.<br># ProjectManager might delegate:<br># - StructuredOutput(agent_transfer=AgentTransfer(target_agent_name=&quot;ContentWriter&quot;, input_data={&quot;topic&quot;: &quot;Introduction to AI in Healthcare&quot;}))<br># - StructuredOutput(agent_transfer=AgentTransfer(target_agent_name=&quot;ImageDesigner&quot;, input_data={&quot;description&quot;: &quot;AI in healthcare infographic&quot;}))</pre><h3>Review/Critique Pattern (Generator-Critic)</h3><p>Description and Use Case: This pattern involves two primary roles: a Generator agent that produces content or a solution, and a Critic agent that evaluates the Generator’s output, providing feedback for refinement. This process can be iterative, with the Generator refining its output based on the Critic’s feedback until a satisfactory result is achieved. This pattern is highly valuable for tasks requiring quality assurance and iterative improvement, such as code review, creative writing refinement, design iteration, or any process where continuous feedback loops lead to better outcomes.</p><p>ADK Primitives Used: LlmAgent (for both the Generator and Critic roles), LoopAgent (for managing the iterative refinement process), and session.state (for passing content between the Generator and Critic, and for conveying feedback).</p><p>Here’s a conceptual example of the Generator-Critic pattern:</p><pre>from google.adk.agents import LlmAgent, LoopAgent, BaseAgent<br>from google.adk.events import Event, EventActions<br>from google.adk.agents.invocation_context import InvocationContext<br>from typing import AsyncGenerator<br><br>class FeedbackChecker(BaseAgent):<br>    async def _run_async_impl(self, ctx: InvocationContext) -&gt; AsyncGenerator[Event, None]:<br>        feedback = ctx.session.state.get(&quot;feedback&quot;, &quot;&quot;)<br>        if &quot;Looks good&quot; in feedback:<br>            yield Event(author=self.name, actions=EventActions(escalate=True)) # Stop loop<br>        else:<br>            yield Event(author=self.name, text=&quot;More refinement needed.&quot;)<br><br># Generator agent<br>content_generator = LlmAgent(name=&quot;ContentGenerator&quot;, instruction=&quot;Write a short story.&quot;, output_key=&quot;story&quot;)<br><br># Critic agent<br>content_critic = LlmAgent(<br>    name=&quot;ContentCritic&quot;,<br>    instruction=&quot;Review the story: {story}. Provide constructive feedback. If it&#39;s perfect, say &#39;Looks good&#39;.&quot;,<br>    output_key=&quot;feedback&quot;<br>)<br><br># Iterative refinement loop<br>refinement_loop = LoopAgent(<br>    name=&quot;StoryRefinement&quot;,<br>    max_iterations=5,<br>    sub_agents=[content_generator, content_critic, FeedbackChecker(name=&quot;Checker&quot;)]<br>)<br><br># The loop continues until the Checker escalates (feedback is positive) or max_iterations is reached.</pre><h3>Iterative Refinement Pattern</h3><p>Description and Use Case: The Iterative Refinement pattern involves an agent repeatedly performing an action, continuously refining its output based on previous iterations or external feedback until a specific condition is met. This pattern is fundamental for tasks that require convergence towards an optimal solution, such as optimizing complex algorithms, converging on a desired state in a system, or solving constraint satisfaction problems where solutions are progressively improved over time.</p><p>ADK Primitives Used: LoopAgent (for managing the iterative process), LlmAgent or BaseAgent (as the refining agent that performs the iterative action), and session.state (for maintaining and updating the state of the solution across iterations).</p><p>Here’s a conceptual example of the Iterative Refinement pattern:</p><pre>from google.adk.agents import LlmAgent, LoopAgent, BaseAgent<br>from google.adk.events import Event, EventActions<br>from google.adk.agents.invocation_context import InvocationContext<br>from typing import AsyncGenerator<br><br>class SolutionEvaluator(BaseAgent):<br>    async def _run_async_impl(self, ctx: InvocationContext) -&gt; AsyncGenerator[Event, None]:<br>        solution = ctx.session.state.get(&quot;current_solution&quot;, &quot;&quot;)<br>        # Simulate evaluation logic<br>        if &quot;optimal&quot; in solution:<br>            yield Event(author=self.name, actions=EventActions(escalate=True))<br>        else:<br>            yield Event(author=self.name, text=&quot;Solution needs further refinement.&quot;)<br><br># Agent that refines the solution<br>solution_refiner = LlmAgent(<br>    name=&quot;SolutionRefiner&quot;,<br>    instruction=&quot;Refine the current solution: {current_solution}.&quot;,<br>    output_key=&quot;current_solution&quot;<br>)<br><br># Iterative refinement loop<br>refinement_loop = LoopAgent(<br>    name=&quot;OptimizationLoop&quot;,<br>    max_iterations=10,<br>    sub_agents=[solution_refiner, SolutionEvaluator(name=&quot;Evaluator&quot;)]<br>)<br><br># The loop continues until the Evaluator escalates (solution is optimal) or max_iterations is reached.</pre><h3>Human-in-the-Loop Pattern</h3><p>Description and Use Case: The Human-in-the-Loop (HITL) pattern integrates human users at specific points within the multi-agent system’s workflow. This allows for human review, approval, or direct input, effectively combining the efficiency of automated processes with the critical oversight and nuanced decision-making capabilities of humans. This pattern is essential for tasks that require subjective judgment, ethical considerations, or access to information that only a human can provide. Common use cases include content moderation, critical decision-making workflows (e.g., financial approvals), personalized recommendations, or legal document review.</p><p>ADK Primitives Used: LlmAgent or BaseAgent (to define the interaction points where human input is required), and external communication mechanisms (such as ADK’s Event system or custom tools for UI integration) to facilitate the interaction with the human user.</p><p>Here’s a conceptual example of the Human-in-the-Loop pattern:</p><pre>from google.adk.agents import LlmAgent, SequentialAgent, BaseAgent<br>from google.adk.events import Event, EventActions<br>from google.adk.agents.invocation_context import InvocationContext<br>from typing import AsyncGenerator<br><br>class HumanApprovalAgent(BaseAgent):<br>    async def _run_async_impl(self, ctx: InvocationContext) -&gt; AsyncGenerator[Event, None]:<br>        # In a real system, this would send a notification to a human and wait for input.<br>        # For this conceptual example, we&#39;ll simulate approval.<br>        print(f&quot;Human Approval Needed for: {ctx.session.state.get(&#39;document_to_review&#39;)}&quot;)<br>        # Simulate human input (e.g., from a UI or external system)<br>        human_decision = input(&quot;Approve? (yes/no): &quot;) # This would be replaced by actual human interaction<br>        if human_decision.lower() == &quot;yes&quot;:<br>            yield Event(author=self.name, text=&quot;Document approved by human.&quot;)<br>        else:<br>            yield Event(author=self.name, text=&quot;Document rejected by human.&quot;, actions=EventActions(escalate=True)) # Escalate to stop workflow<br><br># Agent that generates content<br>document_generator = LlmAgent(name=&quot;DocumentGenerator&quot;, instruction=&quot;Generate a legal document.&quot;, output_key=&quot;document_to_review&quot;)<br><br># Pipeline with human approval<br>document_workflow = SequentialAgent(<br>    name=&quot;DocumentApprovalWorkflow&quot;,<br>    sub_agents=[document_generator, HumanApprovalAgent(name=&quot;Approver&quot;)]<br>)<br><br># The workflow pauses at HumanApprovalAgent, waiting for human input.</pre><h3>Conclusion</h3><p>Multi-agent systems built with the Google Agent Development Kit offer a powerful paradigm for creating sophisticated and modular agentic applications. By leveraging ADK’s core primitives — such as agent hierarchy, workflow agents (SequentialAgent, ParallelAgent, LoopAgent), and inter-agent communication mechanisms (session.state, AgentTransfer, AgentTool) — developers can design systems that are more manageable, scalable, and capable of tackling complex, real-world problems.</p><p>Understanding and applying common multi-agent patterns like Coordinator/Dispatcher, Sequential Pipeline, Parallel Fan-Out/Gather, Hierarchical Task Decomposition, Review/Critique, Iterative Refinement, and Human-in-the-Loop allows for the structured development of highly effective and specialized agentic solutions. As you embark on building your own multi-agent systems, remember to choose the right primitives and patterns that best fit your application’s requirements, leading to more robust and intelligent automated workflows.</p><p>Reference:<a href="https://google.github.io/adk-docs/agents/">https://google.github.io/adk-docs/agents/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59dbfcfa325f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Content for Large Language Models: A Technical Guide to LLM SEO]]></title>
            <link>https://medium.com/@saminchandeepa/optimizing-content-for-large-language-models-a-technical-guide-to-llm-seo-77766a2943fb?source=rss-20594cbd238------2</link>
            <guid isPermaLink="false">https://medium.com/p/77766a2943fb</guid>
            <category><![CDATA[llm-seo]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[seo]]></category>
            <dc:creator><![CDATA[Samin Chandeepa (Adomic)]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 17:47:07 GMT</pubDate>
            <atom:updated>2025-06-22T17:47:07.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7Y4dXAwVwqlr49bOBEIjw.png" /><figcaption>A Technical Guide to LLM SEO</figcaption></figure><p>The evolution of search engines, driven by Large Language Models (LLMs), has fundamentally reshaped Search Engine Optimization (SEO). This guide provides a technical, actionable framework for optimizing content to align with LLM-driven search paradigms, such as Google’s AI Overviews and conversational search interfaces. Drawing from advanced SEO strategies, this article details the mechanisms, techniques, and metrics required to ensure your content is prioritized by LLMs as a definitive source.</p><h3>1. Understanding LLM SEO: A Paradigm Shift</h3><p>LLM SEO focuses on optimizing content for semantic understanding, contextual relevance, and citation by AI-driven systems. Unlike traditional SEO, which prioritizes keyword density and backlink volume, LLM SEO emphasizes <strong>comprehensiveness, authority, and structured data</strong> to align with the natural language processing (NLP) capabilities of LLMs.</p><ul><li><strong>Core Objective</strong>: Ensure content is parsed, understood, and cited by LLMs for direct answers in AI Overviews or conversational responses.</li><li><strong>Key Challenge</strong>: Transition from ranking for specific keywords to being recognized as a primary source for complex, intent-driven queries.</li></ul><h3>2. Mechanisms of LLM-Driven Search</h3><p>LLMs, such as those powering Google’s AI Overviews or AI assistants, leverage advanced NLP techniques to process queries:</p><ul><li><strong>Semantic Analysis</strong>: LLMs use transformer-based architectures (e.g., BERT, T5) to interpret query intent, synonyms, and contextual relationships, moving beyond exact-match keywords.</li><li><strong>Knowledge Graph Integration</strong>: LLMs enhance entity recognition, mapping content to structured knowledge graphs that connect concepts, entities, and attributes.</li><li><strong>E-E-A-T Evaluation</strong>: LLMs assess <strong>Experience, Expertise, Authoritativeness, and Trustworthiness</strong> through signals like author credentials, source credibility, and content depth.</li></ul><p>For example, a query like “best headphones for noisy commutes with long battery life” requires content that addresses multiple facets (noise cancellation, battery metrics, comfort) with verifiable expertise, rather than just repeating “best headphones.”</p><h3>3. Technical Strategies for LLM SEO</h3><h4>3.1. Comprehensive Content Development</h4><ul><li><strong>Depth and Breadth</strong>: Create exhaustive, evergreen content covering all aspects of a topic. For instance, a guide on “noise-cancelling headphones” should include technical specifications (e.g., dB reduction levels), user scenarios (e.g., commuting), and expert reviews.</li><li><strong>Question-Driven Structure</strong>: Anticipate and answer user queries explicitly, incorporating “People Also Ask” questions. Use FAQ sections with concise, direct responses.</li><li><strong>Example</strong>: For the query above, include sections like “Noise Cancellation Technology Explained” and “Battery Life Benchmarks for Top Models.”</li></ul><h4>3.2. Structured Data and Schema Markup</h4><ul><li><strong>Purpose</strong>: Schema markup (e.g., JSON-LD) provides explicit metadata, enabling LLMs to categorize content accurately.</li><li><strong>Implementation</strong>:</li><li>Use schema types like Product, Review, FAQPage, or HowTo to define entities and relationships.</li><li>Example: For a headphone review, implement Product schema with properties like noiseCancellationLevel, batteryLife, and userRating.</li><li>Ensure schema is embedded in the &lt;head&gt; or &lt;body&gt; of HTML pages and validated using tools like Google’s Rich Results Test.</li><li><strong>Benefit</strong>: Structured data enhances entity recognition, increasing the likelihood of citation in AI Overviews.</li></ul><h4>3.3. Semantic Optimization</h4><ul><li><strong>Natural Language Alignment</strong>: Write in a conversational, human-like tone, mirroring how users query AI assistants (e.g., “What makes these headphones good for commuting?”).</li><li><strong>Entity Optimization</strong>: Explicitly define entities (e.g., “Bose NC700 headphones,” “active noise cancellation”) and their relationships using clear, descriptive language.</li><li><strong>Latent Semantic Indexing (LSI)</strong>: Include related terms and concepts (e.g., “ANC algorithms,” “commute comfort”) to reinforce topical relevance.</li></ul><h4>3.4. E-E-A-T Implementation</h4><ul><li><strong>Experience</strong>: Incorporate case studies or firsthand insights (e.g., “We tested the Bose NC700 during a 2-hour train commute”).</li><li><strong>Expertise</strong>: Highlight author credentials in bios (e.g., “Dr. Jane Smith, Audio Engineer with 10+ years in acoustics”).</li><li><strong>Authoritativeness</strong>: Secure backlinks from high-domain-authority sites and cite reputable sources (e.g., IEEE, Consumer Reports).</li><li><strong>Trustworthiness</strong>: Ensure factual accuracy, use HTTPS, and maintain transparent authorship.</li></ul><h4>3.5. Content Formatting for AI Readability</h4><ul><li><strong>Hierarchical Structure</strong>: Use descriptive HTML headings (&lt;h1&gt;, &lt;h2&gt;, &lt;h3&gt;) to organize content logically.</li><li><strong>Scannable Elements</strong>: Employ bullet points, numbered lists, and tables for quick data extraction. Example:</li></ul><pre>### Top Headphones for Commuting<br>- **Bose NC700**: 30dB noise reduction, 20-hour battery life<br>- **Sony WH-1000XM5**: 32dB noise reduction, 30-hour battery life</pre><ul><li><strong>Concise Paragraphs</strong>: Keep paragraphs under 100 words to facilitate LLM parsing.</li></ul><h4>3.6. Technical SEO Foundations</h4><ul><li><strong>Crawlability</strong>: Ensure clean URL structures, XML sitemaps, and noindex directives for low-value pages.</li><li><strong>Site Performance</strong>: Optimize for Core Web Vitals (e.g., LCP &lt; 2.5s, CLS &lt; 0.1) using tools like PageSpeed Insights.</li><li><strong>Mobile Optimization</strong>: Prioritize responsive design, as 60%+ of searches occur on mobile devices.</li></ul><h3>4. Measuring LLM SEO Success</h3><p>Traditional metrics (e.g., keyword rankings) are less relevant in LLM SEO. Focus on:</p><ul><li><strong>AI Citation Rate</strong>: Track appearances in AI Overviews using tools like Semrush or Ahrefs (manual SERP analysis may be required).</li><li><strong>Entity Mentions</strong>: Monitor brand or content references in AI-generated responses across platforms.</li><li><strong>Engagement Depth</strong>: Measure time-on-page and scroll depth for AI-driven traffic, indicating content relevance.</li><li><strong>Topical Authority</strong>: Assess coverage across related queries using tools like Google Search Console’s query clusters.</li><li><strong>Indirect Traffic</strong>: Analyze referral traffic from AI-integrated platforms (e.g., voice assistants, chatbots).</li></ul><h3>5. Challenges and Mitigation Strategies</h3><ul><li><strong>LLM Hallucinations</strong>: Counter inaccuracies by prioritizing primary sources and fact-checking claims. Use internal linking to reinforce factual content.</li><li><strong>Algorithm Volatility</strong>: Stay updated via industry blogs (e.g., Search Engine Journal) and test content performance regularly.</li><li><strong>Resource Intensity</strong>: Allocate budget for long-form content creation and schema implementation. Use AI tools (e.g., SurferSEO) to streamline keyword and entity research.</li></ul><h3>6. Future Outlook</h3><p>LLM SEO represents a convergence of technical SEO, content strategy, and AI-driven discovery. As LLMs integrate into more platforms (e.g., voice assistants, IoT devices), optimizing for semantic relevance and structured data will unlock new channels for visibility. Key trends include:</p><ul><li><strong>Multi-Modal Search</strong>: LLMs will process images, audio, and video, requiring optimization of alt text, transcripts, and multimedia schema.</li><li><strong>Personalized Responses</strong>: Content tailored to user context (e.g., location, device) will gain prominence.</li><li><strong>Zero-Click Dominance</strong>: AI Overviews will reduce direct clicks, making citation and brand authority critical.</li></ul><h3>7. Conclusion</h3><p>LLM SEO demands a shift from keyword-centric tactics to semantic, user-focused strategies. By prioritizing comprehensive content, structured data, and E-E-A-T signals, brands can position themselves as authoritative sources for LLMs. This approach not only ensures visibility in AI-driven search but also future-proofs digital strategies for an increasingly intelligent web.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77766a2943fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s New in Flutter at Google I/O 2025: Flutter 3.32 and Exciting Ecosystem Updates]]></title>
            <link>https://medium.com/@saminchandeepa/whats-new-in-flutter-at-google-i-o-2025-flutter-3-32-and-exciting-ecosystem-updates-0b6a94c40aa9?source=rss-20594cbd238------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b6a94c40aa9</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[google-io-flutter]]></category>
            <dc:creator><![CDATA[Samin Chandeepa (Adomic)]]></dc:creator>
            <pubDate>Wed, 21 May 2025 16:37:26 GMT</pubDate>
            <atom:updated>2025-05-21T16:37:26.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ka7jCWkv_L3lwE44.jpg" /><figcaption>Google I/O 2025</figcaption></figure><p>Google I/O 2025 has once again showcased Flutter’s rapid evolution as the go-to framework for building beautiful, high-performance, and accessible apps across mobile, web, and desktop. The highlight of the event was the release of Flutter 3.32, packed with powerful new features, improvements, and tooling enhancements that make app development more efficient and enjoyable.</p><p>In this article, we’ll walk through all the important Flutter 3.32 updates announced at Google I/O, including framework improvements, platform-specific changes, accessibility advancements, and exciting new AI integrations.</p><h3>Hot Reload on Web (Experimental)</h3><p>One of the most requested features, hot reload for Flutter web, is now available in experimental mode. This means developers can instantly see code changes reflected in running web apps without restarting, significantly speeding up the development cycle.</p><pre>flutter run -d chrome --web-experimental-hot-reload</pre><h4>Running from VS Code</h4><p>If you use debug configurations in VS Code, you can add this extra configuration to your <a href="https://code.visualstudio.com/docs/editor/debugging-configuration">launch.json file</a>:</p><pre>&quot;configurations&quot;: [<br>…<br>  {<br>    &quot;name&quot;: &quot;Flutter for web (hot reloadable)&quot;,<br>    &quot;type&quot;: &quot;dart&quot;,<br>    &quot;request&quot;: &quot;launch&quot;,<br>    &quot;program&quot;: &quot;lib/main.dart&quot;,<br>    &quot;args&quot;: [<br>      &quot;-d&quot;,<br>      &quot;chrome&quot;,<br>      &quot;--web-experimental-hot-reload&quot;,<br>    ]<br>  }<br>]</pre><h3>New Rounded Superellipse Support for iOS and Android</h3><p>Flutter now supports Apple’s iconic “squircle” shape a rounded superellipse which is a key element of native iOS design aesthetics.</p><p>You can add rounded superellipses to your apps using these new APIs:</p><ul><li>RoundedSuperellipseBorder: Use this for painting or as a widget shape.</li><li>ClipRSuperellipse: Clip widgets with the squircle shape.</li><li>Lower-level Canvas and Path APIs:</li></ul><pre>Canvas.drawRSuperellipse<br>Canvas.clipRSuperellipse<br>Path.addRSuperellipse</pre><p><em>Note: This feature is currently supported only on iOS and Android. On other platforms, it gracefully falls back to a standard rounded rectangle. Performance optimizations and additional enhancements are actively in progress, so expect improvements in future releases.</em></p><h3>Cupertino (iOS) UI Enhancements</h3><p>Flutter’s Cupertino library, which provides iOS-style widgets, received several important updates:</p><p><strong>Cupertino Sheet Fixes:</strong></p><ul><li>Fixed issues with how the sheet sets the system UI theme on Android when opening.</li><li>Adjusted navigation bar height to prevent content from being cut off at the bottom, improving visual consistency and usability.</li></ul><p><strong>Navigation Bars:</strong></p><ul><li>The <strong><em>CupertinoSliverNavigationBar.search</em></strong> widget now has improved animation fidelity when opening and closing the search view.</li><li>Alignment of prefix and suffix icons in the search field is now precise and visually correct.</li></ul><h3>Material Design Library Improvements</h3><p>Flutter’s Material library saw a variety of new features and bug fixes that enhance both developer experience and app functionality:</p><ul><li><strong><em>CarouselController </em></strong>: Added a convenient animateToIndex method for smooth, index-based carousel navigation, supporting both fixed and dynamically sized items using flexWeights.</li><li><strong><em>TabBar Widget </em></strong>: New callbacks onHover and onFocusChange give developers finer control over widget appearance during user interaction.</li><li><strong><em>SearchAnchor and SearchAnchor.bar </em></strong>: Introduced viewOnOpen and onOpen callbacks for better handling of open/close events.</li><li><strong><em>CalendarDatePicker </em></strong>: Now accepts a calendarDelegate to support custom calendar systems beyond the Gregorian calendar. For example, you can create calendars where months have custom lengths or start on specific weekdays.</li><li><strong><em>Accessibility and UX Enhancements </em></strong>: Improved user experience for widgets like text fields, focus handling, menus, sliders, and dropdowns.Screen readers now provide more descriptive feedback during interactions.</li><li><strong><em>Web Focus Navigation </em></strong>: Refined focus behavior when semantics are enabled, reducing abrupt jumps and making keyboard navigation smoother.</li><li><strong><em>Android TalkBack Link Recognition </em></strong>: TalkBack now correctly identifies and announces links defined using Semantics.linkUrl or the Link widget from the url_launcher package.</li><li><strong><em>Windows High-Contrast Mode </em></strong>: Flutter for web now supports Windows’ “forced colors” mode (used in high contrast scenarios).Developers can enable this by setting useSystemColors in ThemeData to true, automatically applying system colors and improving visibility for users with visual impairments.</li><li><strong><em>iOS Voice Control </em></strong>: Improved experience by preventing non-actionable widgets from displaying unnecessary labels, resulting in cleaner and more focused voice interactions.</li></ul><h3>Build with AI: Firebase AI Logic</h3><p>Google introduced Firebase AI Logic, an evolution of the Vertex AI Firebase SDK, which now provides access to both Gemini API providers through a single Flutter SDK.</p><ul><li>This lets developers integrate powerful generative AI models like Gemini and Imagen directly into Flutter apps without needing server-side SDKs.</li><li>The new package <strong><em>firebase_ai</em></strong> replaces <strong><em>firebase_vertexai</em></strong> (which will continue to work for now but is recommended to migrate).</li><li>This opens exciting possibilities for AI-driven features such as chatbots, content generation, and intelligent automation inside Flutter apps.</li></ul><h3>Dart and Flutter Support for the Model Context Protocol (MCP)</h3><p>Support for the Model Context Protocol (MCP) and the recently published<a href="https://pub.dev/packages/dart_mcp"> Dart MCP SDK</a> is actively underway. A new Dart Tooling MCP Server is also in development to expose Dart and Flutter static, runtime, and ecosystem tooling to MCP clients like IDEs.</p><p>This integration will bring significant benefits to Dart and Flutter developers, including:</p><ul><li>More accurate and relevant code generation by leveraging semantic information from the actual Dart and Flutter tools.</li><li>Enabling complex automated tasks such as fixing layout issues, managing dependencies, and resolving runtime errors, thanks to the rich context MCP provides.</li></ul><p>MCP support promises to enhance the overall developer experience by making tooling smarter and more context-aware.</p><h3>Discontinued Package Support</h3><p>As part of ongoing maintenance and modernization, Flutter 3.32 discontinues support for six packages:</p><pre>flutter_markdown<br>ios_platform_images<br>css_colors<br>palette_generator<br>flutter_image<br>flutter_adaptive_scaffold</pre><p>Developers using these packages should plan migrations or alternatives accordingly.</p><h3>Minimum OS Version Updates for iOS and macOS</h3><p>Flutter will soon deprecate support for iOS 12 and macOS 10.14 (Mojave), targeting a minimum of:</p><ul><li><strong>iOS 13</strong></li><li><strong>macOS 10.15 (Catalina)</strong></li></ul><p>Apps built with future Flutter versions will no longer run on older OS versions, so developers should plan to update their deployment targets.</p><h3>Other Important Breaking Changes and Deprecations</h3><ul><li><strong><em>ExpansionTileController </em></strong>is deprecated in favor of the new reusable ExpansibleController in the core widgets library.</li><li><strong><em>SelectionChangedCause.scribble</em></strong> renamed to <strong><em>SelectionChangedCause.stylusHandwriting</em></strong> to unify Apple’s Scribble and Android’s Scribe stylus input terminology.</li><li><strong><em>ThemeData.indicatorColor</em></strong> is deprecated; use <strong><em>TabBarThemeData.indicatorColor</em></strong> instead.</li><li>Component themes (<strong><em>cardTheme, dialogTheme, tabBarTheme</em></strong>) now require migration to their respective *<strong><em>ThemeData</em></strong> classes.</li><li>SpringDescription formula correction: Fixes animation physics for underdamped springs with non-default mass values. Developers may need to adjust spring parameters to maintain previous animation behavior.</li></ul><h3>Accessibility Performance and Features</h3><ul><li><strong><em>Semantics Tree Compilation </em></strong>: Compilation time reduced by ~80%, improving frame rates by 30% on web.</li><li><strong><em>Granular Semantics Roles </em></strong>: The new <strong><em>SemanticsRole </em></strong>API lets developers assign specific accessibility roles to widget subtrees, enhancing screen reader accuracy (currently web-only).</li><li><strong><em>Improved Screen Reader Feedback </em></strong>: More descriptive and context-aware announcements across platforms.</li><li><strong><em>Better Keyboard and Focus Handling </em></strong>: Smoother navigation and interaction for users relying on assistive technologies.</li></ul><h3>Multi-Window and Desktop Improvements</h3><ul><li>Multi-window support is progressing with fixes to accessibility, lifecycle, focus, keyboard, and mouse event handling.</li><li>Windows and macOS now support merging UI and platform threads, enabling deeper native API calls via Dart FFI, which opens doors for advanced desktop integrations.</li></ul><h3>DevTools and Developer Experience</h3><ul><li><strong><em>Flutter Property Edito</em></strong>r : New in VS Code and Android Studio/IntelliJ, this tool simplifies editing widget properties and accessing documentation inline.</li><li><strong><em>Deep Link Validator </em></strong>: Helps identify and fix Android deep link configuration issues.</li><li><strong><em>DevTools Enhancements </em></strong>: Improved offline support, CPU profiling, network inspection, and bug fixes across various panels.</li></ul><h3>Conclusion</h3><p>Flutter 3.32, unveiled at Google I/O 2025, delivers a rich set of features that enhance developer productivity, app performance, and user experience across platforms. From experimental<strong> hot reload on web and the new rounded superellipse support to accessibility improvements, AI integration with Firebase AI Logic, and upcoming MCP tooling support</strong>, this release sets the stage for the future of cross-platform app development.</p><p>If you’re a Flutter developer, now is the perfect time to explore these new capabilities, update your apps, and contribute feedback to help shape Flutter’s future.</p><h3>Reference</h3><p>For the full technical breakdown, code samples, and migration guides, see the official release notes:<br><a href="https://medium.com/flutter/whats-new-in-flutter-3-32-40c1086bab6e">What’s New in Flutter 3.32 (Medium)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b6a94c40aa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to AI Agents — How agents reason, plan, and execute tasks.]]></title>
            <link>https://medium.com/@saminchandeepa/introduction-to-ai-agents-how-agents-reason-plan-and-execute-tasks-8d87c922b384?source=rss-20594cbd238------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d87c922b384</guid>
            <dc:creator><![CDATA[Samin Chandeepa (Adomic)]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 15:47:56 GMT</pubDate>
            <atom:updated>2025-02-26T15:47:56.799Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction to AI Agents — How agents reason, plan, and execute tasks.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cga84F17C8mWldYV-33vZQ.png" /></figure><p>Welcome to my article series on AI Agents where we build and deploy our own Agents. In this first article, I will cover the following key topics:</p><ol><li><em>What is an agent, and how does it work?</em></li><li><em>How do agents make decisions, reason, plan, and execute tasks?</em></li><li><em>The role of Large Language Models (LLMs) in building agents</em></li><li><em>The concepts of Tools, Actions, and Agent Environments</em></li><li><em>An overview of the agent workflow path (which I refer to as TAO)</em></li></ol><h3><strong>What is an Agent?</strong></h3><p>To understand what an agent is and how it functions, let’s break it down with a relatable example. By the end of this section, you’ll have a clear understanding of the concept of agents and their applications in artificial intelligence.</p><p>Imagine you’re conducting research on text-to-image generation models. Your goal is to identify the best model for your project ,one capable of generating the highest-quality images. Let’s first think about how we, as humans, typically approach such a task:</p><ol><li><strong>Define the objective</strong>: You start by clarifying your requirement. In this case, it’s finding the best text-to-image (TTI) model for your needs.</li><li><strong>Gather information</strong>: Next, you search online for “best models for text-to-image generation” and compile a list of potential options.</li><li><strong>Evaluate options</strong>: Suppose you identify four suitable models — <em>M1, M2, M3, and M4</em>. To determine which one is best, you might:</li></ol><p><em>Test each model by providing identical prompts and comparing results. Review benchmarks or performance metrics. Explore other evaluation methods.</em></p><p>4. <strong>Make a decision</strong>: After careful analysis, you select Model <em>M2</em> as the best fit for your project.</p><p>This process illustrates how humans approach problem-solving:<em> setting goals, gathering data, evaluating options, and making decisions</em>.</p><p>Now imagine an AI system that can perform these steps autonomously ,this is essentially what an agent does. An agent is a system designed to perceive its environment, reason about its objectives, plan actions to achieve those objectives, and execute those actions effectively. It mimics human decision-making processes but operates at greater speed and scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*3r0C5dSLXdODeEdjNgtVTA.png" /><figcaption>decision-making processes</figcaption></figure><p>So here is the best explanation to define what is an agent,</p><p><em>An Agent is a system that leverages an AI model to interact with its environment in order to achieve a user-defined objective. It combines reasoning, planning, and the execution of actions (often via external tools) to fulfill tasks.</em></p><p>So now you may have some problems ,</p><p><strong>What type of tasks can an Agent do?</strong></p><p>An Agent can perform any task we implement via Tools to complete Actions.(I will explain more about tools and how we can create our own tools so the agent can use them in an upcoming article).</p><p>For example, if I write an Agent to act as my personal assistant (like Siri) on my computer, and I ask it to “send an email to my Manager asking to delay today’s meeting”, I can give it some code to send emails. This will be a new Tool the Agent can use whenever it needs to send an email.</p><p><strong>How do agents make decisions, reason, plan, and execute tasks?</strong></p><p>In the previous section we looked at what agents are agents and what they can do. In this section we will explore the complete AI Agent workflow, a cycle of the Thought-Action-Observation process . (TAO).</p><h3><strong>The Core Components of AI Agents</strong></h3><p>AI agents operate in a continuous cycle of Thinking (Thought) → Acting (Action) → Observing (Observation). This cyclical process allows agents to adapt, learn, and make progress toward their objectives. Let’s break down each of these components in detail:</p><p><strong>Thought</strong></p><p>This is the decision-making phase. During this step, the agent’s reasoning capability , often powered by a Large Language Model (LLM) , analyzes the current situation and determines the next course of action.</p><p><strong>Action</strong></p><p>Once the agent decides on a course of action, it executes it by interacting with external tools or systems. These tools are invoked with specific arguments or parameters based on the agent’s thought process.</p><p><em>For example, an agent might call a text-to-image generation tool with a prompt or query a database for specific information.</em></p><p><strong>Observation</strong></p><p>After performing an action, the agent gathers feedback or results from the environment or tool it interacted with. This step involves reflecting on the outcome of the action whether it succeeded, failed, or produced unexpected results and using that information to refine its future decisions.</p><p>This continuous cycle of <strong><em>Thought → Action → Observation</em></strong> forms the backbone of how agents function. It allows them to dynamically adapt to changing environments, learn from their interactions, and iteratively move closer to achieving their goals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*k4mk8odhLZHrkMGkAIUDvA.png" /><figcaption><em>Thought → Action → Observation</em></figcaption></figure><h3><strong>The role of Large Language Models (LLMs) in building agents</strong></h3><p>Large Language Models (LLMs) play a pivotal role in the development of AI agents. These models are designed to excel at understanding and generating human-like language, making them ideal for tasks that require reasoning, planning, and interaction. Their ability to process and produce coherent text is derived from training on vast amounts of textual data, which enables them to learn patterns, structures, and even subtle nuances in language.</p><p><strong>Key Characteristics of LLMs</strong></p><ul><li><strong>Training Data</strong>: LLMs are trained on diverse datasets, ranging from books and articles to online conversations, enabling them to generalize across a wide range of topics.</li><li><strong>Scale</strong>: These models typically consist of millions to billions of parameters, which are the building blocks that allow them to represent complex relationships in language.</li><li><strong>Architecture</strong>: Most modern LLMs are built on the <em>Transformer architecture</em>. Transformers rely on the “Attention” mechanism, which enables the model to focus on relevant parts of the input data when generating outputs. This architecture became widely recognized with the release of BERT (Bidirectional Encoder Representations from Transformers) by Google in 2018.</li></ul><p><strong>Types of LLMs</strong></p><p>While LLMs can vary in design, many are decoder-based models optimized for text generation tasks. Some well-known examples include:</p><ul><li><em>OpenAI’s GPT series (e.g., GPT-3.5, GPT-4): These models are highly versatile and capable of performing a wide range of language-related tasks.</em></li><li><em>Google’s Gemini: it’s a family of multimodal AI models designed to process multiple modalities or types of data, including audio, images, software code, text and video.</em></li><li><em>Anthropic’s Claude: Designed with a focus on safety and alignment.</em></li><li><em>Meta’s LLaMA (Large Language Model Meta AI): A family of open-source LLMs optimized for research and development.</em></li></ul><p><strong>How LLMs Contribute to Agents</strong></p><p>LLMs serve as the “brain” of an AI agent by handling several critical functions:</p><ol><li><strong>Reasoning</strong>: They analyze input data, infer context, and determine logical next steps.</li><li><strong>Planning</strong>: Based on their reasoning, they generate structured plans for achieving objectives.</li><li><strong>Communication</strong>: LLMs enable agents to interact naturally with humans or other systems by generating coherent and contextually relevant responses.</li><li><strong>Tool Invocation</strong>: They decide when and how to use external tools or APIs by generating precise instructions or arguments.</li></ol><p>In essence, LLMs provide the cognitive foundation that allows agents to think critically, communicate effectively, and execute tasks efficiently. Their ability to understand context and adapt dynamically makes them indispensable in building intelligent agents capable of solving complex problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*LPeJtDwRfhgU00TG3CxbFw.png" /><figcaption>famous models and their providers</figcaption></figure><h3>The concepts of Tools, Actions, and Agent Environments</h3><p><strong>Tools</strong></p><p>Tools are external resources or systems that an agent uses to perform specific tasks or gather additional information. These tools extend the agent’s capabilities beyond its internal knowledge base, allowing it to interact with the environment effectively.</p><p><strong>Examples</strong>:</p><ul><li><strong>Web Search APIs</strong>: An agent tasked with answering complex questions might use a search engine API to retrieve up-to-date information.</li><li><strong>Text-to-Image Generators</strong>: For creative tasks, an agent can use tools like DALL·E or Stable Diffusion to generate images from text prompts.</li><li><strong>Weather Databases</strong>: A travel-planning agent might query weather databases to recommend the best time for a trip.</li><li><strong>Robotic Actuators</strong>: In physical environments, tools could include robotic arms or sensors for tasks like assembly or navigation.</li></ul><p><strong>Actions</strong></p><p>Actions are the steps an agent takes to achieve its goals. These actions are based on decisions made during the reasoning phase and often involve invoking tools or interacting directly with the environment.</p><p><strong>Examples</strong>:</p><ul><li><strong>Calling APIs</strong>: An agent might call a flight-booking API to reserve tickets after determining the best travel dates.</li><li><strong>Executing Commands</strong>: A home automation agent could turn on lights or adjust a thermostat based on user preferences.</li><li><strong>Data Manipulation</strong>: For analytical tasks, an agent might process datasets using statistical tools or machine learning libraries.</li><li><strong>Physical Movement</strong>: In robotics, actions could involve navigating a space, picking up objects, or assembling components.</li></ul><p><strong>Agent Environments</strong></p><p>The environment is the context in which an agent operates. The environment provides feedback in response to the agent’s actions, which helps the agent refine its behavior over time.</p><p><strong>Examples:</strong></p><ul><li><strong>Virtual Assistants</strong>: Operate in digital environments like smartphones or smart speakers, interacting with users and online services.</li><li><strong>Stock Trading Agents</strong>: Operate in financial markets where they analyze data and execute trades based on market conditions.</li></ul><p><strong>How These Concepts Work Together</strong></p><p>The interaction between tools, actions, and environments forms the foundation of an AI agent’s workflow:</p><ol><li><em>The agent perceives its environment (e.g., identifying obstacles in a room).</em></li><li><em>It decides on an action based on its reasoning process (e.g., moving around an obstacle).</em></li><li><em>It uses tools to execute that action if needed (e.g., querying a mapping API for navigation).</em></li><li><em>The environment provides feedback (e.g., confirming successful navigation), which informs future decisions.</em></li></ol><p><strong>Example Workflow:</strong></p><p>Imagine an AI travel assistant tasked with planning a vacation:</p><ol><li><strong>Environment</strong>: The digital space includes weather databases, flight booking platforms, and user preferences.</li><li><strong>Tools</strong>: The assistant uses APIs for weather forecasts and flight availability.</li><li><strong>Actions</strong>: It queries these tools to gather data, compares options, and recommends an itinerary based on user input.</li></ol><p>By combining tools, actions, and environments effectively, AI agents can tackle complex tasks across diverse domains from automating customer support to managing industrial processes or even controlling autonomous vehicles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjuLRFI9lGGD8sfV9PXTvQ.png" /><figcaption>thinking (Thought) → Acting (Action) → Observing (Observation).</figcaption></figure><h3><strong>Conclusion</strong></h3><p>These are the fundamental concepts you need to understand before programming an agent. There is much more to discuss, but these key topics provide a solid foundation. After completing this article series, you will be able to build and deploy your own AI agents.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d87c922b384" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overcoming the 413: FUNCTION_PAYLOAD_TOO_LARGE Secure Bulk File Uploads Using Pre-signed(S3) URLs]]></title>
            <link>https://medium.com/@saminchandeepa/overcoming-the-413-function-payload-too-large-secure-bulk-file-uploads-using-pre-signed-s3-urls-59021570c210?source=rss-20594cbd238------2</link>
            <guid isPermaLink="false">https://medium.com/p/59021570c210</guid>
            <dc:creator><![CDATA[Samin Chandeepa (Adomic)]]></dc:creator>
            <pubDate>Thu, 09 Jan 2025 17:56:03 GMT</pubDate>
            <atom:updated>2025-01-09T18:22:41.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcvCl6425fEqWGWRyqOwow.png" /></figure><p>Handling large file uploads in a serverless setup can be tricky, especially when you hit payload size limits. This article outlines my experience resolving the 413 FUNCTION_PAYLOAD_TOO_LARGE error while building a bulk file uploading feature with a Next.js serverless backend. It also explains pre-signed URLs and their role in securely addressing these challenges. By diving deeper into these challenges and exploring their solutions, I aim to provide a comprehensive guide for developers facing similar issues.</p><h3>The Problem: 413 FUNCTION_PAYLOAD_TOO_LARGE</h3><p>When uploading files via a serverless API route in Next.js, I encountered the following error:</p><pre>FUNCTION_PAYLOAD_TOO_LARGE<br>Payload Too Large</pre><p>This issue arises when the size of the data sent to the server exceeds the platform’s limits. On Vercel, serverless functions have a payload size cap of <strong>4.5MB</strong>. This makes direct large file uploads to serverless endpoints infeasible and requires developers to rethink their approach to file handling.</p><h3>Common Causes of the Error</h3><ul><li>Uploading large files directly via serverless APIs.</li><li>Overlooking platform-specific size limitations.</li><li>Failing to validate file sizes before upload.</li><li>Attempting to process files on the server instead of offloading tasks to storage solutions.</li></ul><p>Such challenges are common in applications dealing with media uploads, and addressing them effectively requires understanding the underlying constraints of serverless platforms.</p><h3>Strategies to Address the Problem</h3><p>Here are some effective ways to handle large file uploads and mitigate this issue:</p><h4>1. Review Payload Size</h4><p>Verify the size of your uploads to ensure they stay within the platform’s limits (4.5MB on Vercel). For smaller files, this check might suffice, but it’s not a scalable solution for handling larger datasets or multimedia files.</p><h4>2. Reduce Payload Size</h4><p>Optimize file sizes by compressing or resizing data before uploading. For instance, image files can be processed using tools like <strong>Sharp</strong>, which significantly reduces file size without compromising quality. For videos, transcoding them into more efficient formats like H.265 can help.</p><h4>3. Split into Smaller Requests</h4><p>Break large files into smaller chunks and upload them in parts. This approach requires managing the reassembly of the file on either the client or server side. Libraries like <strong>Tus</strong> or <strong>Resumable.js</strong> can facilitate chunk-based uploads.</p><h4>4. Client-side Direct Uploads</h4><p>Avoid server limitations entirely by uploading files directly from the client to a storage service such as <strong>AWS S3</strong>, using pre-signed URLs for secure transfer. This bypasses the server’s payload constraints and ensures efficient handling of large files.</p><h4>5. Use External Storage</h4><p>Offload file handling to dedicated cloud storage solutions like <strong>AWS S3</strong>, <strong>Google Cloud Storage</strong>, or <strong>Azure Blob Storage</strong>. These services are optimized for file storage and retrieval, offering features like CDN integration and lifecycle management.</p><h4>6. Adopt Progressive Enhancement</h4><p>Combine these strategies as needed. For example, small files can use direct server uploads, while larger ones are handled via pre-signed URLs or chunked uploads.</p><h3>My Solution: Client-side Uploads with Pre-signed URLs</h3><p>After evaluating these options, I chose <strong>client-side uploads to AWS S3 using pre-signed URLs</strong>. This method proved secure, efficient, and scalable for handling bulk uploads. It not only resolved the 413 FUNCTION_PAYLOAD_TOO_LARGE error but also streamlined the process for future scalability.</p><h3>Understanding Pre-signed URLs</h3><p>A <strong>pre-signed URL</strong> is a temporary, secure link generated by a server that allows users to upload or download files directly to or from a storage service like AWS S3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dIl0fDEWZwjoAKfE.png" /><figcaption>source:AWS TIPS</figcaption></figure><h3>How Pre-signed URLs Work:</h3><ol><li><strong>Server Generates the URL</strong>: A server-side function creates the URL using AWS SDK. This URL includes permissions, expiration time, and file-specific metadata.</li><li><strong>Client Uploads the File</strong>: The client uploads the file directly to the storage service using the URL, avoiding server bottlenecks.</li><li><strong>Controlled Access</strong>: The URL becomes invalid once it expires, preventing unauthorized use or abuse.</li></ol><h3>Key Advantages:</h3><ul><li><strong>Avoid Server Payload Limits</strong>: Files are uploaded directly to storage without involving the server, bypassing payload size constraints.</li><li><strong>Improved Performance</strong>: Offloads resource-heavy processes from serverless backends, ensuring a smoother user experience.</li><li><strong>Enhanced Security</strong>: Pre-signed URLs are time-limited and permission-specific, ensuring secure transfers with minimal exposure.</li><li><strong>Scalability</strong>: This approach is ideal for applications expecting high-volume uploads, such as social media platforms or content management systems.</li></ul><h3>Implementation: File Uploads with Pre-signed URLs</h3><h4>Step 1: Setting Up the API Route</h4><p>I implemented a serverless API route in Next.js to generate pre-signed URLs. Here’s the code:</p><pre>import { NextResponse } from &quot;next/server&quot;;<br>import S3 from &quot;aws-sdk/clients/s3&quot;;<br>import { randomUUID } from &quot;crypto&quot;;<br><br>export async function POST(req: Request) {<br>  const { filetype } = await req.json();<br>  const extension = filetype.split(&quot;/&quot;)[1];<br>  const filename = `${randomUUID()}.${extension}`;<br><br>  const s3 = new S3({<br>    apiVersion: &quot;2006-03-01&quot;,<br>    accessKeyId: process.env.ACCESS_KEY,<br>    secretAccessKey: process.env.SECRET_KEY,<br>    region: process.env.REGION,<br>    signatureVersion: &quot;v4&quot;,<br>  });<br><br>  const bucketName = process.env.S3_BUCKET_NAME;<br>  if (!bucketName) {<br>    console.error(&quot;Bucket name is missing in environment variables.&quot;);<br>    return NextResponse.json(<br>      { error: &quot;Missing bucket name in environment variables&quot; },<br>      { status: 500 }<br>    );<br>  }<br><br>  const s3Params = {<br>    Bucket: bucketName,<br>    Key: filename,<br>    Expires: 300, // 5 minutes<br>    ContentType: `image/${extension}`,<br>  };<br><br>  try {<br>    const uploadUrl = await s3.getSignedUrlPromise(&quot;putObject&quot;, s3Params);<br>    return NextResponse.json({ uploadUrl, key: filename });<br>  } catch (error) {<br>    console.error(&quot;Error generating pre-signed URL:&quot;, error);<br>    return NextResponse.json({ error: &quot;Failed to generate pre-signed URL&quot; }, { status: 500 });<br>  }<br>}q: Request) {<br>  const { filetype } = await req.json();<br>  const extension = filetype.split(&quot;/&quot;)[1];<br>  const filename = `${randomUUID()}.${extension}`;<br><br>  const bucketName = process.env.S3_BUCKET_NAME;<br>  if (!bucketName) {<br>    console.error(&quot;Bucket name is missing in environment variables.&quot;);<br>    return NextResponse.json(<br>      { error: &quot;Missing bucket name in environment variables&quot; },<br>      { status: 500 }<br>    );<br>  }<br><br>  const s3Params = {<br>    Bucket: bucketName,<br>    Key: filename,<br>    Expires: 300, // 5 minutes<br>    ContentType: `image/${extension}`,<br>  };<br><br>  try {<br>    const uploadUrl = await s3.getSignedUrlPromise(&quot;putObject&quot;, s3Params);<br>    return NextResponse.json({ uploadUrl, key: filename });<br>  } catch (error) {<br>    console.error(&quot;Error generating pre-signed URL:&quot;, error);<br>    return NextResponse.json({ error: &quot;Failed to generate pre-signed URL&quot; }, { status: 500 });<br>  }<br>}</pre><p>This route ensures that each upload request generates a unique, secure URL, making the system robust and flexible.</p><h4>Step 2: Uploading Files from the Client</h4><p>The client-side code fetches the pre-signed URL and uploads the file to AWS S3:</p><pre>export const UploadImage = async (formData: FormData): Promise&lt;string | null&gt; =&gt; {<br>  try {<br>    const file = formData.get(&quot;file&quot;);<br>    if (!file || !(file instanceof Blob)) {<br>      throw new Error(&quot;No file provided&quot;);<br>    }<br><br>    const filetype = file.type;<br>    const response = await fetch(&quot;/api/s3/upload&quot;, {<br>      method: &quot;POST&quot;,<br>      body: JSON.stringify({ filetype }),<br>      headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    });<br><br>    if (!response.ok) {<br>      throw new Error(&quot;Failed to get presigned URL&quot;);<br>    }<br><br>    const { uploadUrl } = await response.json();<br>    const uploadResponse = await fetch(uploadUrl, {<br>      method: &quot;PUT&quot;,<br>      body: file,<br>    });<br><br>    if (!uploadResponse.ok) {<br>      throw new Error(&quot;File upload failed&quot;);<br>    }<br><br>    return uploadUrl.split(&quot;?&quot;)[0];<br>  } catch (error) {<br>    console.error(&quot;Error uploading image:&quot;, error);<br>    return null;<br>  }<br>};</pre><p>This setup ensures that files are uploaded efficiently, with minimal latency or failure points.</p><h3>Security Best Practices</h3><ol><li><strong>Restrict Bucket Permissions</strong>: Use bucket policies to allow only necessary actions (e.g., s3:PutObject) for pre-signed URLs.</li><li><strong>Limit URL Expiry</strong>: Set a short expiration time (e.g., 5 minutes) to minimize the risk of misuse.</li><li><strong>Validate File Types</strong>: Ensure both the client and server validate file types to prevent unauthorized uploads or malicious files.</li><li><strong>Secure Environment Variables</strong>: Store AWS keys and other sensitive data securely in environment variables.</li><li><strong>Monitor Upload Activity</strong>: Regularly audit your storage logs to detect any unusual activity or unauthorized access attempts.</li></ol><h3>Conclusion</h3><p>Using pre-signed URLs for client-side uploads solved the 413 FUNCTION_PAYLOAD_TOO_LARGE issue effectively. This approach is scalable, secure, and aligns well with modern serverless architecture. By leveraging AWS S3’s capabilities, I ensured a seamless and secure bulk upload experience. Additionally, implementing security measures ensures the integrity and reliability of the system over time.</p><p>Have you encountered similar challenges with file uploads in serverless environments? Share your experiences and solutions in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59021570c210" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Animation: What are explicit and implicit animation?]]></title>
            <link>https://medium.com/@saminchandeepa/flutter-animation-what-are-explicit-and-implicit-animation-31868f602fc6?source=rss-20594cbd238------2</link>
            <guid isPermaLink="false">https://medium.com/p/31868f602fc6</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-animation]]></category>
            <category><![CDATA[animate-flutter-apps]]></category>
            <dc:creator><![CDATA[Samin Chandeepa (Adomic)]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 06:46:04 GMT</pubDate>
            <atom:updated>2024-10-27T10:01:18.431Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter Animations: What are explicit and implicit animation?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TACljjp4ZcZm7EGxo_cyfw.jpeg" /><figcaption>image credits: <a href="https://www.dhiwise.com/">https://www.dhiwise.com</a></figcaption></figure><p>Animations play a crucial role in mobile app development by enhancing user engagement, providing feedback, and improving the overall visual appeal and usability of the application. With Flutter’s powerful animation capabilities, developers can create rich, interactive experiences that delight users and improve retention.Animations play a pivotal role in creating engaging and interactive mobile applications. In Flutter, Google’s powerful UI toolkit, animations can be categorized into two main types: explicit and implicit.</p><h3>Types of Animations in Flutter</h3><ol><li><strong>Implicit Animations:</strong> These are pre-programmed animations where you don’t need to write the animation code yourself. Instead, you only need to change some properties or values.Examples include AnimatedContainer and AnimatedOpacity.</li><li><strong>Explicit Animations:</strong> These involve building customized animations using widgets like AnimatedBuilder. They allow you to customize various properties and animation elements.</li></ol><h3>What are Implicit Animations?</h3><p>Implicit animations in Flutter are easy-to-use, high-level animations that automatically transition a widget from one state to another. These animations are ideal for simple, single-property changes and require minimal code. Flutter’s implicit animations handle the interpolation and timing, making them perfect for developers looking to add basic animations without delving into complex details.</p><h3><strong>Examples of Implicit Animations:</strong></h3><ul><li>AnimatedContainer</li><li>AnimatedOpacity</li><li>AnimatedPositioned</li><li>AnimatedAlign</li></ul><h3>AnimatedContainer class</h3><p>he <a href="https://api.flutter.dev/flutter/widgets/AnimatedContainer-class.html">AnimatedContainer</a> will automatically animate between the old and new values of properties when they change using the provided curve and duration. Properties that are null are not animated. Its child and descendants are not animated.</p><pre>AnimatedContainer(<br>        width: _isExpanded ? 200.0 : 100.0,<br>        height: _isExpanded ? 200.0 : 100.0,<br>        color: _isExpanded ? Colors.yellow : Colors.redAccent,<br>        alignment:<br>            _isExpanded ? Alignment.center : AlignmentDirectional.topCenter,<br>        duration: const Duration(seconds: 1),<br>        curve: Curves.easeInOut,<br>        child: const Center(child: Text(&quot;Flutter&quot;)),<br>      ),</pre><h3>AnimatedList class</h3><p>This widget’s <a href="https://api.flutter.dev/flutter/widgets/AnimatedListState-class.html">AnimatedListState</a> can be used to dynamically insert or remove items. To refer to the <a href="https://api.flutter.dev/flutter/widgets/AnimatedListState-class.html">AnimatedListState</a> either provide a <a href="https://api.flutter.dev/flutter/widgets/GlobalKey-class.html">GlobalKey</a> or use the static <a href="https://api.flutter.dev/flutter/widgets/AnimatedList/of.html">of</a> method from an item’s input callback.</p><pre>AnimatedList(<br>            key: _listKey,<br>            initialItemCount: _items.length,<br>            itemBuilder: (context, index, animation) {<br>              return _buildItem(_items[index], animation);<br>            },</pre><h3>AnimatedOpacity class</h3><p>Animated version of <a href="https://api.flutter.dev/flutter/widgets/Opacity-class.html">Opacity</a> which automatically transitions the child’s opacity over a given duration whenever the given opacity changes.</p><pre>AnimatedOpacity(<br>          opacity: _opacity,<br>          duration: Duration(seconds: 1),<br>          child: Container(<br>            width: 100,<br>            height: 100,<br>            color: Colors.blue,<br>          ),<br>        ),</pre><h3>AnimatedPositioned class</h3><p>Animated version of <a href="https://api.flutter.dev/flutter/widgets/Positioned-class.html">Positioned</a> which automatically transitions the child’s position over a given duration whenever the given position changes.</p><pre>AnimatedPositioned(<br>            width: selected ? 200.0 : 50.0,<br>            height: selected ? 50.0 : 200.0,<br>            top: selected ? 50.0 : 150.0,<br>            duration: const Duration(milliseconds: 700),<br>            curve: Curves.fastOutSlowIn,<br>            child: GestureDetector(<br>              onTap: () {<br>                setState(() {<br>                  selected = !selected;<br>                });<br>              },<br>              child: const ColoredBox(<br>                color: Colors.blue,<br>                child: Center(child: Text(&#39;Tap me&#39;)),<br>              ),<br>            ),<br>          ),<br>        ],<br>      ),</pre><h3><strong>Custom Implicit Animation</strong></h3><p>When built-in implicit animations don’t meet your needs, you can use <strong>TweenAnimationBuilder</strong> to create custom implicit animations</p><h3>What is a Tween in Flutter?</h3><p>A <strong>Tween</strong> in Flutter stands for “in-between” and is used to define the interpolation between a start and an end value over a specified duration. It provides a range of values that an animation can travel through during its execution, <strong><em>such as moving from 0 to 1, a color from red to blue, or a size from small to large</em></strong>.</p><pre>TweenAnimationBuilder(<br>              tween: Tween&lt;double&gt;(begin: 0, end: 300),<br>              duration: const Duration(milliseconds: 500),<br>              builder: (BuildContext context, double value, Widget? child) {<br>                return Container(<br>                  width: value,<br>                  height: value,<br>                  color: Colors.yellow,<br>                );<br>              },<br>            ),</pre><h3>What are Explicit Animations?</h3><p>Explicit animations offer more control and flexibility compared to implicit animations. They are used for more complex animations involving multiple properties or custom timing. Explicit animations require developers to define the animation’s behavior, including the animation controller, animation curves, and the transition itself.</p><p><strong>Examples of Explicit Animations</strong></p><ul><li>AnimationController :This is the heart of an animation, controlling its duration and progress. It generates values from 0.0 to 1.0 over a specified time, which can be used to animate properties of widgets</li><li>Tween</li><li>CurvedAnimation:This adds an easing curve to the animation, making the changes feel more natural (e.g., easing in and out). It transforms the linear progression of the AnimationController into a non-linear curve.</li><li>AnimatedBuilder:A widget that helps rebuild its child every time the animation changes, making it easier to use animations in the widget tree without explicitly managing state changes.</li></ul><p>Lets create this animation,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3CzjpVP-q6_5-wAzs9Zm_A.png" /></figure><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class HomePageAnimation extends StatefulWidget {<br>  const HomePageAnimation({super.key});<br><br>  @override<br>  State&lt;HomePageAnimation&gt; createState() =&gt; _HomePageAnimationState();<br>}<br><br>class _HomePageAnimationState extends State&lt;HomePageAnimation&gt;<br>    with SingleTickerProviderStateMixin {<br>  late AnimationController controller;<br>  late Animation&lt;double&gt; logoFadeAnimation;<br>  late Animation&lt;Offset&gt; slideAnimation;<br>  late Animation&lt;double&gt; scaleAnimation;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    controller = AnimationController(<br>      vsync: this,<br>      duration: const Duration(milliseconds: 1500),<br>    );<br><br>    logoFadeAnimation = Tween&lt;double&gt;(begin: 0, end: 1).animate(controller);<br><br>    slideAnimation = Tween(<br>      begin: const Offset(-1, -1),<br>      end: Offset.zero,<br>    ).animate(<br>      CurvedAnimation(<br>        parent: controller,<br>        curve: Curves.fastOutSlowIn,<br>      ),<br>    );<br><br>    scaleAnimation = Tween&lt;double&gt;(begin: 0, end: 1).animate(controller);<br><br>    controller.forward();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            FadeTransition(<br>              opacity: logoFadeAnimation,<br>              child: const FlutterLogo(<br>                size: 100.0,<br>              ),<br>            ),<br>            const SizedBox(height: 20.0),<br>            Padding(<br>              padding: const EdgeInsets.symmetric(horizontal: 16.0),<br>              child: SlideTransition(<br>                position: slideAnimation,<br>                child: ScaleTransition(<br>                  scale: scaleAnimation,<br>                  child: const Text(<br>                    &#39;Welcome to Flutter Devs and Flutter Animations as very important part of Flutter Development and Flutter Devs is the best place to learn Flutter Development&#39;,<br>                    textAlign: TextAlign.center,<br>                    style: TextStyle(fontSize: 20.0),<br>                  ),<br>                ),<br>              ),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Explanation of the Code in 5 Steps</h3><p>1.<strong> Initialize State and Controller:</strong> <em>The `HomePageAnimation` widget uses a `StatefulWidget` and an `AnimationController` to manage the animation timing with a duration of 1.5 seconds</em>.<br> <br>2. <strong>Define Animations</strong>:<em> Three animations are set up: `logoFadeAnimation` for fading the logo’s opacity, `slideAnimation` for moving the text from the top-left to its final position, and `scaleAnimation` for scaling the text from no size to full size.</em></p><p>3. <strong>Start Animation:</strong> <em>The `controller.forward()` method starts the animations, causing the defined animations to transition over the specified duration.</em></p><p>4. <strong>Build Widget Tree</strong>: <em>The `build` method constructs a widget tree with a `Scaffold`, `Center`, and `Column` to center and stack the `FlutterLogo` and the text widget vertically.</em></p><p>5. <strong>Apply Animations</strong>: <em>`FadeTransition` animates the logo’s opacity, `SlideTransition` animates the text’s position, and `ScaleTransition` animates the text’s size, creating a smooth and visually appealing entrance effect for both the logo and text.</em></p><h3>Grid Animations and Page Transitions</h3><p>Main Grid page(Home Page) from here we can select a one grid item and then this will animate to the selected item.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;item_details_page.dart&#39;;<br><br>class GridHomePage extends StatelessWidget {<br>  final List&lt;String&gt; items = List&lt;String&gt;.generate(20, (i) =&gt; &#39;Item $i&#39;);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Grid Home Page&#39;),<br>      ),<br>      body: GridView.builder(<br>        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(<br>          crossAxisCount: 2,<br>        ),<br>        itemCount: items.length,<br>        itemBuilder: (context, index) {<br>          return GestureDetector(<br>            onTap: () {<br>              Navigator.push(<br>                context,<br>                PageRouteBuilder(<br>                  pageBuilder: (context, animation, secondaryAnimation) {<br>                    return ItemDetailsPage(item: items[index], index: index);<br>                  },<br>                  transitionsBuilder:<br>                      (context, animation, secondaryAnimation, child) {<br>                    return FadeTransition(<br>                      opacity: animation,<br>                      child: child,<br>                    );<br>                  },<br>                  transitionDuration: const Duration(seconds: 1),<br>                ),<br>              );<br>            },<br>            child: Hero(<br>              tag: &#39;item_$index&#39;,<br>              flightShuttleBuilder: _flightShuttleBuilder,<br>              child: Card(<br>                child: GridTile(<br>                  child: Container(<br>                    decoration: BoxDecoration(<br>                      color: Colors.yellow,<br>                      borderRadius: BorderRadius.circular(10),<br>                    ),<br>                    child: Center(<br>                      child: Text(<br>                        items[index],<br>                        style:<br>                            const TextStyle(color: Colors.black, fontSize: 18),<br>                      ),<br>                    ),<br>                  ),<br>                ),<br>              ),<br>            ),<br>          );<br>        },<br>      ),<br>    );<br>  }<br><br><br>  Widget _flightShuttleBuilder(<br>    BuildContext flightContext,<br>    Animation&lt;double&gt; animation,<br>    HeroFlightDirection flightDirection,<br>    BuildContext fromHeroContext,<br>    BuildContext toHeroContext,<br>  ) {<br>    return AnimatedBuilder(<br>      animation: animation,<br>      builder: (context, child) {<br>        double rotationValue = flightDirection == HeroFlightDirection.push<br>            ? animation.value * 3.14<br>            : (1 - animation.value) * 3.14;<br>        return Transform(<br>          alignment: Alignment.center,<br>          transform: Matrix4.identity()..rotateY(rotationValue),<br>          child: toHeroContext.widget,<br>        );<br>      },<br>    );<br>  }<br>}</pre><p>Here this will create the animation to look like the selected item is rotating around the y-axis.</p><pre>Widget _flightShuttleBuilder(<br>    BuildContext flightContext,<br>    Animation&lt;double&gt; animation,<br>    HeroFlightDirection flightDirection,<br>    BuildContext fromHeroContext,<br>    BuildContext toHeroContext,<br>  ) {<br>    return AnimatedBuilder(<br>      animation: animation,<br>      builder: (context, child) {<br>        double rotationValue = flightDirection == HeroFlightDirection.push<br>            ? animation.value * 3.14<br>            : (1 - animation.value) * 3.14;<br>        return Transform(<br>          alignment: Alignment.center,<br>          transform: Matrix4.identity()..rotateY(rotationValue),<br>          child: toHeroContext.widget,<br>        );<br>      },<br>    );<br>  }<br>}</pre><p>This is the code for the single item page and this will use the same animation to animate back to the main homepage,</p><pre>// item_details_page.dart<br><br>import &#39;package:flutter/material.dart&#39;;<br><br>class ItemDetailsPage extends StatelessWidget {<br>  final String item;<br>  final int index;<br><br>  ItemDetailsPage({required this.item, required this.index});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(item),<br>      ),<br>      body: Center(<br>        child: Hero(<br>          tag: &#39;item_$index&#39;,<br>          flightShuttleBuilder: _flightShuttleBuilder,<br>          child: Card(<br>            elevation: 4.0,<br>            child: Container(<br>              width: 300,<br>              height: 300,<br>              decoration: BoxDecoration(<br>                color: Colors.yellow,<br>                borderRadius: BorderRadius.circular(10),<br>              ),<br>              child: Center(<br>                child: Text(<br>                  item,<br>                  style: const TextStyle(color: Colors.black, fontSize: 18),<br>                ),<br>              ),<br>            ),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br><br>  Widget _flightShuttleBuilder(<br>    BuildContext flightContext,<br>    Animation&lt;double&gt; animation,<br>    HeroFlightDirection flightDirection,<br>    BuildContext fromHeroContext,<br>    BuildContext toHeroContext,<br>  ) {<br>    return AnimatedBuilder(<br>      animation: animation,<br>      builder: (context, child) {<br>        double rotationValue = flightDirection == HeroFlightDirection.push<br>            ? animation.value * 3.14<br>            : (1 - animation.value) * 3.14;<br>        return Transform(<br>          alignment: Alignment.center,<br>          transform: Matrix4.identity()..rotateY(rotationValue),<br>          child: toHeroContext.widget,<br>        );<br>      },<br>    );<br>  }<br>}</pre><h3>Conclusion</h3><p>Animations not only make your app look better but also help convey the app’s functionality and improve the overall user experience. Experiment with different types of animations to see how they can transform your app’s interface and user interactions.</p><p>For the complete code and more examples, you can check out the project on GitHub:</p><p>🔗<a href="https://github.com/HGSChandeepa/Flutter-Animations">View the Code on GitHub</a></p><p>Feel free to clone the repository, explore the code, and modify it to create your own stunning animations in Flutter!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31868f602fc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>