<?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 Giacomo Carfì on Medium]]></title>
        <description><![CDATA[Stories by Giacomo Carfì on Medium]]></description>
        <link>https://medium.com/@giacomo__95?source=rss-dd74b6a2cd57------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*k9oXYSTem1zVwJym-MhpUg.jpeg</url>
            <title>Stories by Giacomo Carfì on Medium</title>
            <link>https://medium.com/@giacomo__95?source=rss-dd74b6a2cd57------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:59:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@giacomo__95/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[Teaching Reinforcement Learning Agents to Reuse Skills Like Humans]]></title>
            <link>https://medium.com/@giacomo__95/teaching-reinforcement-learning-agents-to-reuse-skills-like-humans-7e508d06da29?source=rss-dd74b6a2cd57------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e508d06da29</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Giacomo Carfì]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 19:54:15 GMT</pubDate>
            <atom:updated>2026-01-15T19:54:15.040Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwQc9tIlGUsAsIiVk2pNEA.png" /><figcaption>Weight-Sharing attention module. Each Skill embedding is concatenated with contect embedding and passed through an MLP layer to obtain a weight. Final representation R is computed by a weighted summation.</figcaption></figure><h3>Introduction</h3><p>Reinforcement Learning (RL) has achieved remarkable results in recent years, from mastering Atari games to controlling complex robotic systems. At its core, reinforcement learning studies how an agent can learn to make decisions by interacting with an environment, receiving feedback in the form of rewards, and improving its behavior over time.</p><p>Despite these successes, modern reinforcement learning agents often learn <strong>everything from scratch</strong>. When faced with a new task, they typically discard previous knowledge and re-learn both how to perceive the environment and how to act within it. This stands in sharp contrast to how humans learn.</p><p>Humans do not relearn perception or basic skills every time they encounter a new task. We can read, write, recognize objects, and understand motion — and we <strong>reuse these skills</strong> across a wide range of contexts. This ability to compose and reuse previously acquired skills is a key ingredient of human intelligence.</p><p>This observation motivates the central question of this work:</p><blockquote><strong><em>Can we design reinforcement learning agents that reuse previously learned skills, instead of learning everything end-to-end from scratch?</em></strong></blockquote><p>A standard reinforcement learning algorithm can be conceptually divided into two main components:</p><ol><li><strong>State Representation Learning</strong></li><li><strong>Policy Learning</strong></li></ol><p>The agent interacts with an environment by observing raw inputs — for example, pixels from a video game screen. These raw observations are often high-dimensional, noisy, and difficult to use directly for decision-making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q90sSUi3iekK4kFeyntqfA.png" /></figure><h4>State Representation Learning</h4><p>The role of <em>state representation learning</em> is to transform raw observations into a compact, meaningful internal representation of the environment. This representation, often called a <strong>latent state</strong> or <strong>hidden state</strong>, aims to capture the relevant information needed to make good decisions.</p><p>In many modern RL approaches, this representation is learned jointly with the policy in an end-to-end fashion. While effective, this tightly coupled training has a major drawback: <strong>the learned representations are highly task-specific and difficult to reuse.</strong></p><h4>Policy Learning</h4><p>Once a state representation is available, the <em>policy learning</em> component maps this internal representation to actions. The policy answers the question:</p><blockquote>“Given my current understanding of the environment, what action should I take next?”</blockquote><p>Policy learning is typically the focus of reinforcement learning research. However, its success strongly depends on the quality of the underlying state representation</p><h4>The Core Idea: Reusing Skills for State Representation</h4><p>In this work, we focus on <strong>improving the state representation learning component</strong> of reinforcement learning agents.</p><p>Instead of learning a single monolithic representation from scratch, we propose to <strong>compose and reuse multiple pretrained models</strong>, each encoding a different <em>skill</em>. These models are:</p><ul><li><strong>Pretrained</strong></li><li><strong>Frozen during reinforcement learning</strong></li><li><strong>Specialized in different perceptual abilities</strong></li></ul><p>Inspired by human perception, we treat each pretrained model as a <em>skill</em> that provides a different view of the same observation.</p><p>Having multiple embeddings raises a crucial question:</p><blockquote><strong><em>How should we combine these different representations into a single unified state?</em></strong></blockquote><p>To address this, we introduce an attention-based mechanism called <strong>Weight-Sharing Attention</strong>. This module learns how to dynamically combine the outputs of different skills, producing a single hidden state that is then fed to the policy.</p><p>This article is based on my <strong>Master’s thesis</strong>, which later resulted in a <strong>published research paper</strong>:</p><p>📄 <strong>Paper link:</strong> <a href="https://arxiv.org/abs/2507.07197">Combining Pre-Trained Models for Enhanced Feature Representation in Reinforcement Learning</a></p><p>For clarity and accessibility, this article <strong>covers only a subset of the full paper</strong>. In particular, I will focus on:</p><ul><li>The intuition behind skill-based state representation learning</li><li>How Weight-Sharing Attention works at a conceptual level</li><li>A practical, hands-on implementation of the attention module</li></ul><p>I will <strong>not</strong> cover all experimental details or theoretical analyses present in the paper. For those, I strongly encourage reading the full publication.</p><p>At <a href="https://github.com/Sopralapanca/medium-skill-based-agents">this</a> link, you will find the repository that you can clone with all the necessary code.</p><h3>Like this article? :)</h3><p>Wait, I know I’m boring you with the usual sponsor ads, but this is <strong>not a sponsor</strong> — it’s just a reminder to support people for their work and for providing you good content for free!</p><p>If you liked this article and want to help me write even better content, don’t forget to <strong>follow me</strong> and contribute a tip by clicking the link or buttons below :) Thank you very much!</p><p>To run these experiments, I used <strong>RunPod</strong> — sign up with my <a href="https://runpod.io/?ref=hqoci4az">link</a> to get <strong>$5 one-time credit</strong> and <strong>$10 on your first top-up</strong>. It’s an easy way to try these experiments yourself without needing a local GPU!</p><h3>Weight-Sharing Attention for Skill-Based State Representation</h3><p>In this section, I explain how we combine multiple pretrained skills into a single state representation using <strong>Weight-Sharing Attention</strong>. I first describe the data collection and skill pretraining setup, then introduce the attention mechanism in detail.</p><h4>Data Collection and Environments</h4><p>We consider three Atari environments:</p><ul><li><strong>PongNoFrameskip-v4</strong></li><li><strong>BreakoutNoFrameskip-v4</strong></li><li><strong>MsPacmanNoFrameskip-v4</strong></li></ul><p>To pretrain the skills, we collect trajectories using:</p><ul><li>a <strong>random agent</strong>, and</li><li>a <strong>pretrained PPO agent</strong></li></ul><p>This choice allows us to capture both exploratory and more structured behaviors, leading to a diverse dataset of observations. The collected frames are then used <strong>offline</strong> to pretrain the skill models in an unsupervised manner.</p><h4>Pretrained Skills</h4><p>We implement and pretrain four different skills, each providing a complementary view of the environment:</p><ol><li>Unsupervised State Representation Learning — Based on:<br> 📄 <a href="https://arxiv.org/pdf/1906.08226"><em>Unsupervised State Representation Learning in Atari</em></a></li><li>Unsupervised Video Object Segmentation — Based on: 📄 <a href="https://arxiv.org/pdf/1805.07780"><em>Learning Object Segmentation from Motion</em></a></li><li>Unsupervised Video Keypoint Detection — Based on: 📄 <a href="https://proceedings.neurips.cc/paper_files/paper/2019/file/dae3312c4c6c7000a37ecfb7b0aeb0e4-Paper.pdf"><em>Unsupervised Learning of Object Keypoints for Perception and Control</em></a></li><li>Autoencoder with NatureCNN — we train a standard convolutional autoencoder using the <strong>NatureCNN</strong> architecture (commonly used in Atari RL).</li></ol><p>After pretraining, <strong>all skill models are frozen</strong>. During reinforcement learning:</p><ul><li>No gradients flow into the skill encoders</li><li>Only the attention mechanism and the policy are trained</li></ul><p>We use <strong>Proximal Policy Optimization (PPO)</strong> as the reinforcement learning algorithm where policy and value networks remain unchanged</p><p>The observation encoder is replaced with the proposed skill-based representation module. At time step <strong><em>t</em></strong>, the agent receives as observation the <strong>last 4 stacked frames</strong> of the game. This observation is fed to all frozen skill encoders. Given an observation <strong><em>O, </em></strong>each pretrained skill processes the same input and each skill produces a different embedding.</p><p>In total, we obtain <strong>four embeddings</strong>: one from the state representation model, one from video object segmentation, two from the keypoint model (KeyNet + encoder).</p><p>These embeddings represent <strong>different perspectives of the same world</strong> — motion, objects, structure, and dynamics. The challenge is now to <strong>combine them effectively.</strong></p><h3>Weight-Sharing Attention: Core Idea</h3><p>The key idea is simple:</p><blockquote><em>Each skill should contribute </em><strong><em>dynamically</em></strong><em>, depending on the current context.</em></blockquote><p>We first compute a <strong>context embedding</strong> using the autoencoder: the observation <strong><em>O</em></strong> is passed through the autoencoder encoder and the resulting representation captures a global view of the current state. This context embedding acts as a <em>query</em> that helps decide which skills are more relevant at the current time step.</p><p>To compute the attention weights, for each skill embedding <strong><em>Ei</em></strong>​, we compute a scalar weight <strong><em>Wi</em></strong>​ using a shared MLP. The input is the concatenation of the context embedding <strong><em>C </em></strong>and the skill embedding <strong><em>Ei</em></strong>​. The output is a single scalar score. Crucially, <strong>the same MLP is used for all skills</strong>. This is why the mechanism is called <strong>Weight-Sharing Attention</strong>: the MLP parameters are shared across skills.</p><p>Once all weights are computed, the final hidden state representation is computed as a <strong>weighted sum</strong> of the skill embeddings. This representation is then passed to the <strong>policy and value networks</strong> of PPO.</p><h3>Implementation</h3><p>In this section, we set up the project, generate the dataset, pretrain the skills and train RL agents with the Weight-Sharing Attention module. All experiments are designed to run smoothly on <strong>Google Colab</strong>.</p><h4>Repository Setup, Dependencies, Dataset Creation and Skills Pretraining</h4><p>We start by cloning the repository containing all the code used in this work:</p><pre>git clone https://github.com/Sopralapanca/medium-skill-based-agents.git<br>cd medium-skill-based-agents</pre><p>All dependencies are specified in the pyproject.toml file. We use uv for fast and reliable package installation:</p><pre>uv pip install -r pyproject.toml</pre><p>We are using StableBaselines3 as main python library to run our experiments.</p><p>Before training the skills, we need a dataset of Atari frames. To simplify the work for this article, we generate the dataset by running only a <strong>pretrained PPO agent, </strong>while in the paper a random agent was also used. In total we collect 60.000 frames more or less.</p><pre>python create_dataset.py<br>python convert_to_pt.py</pre><p>Once the dataset is created, we pretrain each skill independently in an <strong>unsupervised</strong> manner.</p><pre>python train_vos.py<br>python train_vok.py<br>python train_usr.py</pre><p>This will save a pytorch model for each skill inside skills/torch_models folder. In contrast to the original work, where a skill was trained for a single environment, this approach trains the skill on data from all environments to create a more robust and generalizable model.</p><p>For readability, <strong>I intentionally do not paste the full implementation of the skill models here</strong>. If you are interested in the full implementation you can find everything in the <a href="https://github.com/Sopralapanca/medium-skill-based-agents">GitHub </a>repository.</p><h4>Environment Setup, Sanity Checks, and Weights &amp; Biases Initialization</h4><p>Before integrating the skill-based representation and the attention module, we first need to make sure that:</p><ol><li>the Atari environments are correctly registered and loaded,</li><li>observations have the expected shape,</li><li>logging is properly initialized.</li></ol><p>This section sets up the environment and performs a simple sanity check using random actions. We start with standard imports and basic configuration.<br> Atari environments rely on ale-py, which must be explicitly registered when using gymnasium.</p><pre># general imports<br>import torch<br>import os<br>import numpy as np<br>import random<br><br># IMPORTANT - REGISTER THE ENVIRONMENTS<br>import gymnasium as gym<br>import ale_py<br>gym.register_envs(ale_py)<br><br>os.environ[&#39;TF_CPP_MIN_LOG_LEVEL&#39;] = &#39;1&#39;  # ignore tensorflow warnings about CPU<br>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br><br>seed = None<br>if seed is not None:<br>    torch.manual_seed(seed)<br>    np.random.seed(seed)<br>    random.seed(seed)</pre><p>Each Atari game is associated with a YAML configuration file that specifies parameters such as number of parallel environments, number of stacked frames. We load these configurations dynamically:</p><pre>import yaml<br><br>def load_env_config(env):<br>    with open(f&#39;environment_configs/{env}.yaml&#39;, &#39;r&#39;) as file:<br>        environment_configuration = yaml.safe_load(file)[&quot;config&quot;]<br>    return environment_configuration</pre><p>We use Stable-Baselines3 utilities to construct vectorized Atari environments with frame stacking and channel transposition.</p><pre>from stable_baselines3.common.env_util import make_atari_env<br>from stable_baselines3.common.vec_env import VecFrameStack, VecTransposeImage<br><br>def create_env(env_id, configs, seed=None):<br>    env = make_atari_env(env_id, n_envs=configs[&quot;n_envs&quot;], seed=seed)<br>    env = VecFrameStack(env, n_stack=configs[&quot;n_stacks&quot;])<br>    env = VecTransposeImage(env)<br>    return env</pre><p>We use <strong>Weights &amp; Biases (wandb)</strong> to track experiments, configurations, and training metrics. You need to create a .env file containing your WANDB_API_KEY.</p><pre>import wandb<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br># YOU NEED TO CREATE  A .env FILE with WANDB_API_KEY<br>key = os.getenv(&quot;WANDB_API_KEY&quot;)<br>if key is None:<br>    raise ValueError(&quot;WANDB_API_KEY not set&quot;)<br><br>def init_wandb(environment_configuration):<br>  wandb.login(key=key)<br><br>  tags = [<br>      f&quot;fe:{environment_configuration[&#39;f_ext_name&#39;]}&quot;,<br>      f&quot;game:{environment_configuration[&#39;game&#39;]}&quot;,<br>  ]<br><br>  run = wandb.init(<br>      project=&quot;medium-skill-based-agents&quot;,<br>      config=environment_configuration,<br>      sync_tensorboard=True,  # auto-upload sb3&#39;s tensorboard metrics<br>      monitor_gym=False,      # disable automatic video logging<br>      group=f&quot;{environment_configuration[&#39;game&#39;]}&quot;,<br>      tags=tags<br>  )<br><br>  return run</pre><p>Before moving on, it is good practice to verify that the environment works as expected.</p><p>We load <strong>PongNoFrameskip-v4</strong>, reset the environment, perform a few random actions, and we visualize one frame to ensure that everything looks correct. If you see a valid Pong frame, the environment is correctly set up.</p><pre>import matplotlib.pyplot as plt<br><br>env = &quot;PongNoFrameskip-v4&quot;<br>environment_configuration = load_env_config(env)<br><br>test_envs = create_env(env_id=env, configs=environment_configuration, seed=seed)<br><br># execute some steps with random moves<br>obs = test_envs.reset()<br><br>for i in range(10):<br>    action = [test_envs.action_space.sample() for _ in range(environment_configuration[&quot;n_envs&quot;])]<br>    obs, rewards, dones, info = test_envs.step(action)<br><br># obs[0] has shape (4, 84, 84) because there are 4 stacked frames, take the last one<br>observation = obs[0][-1]<br>plt.imshow(observation)<br>plt.show()</pre><h3>Training the Agent with Skill-Based Representations</h3><p>We now move to the final stage: training a PPO agent using the skill-based state representation learned through Weight-Sharing Attention.</p><p>For the sake of clarity and reproducibility, this section focuses on a <strong>simplified training setup</strong>, while preserving the key ideas of the full experimental pipeline used in the paper.</p><p>We start by importing the utilities required for training, evaluation, and logging, and we define a helper function that encapsulates the full training loop.</p><pre>from stable_baselines3.common.callbacks import EvalCallback<br>from wandb.integration.sb3 import WandbCallback<br>from rl_zoo3.utils import linear_schedule<br>from stable_baselines3 import PPO<br><br>def train_agent(env_id, configs, policy_kwargs, seed):<br>    <br>    run = init_wandb(configs)<br>    logdir = &quot;./tensorboard_logs&quot;<br>    <br>    monitor_dir = str(run.id)<br>    <br>    vec_envs = create_env(env_id=env_id, configs=configs, seed=seed)<br>    _ = vec_envs.reset()<br>    <br>    # eval_envs = create_env(env_id=env_id, configs=configs, seed=None)<br><br>    model = PPO( <br>        &quot;CnnPolicy&quot;,<br>        vec_envs,<br>        learning_rate=linear_schedule(environment_configuration[&quot;learning_rate&quot;]),<br>        n_steps=environment_configuration[&quot;n_steps&quot;],<br>        n_epochs=environment_configuration[&quot;n_epochs&quot;],<br>        batch_size=environment_configuration[&quot;batch_size&quot;],<br>        clip_range=linear_schedule(environment_configuration[&quot;clip_range&quot;]),<br>        normalize_advantage=environment_configuration[&quot;normalize&quot;],<br>        ent_coef=environment_configuration[&quot;ent_coef&quot;],<br>        vf_coef=environment_configuration[&quot;vf_coef&quot;],<br>        policy_kwargs=policy_kwargs,<br>        verbose=0,<br>        device=device,<br>        tensorboard_log=logdir,<br>    )<br><br>    eval_logs = f&quot;eval_logs/{env}/{monitor_dir}&quot;<br>    os.makedirs(eval_logs, exist_ok=True)<br><br>    # eval_callback = EvalCallback(<br>    #     eval_envs,<br>    #     n_eval_episodes=100,<br>    #     best_model_save_path=f&quot;./agents/{monitor_dir}&quot;,<br>    #     log_path=eval_logs,<br>    #     eval_freq=5000 * environment_configuration[&quot;n_envs&quot;],<br>    #     verbose=0,<br>    # )<br>    <br>    <br>    callbacks = [<br>        WandbCallback(verbose=0),<br>        # eval_callback<br>    ]<br><br>    model.learn(1000000, callback=callbacks, progress_bar=True)<br>    run.finish()</pre><p>For simplicity, the evaluation callback is commented out. Also, in our published work, agents are trained for <strong>10,000,000 environment steps</strong>.<br> For the purpose of this article, we train agents for <strong>1,000,000 steps only</strong>, to reduce computational requirements, simplify reproduction, and make experimentation feasible on Google Colab.</p><p>We now define the policy and value network architectures used by PPO.</p><pre>policy_kwargs = dict(<br>    net_arch={<br>        &quot;pi&quot;: environment_configuration[&quot;net_arch_pi&quot;],<br>        &quot;vf&quot;: environment_configuration[&quot;net_arch_vf&quot;],<br>    },<br>    # activation_fn=torch.nn.ReLU,  # use ReLU in case of multiple layers for the policy learning network<br>)</pre><p>We now load and initialize all pretrained skill models. Each skill encoder is loaded <strong>with pretrained weights</strong> and later frozen inside the feature extractor.</p><pre>from skills.video_object_segmentation import VideoObjectSegmentationModel<br>from skills.video_object_keypoints import Transporter<br>from skills.autoencoder import Autoencoder<br>from skills.unsupervised_state_representation import UnsupervisedStateRepresentationModel<br><br># init skills<br>autoencoder = Autoencoder(channels=1).to(device)<br><br>environment_configuration[&quot;f_ext_kwargs&quot;][&quot;device&quot;] = device <br>environment_configuration[&quot;game&quot;] = env<br><br>usr = UnsupervisedStateRepresentationModel(observation=obs[0], device=device)<br>vok = Transporter().to(device)<br>vos = VideoObjectSegmentationModel(device=device)<br><br>skills = [<br>    usr.get_skill(device=device),<br>    vok.get_skill(device=device, keynet_or_encoder=&quot;encoder&quot;),<br>    vok.get_skill(device=device, keynet_or_encoder=&quot;keynet&quot;),<br>    vos.get_skill(device=device)<br>]<br><br># Test each skill&#39;s input adapter<br>print(&quot;\nTesting skill input adapters:&quot;)<br>test_obs = obs[:1]  # Take one sample from batch<br>test_obs = torch.tensor(test_obs, dtype=torch.float32).to(device)<br><br>for skill in skills:<br>    print(f&quot;\nSkill: {skill.name}&quot;)<br>    print(f&quot;Input shape: {test_obs.shape}&quot;)<br>    adapted = skill.input_adapter(test_obs)<br>    print(f&quot;After adapter: {adapted.shape}&quot;)</pre><p>At this point, all the components are in place but, before proceeding, I want to clarify one important point. The <strong>Weight-Sharing Attention module</strong> is implemented in PyTorch and integrated as a custom feature extractor for Stable-Baselines3.</p><p>Since the implementation is relatively long and has already been <strong>conceptually explained in detail in the previous section</strong>, I will not paste the full code here.</p><p>👉 <strong>If you want to inspect the full implementation</strong>, you can find it in the following file:</p><p>📄 <strong>utils/feature_extractors.py</strong> <em>(</em><a href="https://github.com/Sopralapanca/medium-skill-based-agents"><em>GitHub repository</em></a><em>)</em></p><p>For each environment, we train:</p><ol><li>a <strong>standard PPO agent</strong> with the default convolutional encoder, and</li><li>a <strong>PPO agent with Weight-Sharing Attention</strong> as the state representation module.</li></ol><p>All other hyperparameters are kept identical to ensure a fair comparison.</p><h4>Pong</h4><pre>env = &quot;PongNoFrameskip-v4&quot;<br>environment_configuration = load_env_config(env)<br>environment_configuration[&quot;game&quot;] = env<br><br># standard PPO<br>train_agent(env, environment_configuration, policy_kwargs, seed)</pre><pre>from utils.feature_extractors import WeightSharingAttentionExtractor<br><br>f_ext_kwargs = environment_configuration[&quot;f_ext_kwargs&quot;]<br>environment_configuration[&quot;f_ext_name&quot;] = &quot;wsharing_attention_ext&quot;<br>environment_configuration[&quot;f_ext_class&quot;] = WeightSharingAttentionExtractor<br>f_ext_kwargs[&quot;skills&quot;] = skills<br>f_ext_kwargs[&quot;features_dim&quot;] = 256<br><br>policy_kwargs[&quot;features_extractor_class&quot;] = environment_configuration[&quot;f_ext_class&quot;]<br>policy_kwargs[&quot;features_extractor_kwargs&quot;] = f_ext_kwargs<br><br>train_agent(env, environment_configuration, policy_kwargs, seed)</pre><h4>Breakout</h4><pre>env = &quot;BreakoutNoFrameskip-v4&quot;<br>environment_configuration = load_env_config(env)<br>environment_configuration[&quot;game&quot;] = env<br><br># standard PPO<br>train_agent(env, environment_configuration, policy_kwargs, seed)</pre><pre>f_ext_kwargs = environment_configuration[&quot;f_ext_kwargs&quot;]<br>environment_configuration[&quot;f_ext_name&quot;] = &quot;wsharing_attention_ext&quot;<br>environment_configuration[&quot;f_ext_class&quot;] = WeightSharingAttentionExtractor<br>f_ext_kwargs[&quot;skills&quot;] = skills<br>f_ext_kwargs[&quot;features_dim&quot;] = 256<br><br>policy_kwargs[&quot;features_extractor_class&quot;] = environment_configuration[&quot;f_ext_class&quot;]<br>policy_kwargs[&quot;features_extractor_kwargs&quot;] = f_ext_kwargs<br><br>train_agent(env, environment_configuration, policy_kwargs, seed)</pre><h4>Ms. Pacman</h4><pre>env = &quot;MsPacmanNoFrameskip-v4&quot;<br>environment_configuration = load_env_config(env)<br>environment_configuration[&quot;game&quot;] = env<br><br># standard PPO<br>train_agent(env, environment_configuration, policy_kwargs, seed)</pre><pre>f_ext_kwargs = environment_configuration[&quot;f_ext_kwargs&quot;]<br>environment_configuration[&quot;f_ext_name&quot;] = &quot;wsharing_attention_ext&quot;<br>environment_configuration[&quot;f_ext_class&quot;] = WeightSharingAttentionExtractor<br>f_ext_kwargs[&quot;skills&quot;] = skills<br>f_ext_kwargs[&quot;features_dim&quot;] = 256<br><br>policy_kwargs[&quot;features_extractor_class&quot;] = environment_configuration[&quot;f_ext_class&quot;]<br>policy_kwargs[&quot;features_extractor_kwargs&quot;] = f_ext_kwargs<br><br>train_agent(env, environment_configuration, policy_kwargs, seed)</pre><h3>Results and Discussion</h3><p>In this section, we analyze the learning curves obtained by <strong>standard PPO</strong> and <strong>PPO with Weight-Sharing Attention (WSA)</strong> on the three Atari games considered: Pong, Breakout, and Ms. Pacman. In the following figures, the <strong>x-axis shows</strong> the step, while the <strong>y-axis shows</strong> the mean reward.</p><h4>Pong</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6VXc9JfLrjPhCj7b87d2HQ.png" /></figure><p>As shown in the first figure, <strong>Weight-Sharing Attention significantly outperforms standard PPO on Pong</strong>.</p><p>By the end of training the standard PPO agent reaches a score of approximately <strong>5</strong>, while the WSA agent reaches a score of approximately <strong>10</strong>, effectively <strong>doubling the final reward</strong>.</p><p>More importantly, the benefit of pretrained skills is visible <strong>throughout the entire training process</strong>. The WSA agent consistently achieves higher rewards than PPO from the early stages of learning.</p><p>This behavior highlights a key advantage of the proposed approach: the agent does <strong>not need to learn a representation of the world from scratch</strong>. Instead, thanks to the frozen pretrained skills, it can focus almost entirely on <strong>learning how to act</strong>, rather than how to perceive.</p><p>These results strongly suggest that the learned skills provide a <strong>meaningful and useful representation of the environment</strong>, allowing faster and more stable policy learning.</p><h4>Breakout</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*buaxM3bZZNdNwQalHte3Rw.png" /></figure><p>In the case of <strong>Breakout</strong>, standard PPO and WSA achieve <strong>similar performance</strong>, as shown in the second figure, but PPO was better.</p><p>This result is expected. Breakout is a <strong>more complex game than Pong</strong>, requiring finer control, longer-term planning, and more precise perception of object dynamics. In the full paper, we introduce additional optimizations and architectural refinements to make Weight-Sharing Attention more effective in this setting. For simplicity, those refinements are not included in this article.</p><p>Despite this, it is important to note that <strong>WSA does not degrade performance</strong>. Even without task-specific tuning, the skill-based representation remains competitive with standard end-to-end learning.</p><h3>Ms. Pacman</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_4M422Us-r0U4ixt_8Ck0Q.png" /></figure><p>The third figure reports results on <strong>Ms. Pacman</strong>, a game characterized by high visual complexity and multiple interacting objects.</p><p>Here, we observe an advantage of Weight-Sharing Attention <strong>in the early stages of training</strong>. The WSA agent learns faster and achieves higher rewards earlier compared to standard PPO.</p><p>In the second half of training, the performance of the two agents becomes comparable, with both converging to similar reward levels.</p><p>This behavior suggests that pretrained skills are particularly beneficial during <strong>early exploration and representation bootstrapping</strong>, where learning a good state representation from scratch is most difficult. As training progresses, standard PPO eventually catches up, but WSA provides a clear <strong>learning speed advantage</strong>.</p><h3>Conclusion</h3><p>In this work, we demonstrated that <strong>WSA</strong> is an effective mechanism for equipping reinforcement learning agents with reusable and compositional skills. Across our experiments, WSA improved performance over standard training, showing that explicitly modeling and combining skills enables agents to better leverage prior knowledge and adapt to new tasks more efficiently. These results confirm that WSA represents a practical and promising approach for skill-based reinforcement learning.</p><p>It is important to note that, while <strong>PPO benefits from extensively optimized hyperparameters established in prior literature</strong>, WSA does not yet enjoy the same level of tuning. In our experiments, we deliberately reused PPO hyperparameters for WSA without performing a dedicated hyperparameter search. As a consequence, the reported WSA performance should be considered <strong>suboptimal</strong>, and there is significant room for improvement. A targeted hyperparameter optimization tailored specifically to WSA is likely to yield substantially stronger results.</p><p>Finally, this approach naturally opens several avenues for future work. One promising direction is to <strong>increase the number of available skills</strong>, enabling richer and more expressive policy compositions. Another is to explore <strong>more advanced skill combination and weighting strategies</strong>, moving beyond the current aggregation scheme to dynamically adapt skill contributions based on context or task difficulty. Together, these extensions could further enhance the scalability, flexibility, and effectiveness of skill-based reinforcement learning systems.</p><p>If you liked this article and want to help me write even better content, don’t forget to <strong>follow me</strong> and contribute a tip by clicking the link or buttons below :) Thank you very much!</p><p>To run these experiments, I used <strong>RunPod</strong> — sign up with my <a href="https://runpod.io/?ref=hqoci4az">link </a>to get <strong>$5 one-time credit</strong> and <strong>$10 on your first top-up</strong>. It’s an easy way to try these experiments yourself without needing a local GPU!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e508d06da29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reviving AtariARI — State Representation Learning]]></title>
            <link>https://medium.com/@giacomo__95/reviving-atariari-state-representation-learning-14be54c13fef?source=rss-dd74b6a2cd57------2</link>
            <guid isPermaLink="false">https://medium.com/p/14be54c13fef</guid>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[atari]]></category>
            <dc:creator><![CDATA[Giacomo Carfì]]></dc:creator>
            <pubDate>Thu, 25 Dec 2025 15:00:19 GMT</pubDate>
            <atom:updated>2025-12-25T15:00:19.966Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reviving <em>AtariARI — State Representation Learning</em></h3><p>Reinforcement Learning research moves fast — sometimes faster than the libraries that support it. Many influential papers are accompanied by codebases that were perfectly usable at the time of publication but gradually become harder to run, maintain, or extend as dependencies age.</p><p>One such example is <strong>“Unsupervised State Representation Learning in Atari”</strong> (<a href="https://arxiv.org/abs/1906.08226">arXiv:1906.08226</a>), published in 2019 by researchers at <strong>Mila</strong>. The paper introduced several important ideas around unsupervised and auxiliary-task-based representation learning for reinforcement learning agents in the Atari domain.</p><p>The accompanying repository, <a href="https://github.com/mila-iqia/atari-representation-learning"><strong>mila-iqia/atari-representation-learning</strong></a>, is a valuable research artifact — but it is no longer maintained and relies on a stack that has since become obsolete.</p><p>In this article, I introduce a modernized fork of the original repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8N4jy9lG7aevhTY7UN0pg.png" /><figcaption>This image, from the original paper, shows RAM annotations for Atari games, highlighting key game state variables like agent and ghost positions, score, and lives.</figcaption></figure><h3>The Original Repository and Its Limitations</h3><p>While the research ideas remain relevant, the software stack presents several challenges today:</p><p>The original implementation depends on:</p><ul><li><a href="https://github.com/openai/gym">gym</a> (now deprecated in favor of Gymnasium)</li><li><a href="https://github.com/openai/baselines">OpenAI Baselines</a></li><li><a href="https://github.com/ikostrikov/pytorch-a2c-ppo-acktr-gail">pytorch-a2c-ppo-acktr-gail</a></li></ul><p>All of these dependencies are no longer actively maintained and have become increasingly difficult to install on modern Python versions. Over time, this has led to growing friction when trying to run or extend the code, as many parts of the original stack no longer work smoothly with today’s reinforcement learning ecosystem. In particular, the original setup does not align well with the way Atari ROMs are currently handled through the ale-py library, which has become the standard approach for accessing Atari environments.</p><p>As a result, running the original codebase often requires pinning very old Python versions and manually resolving build or compilation issues. These extra steps make even simple experiments harder to reproduce and significantly raise the barrier for modifying or extending the project. For new contributors especially, this can turn what should be a straightforward research setup into a frustrating and time-consuming process.</p><h3>What Changed in the Fork (and Why)</h3><p>I originally created this fork to use it in my own personal projects, but I decided to share it publicly in case it can be useful to others and to welcome contributions from anyone interested in continuing its development.</p><p>Since the upstream repository is no longer maintained and relies on outdated dependencies, even basic experimentation had become unnecessarily difficult. Instead of applying local patches, I decided to properly modernize the codebase and share the result publicly so that others facing the same issues could benefit from it or contribute further.</p><p>The updated repository is available here: <a href="https://github.com/Sopralapanca/atari-representation-learning">https://github.com/Sopralapanca/atari-representation-learning</a></p><p>The goal of the fork was <strong>not</strong> to reimplement the paper from scratch, but to <strong>update the infrastructure while preserving the original ideas</strong>.</p><h4>Migration from gym to gymnasium</h4><p>The most significant structural change in the fork is the migration from <strong>Gym</strong> to <strong>Gymnasium</strong>, which is now the actively maintained standard for reinforcement learning environments. Gymnasium provides ongoing maintenance, clearer APIs, and a more consistent interface compared to the original Gym library, which has effectively reached end of life.</p><p>This migration required updating several parts of the codebase, including environment creation, wrappers, and the interaction logic between agents and environments. In particular, the reset and step semantics were updated to follow Gymnasium’s terminated and truncated signals, which makes episode handling more explicit and less error-prone. While these changes are mostly mechanical, they are essential for ensuring correctness and long-term maintainability.</p><h4>Atari Support via ale-py</h4><p>Another important change is the move away from legacy Gym Atari bindings in favor of <strong>ale-py</strong>. The fork now relies directly on ale-py to provide Atari environments, which is the approach currently recommended and actively supported by the community.</p><p>Using ale-py ensures proper compatibility with modern Atari ROM handling and avoids several brittle assumptions made by older wrappers. This change also makes the setup more transparent, as the dependency responsible for Atari emulation is explicit rather than hidden behind deprecated abstractions.</p><h4>Removal of Obsolete Libraries</h4><p>Several outdated reinforcement learning libraries were completely removed from the project, most notably <strong>OpenAI Baselines</strong> and <strong>pytorch-a2c-ppo-acktr-gail</strong>. These libraries are no longer maintained and tend to pull in old transitive dependencies that complicate installation and environment management.</p><p>By removing them, the dependency graph becomes significantly simpler and more predictable. This not only makes the project easier to install, but also lowers the barrier for experimentation, refactoring, or integration with newer RL frameworks that contributors may already be using.</p><h3>Example: Getting Started with the Fork</h3><p>Once you’ve installed the updated repository, you can quickly start experimenting with Atari representation learning. You will need the fork itself and, optionally, <strong>Stable Baselines 3</strong> if you plan to use it for agent interactions:</p><pre>pip install git+https://github.com/Sopralapanca/atari-representation-learning.git <br>pip install stable-baselines3[extra]</pre><h4>Collecting Episodes</h4><p>The repository provides utilities for collecting episodes in Atari environments. Here’s a simple helper function to fetch training and validation episodes:</p><pre>from atariari.benchmark.episodes import get_episodes<br><br>def _get_episodes(env_name, steps, collect_mode):<br>    tr_eps, val_eps = get_episodes(<br>        steps=steps,<br>        env_name=env_name,<br>        collect_mode=collect_mode,<br>        train_mode=&quot;train_encoder&quot;,<br>    )<br>    return tr_eps, val_eps</pre><h4>Setting Up an Unsupervised Representation Model</h4><p>The fork includes state representation methods like ST-DIM. Here’s an example class to initialize and train a model:</p><pre>from atariari.methods.encoders import NatureCNN<br>from atariari.methods.stdim import InfoNCESpatioTemporalTrainer<br>import torch<br><br>class UnsupervisedStateRepresentationModel:<br>    def __init__(self, observation, device, max_training_steps=10000, batch_size=64):<br><br>        # DummyWandB is optional; use it if you don&#39;t want to log to wandb<br>        dummy_wandb = DummyWandB()<br>        <br>        args = {<br>            &quot;pretraining_steps&quot;: max_training_steps,<br>            &quot;no_downsample&quot;: True,<br>            &quot;probe_collect_mode&quot;: &quot;random_agent&quot;,<br>            &quot;feature_size&quot;: 512,<br>            &quot;end_with_relu&quot;: True,<br>            &quot;encoder_type&quot;: &quot;Nature&quot;,<br>            &quot;patience&quot;: 15,<br>            &quot;epochs&quot;: 100,<br>            &quot;batch_size&quot;: batch_size,<br>            &quot;lr&quot;: 3e-4,<br>            &quot;method&quot;: &quot;vae&quot;,<br>            &quot;end_with_relu&quot;: False,<br>            &quot;wandb&quot;: dummy_wandb,<br>        }<br><br>        self.args = Args(**args)<br>        self.observation_shape = observation.shape  # e.g., (1, 210, 160)<br>        <br>        self.encoder = NatureCNN(input_channels=self.observation_shape[0], args=self.args).to(device)<br>        self.encoder = torch.compile(self.encoder, mode=&#39;default&#39;)<br><br>        config = {}<br>        config.update(vars(self.args))<br>        config[&quot;obs_space&quot;] = self.observation_shape<br><br>        self.trainer = InfoNCESpatioTemporalTrainer(<br>            self.encoder, config, device=device, wandb=dummy_wandb<br>        )<br><br>    def train(self, train_episodes, val_episodes, val_interval=5):<br>        self.trainer.train(train_episodes, val_episodes, val_interval=val_interval)<br>        # save your model after training</pre><h4>Supporting Classes</h4><p>To keep the example self-contained, here are some helper classes used above. <strong>Using </strong><strong>DummyWandB is optional</strong>; if you prefer, you can replace it with a real <a href="https://wandb.ai/">Weights &amp; Biases</a> run.</p><pre>class Args:<br>    def __init__(self, **kwargs):<br>        self.__dict__.update(kwargs)<br><br>class DummyWandB:<br>    class Run:<br>        def __init__(self):<br>            self.dir = &quot;./skills&quot;<br><br>    def __init__(self):<br>        self.run = self.Run()<br><br>    def log(self, *args, **kwargs):<br>        pass<br><br>    def watch(self, *args, **kwargs):<br>        pass<br><br>    def finish(self):<br>        pass</pre><h3>Contributions and Ongoing Development</h3><p>This fork is very much a <strong>work in progress</strong>. While the codebase has been updated to run on a modern stack, it may still contain bugs, rough edges, or incomplete parts inherited from the original implementation or introduced during the migration. For this reason, contributions, feedback, and bug reports are not just welcome, but actively encouraged.</p><p>The updated repository is available here: <a href="https://github.com/Sopralapanca/atari-representation-learning">https://github.com/Sopralapanca/atari-representation-learning</a></p><p>If you liked the article and want to help me write better and better articles, don’t forget to follow me and contribute a tip by clicking this <a href="https://www.paypal.com/donate/?hosted_button_id=3UNX7F6AFLG96">link</a> or the buttons below :) Thank you very much!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14be54c13fef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG Routers: Semantic Routing with LLMs and Tool Calling]]></title>
            <link>https://medium.com/@giacomo__95/rag-routers-semantic-routing-with-llms-and-tool-calling-b53dd8fae7fa?source=rss-dd74b6a2cd57------2</link>
            <guid isPermaLink="false">https://medium.com/p/b53dd8fae7fa</guid>
            <category><![CDATA[semantic-routing]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[semantic-router]]></category>
            <category><![CDATA[ollama]]></category>
            <dc:creator><![CDATA[Giacomo Carfì]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 18:48:58 GMT</pubDate>
            <atom:updated>2025-03-23T18:48:58.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*nkZvI10lVE5-QAA6Ywq8qQ.png" /><figcaption>Diagram illustrating a RAG (Retrieval-Augmented Generation) system acting as a semantic router. The system processes the chat history (msg1, msg2, msg3) and retrieves relevant past messages and embeddings from a vector database. It uses tool descriptions to decide which tool (e.g., Summarization, Weather Forecast, Topic Extraction) to invoke, providing the user with the appropriate answer.</figcaption></figure><h3>Introduction</h3><p>In the first part of this series (which you can find <a href="https://medium.com/@giacomo__95/using-llms-as-semantic-routers-for-efficient-task-specific-model-selection-example-with-ollama-and-326f15ab2feb">here</a>), we explored how a Large Language Model (LLM) equipped with various tools could act as a semantic router to handle different user queries effectively. The LLM analyzed the chat history and invoked the appropriate tool based on the user’s request, offering a seamless interaction experience. This approach demonstrated the potential of using LLMs to manage diverse tasks, from summarization to weather forecasting, without the need for extensive pre-training or fine-tuning for each specific task.</p><p>Building on this foundation, the second part of this series introduces an enhancement to our system: <strong>integrating a vector database to create a Retrieval-Augmented Generation (RAG) system semantic routing</strong>. By incorporating a vector database, our LLM now has access to a rich repository of past messages and their corresponding embeddings. This additional context empowers the LLM to make more informed decisions when routing user queries to the appropriate tools.</p><p>The vector database serves as a memory bank, allowing the LLM to retrieve relevant historical interactions that may contain similar tool calls or contextual information. This retrieval capability enhances the semantic routing process, improving the accuracy and efficiency of the tool selection. For instance, if a user asks for summarization of recent messages, the LLM can now retrieve past summaries or similar requests, refining its understanding of the task at hand.</p><p>In this follow-up article, we will delve into how integrating the vector database enhances our system&#39;s semantic routing capabilities. We will explore the architecture, implementation details, and benefits of this approach, highlighting how it transforms the LLM’s ability to handle complex and diverse tasks. By the end of this article, you’ll have a comprehensive understanding of how RAG systems can elevate the performance of LLM-based applications, paving the way for more intelligent and context-aware interactions.</p><p>The guide will be developed using <strong>Google Colab</strong> in <strong>Python</strong>, utilizing several key packages including <strong>PostgreSQL</strong> for database management, <strong>pgvector</strong> for handling vector embeddings within PostgreSQL, and <strong>Ollama</strong> for instantiating <strong>Llama3.2</strong> LLM. This combination of tools provides a robust framework for enhancing the semantic routing capabilities of our system.</p><p>The full notebook, including the code and setup details, is available on my <a href="https://github.com/Sopralapanca/medium-articles/blob/main/llm-routing/%5BMedium%5DRAG_semantic_routing_llama.ipynb"><strong>GitHub</strong></a><strong> </strong>repository for reference. In the next section, we will cover the setup process, ensuring you have everything ready to follow along with this tutorial.</p><p>Before we dive into the guide, I invite you to <a href="https://medium.com/m/signin?actionUrl=https%3A%2F%2Fmedium.com%2F_%2Fsubscribe%2Fuser%2Fdd74b6a2cd57&amp;operation=register&amp;redirect=https%3A%2F%2Fmedium.com%2F%40giacomo__95%2Fmarkitdown-ollama-and-llava-markdown-conversion-with-microsofts-markitdown-and-ollama-s-llm-2141bba9d183&amp;user=Giacomo+Carf%C3%AC&amp;userId=dd74b6a2cd57"><strong>follow my profile</strong></a> to stay updated on future articles and insights on LLMs, RAG systems, and more. Your support helps bring more innovative solutions to light.</p><p>In the following sections, we will walk through the setup process and delve into the details of integrating a vector database with our LLM to enhance its semantic routing capabilities.</p><h3>Setup</h3><p>To begin building our semantic router RAG system in Google Colab, we first need to set up PostgreSQL to serve as our vector database. We’ll install PostgreSQL, set up a user and database, and install the pgvector extension for vector storage. Finally, we’ll install the necessary Python packages to interact with the database.</p><h4>1. Installing and Setting Up PostgreSQL</h4><p>First, update the package lists and install PostgreSQL along with its contrib package:</p><pre>!apt update<br>!apt install postgresql postgresql-contrib</pre><p>Start the PostgreSQL service:</p><pre>!service postgresql start</pre><p>Create a new PostgreSQL user and a database:</p><pre>!sudo -u postgres psql -c &quot;CREATE USER rag_router WITH PASSWORD &#39;password&#39;;&quot;<br>!sudo -u postgres psql -c &quot;CREATE DATABASE rag_db OWNER rag_router;&quot;</pre><p>Check the PostgreSQL version to ensure it’s correctly installed (it should be PostgreSQL 14):</p><pre>!psql --version</pre><p>Next, install the necessary server development packages for PostgreSQL:</p><pre>!sudo apt install postgresql-server-dev-14 #change 14 with the PostgreSQL version downloaded</pre><p>Clone the pgvector <a href="https://github.com/pgvector/pgvector">repository</a>, build, and install the extension. For more information visit their GitHub repository.</p><pre>!git clone --branch v0.8.0 https://github.com/pgvector/pgvector.git<br>!cd pgvector &amp;&amp; make &amp;&amp; sudo make install</pre><p>Restart the PostgreSQL service to apply changes:</p><pre>!sudo service postgresql restart</pre><p>Finally, enable the vector extension in the database:</p><pre>!sudo -u postgres psql -d rag_db -c &quot;CREATE EXTENSION IF NOT EXISTS vector;&quot;</pre><p>To interact with PostgreSQL from Python, install the following packages:</p><pre>!pip install sqlalchemy psycopg2-binary pgvector sentence-transformers</pre><p>With PostgreSQL set up and the necessary packages installed, we’re now ready to proceed with implementing the RAG system. In the next section, we’ll connect to our database and start building the system.</p><h4>2. Connecting to the Database and Defining the Table</h4><p>With PostgreSQL and the pgvector extension set up, we can now connect to the database and define the table structure to store our message history and embeddings. We’ll use SQLAlchemy, a popular ORM (Object Relational Mapper) for Python, to handle our database interactions seamlessly.</p><p>We start by setting up the connection to the PostgreSQL database using SQLAlchemy. Here’s the code to create the engine and session:</p><pre>from sqlalchemy import create_engine, Column, Integer, String<br>from sqlalchemy.orm import sessionmaker, declarative_base<br><br># Define connection details<br>DATABASE_URL = &quot;postgresql+psycopg2://rag_router:password@localhost:5432/rag_db&quot;<br><br>engine = create_engine(DATABASE_URL)<br>Base = declarative_base()<br><br>SessionLocal = sessionmaker(bind=engine)<br>session = SessionLocal()</pre><p>This code sets up the connection to our rag_db database using the rag_router user. The SessionLocal is used to create sessions for interacting with the database.</p><p>Next, we define the History table to store messages and their corresponding embeddings. We&#39;ll use the pgvector extension to store the embeddings as vectors. We specify that the embeddings will be stored as a 384-dimensional vector, as we’ll use a sentence transformer model called all-MiniLM-L12-v2later in our implementation:</p><pre>from pgvector.sqlalchemy import Vector<br><br>class History(Base):<br>    __tablename__ = &quot;history&quot;<br><br>    id = Column(Integer, primary_key=True, index=True, autoincrement=True)<br>    user_query = Column(String)<br>    embedding = Column(Vector(384))<br>    history = Column(String)<br><br>Base.metadata.create_all(bind=engine)</pre><p>Specifically, user_query will store the last message sent by the user, embedding will be the vector representation of the user message, history will contain an example of a conversation with the user and the tool call that was made. In this way the search for emebdding will be done considering only the last message sent by the user, while we will enrich the information provided to the language model by considering the whole example including tool call.</p><p>Finally, we create the tables in our database:</p><pre>Base.metadata.create_all(bind=engine)</pre><p>With this setup, we’ve established a connection to our PostgreSQL database and defined the schema for storing historical chat messages and their embeddings. This structure will enable the LLM to retrieve past interactions and make informed decisions when routing user queries.</p><p>In the next section, we will explore how to generate embeddings using a sentence transformer model and populate our database with historical messages.</p><h3>Preparing the Dataset and Seeding the Database</h3><p>Now that we have set up our database, we need to populate it with meaningful data for our RAG system. To do this, we use a sample dataset containing chat interactions, which will allow us to perform similarity searches when retrieving relevant historical messages.</p><h4>1. Downloading the Dataset</h4><p>The dataset is a CSV file that contains user messages along with their associated conversation history. I generated this dataset using ChatGPT to simulate a variety of query-response pairs. You can download it using the following command:</p><pre>!wget https://github.com/Sopralapanca/medium-articles/blob/main/llm-routing/chat_sample.csv?raw=true -O chat_sample.csv</pre><h4>2. Exploring the Dataset</h4><p>Once the dataset is downloaded, we can load it into a pandas DataFrame and inspect its structure:</p><pre>import pandas as pd<br><br>df = pd.read_csv(&quot;chat_sample.csv&quot;)<br>df.head()</pre><p>Each row in the dataset contains:</p><ul><li>history: A JSON-formatted conversation history that tracks how the query was processed.</li><li>message: The user’s input message.</li></ul><p>An example of a row:</p><pre>{<br>    &quot;history&quot;: &quot;[{\&quot;role\&quot;: \&quot;user\&quot;, \&quot;content\&quot;: \&quot;What is the topic of this statement? &#39;The construction of the Great Wall of China stood as a symbol of defense and perseverance.&#39;\&quot;}, {\&quot;role\&quot;: \&quot;assistant\&quot;, \&quot;content\&quot;: \&quot;\&quot;, \&quot;refusal\&quot;: null, \&quot;audio\&quot;: null, \&quot;function_call\&quot;: null, \&quot;tool_calls\&quot;: [{\&quot;id\&quot;: \&quot;call_618996\&quot;, \&quot;function\&quot;: {\&quot;arguments\&quot;: \&quot;{}\&quot;, \&quot;name\&quot;: \&quot;get_topic\&quot;}, \&quot;type\&quot;: \&quot;function\&quot;, \&quot;index\&quot;: 0}]}, {\&quot;role\&quot;: \&quot;tool\&quot;, \&quot;content\&quot;: \&quot;{\\\&quot;result\\\&quot;: \\\&quot;The topic of the sentence is The and its significance in history or technology.\\\&quot;}\&quot;, \&quot;tool_call_id\&quot;: \&quot;call_618996\&quot;}, {\&quot;role\&quot;: \&quot;assistant\&quot;, \&quot;content\&quot;: \&quot;The topic of the sentence is The and its significance in history or technology.\&quot;}]&quot;,<br>    &quot;message&quot;: &quot;What is the topic of this statement? &#39;The construction of the Great Wall of China stood as a symbol of defense and perseverance.&#39;&quot;<br>}</pre><h4>3. Encoding Messages with Sentence Transformers</h4><p>To enable efficient similarity search in our vector database, we encode the messages using a sentence transformer model. Here, we use sentence-transformers/all-MiniLM-L12-v2 from Hugging Face, but you are free to use any model that suits your needs.</p><p>First, we download and load the model:</p><pre>from sentence_transformers import SentenceTransformer<br>model = SentenceTransformer(&#39;sentence-transformers/all-MiniLM-L12-v2&#39;)</pre><p>To compute an embedding for a given text, we can use:</p><pre># Example string to compute embeddings<br>example_string = &quot;This is a sample string for embedding.&quot;<br><br># Compute the embeddings<br>embedding = model.encode(example_string)<br>embedding = embedding.astype(float).tolist()</pre><h4>4. Implementing Similarity Search</h4><p>With the embeddings stored in our database, we need a method to retrieve the most similar past interactions based on a given query. We implement a similarity search function using <strong>L2 distance</strong>:</p><pre>def similarity_search(session, query: str):<br>    vector = model.encode(query)<br>    records = (<br>        session.query(History)<br>        .order_by(History.embedding.l2_distance(vector))<br>        .limit(3)<br>        .all()<br>    )<br>    if records:<br>        return records<br>    else:<br>        return None</pre><h4>5. Seeding the Database with Message Embeddings</h4><p>Now that we have our dataset and encoding model, we can populate the PostgreSQL database with the chat history and message embeddings.</p><pre># Add records to PostgreSQL<br><br>records = []<br>for i, row in df.iterrows():<br>    embedding = model.encode(row[&quot;message&quot;]).astype(float).tolist()<br>    records.append(<br>        History(<br>            user_query=row[&quot;message&quot;],<br>            embedding=embedding,<br>            history=row[&quot;history&quot;]<br>            )<br>        )<br><br>try:<br>  session.add_all(records)<br>  session.commit()<br>except Exception as e:<br>  print(e)<br>  session.rollback()<br>  print(&quot;exception raised, rollbacking...&quot;)</pre><h4>6. Verifying the Data Insertion</h4><p>To confirm that the records were inserted successfully, we can query the database:</p><pre># Check if data is inserted correctly<br>history = session.query(History).all()<br><br>for msg in history:<br>    print(f&quot;Message: {msg.user_query}\nEmb: {msg.embedding}\nHistory: {msg.history}\n&quot;)<br>    break</pre><pre>Message: What is the topic of this statement? &#39;The construction of the Great Wall of China stood as a symbol of defense and perseverance.&#39;<br>Emb: [ 3.56391110e-02  1.39516190e-01 -5.41455634e-02  1.03664258e-02<br>  5.39230816e-02  3.67860869e-02  6.48062080e-02 -1.38131268e-02<br> -2.76730061e-02 -1.11560058e-02  1.47463987e-02 -5.28952740e-02<br>  9.83905196e-02 -1.85867175e-02 -1.47388298e-02  1.54635549e-01<br> -1.80432014e-02  2.56070755e-02 -4.38161269e-02  1.75370611e-02<br>  6.85141832e-02 -8.59485939e-02  1.80035885e-02 -1.59655511e-02<br>  3.60874161e-02 -7.78923854e-02  5.48197068e-02 -2.57355394e-04<br>  9.83621106e-02  6.14276296e-03 -6.19777888e-02  1.48288729e-02<br>  2.15548966e-02 -9.35294840e-04  4.90635224e-02  4.82670143e-02<br>  1.11774608e-01  8.08627345e-03  5.07231131e-02  2.47926861e-02<br>  4.28537503e-02  4.14998718e-02  6.81590289e-02 -2.15036981e-02<br>  8.12526420e-02  2.77387793e-03  3.68143395e-02  6.26895428e-02<br> -5.55345230e-03 -6.85127266e-03  6.40913546e-02 -3.92634273e-02<br> -2.17473134e-02 -5.86708933e-02 -3.40111516e-02  7.87436664e-02<br>  6.57240022e-03  4.95278835e-02 -4.15265560e-02  9.48650911e-02<br> -3.59242558e-02  1.24758534e-01  2.37003900e-02  2.68134382e-02<br>  3.97864431e-02  9.00040846e-03  3.82129252e-02  7.64965937e-02<br>  1.03782411e-04  1.88976265e-02 -6.49116933e-02 -1.23188486e-02<br> -4.75398637e-03  2.99789850e-02  3.54540278e-03  5.00601949e-03<br>  8.93896259e-03  3.41104530e-02  4.67196945e-03 -1.00443669e-01<br>  3.16508338e-02  1.45623286e-03 -4.84539643e-02  7.12452531e-02<br> -9.68752429e-03 -9.10218284e-02 -5.55495620e-02 -3.10241226e-02<br> -4.22470417e-04 -1.19265001e-02 -3.66672128e-02  1.46445353e-02<br>  4.96426970e-02  6.59978241e-02  1.02954879e-01 -3.09354644e-02<br> -3.20205912e-02 -5.73691204e-02  3.43689173e-02  6.34342879e-02<br>  2.55851224e-02  6.27490729e-02  1.06596723e-02 -8.67631882e-02<br> -6.63076481e-03  4.63875290e-03 -3.32081765e-02 -5.73190972e-02<br> -3.84991691e-02 -2.44544484e-02  8.25658254e-03 -2.55440194e-02<br>  1.12267323e-02  7.35786632e-02  2.79526003e-02 -4.73383553e-02<br> -1.58503968e-02  1.05204647e-02 -1.86165944e-02 -2.96575539e-02<br>  7.48385042e-02 -2.12699007e-02  5.57069527e-03 -1.62029061e-02<br> -6.61655515e-02 -9.45105404e-02  4.32871394e-02 -4.66416441e-02<br>  2.62509473e-02  4.39372985e-03 -1.38002979e-02  1.33248335e-02<br> -8.18160269e-03 -8.02748129e-02  2.70134453e-02  1.23223849e-02<br> -7.47878617e-03 -3.02926470e-02 -4.14032638e-02 -5.72613478e-02<br>  3.09377201e-02  1.01244375e-01  3.20321359e-02 -2.97183786e-02<br> -1.10303320e-01 -2.09869090e-02 -4.43669371e-02 -1.02053648e-02<br>  8.20063427e-02  7.62664452e-02 -8.12128708e-02 -5.02047921e-03<br>  5.78943007e-02  1.44760739e-02  4.03009541e-02  7.63541367e-03<br> -8.50614384e-02  1.66245596e-03  8.43952596e-03 -2.15932019e-02<br> -4.56671417e-02  4.75338548e-02 -3.62151600e-02  4.73676398e-02<br> -2.97146812e-02 -1.55824600e-02 -8.67354870e-03  2.77717058e-02<br>  1.74703321e-03  1.81635134e-02  2.87144631e-03 -5.41020604e-03<br>  1.12942189e-01  4.22507748e-02  3.91682814e-04 -8.53203014e-02<br> -4.47661914e-02 -4.76459078e-02 -3.29743652e-03 -1.56637095e-02<br> -4.58651893e-02 -4.28264774e-02  2.43080705e-02 -5.89831397e-02<br> -9.11172256e-02  3.48661244e-02  8.31293017e-02  4.01404984e-02<br> -3.10640279e-02  1.24621168e-02 -2.74060816e-02  1.26842916e-01<br> -2.19727959e-02  9.75351129e-03 -5.09146526e-02 -1.67063437e-02<br> -3.23992246e-03  2.87737064e-02 -1.79229793e-03  3.00386106e-04<br>  3.36830020e-02 -1.28349945e-01 -5.14890850e-02 -3.70209031e-02<br> -1.97049398e-02 -1.65791754e-02  3.59189548e-02 -3.81764360e-02<br> -7.11437687e-02 -3.98273207e-02  8.34823996e-02  4.33139391e-02<br> -1.99118759e-02 -2.18496043e-02  8.09674039e-02 -6.74301088e-02<br>  5.46612293e-02 -4.60898355e-02  2.00929865e-02 -4.15070616e-02<br>  6.55146763e-02  1.45574342e-02 -9.53789726e-02  1.94731380e-32<br> -4.41746990e-04  8.25959083e-04  2.97364648e-02 -7.46690028e-04<br>  7.88325816e-02 -4.50695232e-02 -6.51104674e-02 -8.05454850e-02<br> -7.88509473e-03  3.96083333e-02 -4.75353599e-02 -2.30434928e-02<br> -6.51504025e-02  2.76793819e-02 -5.01169302e-02 -6.53670430e-02<br> -5.98709285e-02  4.23941482e-03 -8.36451054e-02  1.13330772e-02<br> -2.34593190e-02 -4.59063910e-02  3.57888849e-03 -4.64538410e-02<br> -2.98117474e-02  7.94593543e-02 -2.64531281e-02 -1.59601942e-01<br>  4.22903225e-02 -2.06399094e-02  2.75755525e-02  1.84438974e-02<br> -9.15093422e-02  5.66963106e-02  1.66896638e-02 -3.73455472e-02<br>  1.52522415e-01 -8.48315880e-02  2.63659228e-02 -3.79037857e-02<br>  1.38341263e-02  4.33253236e-02 -2.34484095e-02  9.58907083e-02<br> -1.31546184e-01 -1.39121357e-02  4.28867005e-02 -2.43927296e-02<br>  4.78442991e-03 -1.73287131e-02 -6.86097741e-02  3.76354791e-02<br>  1.17679916e-01 -4.43245620e-02  3.07631288e-02  1.20571703e-02<br> -2.17988212e-02  6.58176616e-02  1.77962612e-02 -4.60228510e-02<br>  7.70573970e-03  3.27375829e-02  6.07456602e-02 -4.94542122e-02<br>  1.00167699e-01 -2.38578729e-02  4.65676300e-02  4.62845601e-02<br> -4.97905863e-03  1.85510435e-03 -1.16905391e-01  3.51430066e-02<br> -1.06304400e-01  8.91971216e-02 -3.10810525e-02  5.48285544e-02<br> -3.63852121e-02 -2.21131593e-02  3.69688943e-02  1.48576617e-01<br>  2.97230985e-02 -6.04069978e-02  1.77705847e-02 -5.33979535e-02<br>  2.62360368e-02 -6.37743762e-03 -7.56596848e-02  2.04473902e-02<br>  7.99300298e-02  2.35495856e-03 -3.24344523e-02 -1.81301851e-02<br> -1.31327033e-01 -3.24439183e-02 -7.39989849e-03  4.80660492e-32<br>  2.95547321e-02 -7.94379134e-03 -9.85979363e-02  3.08770710e-03<br>  1.08095780e-02  2.17941068e-02  9.08277463e-03 -3.99402045e-02<br>  1.82272941e-02  3.61790732e-02  2.63478216e-02  1.13106752e-02<br> -6.57167435e-02 -3.85014787e-02 -4.57616001e-02 -1.21498890e-02<br>  1.38666248e-02 -7.27558360e-02  1.94157399e-02 -2.25873925e-02<br>  4.49696966e-02 -2.24020313e-02 -5.85773066e-02 -5.40203154e-02<br> -3.80695499e-02  6.43591136e-02  1.37437014e-02  5.77405235e-03<br>  1.27854757e-02 -2.48799287e-02  1.23569416e-03 -1.18192136e-02<br> -2.60241125e-02 -5.27605973e-02  4.36215987e-03 -9.67641175e-03<br>  4.66862544e-02 -5.00502773e-02  7.56993815e-02 -7.21424446e-02<br> -3.45649831e-02  6.74557760e-02  2.10934952e-02  3.93601432e-02<br> -1.10357683e-02  3.09072342e-02  9.55893192e-03  3.02247368e-02<br> -2.37568989e-02 -4.54251878e-02 -7.33901784e-02  2.13674009e-02<br>  7.13499486e-02 -2.92651337e-02 -7.71111762e-03  1.10905610e-01<br>  2.95666140e-02  4.70999219e-02  9.64558974e-04 -4.27337065e-02<br>  3.81121859e-02  5.68572134e-02 -1.32158529e-02  5.79213873e-02]<br>History: &quot;[{\&quot;role\&quot;: \&quot;user\&quot;, \&quot;content\&quot;: \&quot;What is the topic of this statement? &#39;The construction of the Great Wall of China stood as a symbol of defense and perseverance.&#39;\&quot;}, {\&quot;role\&quot;: \&quot;assistant\&quot;, \&quot;content\&quot;: \&quot;\&quot;, \&quot;refusal\&quot;: null, \&quot;audio\&quot;: null, \&quot;function_call\&quot;: null, \&quot;tool_calls\&quot;: [{\&quot;id\&quot;: \&quot;call_618996\&quot;, \&quot;function\&quot;: {\&quot;arguments\&quot;: \&quot;{}\&quot;, \&quot;name\&quot;: \&quot;get_topic\&quot;}, \&quot;type\&quot;: \&quot;function\&quot;, \&quot;index\&quot;: 0}]}, {\&quot;role\&quot;: \&quot;tool\&quot;, \&quot;content\&quot;: \&quot;{\\\&quot;result\\\&quot;: \\\&quot;The topic of the sentence is The and its significance in history or technology.\\\&quot;}\&quot;, \&quot;tool_call_id\&quot;: \&quot;call_618996\&quot;}, {\&quot;role\&quot;: \&quot;assistant\&quot;, \&quot;content\&quot;: \&quot;The topic of the sentence is The and its significance in history or technology.\&quot;}]&quot;</pre><p>Now that our database is seeded with sample chat messages and embeddings, we are ready to integrate our LLM-powered retrieval system with PostgreSQL. In the next section, we will download Ollama and Llama3.2. Next, we will use the vector database to improve our LLM routing mechanism.</p><h3>Setting Up Ollama and Large Language Models (LLMs)</h3><h4>What is Ollama?</h4><p>Ollama is a powerful framework designed to run and manage large language models (LLMs) efficiently on local machines. It allows users to download, serve, and interact with models without needing external API dependencies. With Ollama, developers can fine-tune model deployment and optimize execution for various tasks, from chatbot applications to complex AI-driven workflows.</p><h4>Downloading and Setting Up Ollama</h4><p>To install Ollama, run the following command:</p><pre>!curl https://ollama.ai/install.sh | sh</pre><p>Once installed, start the Ollama server:</p><pre>!ollama serve &gt; server.log 2&gt;&amp;1 &amp;  # Ollama runs by default at 127.0.0.1:11434</pre><h4>Downloading Large Language Models</h4><p>For this implementation, we use llama3.2:3b both as a router and as specialized task agents. This choice is made for simplicity and illustration purposes. Users can select different models for routing and specialized tasks as long as the chosen routing model supports tool calls.</p><p>To download the models, execute:</p><pre>%%capture<br>agents_model = &quot;llama3.2:3b&quot;<br>#!ollama pull {agents_model}<br><br>%%capture<br>router_model = &quot;llama3.2:3b&quot;<br>!ollama pull {router_model}</pre><p>Check the available models:</p><pre>!ollama ls</pre><pre>NAME           ID              SIZE      MODIFIED               <br>llama3.2:3b    a80c4f17acd5    2.0 GB    Less than a second ago </pre><h4>Serving Models at Different Ports</h4><p>To serve multiple models simultaneously on different ports, set environment variables and run multiple instances of Ollama:</p><pre>import os<br><br>os.environ[&#39;OLLAMA_HOST&#39;] = &quot;127.0.0.1:11438&quot;<br>!ollama serve &gt; server.log 2&gt;&amp;1 &amp;<br><br>os.environ[&#39;OLLAMA_HOST&#39;] = &quot;127.0.0.1:11439&quot;<br>!ollama serve &gt; server.log 2&gt;&amp;1 &amp;</pre><h3>Setting Up Router Model and Specialized Agents</h3><p>Before defining the router model and its tools, install the necessary Python packages:</p><pre>!pip install openai==1.57.4 ollama==0.4.4 pydantic==2.10.3</pre><p>These packages allow us to interact with Ollama, define structured data using Pydantic, and use OpenAI’s API.</p><h3>Defining Available Tools</h3><p>In a function-calling LLM setup, tools act as specialized functions the model can invoke when a user requests specific tasks. We define two tools:</p><pre>from openai import OpenAI<br>import openai<br><br>summarizer_tool = {<br>    &quot;type&quot;: &quot;function&quot;,<br>    &quot;function&quot;: {<br>        &quot;name&quot;: &quot;get_summarization&quot;,<br>        &quot;description&quot;: &quot;Call this method whenever you need to perform a summarization task, for example when a user asks &#39;Summarize this paragraph&#39;. This method does not accept input parameters.&quot;,<br>        &quot;parameters&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {},<br>            &quot;required&quot;: [],<br>            &quot;additionalProperties&quot;: False<br>        }<br>    }<br>}<br><br>topics_tool = {<br>    &quot;type&quot;: &quot;function&quot;,<br>    &quot;function&quot;: {<br>        &quot;name&quot;: &quot;get_topics&quot;,<br>        &quot;description&quot;: &quot;Call this whenever you need to perform a topic extraction task, for example when a user asks &#39;What are the topics of this paragraph?&#39;. This method does not accept input parameters.&quot;,<br>        &quot;parameters&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {},<br>            &quot;required&quot;: [],<br>            &quot;additionalProperties&quot;: False<br>        }<br>    }<br>}<br>tools = [topics_tool, summarizer_tool]</pre><p>These tools are designed for two tasks:</p><ul><li><strong>Summarization</strong>: Extracts a concise summary of a given text.</li><li><strong>Topic Extraction</strong>: Identifies key topics within a paragraph.</li></ul><p>Please note that in this case we do not have the language model generate the input parameters for the tool. This is because, for the chosen tasks, the LLM might invent or change the input text. Instead we will pass to the tool exactly the user’s last message</p><p>For simplicity, we define only two tools, but additional tools can be created by following the same structure. <strong>The descriptions must be precise</strong>, as ambiguous descriptions may confuse the model when deciding which tool to call.</p><h4>Defining Specialized Agents</h4><p>Each specialized agent is responsible for handling a specific task. The summarizer and topic extractor agents are defined as follows:</p><pre>from openai import OpenAI<br><br>summarizer_client = OpenAI(<br>    base_url=&#39;http://localhost:11439/v1&#39;,<br>    api_key=&#39;ollama&#39;,  # required, but unused<br>)<br><br>topic_client = OpenAI(<br>    base_url=&#39;http://localhost:11438/v1&#39;,<br>    api_key=&#39;ollama&#39;,  # required, but unused<br>)</pre><ul><li>The <strong>summarizer_client</strong> connects to the model running on port 11439, which handles summarization.</li><li>The <strong>topic_client</strong> connects to the model running on port 11438, which handles topic extraction.</li></ul><p>We then define a helper function to construct conversation history:</p><pre>def build_history_agents(messages: list[dict[str, str]], sys_prompt: str):<br>    history = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: sys_prompt}]<br>    for message in messages:<br>        if message[&quot;role&quot;] != &quot;system&quot;:<br>            history.append(message)<br>    return history</pre><p>This function ensures that:</p><ul><li>Each agent receives a system message with clear role instructions.</li><li>The conversation history is maintained correctly.</li></ul><h4>Summarization Agent</h4><pre>def get_summarization(history: list[dict[str, str]]):<br>    print(&quot;calling summarization model&quot;)<br><br>    sys_prompt = &quot;You are a summarizer agent. Your only role is to summarize user messages. If the user requests any other action or chit-chat, just answer &#39;Pass.&#39;&quot;<br>    k = build_history_agents(history, sys_prompt)<br><br>    response = summarizer_client.chat.completions.create(<br>        model=agents_model,<br>        messages=k,<br>    )<br><br>    return response.choices[0].message.content</pre><p>This function:</p><ul><li>Calls the summarization model.</li><li>Enforces a strict role for the agent (it only summarizes and ignores unrelated requests).</li><li>Returns the generated summary.</li></ul><h4>Topic Extraction Agent</h4><pre>def get_topics(history: list[dict[str, str]]):<br>    print(&quot;calling topic model&quot;)<br><br>    sys_prompt = &quot;You are a topic extractor model. Your role is to examine user messages and extract the topics. If the user requests any other action or chit-chat, just answer &#39;Pass.&#39;&quot;<br><br>    response = topic_client.chat.completions.create(<br>        model=agents_model,<br>        messages=build_history_agents(history, sys_prompt),<br>    )<br><br>    return response.choices[0].message.content</pre><p>This function:</p><ul><li>Calls the <strong>topic extraction model</strong>.</li><li>Uses a strict prompt to ensure the agent does not perform other tasks.</li><li>Returns the extracted topics.</li></ul><h4>Utility Functions</h4><p><strong>Executing Function Calls</strong></p><pre>import json<br>import re<br><br>def execute_function_call(response, history):<br>  if response.choices[0].finish_reason == &quot;tool_calls&quot;:<br>    tool_call = response.choices[0].message.tool_calls[0]<br>    function_name = tool_call.function.name<br><br>    result = globals()[function_name](history)<br><br><br>    function_call_result_message = {<br>      &quot;role&quot;: &quot;tool&quot;,<br>      &quot;content&quot;: json.dumps({<br>          &quot;result&quot;: result<br>      }),<br>      &quot;tool_call_id&quot;: response.choices[0].message.tool_calls[0].id<br>    }<br><br>    response_dict = response.model_dump()<br>    response_dict[&quot;choices&quot;][0][&quot;message&quot;]<br><br>    history = history + [response_dict[&quot;choices&quot;][0][&quot;message&quot;]] + [function_call_result_message]<br><br>    return history</pre><p>This function manages the execution of tool calls. If the model calls a tool, it retrieves the function name and executes it. The tool’s response is formatted and appended to the conversation history.</p><p><strong>Building Router History</strong></p><pre>def build_router_history(messages: list[dict[str, str]], response):<br>    res = response.choices[0].message.content<br>    messages.append(<br>        {<br>            &quot;role&quot;: &quot;assistant&quot;,<br>            &quot;content&quot;: res<br>        }<br>    )<br>    print(res)<br>    return messages</pre><p>This, appends the router model’s response to the message history and helps in maintaining context across multiple turns.</p><h4>Router</h4><p>The router model determines <strong>which tool or agent should handle a user request</strong>.</p><pre>router_client = OpenAI(<br>    base_url=&#39;http://localhost:11434/v1&#39;,<br>    api_key=&#39;ollama&#39;,  # required, but unused<br>)</pre><p>The function that processes requests using the router:</p><pre>import copy<br><br>router_client = OpenAI(<br>    base_url = &#39;http://localhost:11434/v1&#39;,<br>    api_key=&#39;ollama&#39;, # required, but unused<br>)<br><br><br>def call_router(messages: list[dict[str, str]], use_tools=True):<br><br>  user_request = messages[-1][&quot;content&quot;]<br><br>  # retrieve similar query<br>  res = similarity_search(session, user_request)<br><br>  augmented_history = copy.deepcopy(messages)<br>  augmented_message = f&quot;User request: {user_request}\n&quot;<br><br>  if res:<br>    results = &quot;Retrieved results:\n&quot;<br>    for record in res:<br>        results += record.history + &quot;\n\n&quot;<br><br>    augmented_message += results<br><br>  augmented_history[-1][&quot;content&quot;] = augmented_message<br><br><br>  response = router_client.chat.completions.create(<br>    model=router_model,<br>    messages=augmented_history,<br>    tools=tools if use_tools else None<br>  )<br><br>  return response</pre><p>This function:</p><ol><li><strong>Processes the user’s request</strong> and augments it with retrieved information (if available).</li><li><strong>Passes the request to the router model</strong>, which decides whether to:</li></ol><ul><li>Handle the request directly.</li><li>Invoke a specialized agent via function calling.</li></ul><ol><li><strong>Uses function calling if enabled (</strong><strong>use_tools=True)</strong> to allow routing to the appropriate tool</li></ol><h3>Chatting with the Assistant</h3><p>Now that we have set up our router model and specialized agents, we can interact with the assistant. The router’s job is to analyze the chat history and user intent, determine which tool to use, and invoke the appropriate specialized model. If a request doesn’t require a specialized tool, the router will answer directly.</p><p>Below, we define a system prompt that guides the router on how to handle user requests.</p><h4>System Prompt Explanation</h4><p>The system prompt is crucial because it defines how the router should behave. It informs the model that it acts as a <strong>RAG routing model</strong>, meaning it should analyze both the user request and retrieved historical data to decide which tool to call.</p><p><strong>Key elements of the system prompt:</strong></p><ol><li><strong>Defining the Router’s Role: </strong>The router understands user intent based on chat history and available tools.</li><li><strong>Listing Available Tools: </strong>get_summarization used to summarize a paragraph,get_topics used to extract topics from a paragraph.</li><li><strong>Guidelines for Answering: i</strong>f the request <strong>matches</strong> a tool, call the tool. If the request <strong>does not</strong> require a tool, respond directly.</li><li><strong>How User Messages Are Structured: </strong>The user request is formatted as:</li></ol><ul><li>User request: -&gt; actual user message</li><li>Retrieved results: -&gt; list of similar requests retrieved from a database</li></ul><p><strong>Code: Interacting with the Assistant</strong></p><p>We create a conversation history and send a summarization request.</p><pre>sys_prompt = &quot;&quot;&quot;<br>You are a RAG routing model. Your role is to understand the chat history and user intent and use available tools to answer the questions.<br>Your available tools are:<br>- get_summarization: use it to summarize a user paragraph.<br>- get_topics: use it to extract the topics from a user paragraph.<br><br>For all other requests you can answer directly.<br><br>User messages will be provided to you in the form of:<br>&#39;User request: -&gt; actual user message&#39;<br>&#39;Retrieved results: -&gt; list of similar requests retrieved from a database that you can use to understand which tool to call&#39;<br>&quot;&quot;&quot;<br><br>messages = [<br>  {<br>      &quot;role&quot;: &quot;system&quot;,<br>      &quot;content&quot;: sys_prompt<br>  },<br>  {<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;content&quot;: &quot;Hi, can you summarize this paragraph? The red glow of tail lights indicating another long drive home from work after an even longer 24-hour shift at the hospital. The shift hadn’t been horrible but the constant stream of patients entering the ER meant there was no downtime. She had some of the “regulars” in tonight with new ailments they were sure were going to kill them. It’s amazing what a couple of Tylenol and a physical exam from the doctor did to eliminate their pain, nausea, headache, or whatever other mild symptoms they had. Sometimes she wondered if all they really needed was some interaction with others and a bit of the individual attention they received from the nurses.&quot;<br>  }<br>]<br><br>response = call_router(messages)<br>print(response)</pre><p>We obtain as response:</p><pre>ChatCompletion(id=&#39;chatcmpl-793&#39;, choices=[Choice(finish_reason=&#39;tool_calls&#39;, index=0, logprobs=None, message=ChatCompletionMessage(content=&#39;&#39;, refusal=None, role=&#39;assistant&#39;, audio=None, function_call=None, tool_calls=[ChatCompletionMessageToolCall(id=&#39;call_i71ihvtb&#39;, function=Function(arguments=&#39;{}&#39;, name=&#39;get_summarization&#39;), type=&#39;function&#39;, index=0)]))], created=1742753707, model=&#39;llama3.2:3b&#39;, object=&#39;chat.completion&#39;, service_tier=None, system_fingerprint=&#39;fp_ollama&#39;, usage=CompletionUsage(completion_tokens=15, prompt_tokens=1222, total_tokens=1237, completion_tokens_details=None, prompt_tokens_details=None))</pre><p>When analyzing the response, we observe that the LLM correctly calls the get_summarization tool. We now execute the tool call.</p><pre>fun_call_result = execute_function_call(response, messages)</pre><p>Analyzign the result of the function call we obtain:</p><pre>calling summarization model<br>[{&#39;role&#39;: &#39;system&#39;,<br>  &#39;content&#39;: &quot;\nYou are a RAG routing model. Your role is to understand the chat history and user intent and use available tools to answer the questions.\nYour available tools are:\n- get_summarization: use it to summarize a user paragraph.\n- get_topics: use it to extract the topics from a user paragraph.\n\nFor all other requests you can answer directly.\n\nUser messages will be provided to you in the form of:\n&#39;User request: -&gt; actual user message&#39;\n&#39;Retrieved results: -&gt; list of similar requests retrieved from a database that you can use to understand which tool to call\n&quot;},<br> {&#39;role&#39;: &#39;user&#39;,<br>  &#39;content&#39;: &#39;Hi, can you summarize this paragraph? The red glow of tail lights indicating another long drive home from work after an even longer 24-hour shift at the hospital. The shift hadn’t been horrible but the constant stream of patients entering the ER meant there was no downtime. She had some of the “regulars” in tonight with new ailments they were sure were going to kill them. It’s amazing what a couple of Tylenol and a physical exam from the doctor did to eliminate their pain, nausea, headache, or whatever other mild symptoms they had. Sometimes she wondered if all they really needed was some interaction with others and a bit of the individual attention they received from the nurses.&#39;},<br> {&#39;content&#39;: &#39;&#39;,<br>  &#39;refusal&#39;: None,<br>  &#39;role&#39;: &#39;assistant&#39;,<br>  &#39;audio&#39;: None,<br>  &#39;function_call&#39;: None,<br>  &#39;tool_calls&#39;: [{&#39;id&#39;: &#39;call_i71ihvtb&#39;,<br>    &#39;function&#39;: {&#39;arguments&#39;: &#39;{}&#39;, &#39;name&#39;: &#39;get_summarization&#39;},<br>    &#39;type&#39;: &#39;function&#39;,<br>    &#39;index&#39;: 0}]},<br> {&#39;role&#39;: &#39;tool&#39;,<br>  &#39;content&#39;: &#39;{&quot;result&quot;: &quot;A nurse worked two shifts in the hospital due to constant patient flow, leaving her little time for rest or downtime. She dealt with \\&quot;regulars\\&quot; who seemed severe, but were often treated with relatively simple medications, leading her to wonder if some patients simply needed human interaction and care instead of urgent treatment.&quot;}&#39;,<br>  &#39;tool_call_id&#39;: &#39;call_i71ihvtb&#39;}]</pre><p>As you can see from the last message, actually we have a summarization of the paragraph computed by the summarization agent. So pass it back to the router.</p><pre>response = call_router(fun_call_result, use_tools=False)<br>res = build_router_history(messages, response)</pre><p>Which will answer:</p><pre>The nurse worked two long shifts in the hospital due to constant patient flow, leaving her little time for rest or downtime. She dealt with &quot;regulars&quot; who seemed severe, but were often treated with relatively simple medications, leading her to wonder if some patients simply needed human interaction and care instead of urgent treatment.</pre><p>Now, we ask the assistant to extract topics from the first message.</p><pre>messages.append({<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;content&quot;: &quot;Now can you extract topics from the paragraph that I sent you on the first message?&quot;<br>  }<br>)<br><br>response = call_router(messages)<br>print(response)</pre><p>Again, we analyze the response and see that the router correctly calls the get_topics tool.</p><pre>ChatCompletion(id=&#39;chatcmpl-648&#39;, choices=[Choice(finish_reason=&#39;tool_calls&#39;, index=0, logprobs=None, message=ChatCompletionMessage(content=&#39;&#39;, refusal=None, role=&#39;assistant&#39;, audio=None, function_call=None, tool_calls=[ChatCompletionMessageToolCall(id=&#39;call_ipcwovno&#39;, function=Function(arguments=&#39;{&quot;$&quot;:&quot;[]&quot;}&#39;, name=&#39;get_topics&#39;), type=&#39;function&#39;, index=0)]))], created=1742753722, model=&#39;llama3.2:3b&#39;, object=&#39;chat.completion&#39;, service_tier=None, system_fingerprint=&#39;fp_ollama&#39;, usage=CompletionUsage(completion_tokens=17, prompt_tokens=1155, total_tokens=1172, completion_tokens_details=None, prompt_tokens_details=None))</pre><p>We then execute the function call.</p><pre>fun_call_result = execute_function_call(response, messages)<br>response = call_router(fun_call_result, use_tools=False)<br>res = build_router_history(messages, response)</pre><p>At this point, the topics are correctly extracted.</p><pre>Here are the topics extracted from the original paragraph:<br><br>1. Nursing<br>2. Hospital shift<br>3. Patient care<br>4. ER (Emergency Room) environment<br>5. Human interaction<br>6. Physical and mental well-being of patients</pre><h3>Conclusion</h3><p>In this section, we demonstrated how a retrieval-augmented generation (RAG) system can serve as a <strong>semantic router</strong>, effectively directing user queries to the appropriate specialized models. By defining a <strong>clear system prompt</strong> and specifying <strong>available tools</strong>, we enabled the router to make informed decisions on whether to respond directly or invoke a tool.</p><p>We tested this by:</p><ul><li>Requesting a <strong>summary</strong> of a paragraph, which correctly triggered the get_summarization tool.</li><li>Asking for <strong>topics</strong> from the same paragraph, which prompted the system to call the get_topics tool.</li></ul><h4>Impact of the System Prompt and Tool Definitions</h4><p>The accuracy of the router’s decisions depends significantly on how the system prompt is written and how the tools are defined. A well-structured prompt ensures that the model understands when to call a tool and which tool to choose. The more clearly each tool is described, the less ambiguity there is, reducing the risk of incorrect function calls.</p><p>By modifying the system prompt or adding more tools, we can extend the router’s capabilities to handle additional tasks such as <strong>text classification, sentiment analysis, or translation</strong>. This flexibility makes the system highly adaptable to different applications.</p><h4>Using Different Models for Different Tasks</h4><p>One of the strengths of this approach is its <strong>modular design</strong>, which allows different models to handle different tasks. The router itself can be implemented using a general-purpose language model, while specialized tasks like summarization or topic extraction can be handled by models optimized for those specific domains. This flexibility allows for better trade-offs between accuracy, efficiency, and cost.</p><h4>Advantages of Using RAG as a Semantic Router</h4><p>A RAG-based router provides several key benefits over traditional rule-based approaches:</p><ul><li><strong>Better intent understanding</strong>: The system can infer user intent by analyzing both the chat history and retrieved examples.</li><li><strong>Context-aware decision-making</strong>: Retrieved past interactions help refine tool selection and improve response quality.</li><li><strong>Dynamic adaptability</strong>: The system can evolve by integrating new tools and models as requirements change.</li></ul><p>By leveraging <strong>retrieval-augmented generation (RAG)</strong> with a structured routing mechanism, we enhance the <strong>efficiency, accuracy, and flexibility</strong> of AI-driven assistants. This approach allows language models to move beyond generic responses and provide <strong>task-specific, context-aware interactions</strong>, making them more reliable and effective for real-world applications.</p><p>If you liked the article and want to help me write better and better articles, don’t forget to follow me and contribute a tip by clicking this <a href="https://www.paypal.com/donate/?hosted_button_id=3UNX7F6AFLG96">link</a> or the buttons below :) Thank you very much!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b53dd8fae7fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PDF to Markdown with VLMs: LLama 3.2 Vision and getomni-ai/zerox]]></title>
            <link>https://medium.com/@giacomo__95/vlms-for-pdf-to-markdown-table-conversion-llama-3-2-vision-llava-and-getomni-ai-zerox-00b167cbe6a1?source=rss-dd74b6a2cd57------2</link>
            <guid isPermaLink="false">https://medium.com/p/00b167cbe6a1</guid>
            <category><![CDATA[conversion]]></category>
            <category><![CDATA[vision-language-model]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[markdown]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Giacomo Carfì]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 21:50:38 GMT</pubDate>
            <atom:updated>2025-02-04T06:17:38.030Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0PVHGL3Vpp1iEmbWnPY2g.png" /><figcaption>Comparison of a table in a PDF alongside its converted Markdown representation. The left shows the original table, while the right displays the table after conversion, highlighting the formatting and structure in Markdown</figcaption></figure><h3>Introduction</h3><p>In the age of Retrieval-Augmented Generation (RAG) systems, where accurate and well-structured data is essential, converting PDFs to Markdown has become a crucial task. Markdown, with its lightweight and human-readable format, is often the backbone for organizing information that powers these systems. While several libraries excel at extracting plain text from PDFs and converting it into Markdown, extracting tables — especially those with complex layouts — remains a significant challenge.</p><p>Tables often contain rich, structured data, but their intricate formatting makes them difficult to process accurately with traditional text-based tools. Misinterpretation of table structures can lead to distorted information, which, in turn, impacts downstream applications like RAG systems.</p><p>This is where Vision Language Models (VLMs) step in as a game-changer. By treating a PDF as an image and leveraging the advanced language capabilities of Large Language Models (LLMs), VLMs can comprehend both the visual structure and the semantic meaning of tables. They enable a seamless conversion of even the most complex tables into clean and structured Markdown.</p><p>To demonstrate the potential of VLMs in this domain, I created a Google Colab notebook showcasing how to use state-of-the-art vision models like LLama 3.2 Vision and LLaVA, in combination with the <a href="https://github.com/getomni-ai/zerox">getomni-ai/zerox</a> library. This powerful workflow provides an effective solution for extracting and converting tables from PDFs into well-formatted Markdown, ensuring that no data is lost in translation.</p><p>In this article, I’ll guide you step by step through the process, highlighting how these tools can revolutionize PDF-to-Markdown table conversion.</p><p>Before we begin, I’d like to remind you that the full notebook can be found in my <a href="https://github.com/Sopralapanca/medium-articles/blob/main/RAG-file-processing/%5BMedium%5Dpdf_to_markdown_VLMs.ipynb">GitHub</a> repository. If you enjoyed this article, please give it a clap, comment with your suggestions, and consider <a href="https://medium.com/m/signin?actionUrl=https%3A%2F%2Fmedium.com%2F_%2Fsubscribe%2Fuser%2Fdd74b6a2cd57&amp;operation=register&amp;redirect=https%3A%2F%2Fmedium.com%2F%40giacomo__95%2Fmarkitdown-ollama-and-llava-markdown-conversion-with-microsofts-markitdown-and-ollama-s-llm-2141bba9d183&amp;user=Giacomo+Carf%C3%AC&amp;userId=dd74b6a2cd57">following</a> me to support my work!</p><p><strong>Keywords: </strong>Vision Language Models, VLMs, LLama 3.2 Vision, LLaVA, PDF to Markdown conversion, PDF table extraction, Markdown formatting, getomni-ai/zerox, Ollama, Complex table layouts, Vision-based PDF tools, Markdown for RAG systems, Table extraction with VLMs, PDF to Markdown</p><h3>Initial Setup</h3><p>Before diving into the implementation, it’s important to ensure that we have enough computational resources to run Vision Language Models efficiently. LLama 3.2 Vision requires at least <strong>12GB of VRAM</strong>, so leveraging Google Colab’s <strong>free GPU</strong> is a great option.</p><p>To enable GPU in Google Colab, follow these steps:</p><ol><li>Click on <strong>Runtime</strong> in the menu bar.</li><li>Select <strong>Change runtime type</strong>.</li><li>In the dropdown menu, set <strong>Hardware accelerator</strong> to <strong>GPU</strong>.</li><li>Click <strong>Save</strong> to apply the changes.</li></ol><p>Now, your Colab environment is equipped with a <strong>Tesla T4 (16GB VRAM) or an equivalent GPU</strong>, making it capable of running large vision models smoothly.</p><p>We are ready to start, we need to install the required dependencies, set up Ollama, and download the necessary Vision Language Models.</p><h4>1. Install System Dependencies</h4><p>We need poppler-utils, which is required for processing PDFs:</p><pre>!sudo apt-get install poppler-utils</pre><h4>2. Install and Start Ollama</h4><p>Ollama is used to serve Vision Language Models locally. We first install it and then start the server in the background:</p><pre>!curl https://ollama.ai/install.sh | sh<br>!ollama serve &gt; server.log 2&gt;&amp;1 &amp;</pre><h4>3. Download Vision Models</h4><p>We will use <strong>LLaVA (7B)</strong> and <strong>LLama 3.2 Vision</strong> models for extracting tables from PDFs:</p><pre>llava_model = &quot;llava:7b&quot;<br>llama_vision_model = &quot;llama3.2-vision&quot;<br><br>!ollama pull {llava_model}<br>!ollama pull {llama_vision_model}</pre><h4>4. Install Required Python Packages</h4><p>We will use py-zerox, a simple yet powerful library that leverages Vision Language Models to extract structured information from documents. Instead of treating PDFs as plain text, py-zerox converts them into images and processes them using AI models to generate Markdown. This approach is particularly effective for handling complex layouts, including tables and charts.</p><p>We also install additional dependencies:</p><ul><li><strong>litellm</strong>: A lightweight wrapper for various LLM APIs.</li><li><strong>nest_asyncio</strong>: Allows running asynchronous tasks within Jupyter notebooks.</li><li><strong>camelot-py</strong>: A popular library for table extraction from PDFs for a base reference.</li></ul><pre>!pip install py-zerox litellm==1.57.4 nest_asyncio camelot-py</pre><p>If you liked the article and want to help me write better and better articles, don’t forget to follow me and contribute a tip by clicking this <a href="https://www.paypal.com/donate/?hosted_button_id=3UNX7F6AFLG96">link</a> or the buttons below :) Thank you very much!</p><h4>5. Download the Sample PDF</h4><p>For demonstration, we’ll use a <strong>sample PDF</strong> containing complex tables:</p><pre>!wget -O table.pdf https://ada.nv.gov/uploadedFiles/adanewnvgov/content/home/features/ADAClasses/Merged%20Cell%20Table.pdf</pre><h3>Extracting Tables Using Camelot (Baseline)</h3><p>Before leveraging Vision Language Models, let’s establish a <strong>baseline</strong> using <strong>Camelot</strong>, a powerful Python library designed specifically for table extraction from PDFs. <strong>Camelot</strong> works best with PDFs that contain <strong>text-based tables</strong> (i.e., tables that are not embedded as images). It parses the PDF and detects table structures using heuristic and rule-based approaches.</p><h4>How Camelot Works</h4><ol><li><strong>Reads a PDF file</strong> and identifies tables based on the underlying text structure.</li><li><strong>Extracts tabular data</strong> and converts it into a structured format (DataFrame).</li><li><strong>Supports multiple extraction modes</strong> (e.g., lattice-based for well-defined tables and stream-based for free-form tables).</li><li><strong>Output tables in different formats</strong>, including Pandas DataFrames, CSV, and Markdown.</li></ol><p>Let’s use Camelot to extract tables from our <strong>sample PDF</strong> and print them in Markdown format:</p><pre>import camelot<br><br># Read the PDF and extract tables<br>tables = camelot.read_pdf(&#39;/content/table.pdf&#39;)<br><br># Convert and print tables in Markdown format<br>for table in tables:<br>    print(table.df.to_markdown())</pre><h4>Output of Camelot</h4><p>Here is the output generated by Camelot when extracting tables from our <strong>sample PDF</strong>:</p><pre>|    | 0                | 1                | 2             |<br>|---:|:-----------------|:-----------------|:--------------|<br>|  0 | Health Insurance |                  |               |<br>|  1 | PPO              | Office Copay     | $10.00        |<br>|  2 |                  | O                | $1500 Single  |<br>|    |                  | ut- of -pocket   | $2750 Family  |<br>|    |                  | Maximum          |               |<br>|  3 |                  | F                | $             |<br>|    |                  | amily            | 350 monthly   |<br>|  4 | HMO              | O                | $             |<br>|    |                  | ffice Copay      | 5.00 Single   |<br>|  5 |                  | O                | $1000 Single  |<br>|    |                  | ut - of - pocket | $2250 Family  |<br>|  6 |                  | F                | $             |<br>|    |                  | amily            | 250 Monthly   |</pre><p>As we can see, the extracted table is <strong>not well-structured</strong> and contains multiple issues:</p><ul><li><strong>Misaligned Content:</strong></li><li>The column headers are missing, making it hard to interpret the data.</li><li>“Health Insurance” should be the <strong>title of the table</strong>, but it appears as part of the extracted content.</li><li><strong>PPO and HMO</strong> categories are not properly aligned under the correct columns.</li><li><strong>Incorrectly Parsed Words:</strong></li><li>Words such as &quot;o ut- of -pocket&quot; and &quot;F amily&quot; are split incorrectly, leading to <strong>misspelled words</strong>.</li><li>“Office Copay” for HMO appears split across different rows (&quot;O ffice Copay&quot;).</li></ul><p>These errors make it difficult to use the extracted table for downstream tasks like <strong>RAG </strong>systems, where well-formatted Markdown tables are crucial.</p><h4>Limitations of Camelot</h4><ul><li><strong>Does not work well with scanned PDFs or image-based tables</strong>.</li><li><strong>Struggles with complex layouts</strong> like merged cells, multi-line rows, or irregular table structures.</li><li><strong>May require fine-tuning</strong> of parameters depending on the PDF structure.</li></ul><p>Since many PDFs contain tables as <strong>images</strong> rather than selectable text, Camelot might fail to extract them properly. This is where <strong>Vision Language Models</strong> can help by analyzing the document visually and generating structured Markdown output.</p><p>In the next section, we’ll explore how <strong>LLama 3.2 Vision and LLaVA </strong>can extract tables more effectively using py-zerox.</p><h3>Implementing Vision Language Models for Table Extraction</h3><p>Since <strong>py-zerox</strong> uses litellm for model inference, we need to apply a small <strong>fix</strong> to ensure compatibility. The issue described in <a href="https://github.com/getomni-ai/zerox/issues/106">getomni-ai/zerox#106</a> highlights a problem where litellm requires a specific override to function correctly with local models like <strong>Ollama</strong>.</p><p>By default, litellm does not correctly detect <strong>vision models</strong> when running locally via <strong>Ollama</strong>. This leads to errors when passing images to models like <strong>LLaVA and LLama 3.2 Vision</strong>.</p><p>To address this, we:</p><ol><li><strong>Modify how </strong><strong>litellm determines vision models</strong> – We create custom functions to check if a model supports vision, based on offline and online checks.</li><li><strong>Override the default prompt processing function</strong> — ollama_pt is modified to properly structure the input for models, ensuring images and text are handled correctly.</li><li><strong>Bypass unnecessary API key validation</strong> — This prevents errors related to missing API keys when running local models.</li></ol><h4>Applying the Fix</h4><p>Run the following code before using py-zerox with <strong>Ollama Vision Models</strong>:</p><pre>import litellm.litellm_core_utils.prompt_templates.factory as factory<br>import litellm.llms.ollama.completion.transformation as transformation<br>import litellm<br><br>import requests<br><br>def ollama_query_online_is_vision_model(model:str):<br>    if &quot;/&quot; not in model:<br>        model_fullname = f&quot;library/{model}&quot;<br>    else:<br>        model_fullname = model<br>    url = f&quot;https://ollama.com/{model_fullname}&quot;<br>    response = requests.get(url).text<br>    ret = &quot;&gt;vision&lt;/span&gt;&quot; in response<br>    return ret<br><br>def ollama_query_offline_is_vision_model(model:str):<br>    known_vision_models = [&#39;moondream&#39;, &#39;jyan1/paligemma-mix-224&#39;,&#39;benzie/llava-phi-3&#39; , &#39;mskimomadto/chat-gph-vision&#39;,  &#39;knoopx/llava-phi-2&#39;, &#39;llava&#39;]<br>    for it in known_vision_models:<br>        if it in model:<br>            return True<br>    if &quot;vision&quot; in model:<br>        return True<br>    if model.lower().endswith(&quot;vlm&quot;):<br>        return True<br>    if model.lower().endswith(&#39;v&#39;):<br>        return True<br><br>def ollama_is_vision_model(model:str, online:bool = False):<br>    factory.verbose_logger.info(&quot;Checking if model is vision model: {}&quot;.format(model))<br>    factory.verbose_logger.info(&quot;Checking method online: {}&quot;.format(str(online)))<br>    if online:<br>        ret = ollama_query_online_is_vision_model(model)<br>    else:<br>        ret = ollama_query_offline_is_vision_model(model)<br>    factory.verbose_logger.info(&quot;Checking vision support result: {}&quot;.format(str(ret)))<br>    return ret<br><br>def ollama_pt(<br>    model, messages<br>) -&gt; factory.Union[<br>    str, factory.OllamaVisionModelObject<br>]:  # https://github.com/ollama/ollama/blob/af4cf55884ac54b9e637cd71dadfe9b7a5685877/docs/modelfile.md#template<br>    if &quot;instruct&quot; in model:<br>        prompt = factory.custom_prompt(<br>            role_dict={<br>                &quot;system&quot;: {&quot;pre_message&quot;: &quot;### System:\n&quot;, &quot;post_message&quot;: &quot;\n&quot;},<br>                &quot;user&quot;: {<br>                    &quot;pre_message&quot;: &quot;### User:\n&quot;,<br>                    &quot;post_message&quot;: &quot;\n&quot;,<br>                },<br>                &quot;assistant&quot;: {<br>                    &quot;pre_message&quot;: &quot;### Response:\n&quot;,<br>                    &quot;post_message&quot;: &quot;\n&quot;,<br>                },<br>            },<br>            final_prompt_value=&quot;### Response:&quot;,<br>            messages=messages,<br>        )<br>    elif ollama_is_vision_model(model):<br>        prompt = &quot;&quot;<br>        images = []<br>        for message in messages:<br>            if isinstance(message[&quot;content&quot;], str):<br>                prompt += message[&quot;content&quot;]<br>            elif isinstance(message[&quot;content&quot;], list):<br>                # see https://docs.litellm.ai/docs/providers/openai#openai-vision-models<br>                for element in message[&quot;content&quot;]:<br>                    if isinstance(element, dict):<br>                        if element[&quot;type&quot;] == &quot;text&quot;:<br>                            prompt += element[&quot;text&quot;]<br>                        elif element[&quot;type&quot;] == &quot;image_url&quot;:<br>                            base64_image = factory.convert_to_ollama_image(<br>                                element[&quot;image_url&quot;][&quot;url&quot;]<br>                            )<br>                            images.append(base64_image)<br>        return {&quot;prompt&quot;: prompt, &quot;images&quot;: images}<br>    else:<br>        prompt = &quot;&quot;<br>        for message in messages:<br>            role = message[&quot;role&quot;]<br>            content = message.get(&quot;content&quot;, &quot;&quot;)<br><br>            if &quot;tool_calls&quot; in message:<br>                tool_calls = []<br><br>                for call in message[&quot;tool_calls&quot;]:<br>                    call_id: str = call[&quot;id&quot;]<br>                    function_name: str = call[&quot;function&quot;][&quot;name&quot;]<br>                    arguments = factory.json.loads(call[&quot;function&quot;][&quot;arguments&quot;])<br><br>                    tool_calls.append(<br>                        {<br>                            &quot;id&quot;: call_id,<br>                            &quot;type&quot;: &quot;function&quot;,<br>                            &quot;function&quot;: {&quot;name&quot;: function_name, &quot;arguments&quot;: arguments},<br>                        }<br>                    )<br><br>                prompt += f&quot;### Assistant:\nTool Calls: {factory.json.dumps(tool_calls, indent=2)}\n\n&quot;<br><br>            elif &quot;tool_call_id&quot; in message:<br>                prompt += f&quot;### User:\n{message[&#39;content&#39;]}\n\n&quot;<br><br>            elif content:<br>                prompt += f&quot;### {role.capitalize()}:\n{content}\n\n&quot;<br><br>    return prompt<br><br>del factory.ollama_pt<br>del transformation.ollama_pt<br>del litellm.main.ollama_pt<br><br>setattr(factory, &quot;ollama_pt&quot;, ollama_pt)<br>setattr(transformation, &quot;ollama_pt&quot;, ollama_pt)<br>setattr(litellm.main, &quot;ollama_pt&quot;, ollama_pt)</pre><pre>import litellm<br><br>litellm.supports_vision = lambda *args, **kwargs: True<br>litellm.check_valid_key = lambda *args, **kwargs: True</pre><p>After applying this fix, <strong>py-zerox will correctly process PDFs using vision models</strong>, allowing seamless table extraction and Markdown conversion. 🚀</p><h4>Setting Up py-zerox with Ollama Vision Models</h4><p>To process PDFs effectively with py-zerox, we need to import the required libraries and configure Ollama&#39;s <strong>API base URL</strong>. Since Ollama runs locally, we set:</p><pre>os.environ[&#39;OLLAMA_API_BASE&#39;] = &quot;http://localhost:11434&quot;</pre><p>This ensures py-zerox correctly routes requests to our locally hosted <strong>vision model</strong>.</p><p>Since py-zerox relies on <strong>async functions</strong>, running it in <strong>Google Colab</strong> requires a fix.<br>Colab&#39;s environment <strong>already runs an event loop</strong>, which conflicts with asyncio.run().<br>To prevent this issue, we use nest_asyncio.apply(), which allows <strong>nested event loops</strong> within notebooks. So the code of this part is this:</p><pre>from pyzerox import zerox<br>import os<br>import json<br>import asyncio<br>import nest_asyncio<br><br># Enable nested asyncio in Google Colab<br>nest_asyncio.apply()  # Prevents runtime errors due to Colab&#39;s existing event loop<br><br># Set Ollama API base URL for using a vision model<br>os.environ[&#39;OLLAMA_API_BASE&#39;] = &quot;http://localhost:11434&quot;<br><br># Define paths<br>pdf_path = &quot;/content/table.pdf&quot;  # Path to input PDF<br>output_path = &quot;./&quot;  # Path to save extracted content<br><br># Additional keyword arguments for processing<br>kwargs = {}</pre><p>To interact with py-zerox and extract content from a PDF using an <strong>Ollama Vision Model</strong>, we define the call_model() function.</p><pre>async def call_model(model, file, custom_system_prompt, kwargs):<br>    select_pages = None  # None = all pages, or specify a page number / list of numbers<br>    model = f&quot;ollama/{model}&quot;  # Ensure correct model format<br><br>    # Run zerox asynchronously<br>    result = await zerox(<br>        file_path=pdf_path,<br>        model=model,<br>        output_dir=output_path,<br>        custom_system_prompt=custom_system_prompt,<br>        select_pages=select_pages,<br>        validate_vision_capability=False,<br>        **kwargs<br>    )<br><br>    return result.pages[0].content  # Return extracted content from the first page</pre><h3>First Try: Using LLaMA Vision Model Without Customizing the System Prompt</h3><p>In this first attempt, we used the <strong>LLaMA Vision Model</strong> to extract content from the provided PDF without customizing the system prompt. By leveraging the vision capabilities of the model, the process involves sending the document directly to the model for analysis.</p><h4>Code:</h4><pre>result = asyncio.run(call_model(model=llama_vision_model, file=pdf_path, custom_system_prompt=None, kwargs=kwargs))<br>print(result)</pre><h4>Output:</h4><pre>| **Health Insurance** | **PPO** |<br>| --- | --- |<br>| **Office Copay** | $10.00 |<br>| **Out-of-pocket Maximum** | Single: $1500, Family: $2750 |<br>| **Family** | Monthly: $350 |<br><br>| **HMO** |<br>| --- |<br>| **Office Copay** | $5.00 |<br>| **Out-of-pocket Maximum** | Single: $1000, Family: $2250 |<br>| **Family** | Monthly: $250 |</pre><h4>Analysis of Results:</h4><ul><li>Unlike Camelot, which struggles with alignment and misinterpretation of table content, the <strong>LLaMA Vision Model</strong> extracts a more semantically accurate representation of the data.</li><li>For example, we see a clear differentiation between the <strong>PPO</strong> and <strong>HMO</strong> sections, which Camelot had difficulty separating due to misalignment.</li><li>Key terms like “Office Copay,” “Out-of-pocket Maximum,” and “Family” are properly grouped, showing the model’s understanding of the table structure and contents.</li></ul><p>Please note that the model mistakenly includes <strong>“Health Insurance”</strong> as part of the table, while it should actually be the title or header for the table. This small issue suggests that the model might not be fully aware of the distinction between a title and table content. A more customized system prompt could help address this by guiding the model to treat such titles separately.</p><h3>Second Try: Customizing the System Prompt for More Reliable Information</h3><p>In this second attempt, we customized the system prompt to guide the model to extract tables more accurately. This customization aims to ensure that the vision model understands the document’s structure more effectively, especially for documents with complex or unusual layouts.</p><h4>Custom System Prompt:</h4><pre>custom_system_prompt = &quot;&quot;&quot;For the below PDF page, extract tables and text in markdown format. You will extract multiple tables. If the tables have an unusual or complex layout, you are allowed to reorganize them, but you must ensure that all information from the original tables is preserved. Return only the markdown with no explanation text. Tables may be empty, do not exclude them. Do not exclude any content from the page. Do not write anything else. \n\n&quot;&quot;&quot;</pre><h4>Code:</h4><pre>result = asyncio.run(call_model(model=llama_vision_model, file=pdf_path, custom_system_prompt=custom_system_prompt, kwargs=kwargs))<br>print(result)</pre><h4>Output:</h4><p>Here is an extract of the resulting tables after applying the custom system prompt:</p><pre>## Table 1: Health Insurance PPO and HMO Plans<br><br>| **Health Insurance** | **PPO** | **HMO** |<br>| --- | --- | --- |<br>| **Office Copay** | $10.00 | $5.00 |<br>| **Out-of-Pocket Maximum** | $1500 | $1000 |<br>| **Family Plan** | $2750 | $2250 |<br><br>## Table 2: Insurance Plans<br><br>| **Insurance Plan** | **Description** |<br>| --- | --- |<br>| **PPO** | Preferred Provider Organization |<br>| **HMO** | Health Maintenance Organization |</pre><h4>Analysis of Results:</h4><ul><li>The custom prompt has allowed the model to not only extract the relevant tables but also to reorganize them where necessary, ensuring the extracted data is structured more clearly and semantically.</li><li>In this case, we see two distinct tables: one for the <strong>PPO and HMO Plans</strong> and another describing the types of <strong>Insurance Plans</strong>. This is a significant improvement over the unstructured output from the previous attempt.</li><li>However, the extraction of <strong>Out-of-Pocket Maximum</strong> values like <em>Single: $1500, Family: $2750</em> still suffers from a formatting issue. Instead of being placed on a single line under the relevant columns, the values are split across multiple lines, which is less ideal. The model should ideally place these values in a single line for clarity, but it seems that the system prompt was not enough to fully address this layout nuance.</li></ul><h3>Third Try: Using LLaVA 7B Without Customizing the System Prompt</h3><p>In this attempt, we try using the <strong>LLaVA 7B model</strong> without providing any custom system prompt, allowing the model to extract tables and text based solely on its default behavior.</p><h4>Code:</h4><pre>result = asyncio.run(call_model(model=llava_model, file=pdf_path, custom_system_prompt=None, kwargs=kwargs))<br>print(result)</pre><h4>Output:</h4><p>Here is an extract of the result:</p><pre># Chapter 7: Business Intelligence Dashboards - Power BI<br>The purpose of this chapter is to provide an introduction to using Microsoft Power BI for creating interactive business intelligence dashboards.<br>This is a **Chapter Title**.<br><br>## Table of Contents<br>1. Overview<br>2. Installation Process<br>3. Data Source Examples<br>4. Dashboard Design Guidelines<br>5. Creating Interactive Elements<br>6. Publishing and Sharing Dashboards<br><br>```markdown<br>This chapter provides an overview of creating interactive business intelligence dashboards using Microsoft Power BI.<br>```<br><br>It covers the following topics:</pre><h4>Analysis of Results:</h4><ul><li>Unlike previous attempts where some structure was maintained, LLaVA 7B here has completely <strong>failed to extract the table</strong>. The output seems to have <strong>hallucinated content</strong> that is entirely unrelated to the original PDF, with a focus on <strong>chapter titles</strong> and a <strong>table of contents</strong>.</li><li>There are no tables extracted from the document at all. Instead of structured tabular data, we receive <strong>text-based content</strong> that seems to be a complete misinterpretation of the content in the PDF.</li><li>This highlights the potential limitations of using large vision models like LLaVA 7B without any guidance or system prompts. Although the model is generally good at understanding context and structure, it is not capable of accurately identifying or extracting complex tabular data without more explicit instructions.</li><li>Additionally, we can see that LLaVA has inserted <strong>irrelevant content</strong> such as the <strong>Chapter Title</strong> and <strong>table of contents</strong>, which further illustrates the lack of control over the output generation.</li></ul><h3>Fourth Try: Using LLaVA 7B with Custom Prompt</h3><p>In this fourth attempt, we once again used the LLaVA 7B model, but this time with a <strong>custom system prompt</strong>. The goal was to see if providing more specific instructions about table extraction would yield better results.</p><h4>Code:</h4><pre>custom_system_prompt = &quot;&quot;&quot;<br>You are a model tasked with converting PDFs into Markdown format. Your main goal is to extract and convert all the tables present in the PDF into Markdown tables. If the tables have an unusual or complex layout, you are allowed to reorganize them, but you must ensure that all information from the original tables is preserved. Your output should be the complete Markdown representation of the PDF, with a particular emphasis on accurately converting the tables. Do not include any comments, explanations, or additional text—only the Markdown content of the PDF.<br>&quot;&quot;&quot;<br><br>result = asyncio.run(call_model(model=llava_model, file=pdf_path, custom_system_prompt=custom_system_prompt, kwargs=kwargs))<br>print(result)</pre><h4>Output:</h4><p>Here is an extract of the resulting text from LLaVA with the custom system prompt:</p><pre>| Item                         | Quantity   |<br>|--------------------------------|--------------|<br>| Office Supplies                    | 1           |<br>| File Cabinet                     | 1           |<br>| Worktable                          | 2           |<br>| Chair                               | 1           |<br>| Coffee Maker                      | 1           |<br>| Printer/Scanner                       | 1           |<br>| Desk Lamp                           | 1           |<br>| Computer Monitor                   | 1           |<br>| Keyboard                              | 1           |<br>| Mouse                                 | 1           |</pre><h4>Analysis of Results:</h4><ul><li>Despite using a custom system prompt, LLaVA 7B has <strong>once again misinterpreted the content</strong> and hallucinated an unrelated table. The table shown in the output seems to be about office supplies, which doesn’t correspond to any content from the original PDF.</li><li>The table extracted is entirely <strong>irrelevant</strong> to the content of the PDF. This suggests that LLaVA 7B, even with explicit instructions, is still <strong>unable to focus on extracting relevant tables</strong> accurately. It seems to produce an <strong>office supply list</strong> instead of the desired tables from the original PDF.</li><li>The hallucination of unrelated content continues. This highlights a <strong>major limitation</strong> when using large language models like LLaVA without proper fine-tuning or specific adaptation to the task at hand.</li></ul><h3>Conclusion: Camelot vs Vision Models (LLama &amp; LLaVA)</h3><p>When choosing between <strong>Camelot</strong> and <strong>Vision Language Models (VLMs)</strong> like <strong>LLama</strong> and <strong>LLaVA</strong> for PDF table extraction, there are clear pros and cons to each approach.</p><h4>Camelot</h4><p><strong>Pros:</strong></p><ul><li><strong>Light and Fast</strong>: Camelot is an efficient tool specifically designed for <strong>table extraction</strong> from PDFs. It can process documents quickly and with minimal computational resources.</li><li><strong>Great for Simple Layouts</strong>: Camelot excels at extracting tables with straightforward layouts, such as those where rows and columns are clearly defined. It’s a perfect choice for documents with clean, well-organized tables.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Limited Handling of Complex Layouts</strong>: Camelot may struggle with PDFs containing complex or irregular table layouts. It can have difficulties when dealing with nested tables, multi-page tables, or cases where content is spread across various sections.</li></ul><h4>Vision Language Models (LLaMA &amp; LLaVA)</h4><p><strong>Pros:</strong></p><ul><li><strong>Handling Complex Layouts</strong>: VLMs like <strong>LLaMA</strong> and <strong>LLaVA</strong> are powerful tools that can handle more complex PDF layouts, such as documents with intricate formatting or multi-column structures. These models are capable of processing tables that don’t fit neatly into a grid, such as those with merged cells or inconsistent row and column lengths.</li><li><strong>Adaptability</strong>: Vision models can adapt to a variety of content and can, in theory, reorganize information from complex layouts while maintaining the original content.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Heavy Resource Requirements</strong>: VLMs are large models that demand substantial computational resources. Running these models requires <strong>powerful hardware</strong> and <strong>longer processing times</strong>, which might not be suitable for quick, on-the-fly PDF processing.</li><li><strong>Hallucination and Inaccuracy</strong>: As seen in the experiments, models like <strong>LLaVA</strong> can hallucinate irrelevant content or fail to extract tables accurately, especially when tasked with complex layouts. In many cases, they struggle with focus and precision, producing outputs that do not correspond to the expected results.</li></ul><p>If you liked the article and want to help me write better and better articles, don’t forget to follow me and contribute a tip by clicking this <a href="https://www.paypal.com/donate/?hosted_button_id=3UNX7F6AFLG96">link</a> or the buttons below :) Thank you very much!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00b167cbe6a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using LLMs for Semantic Routing with Ollama and Qwen]]></title>
            <link>https://medium.com/@giacomo__95/using-llms-as-semantic-routers-for-efficient-task-specific-model-selection-example-with-ollama-and-326f15ab2feb?source=rss-dd74b6a2cd57------2</link>
            <guid isPermaLink="false">https://medium.com/p/326f15ab2feb</guid>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[semantic-routing]]></category>
            <category><![CDATA[semantic-router]]></category>
            <category><![CDATA[qwen2-5]]></category>
            <dc:creator><![CDATA[Giacomo Carfì]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 21:42:06 GMT</pubDate>
            <atom:updated>2025-01-11T21:20:39.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*zsl9uZT-rPDY22zZw41g5g.png" /><figcaption>Semantic Routing LLM architecture. Chat history goes through an LLM equipped with tools. The router can dispatch the history to other LLMs based on the context and the task that needs to be computed.</figcaption></figure><p>The growing variety of specialized large language models (LLMs) poses a challenge: how to direct specific tasks to the most capable model efficiently. Traditional systems rely on predefined rules or manual intervention, which can be inefficient and inflexible. A smarter solution is needed — one that dynamically evaluates the context and routes tasks to the right model automatically.</p><p>Before we begin, I’d like to remind you that the full notebook can be found in my <a href="https://github.com/Sopralapanca/medium-articles/blob/main/llm-routing/%5BMedium%5Dllm_semantic_routing_ollama.ipynb">GitHub</a> repository. If you enjoyed this article, please give it a clap, comment with your suggestions, and consider <a href="https://medium.com/m/signin?actionUrl=https%3A%2F%2Fmedium.com%2F_%2Fsubscribe%2Fuser%2Fdd74b6a2cd57&amp;operation=register&amp;redirect=https%3A%2F%2Fmedium.com%2F%40giacomo__95%2Fmarkitdown-ollama-and-llava-markdown-conversion-with-microsofts-markitdown-and-ollama-s-llm-2141bba9d183&amp;user=Giacomo+Carf%C3%AC&amp;userId=dd74b6a2cd57&amp;source=post_page-dd74b6a2cd57--byline--2141bba9d183---------------------post_header-----------">following</a> me to support my work!</p><p><strong>Keywords: </strong>Large Language Models (LLMs), Semantic Router, Semantic Routing LLM, Model Selection, Task-Specific AI, Function Calling, Ollama, Qwen, Multi-Model Workflow, Intelligent Routing, Dynamic Task Assignment, Specialized LLMs, Context-Aware AI,</p><h3>Introduction</h3><p>In the era of AI, we are often faced with the challenge of choosing the right model for a specific task. With the increasing number of specialized large language models (LLMs) trained for distinct applications — from sentiment analysis to code generation — deploying them efficiently has become a critical concern. While this specialization is a significant advantage, it also introduces a critical challenge: determining which model to use for a given task.</p><p>Traditional approaches to this problem typically rely on predefined rules or human intervention to match tasks with the appropriate models or pass all tasks to a single, general-purpose model. However, these methods have inherent limitations. Rule-based systems can be rigid, and unable to adapt to nuanced or unforeseen contexts. Human-driven selection processes, on the other hand, are time-consuming and prone to error, especially as the complexity and volume of tasks increase. Fundamentally, these approaches lack a clear and dynamic mechanism to understand the context of a given input and route it to the most suitable model.</p><p>Additionally, specialized models often vary in terms of cost — some are more computationally expensive than others. Without a mechanism to optimize the selection process, organizations risk unnecessary expenses while compromising performance.</p><p>To address this, I propose using an LLM as a <strong><em>semantic router</em></strong> — an intelligent system capable of analyzing the context of a message history and determining the most suitable specialized model for the task. By routing tasks to specialized agents designed to tackle specific challenges, this approach not only improves task accuracy but, depending on your configuration, can save you money by using smaller, less expensive models finetuned to a specific task. This method offers a more flexible, dynamic, and efficient solution for working with multiple specialized LLMs, helping organizations optimize their AI infrastructure. In this article, I will demonstrate how this semantic routing mechanism can be implemented using services like Ollama to run models locally and using Qwen as an open-source model to perform specific tasks efficiently and cost-effectively.</p><p>The entire code runs on <strong>Google Colab</strong>, preferably best run on a GPU, but can also be run on a CPU.</p><h3>Setup</h3><h4><strong>Downloading and Configuring Ollama</strong></h4><p>To implement a semantic router using multiple LLMs, we begin by downloading and setting up Ollama, a platform that allows for easy instantiation and management of various models. Ollama provides a simple interface for pulling and running models locally, which is ideal for testing different models in real-time.</p><p>The first step is to install Ollama using the following command:</p><pre>!curl https://ollama.ai/install.sh | sh</pre><p>This script automatically installs Ollama on your machine. Once the installation is complete, we can start the Ollama server by running:</p><pre>!ollama serve &gt; server.log 2&gt;&amp;1 &amp;</pre><p>This command launches the Ollama server in the background, which will be available at the default address 127.0.0.1:11434. The server enables interaction with the models and is essential for managing and querying multiple LLMs.</p><p>Next, we proceed to download the required models using Ollama’s pull command. The agents_model is a specialized LLM—<em>qwen2.5:1.5b</em>—which we will use for specific tasks. The router_model, on the other hand, is a slightly larger model—<em>qwen2.5:3b</em>—which will act as the semantic router. This model will analyze the message history and decide which specialized agent should handle a particular task.</p><p>It is important to download a model that supports tools. For more information, you can see OpenAI API about <a href="https://platform.openai.com/docs/guides/function-calling">function calling</a>.</p><pre>%%capture<br>agents_model = &quot;qwen2.5:1.5b&quot;<br>!ollama pull {agents_model}<br><br>%%capture<br>router_model = &quot;qwen2.5:3b&quot;<br>!ollama pull {router_model}</pre><p>After pulling the models, we can verify that they were successfully downloaded by listing all available models with:</p><pre>!ollama ls</pre><h4><strong>Serving the Models at Different Ports</strong></h4><p>To efficiently manage multiple models with Ollama, we need to run each model on a separate server instance, each bound to a different port. This allows us to route requests to the appropriate model based on the task or context.</p><p>The following code snippet demonstrates how to set different ports for each Ollama server instance:</p><pre>import os<br><br>os.environ[&#39;OLLAMA_HOST&#39;] = &quot;127.0.0.1:11438&quot;<br>!ollama serve &gt; server.log 2&gt;&amp;1 &amp;<br><br>os.environ[&#39;OLLAMA_HOST&#39;] = &quot;127.0.0.1:11439&quot;<br>!ollama serve &gt; server.log 2&gt;&amp;1 &amp;</pre><p>Here, we set the OLLAMA_HOST environment variable to specify the IP address and port number for each Ollama server. By exporting different ports, we can run multiple instances of Ollama on the same machine, each serving a different model. In this case, the first model runs on127.0.0.1:11438, and the second on 127.0.0.1:11439. Also, remember that there is another instance of Ollama running at 127.0.0.1:11434 which we will use for our router.</p><p>This setup is particularly useful in scenarios where <strong>different models must be deployed independently</strong> or when testing different configurations. Additionally, this approach mimics a microservice architecture, where each model can be served as an independent service, accessible via <strong>RESTful API calls</strong>. In an online deployment scenario, each server can host a different model, and requests can be routed dynamically to the appropriate model based on the task at hand. This provides a scalable and flexible solution for deploying multiple LLMs, allowing for efficient load balancing, resource management, and integration across different systems.</p><h4><strong>Install required packages</strong></h4><p>Finally, install the required Python packages for this tutorial</p><pre>%%capture<br>!pip install openai==1.57.4 ollama==0.4.4 pydantic==2.10.3</pre><h3>Tools Definition</h3><p>In the context of a semantic router, tools are functions or external services that an LLM can call to perform specific tasks. These tools enable the LLM to handle specialized operations efficiently, whether it’s summarizing text, extracting topics, or fetching dynamic information. The key advantage of using tools in this setup is that they allow the LLM to focus on context analysis and routing while delegating specific tasks to lightweight, efficient functions.</p><p>For this example, I have defined three different tools:</p><ol><li><strong>Summarizer Tool</strong>: This tool is responsible for summarizing a paragraph of text. It’s invoked whenever the user requests a summary, such as “Summarize this paragraph.”</li><li><strong>Topic Extractor Tool</strong>: This tool extracts topics from a given text, responding to queries like “What are the topics of this paragraph?”</li><li><strong>Today Agent Tool</strong>: This tool simply returns the current day of the week. It’s used when the user asks, “What day is it today?”</li></ol><p>Each tool is defined as a dictionary with the type set to &quot;function&quot;, and it includes the function&#39;s name, description, and parameters. Here&#39;s how the tools are structured:</p><pre>from openai import OpenAI<br>import openai<br><br>summarizer_tool = {<br>    &quot;type&quot;: &quot;function&quot;,<br>    &quot;function&quot;: {<br>        &quot;name&quot;: &quot;get_summarization&quot;,<br>        &quot;description&quot;: &quot;Call this method whenever you need to perform a summarization task, for example when a user asks &#39;Summarize this paragraph&#39;. This method does not accepts input parameters.&quot;,<br>        &quot;parameters&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {},<br>            &quot;required&quot;: [],<br>            &quot;additionalProperties&quot;: False<br>        }<br>    }<br>}<br><br>topics_tool = {<br>    &quot;type&quot;: &quot;function&quot;,<br>    &quot;function&quot;: {<br>        &quot;name&quot;: &quot;get_topics&quot;,<br>      &quot;description&quot;: &quot;Call this whenever you need to perform a topic extraction extraction task, for example when a user asks &#39;What are the topics of this paragraph?&#39;. This method does not accepts input parameters.&quot;,<br>      &quot;parameters&quot;: {<br>          &quot;type&quot;: &quot;object&quot;,<br>          &quot;properties&quot;: {},<br>          &quot;required&quot;: [],<br>          &quot;additionalProperties&quot;: False<br>      }<br>    }<br>}<br><br><br>today_tool = {<br>    &quot;type&quot;: &quot;function&quot;,<br>    &quot;function&quot;: {<br>        &quot;name&quot;: &quot;get_current_day&quot;,<br>      &quot;description&quot;: &quot;Get the current day of the week. Call this whenever you need to know what day it is today, for example when the user asks &#39;What day is it?&#39;. This method does not accepts input parameters.&quot;,<br>      &quot;parameters&quot;: {<br>          &quot;type&quot;: &quot;object&quot;,<br>          &quot;properties&quot;: {},<br>          &quot;required&quot;: [],<br>          &quot;additionalProperties&quot;: False<br>      }<br>    }<br>}<br><br><br>tools = [topics_tool, summarizer_tool, today_tool]</pre><p>It’s important to note that tools don’t necessarily need to call another LLM. In this case, <em>today_tool</em> is a simple function that returns the current day, without the need for an LLM to be involved. This design allows for significant flexibility, as you can define as many tools as necessary, each performing a specific function.</p><p>In the context of the semantic router, the LLM can analyze the context of a message, determine which tool is needed, and then call the appropriate tool. This setup not only enhances performance by offloading tasks to specialized functions but also keeps the process efficient and cost-effective, as we don’t always need to invoke an expensive model for every operation.</p><h3>Agent Definition</h3><p>The core of the system is built around agents, which are responsible for performing specific tasks such as summarization, topic extraction, and providing the current day of the week. These agents are designed to interface with specialized models via a mechanism compatible with OpenAI’s API. By leveraging the OpenAI interface, we can easily communicate with each agent and use their capabilities in a streamlined way.</p><p>In this setup, we define three agents:</p><ol><li><strong>Summarizer Agent</strong>: This agent is responsible for summarizing the text provided by the user. It interacts with the summarization model.</li><li><strong>Topic Extractor Agent</strong>: This agent extracts topics from user messages. It uses a general-purpose model designed for topic extraction tasks.</li><li><strong>Today Agent</strong>: This agent simply returns the current day of the week.</li></ol><p>We begin by defining clients to interact with the agents. The OpenAI interface is used to communicate with the agents through their respective servers running on different ports.</p><pre>from openai import OpenAI<br><br>summarizer_client = OpenAI(<br>    base_url = &#39;http://localhost:11439/v1&#39;,<br>    api_key=&#39;ollama&#39;,  <br>)<br><br>general_client = OpenAI(<br>    base_url = &#39;http://localhost:11438/v1&#39;,<br>    api_key=&#39;ollama&#39;, <br>)</pre><h4>Building the History for Agents</h4><p>To maintain a conversation history that the agents can reference, we define a function build_history_agents. This function takes a list of messages and a system prompt to create a structured message history for each agent.</p><pre>def build_history_agents(messages: list[dict[str, str]], sys_prompt: str):<br>    history = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: sys_prompt}]<br>    <br>    for message in messages:<br>        if message[&quot;role&quot;] != &quot;system&quot;:<br>            history.append(message)<br><br>    return history</pre><h4>Summarizer Agent</h4><p>The get_summarization function is responsible for calling the summarizer agent to perform the summarization task. The agent is instructed to summarize user messages, and if the user asks for anything other than a summary, the agent simply responds with &quot;Pass.&quot;</p><pre>def get_summarization(history: list[dict[str, str]]):<br>    print(&quot;calling summarization model&quot;)<br><br>    sys_prompt = &quot;You are a summarizer agent. Your only role is to summarize user message. When user asks for other action or want to chit-chat just answer &#39;Pass.&#39;&quot;<br><br>    response = summarizer_client.chat.completions.create(<br>        model=agents_model,<br>        messages=build_history_agents(history, sys_prompt),<br>    )<br><br>    return response.choices[0].message.content</pre><h4>Topic Extractor Agent</h4><p>Similarly, the get_topics function calls the topic extractor agent. It is designed to extract the topics from the user’s messages, and again, if the user asks for any other action, the agent replies with &quot;Pass.&quot;</p><pre>def get_topics(history: list[dict[str, str]]):<br>    print(&quot;calling topic model&quot;)<br><br>    sys_prompt = &quot;You are a topic extractor model. Your role is to examine user message and extract the topics. When user asks for other action or want to chit-chat just answer &#39;Pass.&#39;&quot;<br><br>    response = general_client.chat.completions.create(<br>        model=agents_model,<br>        messages=build_history_agents(history, sys_prompt),<br>    )<br><br>    return response.choices[0].message.content</pre><h4>Today Agent</h4><p>The get_current_day function defines the Today agent, which doesn’t require any external model. It simply returns the current day of the week, leveraging Python’s datetime module.</p><pre>import datetime<br><br>def get_current_day():<br>    print(&quot;calling today model&quot;)<br>    return datetime.datetime.now().strftime(&quot;%A&quot;)</pre><p>This setup allows flexibility in defining any number of agents, each handling a specific task. The agents can be simple functions that perform specific operations, like summarization or topic extraction, without requiring additional LLMs. This makes the system both efficient and cost-effective, as only specialized agents are invoked when needed. Furthermore, you can easily expand the list of agents to handle other tasks, such as sentiment analysis, question answering, or even complex multi-step processes.</p><h4>Importance of Precise System Prompts and Tool Descriptions</h4><p>In the context of using LLMs as semantic routers, the precision of <strong>system prompts</strong> and <strong>tool descriptions</strong> plays a critical role in ensuring the effectiveness and accuracy of the agents. The system prompts serve as instructions to the models, guiding them to perform specific tasks within well-defined boundaries. Similarly, tool descriptions need to be clear and specific so that the LLMs can invoke the correct tool and understand its intended function.</p><p>For example, in the case of the summarizer agent, the system prompt clearly instructs the model to summarize the user’s message and respond with “Pass” when faced with requests outside its scope. Without such precision, the agent could misunderstand the request or take inappropriate actions.</p><h3>Router</h3><p>In our approach, the router’s role is to determine which specialized agent or tool to invoke based on the context of the conversation. The router is equipped with utilities to handle <strong>function calls</strong>, manage the <strong>history</strong> of messages, and facilitate communication between the system and the relevant tools or models.</p><h4>Utilities</h4><p>The <strong>execute_function_call</strong> utility is responsible for invoking the correct function when a specific tool is required. Once the response from the router indicates that a tool needs to be called, the function checks which tool it needs to invoke and executes the corresponding function. For example, if the tool call is for retrieving the current day, the get_current_day function is triggered, whereas for other tasks, such as summarization or topic extraction, the relevant agent function is invoked.</p><pre>import json<br>import re<br><br>def execute_function_call(response, history):<br>  if response.choices[0].finish_reason == &quot;tool_calls&quot;:<br>    tool_call = response.choices[0].message.tool_calls[0]<br>    function_name = tool_call.function.name<br><br>    if function_name == &quot;get_current_day&quot;:<br>      result = globals()[function_name]()<br>    else:<br>      result = globals()[function_name](history)<br><br><br>    function_call_result_message = {<br>      &quot;role&quot;: &quot;tool&quot;,<br>      &quot;content&quot;: json.dumps({<br>          &quot;result&quot;: result<br>      }),<br>      &quot;tool_call_id&quot;: response.choices[0].message.tool_calls[0].id<br>    }<br><br>    response_dict = response.model_dump()<br>    response_dict[&quot;choices&quot;][0][&quot;message&quot;]<br><br>    history = history + [response_dict[&quot;choices&quot;][0][&quot;message&quot;]] + [function_call_result_message]<br><br>    return history<br></pre><p>In this utility:</p><ul><li><strong>Tool Call Identification:</strong> The system identifies the function name from the tool_calls in the response and uses globals() to dynamically invoke the correct function, whether it&#39;s retrieving the current day or calling an agent for topic extraction or summarization.</li><li><strong>Function Execution:</strong> Based on the function name, the appropriate function (get_current_day, get_summarization, or get_topics) is executed, and its result is captured.</li><li><strong>Message History Update:</strong> The response message and the tool call result are added to the conversation history, ensuring the routing system keeps track of the dialogue and the functions executed.</li></ul><p>Additionally, the <strong>build_router_history</strong> utility is used to manage the conversation history by appending the assistant’s response to the message history. This utility ensures that the history accurately reflects the flow of conversation, including any actions taken by the system (e.g., calling a summarizer or topic extractor).</p><pre>def build_router_history(messages: list[dict[str, str]], response):<br>    res = response.choices[0].message.content<br>    messages.append(<br>        {<br>            &quot;role&quot;: &quot;assistant&quot;,<br>            &quot;content&quot;: res<br>        }<br>    )<br>    print(res)<br>    return messages</pre><h4>Importance of Message History Management</h4><p>Managing the message history is crucial because it serves as the context for subsequent interactions. Each time the router receives a new message and processes a function call, it appends the relevant details to the history. This ensures that the router always has access to the full context of the conversation, enabling it to make better decisions about which tool or agent to invoke.</p><p>For instance, when a user requests a summary of a paragraph, the system will examine the entire message history, which might include previous requests, responses, or even tool invocations, to decide the appropriate action. This history-driven approach ensures that the router remains context-aware and efficient, reducing errors and unnecessary resource consumption.</p><p>By maintaining a comprehensive history and using dynamic function calls, the router becomes highly adaptable and capable of handling a wide variety of tasks, each assigned to the most specialized and cost-effective model available.</p><h4>Router Definition</h4><p>The <strong>router</strong> is the key component of this system, responsible for directing messages to the appropriate specialized tool or agent based on the context. The router works by analyzing the conversation history and invoking the correct function when necessary. Here’s the code for defining the router and its client:</p><pre>router_client = OpenAI(<br>    base_url = &#39;http://localhost:11434/v1&#39;,<br>    api_key=&#39;ollama&#39;, # required, but unused<br>)</pre><p>We can also define a utility function to talk with the router</p><pre>def call_router(messages: list[dict[str, str]], use_tools=True):<br><br>  response = router_client.chat.completions.create(<br>    model=router_model,<br>    messages=messages,<br>    tools=tools if use_tools else None<br>  )<br><br>  return response</pre><h3>Chat with the Assistant: Routing in Action</h3><p>Once everything is set up, it’s time to see the routing mechanism in action. The idea is that the router model will analyze the conversation history and user intent, deciding whether the conversation should be handed over to a specialized agent (like a summarizer or topic extractor) or if it can continue with the assistant’s responses.</p><p>Here’s how we set up a first test case where we want the router to redirect the user’s request to the summarization model:</p><pre>sys_prompt = &quot;You are a routing model. Your role is to understand the chat history and user intent and eventualy to redirect the messages to the correct model that will handle the conversation. Your are allowed to chat with the user but only for chit-chatting, otherwise if you are asked to perform specific tasks just call other functions.&quot;<br><br>messages = [<br>  {<br>      &quot;role&quot;: &quot;system&quot;,<br>      &quot;content&quot;: sys_prompt<br>  },<br>  {<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;content&quot;: &quot;Hi, can you summarize this paragraph? The red glow of tail lights indicating another long drive home from work after an even longer 24-hour shift at the hospital. The shift hadn’t been horrible but the constant stream of patients entering the ER meant there was no downtime. She had some of the “regulars” in tonight with new ailments they were sure were going to kill them. It’s amazing what a couple of Tylenol and a physical exam from the doctor did to eliminate their pain, nausea, headache, or whatever other mild symptoms they had. Sometimes she wondered if all they really needed was some interaction with others and a bit of the individual attention they received from the nurses.&quot;<br>  }<br>]</pre><p>In this code:</p><ul><li><strong>System Prompt:</strong> The sys_prompt sets the behavior of the router. It explains that the router’s primary responsibility is to understand the conversation and delegate tasks to the appropriate model, but the router is also allowed to chat for light conversations.</li><li><strong>User Input:</strong> The user asks the router to summarize a paragraph, which is a specific task that requires the summarization agent.</li></ul><p>Now, let’s call the router to handle this request:</p><pre>response = call_router(messages)</pre><p>Analyzing the response we obtain:</p><pre>ChatCompletion(id=&#39;chatcmpl-4&#39;, choices=[Choice(finish_reason=&#39;tool_calls&#39;, index=0, logprobs=None, message=ChatCompletionMessage(content=&#39;&#39;, refusal=None, role=&#39;assistant&#39;, audio=None, function_call=None, tool_calls=[ChatCompletionMessageToolCall(id=&#39;call_96uqu57o&#39;, function=Function(arguments=&#39;{&quot;text&quot;:&quot;The red glow of tail lights indicating another long drive home from work after an even longer 24-hour shift at the hospital. The shift hadn’t been horrible but the constant stream of patients entering the ER meant there was no downtime. She had some of the \&#39;regulars\&#39; in tonight with new ailments they were sure were going to kill them. It\&#39;s amazing what a couple of Tylenol and a physical exam from the doctor did to eliminate their pain, nausea, headache, or whatever other mild symptoms they had. Sometimes she wondered if all they really needed was some interaction with others and a bit of the individual attention they received from the nurses.&quot;}&#39;, name=&#39;get_summarization&#39;), type=&#39;function&#39;, index=0)]))], created=1735233239, model=&#39;qwen2.5:3b&#39;, object=&#39;chat.completion&#39;, service_tier=None, system_fingerprint=&#39;fp_ollama&#39;, usage=CompletionUsage(completion_tokens=152, prompt_tokens=502, total_tokens=654, completion_tokens_details=None, prompt_tokens_details=None))</pre><p>As can be seen from finish_reason=’tool_calls’ the router actually invoked the tools that perform the summarization task.</p><p>Now we can execute the function that the router told us with the code:</p><pre># Execute the function call and update the messages<br>messages = execute_function_call(response, messages)<br><br># Call the router again with the updated messages, this time without using any tools (since the task is complete)<br>response = call_router(messages, use_tools=False)<br><br># Build the final history of the conversation including the router&#39;s response<br>messages = build_router_history(messages, response)</pre><p>The output of the summarization model is this below, great!</p><pre>The summary of the paragraph is:<br><br>A person reflects on their 24-hour shift at the hospital, noting that while it hasn&#39;t been terrible overall—constantly dealing with patient influxes without downtime—they often have repeat patients who come back after various minor issues (such as pain and nausea). These issues are typically resolved through medication (Tylenol) along with physical examinations from doctors. The person reflects on how the shifts remind them of how simple interactions and more personalized care can resolve many minor problems associated with being alone in the Emergency Room all day long.</pre><p>Now we test the router again, this time we want to know what day is it today. I update the history and call again the router</p><pre>messages.append({<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;content&quot;: &quot;Now I want to know what day is it&quot;<br>  }<br>)<br><br>response = call_router(messages)<br>print(response)</pre><p>Again the router acts as we expect since, analyzing the response, a tool call to the right tool is performed.</p><pre>ChatCompletion(id=&#39;chatcmpl-650&#39;, choices=[Choice(finish_reason=&#39;tool_calls&#39;, index=0, logprobs=None, message=ChatCompletionMessage(content=&#39;&#39;, refusal=None, role=&#39;assistant&#39;, audio=None, function_call=None, tool_calls=[ChatCompletionMessageToolCall(id=&#39;call_ppy9ohoc&#39;, function=Function(arguments=&#39;{}&#39;, name=&#39;get_current_day&#39;), type=&#39;function&#39;, index=0)]))], created=1735233249, model=&#39;qwen2.5:3b&#39;, object=&#39;chat.completion&#39;, service_tier=None, system_fingerprint=&#39;fp_ollama&#39;, usage=CompletionUsage(completion_tokens=17, prompt_tokens=757, total_tokens=774, completion_tokens_details=None, prompt_tokens_details=None))</pre><p>We can execute the function again with the same code above:</p><pre>messages = execute_function_call(response, messages)<br><br>response = call_router(messages, use_tools=False)<br>messagges = build_router_history(messages, response)<br><br># the response this time is Today is Thursday.</pre><p>Finally, testing the router again for the last tool</p><pre>messages.append({<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;content&quot;: &quot;Now can you extract topics from the paragraph that I sent you on the first message?&quot;<br>  }<br>)<br><br>response = call_router(messages)<br><br>messages = execute_function_call(response, messages)<br>response = call_router(messages, use_tools=False)<br>messagges = build_router_history(messages, response)</pre><p>The response is:</p><pre>The main topics from the paragraph are:<br><br>1. A 24-hour shift at the hospital&#39;s Emergency Room (ER)<br>2. The constant influx of patients during the shift<br>3. The treatments provided (Tylenol, physical exams)<br>4. Repeat patients with various minor issues<br>5. Reflection on personal care and interactions needed for better patient outcomes</pre><p>Great, everything worked as planned, so we thank the AI for the great job.</p><pre>messages.append({<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;content&quot;: &quot;Thank you!! You are a very helpful assistant. Now, say hello to our Medium friends :)&quot;<br>  }<br>)<br><br>response = call_router(messages)<br>messagges = build_router_history(messages, response)<br><br># response: Hello to our Medium friends! How can I assist you further?</pre><h3>Conclusions</h3><p>This exploration of using LLMs as semantic routers with function calling demonstrates a powerful approach to managing complex conversational flows and information processing. In this examples, I used small models like Qwen-2 3B, but one can adopt more powerful models.</p><p><strong>Pros:</strong></p><ul><li><strong>Contextual Awareness:</strong> Unlike traditional rule-based systems, LLM routers can understand the nuances of natural language and the context of the entire conversation history, leading to more accurate and relevant routing decisions.</li><li><strong>Adaptability and Extensibility:</strong> Adding new functionalities is relatively straightforward. Simply define a new function and provide a description to the router LLM. No extensive code rewrites or complex rule updates are required. This makes the system highly adaptable to evolving needs.</li><li><strong>Improved User Experience:</strong> By delegating tasks to specialized agents, we can achieve better performance for each specific task, leading to more accurate summaries, more relevant topic extractions, and ultimately a more satisfying user experience.</li><li><strong>Local Execution with Ollama:</strong> Using Ollama for local model execution provides significant benefits in terms of privacy, control, and reduced latency, especially for sensitive data or applications requiring real-time responses.</li></ul><p>However, this approach also presents some challenges:</p><p><strong>Cons:</strong></p><ul><li><strong>Latency:</strong> While local execution helps, LLM inference still introduces latency. Routing decisions and agent executions add up, potentially impacting response times, especially with more complex conversations and multiple function calls.</li><li><strong>Cost:</strong> Running multiple LLMs, even smaller ones like the 1.5B models, can be computationally expensive, especially for high-volume applications. This needs to be carefully considered for production deployments. Also, in terms of money, multiple inference steps are performed for the same message.</li><li><strong>Prompt Engineering Sensitivity:</strong> The performance of the router heavily relies on effective prompt engineering. Carefully crafted prompts are essential for guiding the router’s behavior and ensuring correct function calls.</li></ul><p>If you liked the article and want to help me write better and better articles, don’t forget to follow me and contribute a tip by clicking this <a href="https://www.paypal.com/donate/?hosted_button_id=3UNX7F6AFLG96">link</a> or the buttons below :) Thank you very much!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=326f15ab2feb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microsoft MarkItDown + Ollama and LLaVA: Markdown Conversion with LLM]]></title>
            <link>https://medium.com/@giacomo__95/markitdown-ollama-and-llava-markdown-conversion-with-microsofts-markitdown-and-ollama-s-llm-2141bba9d183?source=rss-dd74b6a2cd57------2</link>
            <guid isPermaLink="false">https://medium.com/p/2141bba9d183</guid>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[markdown]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[llava]]></category>
            <category><![CDATA[microsoft]]></category>
            <dc:creator><![CDATA[Giacomo Carfì]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 15:32:37 GMT</pubDate>
            <atom:updated>2025-01-05T20:29:36.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*kaJ02erzyYsnGW2dDGuQgw.jpeg" /></figure><p>Processing documents into markdown format has become a key feature for building Retrieval-Augmented Generation (RAG) systems. In this article, we explore how to use Microsoft’s latest library to process files and convert them into markdown. We’ll also showcase the use of open-source vision language models like LLaVA using Ollama to handle images and text processing. Let’s dive in!</p><p>Before we begin, I’d like to remind you that the code snippets shared in this article can be found in my <a href="https://github.com/Sopralapanca/medium-articles/tree/main/RAG-file-processing">GitHub</a> repository. If you enjoyed this article, please give it a clap, leave a comment with your suggestions, and consider following me to support my work!</p><p><strong>Keywords:</strong> PDF, DOCX, PPTX, HTML, markdown, Ollama, OpenAi, RAG, Microsoft, file processing, MarkItDown, LLaVA</p><h3>Introduction</h3><p>Retrieval-Augmented Generation (RAG) enhances language models by combining retrieved external knowledge with generative capabilities. A <strong>retriever</strong> fetches relevant data from a knowledge base, and a <strong>generator</strong> uses it to create accurate, context-rich responses.</p><p>RAG excels in tasks requiring factual accuracy and domain-specific insights. Its effectiveness relies on well-structured input data, making tools that convert files into formats like Markdown essential for clean and organized retrieval.</p><p>For a RAG system to perform optimally, it requires well-structured input data. This is where tools for converting unstructured data into structured formats, like Markdown, become essential. Markdown’s simplicity and readability make it an ideal format for feeding knowledge into these systems.</p><p><a href="https://github.com/microsoft/markitdown">MarkItDown</a> is a new library from Microsoft designed to convert various file types into Markdown format. Its key strengths lie in its ease of use and its integration with large language models for tasks like image captioning. However, as a relatively new and still-developing tool, it has some limitations. Bugs may be present, and the range of supported file types is limited to:</p><ul><li><strong>PDFs</strong></li><li><strong>PowerPoint</strong></li><li><strong>Word</strong></li><li><strong>Excel</strong></li><li><strong>Images</strong> (EXIF metadata and OCR)</li><li><strong>Audio</strong> (EXIF metadata and speech transcription)</li><li><strong>HTML</strong></li><li><strong>Text-based formats</strong> (CSV, JSON, XML)</li><li><strong>ZIP files</strong> (iterates over contents)</li></ul><p>While promising, improvements are needed to expand its capabilities and refine its outputs. For example PDFs file are just converted into plain text and not markdown. Files like .doc, .ppt are not supported. Only .docs and .pptx.</p><p>In this notebook, I demonstrate:</p><ul><li>How to process PDFs, DOCX, PPTX, HTML, and images using Microsoft’s library.</li><li>Convert the extracted content into structured Markdown.</li><li>Use open-source models like Ollma and LLaVa for image-based processing, avoiding proprietary models like OpenAI.</li></ul><h3>Step 1: Setting Up the Environment</h3><p>I write my code in Google Colab. For improved performance, you can enable GPU acceleration in the runtime settings, though the script will also run on a CPU. Keep in mind that you’ll need approximately 7GB of RAM to execute it.</p><p>I’m using Python version <em>3.10.12</em>, and I’ll specify the package versions where necessary.</p><p>To get started, first download the sample files present in my GitHub repository: <a href="https://github.com/Sopralapanca/medium-articles/blob/main/RAG-file-processing/Dickinson_Sample_Slides.pptx">1</a>, <a href="https://github.com/Sopralapanca/medium-articles/blob/main/RAG-file-processing/file-sample_1MB.docx">2</a>, <a href="https://github.com/Sopralapanca/medium-articles/blob/main/RAG-file-processing/sample1.html">3</a>, <a href="https://github.com/Sopralapanca/medium-articles/blob/main/RAG-file-processing/sampleimage.jpg">4</a>, <a href="https://github.com/Sopralapanca/medium-articles/blob/main/RAG-file-processing/somatosensory.pdf">5</a>.</p><p>Then, download and install MarkItDown using pip:</p><pre>pip install markitdown==0.0.1a3</pre><h3>Step 2: Converting Content to Markdown</h3><p>This step showcases the simplicity and power of Microsoft’s MarkItDown library. With just a few lines of code, you can seamlessly convert your files into Markdown format.</p><p>Here’s how you can get started:</p><pre># Instantiate the MarkItDown object<br>md = MarkItDown()</pre><p>Once the object is created, you’re ready to process your files effortlessly!</p><h4>Processing .pptx</h4><p>To process a file, simply copy and paste its path, and MarkItDown will automatically infer the file extension and handle it appropriately. For example, to process a .pptx file, you can use the following code:</p><pre>result = md.convert(&quot;/content/Dickinson_Sample_Slides.pptx&quot;)<br>print(result.text_content)</pre><p>The sample output is shown below. As you can see, MarkItDown effectively extracts annotations, tables, sections, and much more, providing a well-structured Markdown representation of the file content.</p><pre>&lt;!-- Slide number: 3 --&gt;<br><br>![Dickinson_hoefler_0-100-81-4.eps](Picture5.jpg)<br>Presentation Title<br>Author<br>Department<br>Date<br>Location<br><br>### Notes:<br>Cover slide option #3<br><br>&lt;!-- Slide number: 4 --&gt;<br># GraphTitle<br>Additional Notes - Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem<br><br>### Chart<br><br>| Category | Graph information | Graph information |<br>|---|---|---|<br>| 2002 | None | -1.0 |<br>| 2003 | None | 1.4 |<br>| 2004 | None | 1.6 |<br>| 2005 | None | 2.5 |<br>| 2006 | None | 3.3 |<br>| 2007 | None | 4.1 |<br>| 2008 | None | 5.1 |<br>| 2009 | 0.507 | 6.478000000000002 |<br>| 2010 | 0.455 | 5.833 |<br>| 2011 | 1.5249999999999975 | 5.830999999999999 |<br>| 2012 (Proj) | 2.22 | 3.4999999999999987 |</pre><h4>Processing .docx</h4><pre>result = md.convert(&quot;/content/file-sample_1MB.docx&quot;)<br>print(result.text_content)</pre><h4>Processing HTML</h4><pre>result = md.convert(&quot;/content/sample1.html&quot;)<br>print(result.text_content)</pre><h4>Processing .pdf</h4><p>I inspected the library’s source code and, unfortunately, discovered that PDF files are not yet supported for Markdown conversion. The screenshot below highlights this limitation directly from the source code.</p><p>Hopefully, future updates will address this and include support for PDFs in Markdown conversion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9yOD3BvPAH8ww7ilD_pcA.png" /></figure><pre>result = md.convert(&quot;/content/somatosensory.pdf&quot;)<br>print(result.text_content)</pre><h3>Step 3: Using Ollama and LLaVA for Image Processing</h3><p>One of the standout features of this library is its ability to integrate with a large language model to generate captions for images. While Microsoft’s examples demonstrate this using OpenAI models, you can also use Ollama to run a local model and achieve the same functionality. This flexibility makes the library versatile for different use cases and setups.</p><h4>What is Ollama</h4><p><a href="https://ollama.com/">Ollama</a> is a platform for running large language models (LLMs) locally on your machine, offering a privacy-focused and efficient alternative to cloud-based solutions. It supports various open-source and proprietary models, enabling users to leverage powerful AI capabilities without relying on external servers.</p><h4>What is LLaVA</h4><p><a href="https://llava-vl.github.io/">LLaVA</a> (Large Language and Vision Assistant) is a model designed to combine language and vision capabilities, enabling it to process and understand both text and images. It can generate detailed descriptions of images, answer questions about visual content, and perform tasks that require a blend of language understanding and visual interpretation, making it useful for applications like image captioning, visual question answering, and more.</p><h4>Use Them Together!</h4><p>To get started, first download and set up the Ollama service. Once that’s done, start Ollama and download the model of your choice.</p><p>If you’re working in a Colab environment, here’s the code to get everything running:</p><pre>!curl https://ollama.ai/install.sh | sh<br><br>!ollama serve &gt; server.log 2&gt;&amp;1 &amp;<br><br>model = &quot;llava&quot;<br>!ollama pull {model}</pre><p>Ollama will run in the background, pulling the model and serving it locally at localhost:11424.</p><p>Now we need to install the necessary packages for both OpenAI and Ollama. The OpenAI package will allow us to instantiate an OpenAI client that connects to the local Ollama server, running our model locally.</p><p>Use the following command to install the required packages:</p><pre>!pip install openai==1.57.4 ollama==0.4.4</pre><p>Once the packages are installed, we can set up the OpenAI client to use Ollama’s model locally. Even though we specify anapi_key, it is not actually used in this case since Ollama doesn’t require one for local access. We will define the base_url point to Ollama’s local server, which runs at port 11434.</p><p>Here’s how to set it up:</p><pre>from openai import OpenAI<br># Instantiate the OpenAI client with Ollama&#39;s local server URL<br>client = OpenAI(<br>    base_url=&#39;http://localhost:11434/v1&#39;,  # Ollama&#39;s local server URL<br>    api_key=&#39;ollama&#39;,  # Required, but not used for local models<br>)</pre><p>Now you’re ready to interact with your model locally! The OpenAI client is configured to send requests to the Ollama server, which serves the model of your choice. This setup enables you to seamlessly use the capabilities of large language models like Ollama while running them on your own machine.</p><p>To integrate the power of MarkItDown with a large language model for image captioning, simply instantiate a new MarkItDown object and pass the llm_client and llm_model defined earlier. This will allow MarkItDown to leverage the LLM&#39;s capabilities for generating descriptions and processing content.</p><p>Here’s how you can set it up:</p><pre>md = MarkItDown(llm_client=client, llm_model=model)<br>result = md.convert(&quot;/content/sampleimage.jpg&quot;)<br>print(result.text_content)</pre><p>Example output:</p><pre># Description:<br>The image shows two RAM (Random Access Memory) modules, presented inside their original packaging. Both modules have red and black aluminum heat spreaders, indicating they are intended to be used in desktop computers or laptops, where they are placed directly onto the motherboard to allow the CPU to access data quickly.<br><br>The upper RAM module has a white label with red text at the top that reads &#39;Crucial&#39;. This is likely the brand name of the product. Below this label, there&#39;s another smaller label that shows specifications: &#39;1x16GB&#39;, &#39;DDR4 SODIMM&#39;, &#39;CL&#39;, &#39;8GB&#39;, and what appears to be the model number (not entirely visible in the image).<br><br>The lower RAM module has a similar presentation but with different specifications. The text &#39;WENGEN&#39; is clearly seen on this module, suggesting that it may be made by Wenger or is part of a series branded by Wenger. Other details about this module are not fully visible in the image.<br><br>Both modules have &#39;CL&#39; printed, which stands for Cascade Latitude, indicating the type of latency timing in use with these memory modules. The &#39;8GB&#39; suggests a storage capacity of 8 Gigabytes. The packaging contains clear plastic covers to protect the RAM modules from damage while they are out of their intended computer setup.<br><br>The setting looks like a domestic environment, as evidenced by the plain background and the presence of common household objects, such as what appears to be a table or desk surface in the top right corner. The specific focus on these items suggests that this picture might have been taken during a hobbyist activity or for showcasing the new RAM modules someone purchased or obtained.</pre><h3>Conclusions</h3><p>In this article, we’ve explored the power of <strong>MarkItDown</strong>, <strong>Ollama</strong>, and <strong>LLaVA</strong>, three powerful tools that, when combined, enable seamless file conversions and intelligent content analysis. MarkItDown stands out for its ability to convert various file formats into Markdown, while integrating large language models like <strong>Ollama</strong> and <strong>LLaVA</strong> to enhance the process. These tools allow not only the extraction of structured content but also the generation of meaningful descriptions for images, making the process highly efficient and flexible.</p><p><strong>MarkItDown</strong> handles file conversions for various formats such as PDFs, PowerPoint presentations, Word documents, Excel sheets, images, and more, converting them into easy-to-read Markdown. The inclusion of large language models like <strong>Ollama</strong> adds an additional layer of power, enabling the tool to not only convert files but also generate image captions and enhance content understanding. <strong>LLaVA</strong> further integrates vision and language processing, making it even more versatile for tasks that require both image and text analysis.</p><p>However, it’s important to note a few limitations:</p><ul><li><strong>PDFs</strong> are currently only converted to plain text, not Markdown.</li><li><strong>.doc</strong> files are not yet supported.</li><li>The tool performs best with a <strong>GPU</strong>, though it also works on a CPU (with approximately 7 GB of RAM required).</li><li>While <strong>MarkItDown</strong> can extract tables and images from <strong>.docx</strong> and <strong>.pptx</strong> files, its current functionality is still evolving and might not handle all complex content perfectly.</li></ul><p>Despite these limitations, MarkItDown, combined with <strong>Ollama</strong> and <strong>LLaVA</strong>, provides a robust and flexible solution for converting and processing various file types, making it a valuable tool for developers, researchers, and content creators.</p><p>For more details, visit the <a href="https://github.com/Microsoft/MarkItDown">MarkItDown GitHub Repository</a>.</p><p>If you liked the article and want to help me write better and better articles, don’t forget to follow me and contribute a tip by clicking this <a href="https://www.paypal.com/donate/?hosted_button_id=3UNX7F6AFLG96">link</a> or the buttons below :) Thank you very much!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2141bba9d183" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Restricted Boltzmann Machines (RBMs) from Scratch in Python: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@giacomo__95/building-restricted-boltzmann-machines-rbms-from-scratch-and-testing-it-with-mnist-data-a-806842c0a37b?source=rss-dd74b6a2cd57------2</link>
            <guid isPermaLink="false">https://medium.com/p/806842c0a37b</guid>
            <category><![CDATA[boltzmann]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[boltzmann-machines]]></category>
            <category><![CDATA[rbm]]></category>
            <dc:creator><![CDATA[Giacomo Carfì]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 11:13:57 GMT</pubDate>
            <atom:updated>2025-01-06T11:32:21.440Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*luQLS9thkc5fUf_X75seKA.png" /></figure><p>In this tutorial, we’ll explore how to build a Restricted Boltzmann Machine (RBM) from scratch using NumPy. We’ll apply it to the classic MNIST dataset of handwritten digits, train the RBM to encode and reconstruct the data, and evaluate its performance using the Structural Similarity Index Measure (SSIM). No deep learning libraries will be used — everything is done using basic matrix operations.</p><h3>Introduction</h3><p>Restricted Boltzmann Machines (RBMs) are a class of unsupervised machine learning models used primarily for dimensionality reduction and feature learning, and as building blocks for more complex architectures like deep belief networks (DBNs). RBMs consist of two layers: a visible layer (representing the input data) and a hidden layer (representing latent variables or features), where each neuron in one layer is connected to every neuron in the other.</p><p>The RBM learns to encode information from the visible layer into a hidden layer by minimizing a loss function that measures how well it can reconstruct the input. This makes RBMs ideal for tasks such as image compression and generation.</p><h4>Task Overview:</h4><p>We will:</p><ol><li>Load the MNIST dataset.</li><li>Build an RBM using NumPy.</li><li>Train the RBM to encode and reconstruct the data.</li><li>Use SSIM to measure the quality of reconstruction.</li></ol><p>Let’s begin by loading and visualizing the dataset.</p><h3>Step 1: Setting Up the Environment</h3><p>To get started, we will first install the necessary libraries like: scikit-learn, numpy, and scikit-image for calculating the SSIM metric. If you&#39;re running this in a notebook, use the following code to install these dependencies:</p><pre>!pip install scikit-learn==1.3.2 numpy==1.26.4 pandas==2.1.4 pillow==9.4.0</pre><h3>Step 2: Loading and Visualizing MNIST Data</h3><p>We’ll use sklearn.datasets to fetch the MNIST dataset, which contains 70,000 images of handwritten digits.</p><pre>from sklearn.datasets import fetch_openml<br>from sklearn.model_selection import train_test_split<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br>def plot_example(X, y):<br>    &quot;&quot;&quot;Plot the first 5 images and their labels in a row.&quot;&quot;&quot;<br>    for i, (img, y) in enumerate(zip(X[:5].reshape(5, 28, 28), y[:5])):<br>        plt.subplot(151 + i)<br>        plt.imshow(img, cmap=&#39;gray&#39;)<br>        plt.xticks([])<br>        plt.yticks([])<br>        plt.title(y)<br><br>X, Y = fetch_openml(&quot;mnist_784&quot;, version=1, return_X_y=True, as_frame=False)<br>print(X.shape)<br>plot_example(X, Y)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*P-_Js88BtQ5qxC9_qufLXw.png" /></figure><h3>Step 3: Preparing the Data</h3><p>To prepare the MNIST data for our RBM, we need to normalize and binarize the pixel values and then split the dataset. First, we normalize the pixel values from the range [0, 255] to [0, 1], and then binarize them.</p><p>Next, we split the data into training and test sets. We reserve 10,000 samples for testing and use the rest for training:</p><pre># normalize data<br>X /= 255<br><br># binarize data<br>X = np.where(X &gt; 0.5, 1, 0)<br><br># train - test split<br>X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=10000, random_state=42, stratify=Y)</pre><p>With the data prepared, we can now proceed to build and train our RBM.</p><h3>Step 4: Implementing the RBM</h3><p>We’ll now implement the RBM from scratch using NumPy. Our RBM class includes methods for training the model using Contrastive Divergence, reconstructing data, and visualizing the learned weights.</p><h4>RBM Implementation</h4><p>Here’s the code for the RBM class:</p><pre>from sklearn.utils import gen_batches<br><br>class RBM():<br><br>  def __init__(self, visible_dim, hidden_dim):<br>    self.visible_dim = visible_dim<br>    self.hidden_dim = hidden_dim<br>    # weights<br>    self.W = np.random.randn(visible_dim, hidden_dim)<br>    # biases<br>    self.bh = np.random.randn(hidden_dim)<br>    self.bv = np.random.randn(visible_dim)<br><br><br>  def fit(self, X, epochs=10, batch_dim=16, lr=0.01):<br>    &#39;&#39;&#39;<br>    Trains the restricted boltzmann machine<br>    &#39;&#39;&#39;<br>    for epoch in range(epochs):<br>      # saving the image of the weights<br>      self.plot_weights(step=epoch, save=True)<br><br>      error_epoch = 0<br>      batches = list(gen_batches(X.shape[0], batch_dim))<br><br>      for batch in batches:<br>        batch = X[batch.start:batch.stop]<br>        batch_size = batch.shape[0]<br><br>        # Wake - prob of h given v<br>        ones_poshidP = np.ones((batch_size, self.hidden_dim))<br>        poshidP = ones_poshidP/(ones_poshidP + np.exp(-np.dot(batch,self.W) - self.bh))<br>        wake = np.dot(batch.T, poshidP)<br><br>        # Dream - prob of v giben h<br>        ones_reconDataP = np.ones((batch_size, self.visible_dim))<br>        reconDataP = ones_reconDataP / (ones_reconDataP + np.exp(-np.dot(poshidP, np.transpose(self.W))-self.bv))<br>        ones_neghidP = np.ones((batch_size, self.hidden_dim))<br>        neghidP = ones_neghidP / (ones_neghidP + np.exp(-np.dot(reconDataP, self.W) - self.bh))<br>        dream = np.dot(np.transpose(reconDataP), neghidP)<br><br>        # Error<br>        error = np.sum((batch-reconDataP)**2)/batch_size<br><br>        # Update Contrastive Divergence-1<br>        self.W += lr*(wake-dream)/batch_size<br>        self.bh += lr*(np.sum(poshidP-neghidP, axis=0))/batch_size<br>        self.bv += lr*(np.sum(batch-reconDataP, axis=0))/batch_size<br><br>        error_epoch += error<br><br>      error_epoch /= len(batches)<br>      print(f&quot;epoch: {epoch}/{epochs} \t{&#39;error:&#39;} {error_epoch}&quot;)<br><br><br>  def reconstruct(self, X):<br>    &#39;&#39;&#39;<br>    Reconstruct the data from the hidden encoding<br>    &#39;&#39;&#39;<br>    ones_poshidP = np.ones((X.shape[0], self.hidden_dim))<br>    poshidP = ones_poshidP/(ones_poshidP + np.exp(-np.dot(X,self.W)-self.bh))<br>    poshidS = poshidP &gt; np.random.uniform(size=poshidP.shape)<br><br>    ones_reconDataP = np.ones((X.shape[0], self.visible_dim))<br>    reconDataP = ones_reconDataP / (ones_reconDataP + np.exp(-np.dot(poshidS,np.transpose(self.W))-self.bv))<br><br>    return reconDataP<br><br>  def plot_weights(self, title=&#39;weights&#39;, step=0, save=True):<br>    &#39;&#39;&#39;<br>    Plot the weights of the RBM, one plot for each hidden unit.<br>    &#39;&#39;&#39;<br><br>    cols = 5<br>    rows = int(self.hidden_dim / cols)<br><br><br>    plt.clf()<br>    fig, axes = plt.subplots(rows, cols, figsize=(10,10))<br>    fig.suptitle(f&quot;{title} step:{step}&quot;)<br>    for i in range(rows):<br>        for j in range(cols):<br>            axes[i, j].imshow(self.W[:,i*cols+j].reshape(28, 28), cmap=&#39;gray&#39;)<br>            axes[i, j].axis(&#39;off&#39;)<br><br>    plt.subplots_adjust(wspace=1, hspace=1)<br><br>    if save:<br>      plt.savefig(f&quot;{title}_step_{step}.png&quot;)<br>    else:<br>      plt.show()<br><br>    plt.close()</pre><h4>Explanation:</h4><ul><li><strong>Initialization</strong>: We initialize weights and biases with small random values.</li><li><strong>Training (</strong><strong>fit method)</strong>: We use Contrastive Divergence to update weights and biases. We compute the positive phase (wake) and the negative phase (dream) to adjust the model parameters and minimize reconstruction error.</li><li><strong>Reconstruction (</strong><strong>reconstruct method)</strong>: Given visible data, we reconstruct the data from the hidden layer.</li><li><strong>Weight Visualization (</strong><strong>plot_weights method)</strong>: We visualize the learned weights to understand the features captured by the hidden units.</li></ul><h3>Step 5: Training the RBM</h3><p>With our RBM implemented, it’s time to train it using the prepared MNIST dataset. We’ll configure the model and then run the training process.</p><p>We initialize the RBM with a specified number of hidden units. In this case, we use 30 hidden units, which means the RBM will learn to capture 30 different features from the input data.</p><pre># Turn off interactive mode of matplotlib to avoid showing multiple plots<br>plt.ioff() # Initialize RBM with 30 hidden units<br>rbm = RBM(visible_dim=X_train.shape[1], hidden_dim=30)<br># Train the RBM<br>rbm.fit(X_train, epochs=20, batch_dim=128, lr=0.7)<br># Turn interactive mode back on<br>plt.ion()</pre><h4>Explanation of Parameters:</h4><ul><li><strong>Hidden Dimensions (</strong><strong>hidden_dim)</strong>: This parameter defines the number of hidden units in the RBM. Each hidden unit represents a feature that the RBM learns from the input data. More hidden units allow the model to capture more complex patterns but also increase the risk of overfitting and the computational cost.</li><li><strong>Batch Dimension (</strong><strong>batch_dim)</strong>: During training, the dataset is divided into smaller batches rather than processing the entire dataset at once. This technique, known as mini-batch training, helps in managing memory usage and accelerates the training process. The batch_dim parameter specifies the size of these mini-batches. In our case, we use a batch size of 128.</li><li><strong>Learning Rate (</strong><strong>lr)</strong>: The learning rate determines how much to adjust the weights during each update step. A higher learning rate might speed up training but can lead to instability, while a lower learning rate provides more stable updates but may slow down convergence. Here, we set the learning rate to 0.7.</li></ul><h4>Training Process</h4><p>The fit method performs the training using the Contrastive Divergence algorithm. For each epoch (a complete pass through the training data), the model:</p><ol><li>Splits the training data into batches.</li><li>For each batch, compute the positive phase (wake) and negative phase (dream) to update the weights and biases.</li><li>Calculates the reconstruction error to monitor training progress.</li></ol><p>At the end of each epoch, the weights are visualized to monitor how they evolve during training.</p><h3>Step 6: Visualizing the Weights During Training</h3><p>To understand how the RBM learns and what features it captures, we can visualize the weights at different epochs during training. This helps us see the evolution of learned features over time.</p><h4>Generating Weight Visualizations</h4><p>During training, we save images of the weights at each epoch. These images show how the weights corresponding to each hidden unit evolve. We then compile these images into a GIF for an animated view of the training progress.</p><p>Here’s the code to create a GIF from the weight images:</p><pre># show the weights over epochs<br>import glob<br>from PIL import Image<br>import re<br>import math<br>from pathlib import Path<br><br>file_pattern = re.compile(r&#39;.*?(\d+).*?&#39;)<br>def get_order(file):<br>    match = file_pattern.match(Path(file).name)<br>    if not match:<br>        return math.inf<br>    return int(match.groups()[0])<br><br><br>frames = [Image.open(image) for image in sorted(glob.glob(f&quot;./weights_step_*.png&quot;), key=get_order)]<br>frame_one = frames[0]<br>frame_one.save(&quot;weights.gif&quot;, format=&quot;GIF&quot;, append_images=frames,<br>               save_all=True, duration=1000, loop=0)<br><br># if you are using a notebook<br>from IPython.display import Image<br>Image(open(&#39;weights.gif&#39;,&#39;rb&#39;).read())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*TvZjLlF130eCd1gq-BetSA.gif" /><figcaption>Restricted Boltzmann Machine weights over epochs visualization</figcaption></figure><h4>Interpretation of the Visualization</h4><p>In the generated GIF, you can observe that as the epochs progress, the weights start to form recognizable patterns, often resembling numerical digits. This indicates that the RBM is learning to represent different features of the input data.</p><p>Specifically:</p><ul><li><strong>Formation of Numbers</strong>: As training progresses, each hidden unit’s weight pattern begins to resemble specific digits. This suggests that the RBM is capturing essential features of the digits from the MNIST dataset.</li><li><strong>Understanding Features</strong>: When weights start to align with recognizable patterns, it means that the RBM’s hidden units are effectively encoding parts of the input data. Each unit is learning to detect particular features that are useful for reconstructing the digits.</li></ul><p>The visual evolution in the GIF provides insights into how the RBM internalizes and represents different aspects of the data, highlighting its learning process and the features it captures.</p><h3>Step 7: Testing and Visualizing Reconstruction</h3><p>To evaluate the performance of our trained RBM, we will test it on a subset of the MNIST dataset and visualize how well it can reconstruct the input images. This allows us to assess how effectively the RBM has learned to capture and reproduce the features of handwritten digits.</p><h4>Testing the RBM</h4><p>We select one image from the test set for each digit (0 through 9) and use the RBM to reconstruct these images. We then compare the original images with their reconstructions.</p><p>Here’s the code to perform this task and visualize the results:</p><pre># get one image of the test set for each digit<br># Create a list of indices for each digit<br>digit_indices = [np.where(Y_test == str(i))[0][0] for i in range(10)]<br>resticted_set = X_test[digit_indices]<br><br>reconstructed = rbm.reconstruct(resticted_set)<br><br># show 10 sample images<br>rows = 2<br>columns = 10<br><br>fig, axes = plt.subplots(rows, columns,sharey = True,figsize=(30, 6))<br>for i in range(rows):<br>    for j in range(columns):<br>        if i==0:<br>          axes[i, j].imshow(resticted_set[j].reshape(28, 28), cmap=&#39;gray&#39;)<br>        else:<br>          axes[i, j].imshow(reconstructed[j].reshape(28, 28), cmap=&#39;gray&#39;)<br><br>        axes[i, j].tick_params(left = False, right = False , labelleft = False,<br>                labelbottom = False, bottom = False)<br><br>axes[0, 0].set_ylabel(&quot;ACTUAL&quot;, fontsize=12)<br>axes[1, 0].set_ylabel(&quot;REC.&quot;, fontsize=12)<br>plt.show()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ux2fggCEpfDup_LNX7NDnQ.png" /><figcaption>MNIST handwritten digits: Original vs. Reconstructed</figcaption></figure><p><strong>Original vs. Reconstructed</strong>: The top row displays the original images selected from the test set, while the bottom row shows their reconstructed versions produced by the RBM.</p><p>This visualization provides a clear illustration of the RBM’s ability to encode and reconstruct images, showcasing the effectiveness of the model in learning the underlying structure of the input data.</p><h3>Step 8: Evaluating Reconstruction Quality</h3><p>To quantitatively assess how well our RBM reconstructs the images, we use the Structural Similarity Index (SSIM). SSIM measures the similarity between the original and reconstructed images, providing a numerical value that reflects the quality of the reconstruction.</p><h4>Computing the SSIM Score</h4><p>First, we reconstruct the entire test set and then compute the SSIM score for each image pair (original and reconstructed) to evaluate their similarity.</p><p>Here’s the code for evaluating the SSIM score:</p><pre>from skimage.metrics import structural_similarity as ssim<br># reconstruct the whole testset<br>reconstructed = rbm.reconstruct(X_test)<br><br># convert test set into float numbers to apply ssim score<br>X_test1 = X_test.astype(float)<br><br>ssim_score=0<br>for i in range(len(X_test1)):<br>  ssim_score +=ssim(X_test1[i], reconstructed[i], data_range=X_test1[i].max() - X_test1[i].min())<br><br># mean overall the samples<br>ssim_score /= len(X_test)<br><br>print(f&quot;SSIM score: {ssim_score}&quot;)</pre><h3>Final Notes</h3><p>In this article, we walked through the process of implementing and training a Restricted Boltzmann Machine (RBM) from scratch using NumPy. We began by loading and preparing the MNIST dataset, followed by implementing the RBM and training it to learn and reconstruct handwritten digits. We then visualized the evolution of the learned features over epochs and evaluated the model’s performance using the Structural Similarity Index (SSIM).</p><h4>Summary of Steps</h4><ol><li><strong>Data Preparation</strong>: We normalized and binarized the MNIST dataset and split it into training and test sets.</li><li><strong>RBM Implementation</strong>: We built an RBM class from scratch, including methods for training with Contrastive Divergence, reconstructing data, and visualizing learned weights.</li><li><strong>Training</strong>: We trained the RBM using mini-batch gradient descent and monitored the learning process through weight visualizations.</li><li><strong>Visualization</strong>: We generated a GIF to visualize how the RBM’s weights evolved during training.</li><li><strong>Evaluation</strong>: We tested the RBM on the test set and computed the SSIM score to quantitatively assess the quality of the reconstructed images.</li></ol><h4>Personal Reflections</h4><p>Implementing the RBM from scratch provided valuable insights into the inner workings of this type of model. By handling the training process and weight updates manually, we gained a deeper understanding of how RBMs learn and reconstruct data. The visualization of the learned features and the evaluation metrics further highlighted the effectiveness of the model in capturing and reproducing the essential characteristics of handwritten digits.</p><p>Feel free to explore the complete implementation and experiment with different configurations and datasets. You can find the detailed code and additional notes in my <a href="https://github.com/Sopralapanca/medium-articles/blob/main/PatternRecognition/%5BMedium%5DRestrictedBoltzmanMachine.ipynb">GitHub notebook</a>.</p><p>If you liked the article and want to help me write better and better articles, don’t forget to follow me and contribute a tip by clicking this <a href="https://www.paypal.com/donate/?hosted_button_id=3UNX7F6AFLG96">link</a> or the buttons below :) Thank you very much!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=806842c0a37b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Unsupervised Image Segmentation using Normalized Cuts (NCut) in Python]]></title>
            <link>https://medium.com/@giacomo__95/a-guide-to-unsupervised-image-segmentation-using-normalized-cuts-ncut-in-python-779be5a66875?source=rss-dd74b6a2cd57------2</link>
            <guid isPermaLink="false">https://medium.com/p/779be5a66875</guid>
            <category><![CDATA[normalized-cut]]></category>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ncut]]></category>
            <dc:creator><![CDATA[Giacomo Carfì]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 12:30:41 GMT</pubDate>
            <atom:updated>2024-09-09T12:31:27.105Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Image segmentation plays a vital role in understanding and analyzing visual data, and <strong>Normalized Cuts (NCut)</strong> is a widely used method for graph-based segmentation. In this article, we will explore how to apply NCut for unsupervised image segmentation in Python using a dataset from Microsoft Research, with a focus on improving segmentation quality using superpixels.</p><h3>Dataset Overview</h3><p>The dataset used for this task can be downloaded from the following link: <a href="http://download.microsoft.com/download/A/1/1/A116CD80-5B79-407E-B5CE-3D5C6ED8B0D5/msrc_objcategimagedatabase_v1.zip%20-O%20msrc_objcategimagedatabase_v1.zip">MSRC Object Category Image Database</a>. This dataset contains original images as well as their semantic segmentation into nine object classes (indicated by image files ending with “_GT”). These images are grouped into thematic subsets, where the first number in the file name refers to a class subset. This dataset is perfect for experimenting with segmentation tasks.</p><h3>Problem Statement</h3><p>We perform image segmentation on an image in the dataset using the <strong>NCut algorithm. </strong>Segmentation at the pixel level is computationally expensive and often noisy. To overcome this, we use <strong>SLIC</strong> (Simple Linear Iterative Clustering) to generate <strong>superpixels</strong>, which groups similar pixels and reduces the problem size. To evaluate the accuracy of the segmentation different metrics (e.g., Intersection over Union, SSIM, Rand Index) can be used.</p><h3>Implementation</h3><h4>1. Install Required Libraries</h4><p>We use skimage for image processing, numpy for numerical computations, and matplotlib for visualization.</p><pre>pip install numpy matplotlib<br>pip install scikit-image==0.24.0</pre><h4>2. Load and Preprocess the Dataset</h4><p>After downloading and extracting the dataset, load the images and ground truth segmentation:</p><pre>wget http://download.microsoft.com/download/A/1/1/A116CD80-5B79-407E-B5CE-3D5C6ED8B0D5/msrc_objcategimagedatabase_v1.zip -O msrc_objcategimagedatabase_v1.zip<br>unzip msrc_objcategimagedatabase_v1.zip<br>rm msrc_objcategimagedatabase_v1.zip</pre><pre>from skimage import io, segmentation, color, measure<br>from skimage import graph<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Load the image and its ground truth<br>image = io.imread(&#39;/content/MSRC_ObjCategImageDatabase_v1/1_16_s.bmp&#39;)<br>ground_truth = io.imread(&#39;/content/MSRC_ObjCategImageDatabase_v1/1_16_s_GT.bmp&#39;)<br><br># show images side by side<br>fig, ax = plt.subplots(1, 2, figsize=(10, 5))<br>ax[0].imshow(image)<br>ax[0].set_title(&#39;Image&#39;)<br>ax[1].imshow(ground_truth)<br>ax[1].set_title(&#39;Ground Truth&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*m0xlQACRa9iRPwba9ZUsOA.png" /></figure><h4>3. Generate Superpixels using SLIC and create a Region Adjacency Graph</h4><p>We use the SLIC algorithm to compute superpixels before applying NCut. Using the generated superpixels, we construct a <strong>Region Adjacency Graph (RAG)</strong> based on mean color similarity:</p><pre>from skimage.util import img_as_ubyte, img_as_float, img_as_uint, img_as_float64<br><br>compactness=30 <br>n_segments=100 <br>labels = segmentation.slic(image, compactness=compactness, n_segments=n_segments, enforce_connectivity=True)<br>image_with_boundaries = segmentation.mark_boundaries(image, labels, color=(0, 0, 0))<br>image_with_boundaries = img_as_ubyte(image_with_boundaries)<br>pixel_labels = color.label2rgb(labels, image_with_boundaries, kind=&#39;avg&#39;, bg_label=0</pre><p>compactness controls the balance between the color similarity and spatial proximity of pixels when forming superpixels. It determines how much emphasis is placed on keeping the superpixels compact (closer in spatial terms) versus ensuring that they are more homogeneously grouped by color.</p><p><strong>Higher Values</strong>: A higher compactness value causes the algorithm to prioritize creating superpixels that are spatially tight and uniform in size, with less attention to color similarity. This might result in superpixels that are less sensitive to edges or color gradients.</p><p><strong>Lower Values</strong>: A lower compactness value allows the superpixels to vary more in spatial size in order to respect the color differences more accurately. This typically results in superpixels that follow the boundaries of objects in the image more closely.</p><p>n_segments controls the number of superpixels (or segments) that the SLIC algorithm attempts to generate in the image. Essentially, it sets the resolution of the segmentation.</p><p><strong>Higher Values</strong>: A higher n_segments value creates more superpixels, which means each superpixel will be smaller and the segmentation will be more fine-grained. This can be useful when the image has complex textures or small objects.</p><p><strong>Lower Values</strong>: A lower n_segments value produces fewer, larger superpixels. This is useful when you want a coarse segmentation of the image, grouping larger areas into single superpixels.</p><h4>4. Apply Normalized Cuts (NCut) and Visualize the Result</h4><pre># using the labels found with the superpixeled image<br># compute the Region Adjacency Graph using mean colors<br>g = graph.rag_mean_color(image, labels, mode=&#39;similarity&#39;)<br><br># perform Normalized Graph cut on the Region Adjacency Graph<br>labels2 = graph.cut_normalized(labels, g)<br>segmented_image = color.label2rgb(labels2, image, kind=&#39;avg&#39;)</pre><pre>f, axarr = plt.subplots(nrows=1, ncols=4, figsize=(25, 20))<br><br>axarr[0].imshow(image)<br>axarr[0].set_title(&quot;Original&quot;)<br><br>#plot boundaries<br>axarr[1].imshow(image_with_boundaries)<br>axarr[1].set_title(&quot;Superpixels Boundaries&quot;)<br><br>#plot labels<br>axarr[2].imshow(pixel_labels)<br>axarr[2].set_title(&#39;Superpixel Labels&#39;)<br><br>#compute segmentation<br>axarr[3].imshow(segmented_image)<br>axarr[3].set_title(&#39;Segmented image (normalized cut)&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5ypHEmiHiDnSO_3JKGNsw.png" /></figure><h4>5. Evaluation Metrics</h4><p>The key challenge in unsupervised segmentation is that NCut doesn’t know the exact number of classes in the image. The number of segments found by NCut may exceed the actual number of ground truth regions. As a result, we need robust metrics to assess segmentation quality.</p><p>Intersection Over Union (IoU)</p><p><strong>Intersection over Union (IoU)</strong> is a widely used metric for evaluating segmentation tasks, particularly in computer vision. It measures the overlap between the predicted segmented regions and the ground truth regions. Specifically, IoU calculates the ratio of the area of overlap between the predicted segmentation and the ground truth to the area of their union.</p><p>Structural Similarity Index (SSIM)</p><p><strong>Structural Similarity Index (SSIM)</strong> is a metric used to assess the perceived quality of an image by comparing two images in terms of <strong>luminance, contrast, and structure</strong></p><p>To apply these metrics we need that the prediction and the ground truth image have the same labels. To compute the labels we compute a mask on the ground and on the prediction assign an ID to each color found on the image</p><p>Segmentation using NCut however may find more regions than ground truth, this will lower the accuracy.</p><pre>def compute_mask(image):<br>  color_dict = {}<br><br>  # Get the shape of the image<br>  height,width,_ = image.shape<br><br>  # Create an empty array for labels<br>  labels = np.zeros((height,width),dtype=int)<br>  id=0<br>  # Loop over each pixel<br>  for i in range(height):<br>      for j in range(width):<br>          # Get the color of the pixel<br>          color = tuple(image[i,j])<br>          # Check if it is in the dictionary<br>          if color in color_dict:<br>              # Assign the label from the dictionary<br>              labels[i,j] = color_dict[color]<br>          else:<br>              color_dict[color]=id<br>              labels[i,j] = id<br>              id+=1<br><br>  return(labels)</pre><pre>def show_img(prediction, groundtruth):<br>  f, axarr = plt.subplots(nrows=1, ncols=2, figsize=(15, 10))<br><br>  axarr[0].imshow(groundtruth)<br>  axarr[0].set_title(&quot;groundtruth&quot;)<br>  axarr[1].imshow(prediction)<br>  axarr[1].set_title(f&quot;prediction&quot;)</pre><pre>prediction_mask = compute_mask(segmented_image)<br>groundtruth_mask = compute_mask(ground_truth)<br><br>#usign the original image as baseline to convert from labels to color<br>prediction_img = color.label2rgb(prediction_mask, image, kind=&#39;avg&#39;, bg_label=0)<br>groundtruth_img = color.label2rgb(groundtruth_mask, image, kind=&#39;avg&#39;, bg_label=0)<br><br>show_img(prediction_img, groundtruth_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*papljdjnmGeRDIqkIid7dg.png" /></figure><pre>from sklearn.metrics import jaccard_score<br>from skimage.metrics import structural_similarity as ssim<br><br>ssim_score = ssim(prediction_img, groundtruth_img, channel_axis=2)<br>print(f&quot;SSIM SCORE: {ssim_score}&quot;)<br><br>jac = jaccard_score(y_true=np.asarray(groundtruth_mask).flatten(),<br>                        y_pred=np.asarray(prediction_mask).flatten(),<br>                        average = None)<br><br># compute mean IoU score across all classes<br>mean_iou = np.mean(jac)<br>print(f&quot;Mean IoU: {mean_iou}&quot;)</pre><h3>Conclusion</h3><p>Normalized Cuts is a powerful method for unsupervised image segmentation, but it comes with challenges such as over-segmentation and tuning parameters. By incorporating superpixels and evaluating the performance using appropriate metrics, NCut can effectively segment complex images. The IoU and Rand Index metrics provide meaningful insights into the quality of segmentation, though further refinement is needed to handle multi-class scenarios effectively.</p><p>Finally, a complete example is available in my notebook <a href="https://github.com/Sopralapanca/medium-articles/blob/main/PatternRecognition/%5BMedium%5DNCut.ipynb">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=779be5a66875" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: How to Automate Instagram Posts Likes, Reels, using Instagrapi in Python]]></title>
            <link>https://medium.com/@giacomo__95/how-to-automate-instagram-posts-likes-reels-using-instagrapi-in-python-37568642bc73?source=rss-dd74b6a2cd57------2</link>
            <guid isPermaLink="false">https://medium.com/p/37568642bc73</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[reel]]></category>
            <category><![CDATA[instagram-followers]]></category>
            <dc:creator><![CDATA[Giacomo Carfì]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 07:57:57 GMT</pubDate>
            <atom:updated>2024-09-08T11:23:26.283Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObjfKIqm50QxQUTcEhy67g.png" /></figure><p>Instagram is a powerful platform for sharing content, growing an audience, and connecting with people. However, managing an account — especially a professional or business one — can be time-consuming. In this tutorial, I’ll show you how to automate some of the more tedious Instagram tasks using the <strong>Instagrapi</strong> Python library, such as creating posts, reels, following users, and more.</p><p>By the end of this article, you’ll be able to:</p><ul><li>Automate photo and video posts</li><li>Post comments and hashtags on your content</li><li>Manage followers and following lists</li><li>Automate following a user</li></ul><p>Let’s get started!</p><h3>Step 1: Installing the Required Library</h3><p>First, make sure you have Python installed. Then, install the Instagrapi library (version 2.1.2) for this tutorial to ensure compatibility and reproducibility.</p><pre>pip install instagrapi==2.1.2</pre><h3>Step 2: Logging Into Your Instagram Account</h3><p>Before interacting with Instagram, you need to log into your account. For security reasons, it’s recommended to store the login session so that you don’t have to log in repeatedly.</p><p>Here’s how you can define your username and password and log in to the Instagrapi client:</p><pre>from instagrapi import Client<br>import random<br><br># Define your username and password<br>instagram_username = &quot;YOUR USERNAME&quot;<br>instagram_password = &quot;YOUR PASSWORD&quot;<br><br># Initialize the client and load session<br>ig_client = Client()<br>instagram_session = &quot;instagram_session&quot;<br>instagram_session_path = f&quot;./{instagram_session}.json&quot;<br><br># Try loading an existing session, otherwise log in<br>try:<br>    ig_client.load_settings(instagram_session_path)<br>except FileNotFoundError:<br>    ig_client.login(instagram_username, instagram_password)<br>    ig_client.dump_settings(instagram_session_path)</pre><p>If this is your first time logging in, Instagram may ask for verification via email or SMS. You will need to enter that code to proceed.</p><h3>Step 3: Posting a Photo with a Comment</h3><p>Once logged in, you can automate posting a photo to your feed. You can also leave a comment or include hashtags directly in the caption.</p><p>Here’s an example of how to upload an image:</p><pre># Define image path, caption, and hashtags<br>img_path = &quot;./img.jpg&quot;<br>text = &quot;A beautiful caption here!&quot;<br>hashtags = &quot;#hashtag1 #hashtag2&quot;<br><br># Upload the photo<br>media = ig_client.photo_upload(img_path, caption=text)<br><br># Leave a comment with hashtags<br>media_id = media.dict()[&quot;id&quot;]<br>ig_client.media_comment(media_id, f&quot;\n\n\n\n {hashtags}&quot;)</pre><h3>Step 4: Posting a Reel with Hashtags</h3><p>Similarly, you can post Instagram reels. Here’s how:</p><pre># Define video path, caption, and hashtags<br>video_path = &quot;./video_reel.mp4&quot;<br>text = &quot;A beautiful caption here!&quot;<br>hashtags = &quot;#hashtag1 #hashtag2&quot;<br><br># Upload the reel<br>media = ig_client.clip_upload(video_path, caption=text)<br><br># Leave a comment with hashtags<br>media_id = media.dict()[&quot;id&quot;]<br>ig_client.media_comment(media_id, f&quot;{hashtags}&quot;)</pre><h3>Step 5: Managing Followers and Following</h3><p>You can retrieve the list of your followers and people you follow using Instagrapi. This is useful for managing your account or simply keeping track of your connections.</p><pre># Get your user ID (PK)<br>my_pk = ig_client.account_info().dict()[&quot;pk&quot;]<br><br># Retrieve followers and following lists<br>following_dict = ig_client.user_following(my_pk)<br>followers_dict = ig_client.user_followers(my_pk)</pre><h3>Step 6: Following a Random User</h3><p>One cool feature of Instagrapi is that it allows you to follow users programmatically. Be cautious with this functionality as overuse can result in your account being flagged as a bot.</p><p>Here’s how to follow a random user from your followers’ list:</p><pre># Get the ID of a random follower who is not private<br>ids = [key for key, user in followers_dict.items() if not user.is_private]<br>random_user = random.choice(ids)<br><br># Retrieve this user&#39;s followers<br>random_user_followers = ig_client.user_followers(random_user)<br>ids = [key for key, user in random_user_followers.items() if not user.is_private]<br><br># Follow one of their followers if available<br>if len(ids) &gt; 0:<br>    random_user_follower = random.choice(ids)<br>    ig_client.user_follow(random_user_follower)<br>else:<br>    print(f&quot;No followers for user with id {random_user_followers}&quot;)</pre><h3>Step 7: Liking a Post</h3><p>You can also automate liking posts. Here’s how to like the most recent post from one of your following accounts:</p><pre># Get the ID of a random user you are following<br>ids = [key for key, user in following_dict.items() if not user.is_private]<br>random_user = random.choice(ids)<br><br># Retrieve their media (posts)<br>media_list = ig_client.user_medias(random_user)<br><br># Like their latest post<br>if len(media_list) &gt; 0:<br>    last_post_id = media_list[0].dict()[&quot;id&quot;]<br>    ig_client.media_like(last_post_id)<br>else:<br>    print(f&quot;No media for user with id {random_user}&quot;)</pre><h3>Conclusion</h3><p>By following this tutorial, you’ve now automated several tasks on Instagram, from posting photos and reels to following users and liking posts. This is a powerful way to save time, especially if you manage multiple accounts or need to maintain regular activity.</p><p>Be mindful of Instagram’s policies, especially around bot-like behavior such as automated follows and likes, to avoid penalties.</p><p>To explore more advanced functionalities of the Instagrapi library, check out the <a href="https://subzeroid.github.io/instagrapi/">official documentation here</a>.</p><p>Finally, a complete example is available in my notebook <a href="https://github.com/Sopralapanca/medium-articles/blob/main/Instagram/%5BMedium%5DInstagrapi.ipynb">here</a>.</p><p>Happy automating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37568642bc73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: How to Build Telegram Bots with Python and Telethon. A Beginner’s Guide.]]></title>
            <link>https://medium.com/@giacomo__95/how-to-build-telegram-bots-with-python-and-telethon-a-beginners-guide-81ca94999a02?source=rss-dd74b6a2cd57------2</link>
            <guid isPermaLink="false">https://medium.com/p/81ca94999a02</guid>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[telethon]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[telegramchannels]]></category>
            <dc:creator><![CDATA[Giacomo Carfì]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 22:08:09 GMT</pubDate>
            <atom:updated>2024-09-09T07:47:24.216Z</atom:updated>
            <content:encoded><![CDATA[<p>Telegram has become a powerful personal, professional, and even automated communication tool. Telethon, a Python-based library, provides a seamless way to interact with Telegram’s API, enabling users to easily automate tasks, manage accounts, and create bots. However, as with any rapidly growing technology, keeping up with the latest developments can be a challenge. I found myself navigating a sea of outdated tutorials, deprecated methods, and broken scripts when trying to automate my Telegram workflow. That’s exactly why I decided to write this beginner-friendly guide. Whether you’re completely new to Telegram automation or just looking for a clearer path forward, this guide is designed to help you build your first bot, automate your workflows, and make the most out of Telethon from the ground up.</p><h3>Setup</h3><p>First, <a href="https://my.telegram.org/">click here</a>. This is the official Telegram platform where developers can manage their apps and access Telegram’s API. Once there, log in using the phone number associated with your Telegram account. After logging in, you’ll need to create a new application, which is essential for interacting with Telegram’s API.</p><p>To do this, enter a name for your app in the “App title” field and a short identifier in the “Short name” field (this is usually just a brief version of your app’s name). You can leave the “URL” field blank if you don’t have a specific URL to associate with your app. Next, select a platform from the dropdown (e.g., Desktop, Mobile, Web) and click the “Create Application” button. After completing these steps, you’ll receive an api_id and api_hash, which are crucial credentials that your Telethon scripts will use to authenticate and interact with Telegram&#39;s servers</p><h3>Installation</h3><p>Installing Telethon is a straightforward process that can be done using Python’s package manager, pip. Simply run pip install telethon in your terminal to get started. This will install the latest version of Telethon along with all the necessary dependencies, ensuring you&#39;re ready to dive into Telegram automation with ease. For reproducibility, install the same version I used for this tutorial.</p><pre>pip install Telethon==1.36.0</pre><p>If you are running the script in a Google Colab notebook also install this to avoid conflicts with already running event loop in the Colab environment</p><pre># to run the script in google colab, this can be avoided if you are running the code in your pc <br>!pip install nest_asyncio<br><br>import nest_asyncio<br><br># Apply the patch to allow nested event loops<br>nest_asyncio.apply()</pre><p>Once installed, you’re ready to build your Telegram bot.</p><h3>Configuring Your Telethon Client</h3><p>To set up your Telethon client, you need to provide your Telegram API credentials. Replace api_id and api_hash with the values you obtained from <a href="https://my.telegram.org/">my.telegram.org</a>, and set phone to your phone number in international format, including the country code (e.g., +1234567890).</p><pre>api_id = &quot;YOUR API ID&quot;<br>api_hash = &quot;YOUR API HASH&quot;<br>phone = &quot;YOUR PHONE NUMBER WITH +xxx&quot;</pre><p>Import some libraries that we will use later</p><pre>from telethon import TelegramClient, events<br>import asyncio<br>import os<br>from sqlite3 import OperationalError</pre><p>Login to the TelegramClient. When you run the script below for the first time, it will prompt you to log in to the TelegramClient. You’ll receive a security code via Telegram; enter this code when prompted and press enter to authenticate and start using your Telethon client.</p><pre>if __name__ == &#39;__main__&#39;:<br><br>    telethon_session_name = &#39;telethon_session&#39;<br>    session_file = f&#39;./{telethon_session_name}.session&#39;<br>    <br>    try:<br>      telegram_client = TelegramClient(session_file, api_id, api_hash)<br>    <br>    except OperationalError:<br>      # if you have login problem like locked database, try to delete it<br>      if os.path.exists(session_file):<br>          os.remove(session_file)<br>          telegram_client = TelegramClient(session_file, api_id, api_hash)<br>      else:<br>          raise<br><br>    try:<br>        loop = asyncio.get_event_loop()<br>        loop.run_until_complete(<br>            main(tg_client=telegram_client))<br>    except Exception as e:<br>        print(f&quot;An error occurred: {e}&quot;)<br>    finally:<br>        # If you run the script in google colab leave the following code commented, otherwhise remove comments and delete pass<br>        #loop.run_until_complete(asyncio.sleep(2)) <br>        #loop.close()<br>        pass</pre><h3>Handling Incoming Messages and Media Automation</h3><p>Now we focus on automating the process of handling incoming messages and managing media within specified Telegram channels. The provided code snippet sets up a Telethon client to listen for new messages from a list of channels. When a new message arrives, the script retrieves the latest message from the channel, downloads any attached media to a specified path, and then forwards this media to another channel with a custom caption. This automation is particularly useful for tasks like aggregating content from multiple channels and redistributing it efficiently.</p><p>First, define the names of the channels you want to monitor and the channel you own where you want to forward messages.</p><pre>#suppose we want to monitor a list of channels and manage an owned channel<br>channels_list = [&quot;channel1&quot;, &quot;channel2&quot;]<br>my_channel = &quot;my_channel&quot;</pre><p>Next, we utilize the NewMessage event, which triggers whenever a new message arrives in your account. The script checks if the sender of the message is one of the monitored channels, retrieves the latest message from that channel, and uses download_media() it to download any attached files. Subsequently, it employs send_file() to forward the downloaded file to your own channel.</p><pre>async def main(tg_client):<br>  print(&quot;starting...&quot;)<br>  await tg_client.start(phone)<br><br>  @tg_client.on(events.NewMessage(incoming=True, from_users=channels_list))<br>  async def my_event_handler(event):<br><br>      sender = await event.get_sender()<br><br>      if sender.username in channels_list:<br>          channel = sender.username<br>          <br>          # get last message of the channel<br>          async for message in tg_client.iter_messages(channel, limit=1):<br>              print(message.text)<br>              <br>              img_path = &quot;./imgs/image.jpg&quot;<br>              await tg_client.download_media(message=message.media, file=img_path)<br><br>              await tg_client.send_file(entity=my_channel, file=img_path, caption=&quot;My Caption&quot;)<br>  <br>  <br>  await tg_client.run_until_disconnected()</pre><p>Additional actions can be explored by reviewing the official Telegram API documentation. For a complete example, refer to this <a href="https://github.com/Sopralapanca/medium-articles/blob/main/Telegram/%5BMedium%5DTelethon.ipynb">notebook</a>. You can also check out the full list of available events at <a href="https://docs.telethon.dev/en/stable/modules/events.html">Telethon’s events documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81ca94999a02" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>