<?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 Gabriel Rodewald on Medium]]></title>
        <description><![CDATA[Stories by Gabriel Rodewald on Medium]]></description>
        <link>https://medium.com/@gabrielrodewald?source=rss-6f32802fcc06------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FVIAROV4qm3IRt_0NoWveg.jpeg</url>
            <title>Stories by Gabriel Rodewald on Medium</title>
            <link>https://medium.com/@gabrielrodewald?source=rss-6f32802fcc06------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 17:05:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gabrielrodewald/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[Production-Ready LLM Security with Ansible: Complete Step-by-Step Guide Introduction to Ansible]]></title>
            <link>https://medium.com/@gabrielrodewald/production-ready-llm-security-with-ansible-complete-step-by-step-guide-introduction-to-ansible-a1d495b9c5df?source=rss-6f32802fcc06------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1d495b9c5df</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[Gabriel Rodewald]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 16:36:02 GMT</pubDate>
            <atom:updated>2025-09-01T16:36:02.693Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*q9AmhOZJ8Qzf-wRj7Jo92g.jpeg" /></figure><p>Planning to host your own LLM chat server but worried about security?</p><p><strong>You’re absolutely right to be concerned.</strong></p><p>Setting up proper security isn’t just about installing a firewall and calling it a day — it requires a systematic approach that covers multiple layers of protection.</p><p>You can skip to a specific section if you’ve had previous experience with server security. What you’ll find in this article:</p><ul><li>What is Ansible and why use it for server security?</li><li>Essential security tools every server needs</li><li>Setting up your Ansible environment properly</li><li>Creating bulletproof server hardening playbooks</li><li>Implementing fail2ban for intrusion prevention</li><li>UFW firewall configuration for LLM servers</li><li>System monitoring and log management</li><li>Testing your security setup</li></ul><h3>1. What is Ansible and Why Security First?</h3><p>Ansible is a bloody brilliant automation tool that lets you manage server configurations through code. Instead of manually SSH-ing into servers and running commands (which is error-prone and doesn’t scale), you write “playbooks” that describe exactly how your servers should be configured.</p><p>For LLM deployment, security should be your first priority, not an afterthought. These servers often handle sensitive data, consume significant resources, and become attractive targets for attackers looking to exploit computational power for cryptocurrency mining or worse.</p><p>➡️ Ansible Documentation: <a href="https://docs.ansible.com/">https://docs.ansible.com</a></p><p>➡️ Why Security First: Because your LLM server will be exposed to the internet, and attacks start within minutes of deployment</p><h3>2. Essential Security Tools Every Server Needs</h3><p>Before we dive into playbooks, let’s understand the core security components we’ll be deploying.</p><h4>Fail2Ban</h4><p>Your first line of defence against brute-force attacks. It monitors log files and automatically bans IP addresses that show malicious behaviour patterns. Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IhLhgQClwStQWkmMFDvR5w.png" /></figure><p>If you’d like to keep custom filters, the easiest way is to create a custom jail and add your filters.</p><ol><li>Create new filter and save the file:</li></ol><pre># cd /etc/fail2ban/filter.d/nginx-spring-acurator.conf<br><br># --------------------------------------------------<br># nginx-spring-acurator.conf, including comments<br># --------------------------------------------------<br># Spring Boot Actuator Security Filter<br># Detects unauthorized access to Spring Boot Actuator endpoints<br><br>[Definition]<br><br># Spring Boot Actuator endpoint access attempts<br>failregex = ^&lt;HOST&gt; .* &quot;(GET|POST) /?actuator/?.*&quot; \d+ \d+<br>            ^&lt;HOST&gt; .* &quot;(GET|POST) /?management/?.*&quot; \d+ \d+<br><br>            # Specific high-risk actuator endpoints<br>            ^&lt;HOST&gt; .* &quot;(GET|POST) /?actuator/(beans|configprops|dump|env|health|info|mappings|metrics|shutdown|trace|heapdump|threaddump|gateway/routes).*&quot; \d+ \d+<br><br>            # Management endpoints<br>            ^&lt;HOST&gt; .* &quot;(GET|POST) /?management/(health|info|metrics|env|configprops|beans|mappings|shutdown).*&quot; \d+ \d+<br><br>            # Jolokia JMX access attempts<br>            ^&lt;HOST&gt; .* &quot;(GET|POST) /?jolokia/?.*&quot; \d+ \d+<br><br>            # Spring Boot admin endpoints<br>            ^&lt;HOST&gt; .* &quot;(GET|POST) /?admin/?.*&quot; \d+ \d+<br><br>ignoreregex =</pre><p>2. Test filter against access.log:</p><pre>sudo fail2ban-regex /var/log/nginx/access.log /etc/fail2ban/filter.d/nginx-spring-acurator.conf<br><br># To check what went wrong, use:<br># to find phrase in multiple files:<br># grep -r &quot;\\%&quot; /etc/fail2ban/filter.d/ | grep &lt;phrase&gt;<br><br># to check fail2ban journal:<br># sudo journalctl -u fail2ban.service -n 10 --no-pager -l</pre><p>3. Add filter to custom jail:</p><pre># cd /etc/fail2ban/jail.d/<br>touch my-custom-nginx-jail.conf<br><br># --------------------<br># file content<br># --------------------<br>[DEFAULT]<br>bantime = 3600 # 1h<br>findtime = 600 # 10 minutes<br>maxretry = 3<br><br>[nginx-spring-actuator]<br>enabled = true<br>filter = nginx-spring-actuator<br>action = iptables-allports[name=nginx-spring-actuator, protocol=all]<br>logpath = /var/log/nginx/access.log<br>         /var/log/nginx/error.log<br>maxretry = 1<br>bantime = 172800<br>findtime = 1200<br><br># other filters<br># ...</pre><p>4. Reload fail2ban</p><p>Check current fail2ban status and if all’s fine, reload:</p><pre># check<br>fail2ban-client -t<br>fail2ban-client status<br><br># reload<br>systemctl restart fail2ban</pre><h4>UFW (Uncomplicated Firewall)</h4><p>A straightforward interface for iptables that controls network traffic to your server. We’ll configure it to allow only necessary ports. Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YbxE6brM15zk2HPiTI4NKA.png" /></figure><p><strong>Lynis</strong>: Security auditing tool that scans your system and provides hardening recommendations. Report example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*bjhBvUE5FDwdoFNQAAIPTA.png" /></figure><h4><strong>ClamAV</strong></h4><p>Antivirus scanner for detecting malware and suspicious files.</p><h4><strong>Suricata</strong></h4><p>Network intrusion detection system that monitors network traffic for threats.</p><h4><strong>GoAccess</strong></h4><p>Real-time web log analyzer and interactive viewer that provides fast, valuable HTTP statistics by parsing server access logs. Report example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hv6k4mT2W4oqus-kfyUUpQ.png" /></figure><h3>3. Setting Up Your Ansible Environment</h3><h4>Installing Ansible on Windows (WSL)</h4><p>If you’re on Windows, you’ll need WSL. Here’s the proper setup:</p><pre># Open PowerShell as Administrator<br>wsl --install<br><br># After restart, in WSL terminal:<br>sudo apt update &amp;&amp; sudo apt upgrade -y<br>sudo apt install software-properties-common<br>sudo apt-add-repository ppa:ansible/ansible<br>sudo apt update<br>sudo apt install ansible -y<br>ansible --version</pre><h4>SSH Key Management</h4><p>Copy your SSH keys to WSL and set proper permissions:</p><pre>cd /root/.ssh<br><br># Obligatory on WSL, as you cannot change privileges of the host file<br>cp /mnt/c/Users/YOUR_USERNAME/.ssh/* .<br><br># Critical: Set restrictive permissions<br>chmod 600 your_private_key<br>chmod 644 your_private_key.pub</pre><p>⚠️ Important: SSH will refuse keys with overly permissive permissions. Always use chmod 600 for private keys.</p><h4>Project Directory Structure</h4><p>Create a proper Ansible project structure:</p><pre>mkdir llm-server-security &amp;&amp; cd llm-server-security<br><br># Create the directory structure<br>mkdir -p {group_vars,host_vars,roles,playbooks,inventory}<br><br># Your structure should look like:<br>├── inventory.ini<br>├── group_vars/<br>│   └── all.yml<br>├── host_vars/<br>│   └── your-server.yml<br>├── roles/<br>├── playbooks/<br>└── ansible.cfg</pre><h3>4. Creating Your Inventory and Host Variables</h3><h4>inventory.ini</h4><pre>[llm_servers]<br>your-llm-server ansible_host=YOUR_SERVER_IP ansible_port=22 ansible_user=YOUR_USER ansible_become=true<br><br>[webservers:children]<br>llm_servers</pre><h4>host_vars/your-llm-server.yml</h4><p>Before creating this file, we’ll encrypt it with ansible-vault for security:</p><pre># Basic connection details<br>ansible_ssh_private_key_file: /path/to/your/private/key<br>ansible_become_password: YOUR_SUDO_PASSWORD<br>ansible_ssh_passphrase: YOUR_SSH_KEY_PASSPHRASE  # if applicable<br><br># Server-specific configuration<br>server_admin_email: admin@yourdomain.com<br>allowed_ssh_users:<br>  - your_username<br>  - backup_user<br><br># Security settings<br>fail2ban_destemail: security@yourdomain.com<br>fail2ban_sender: fail2ban@yourdomain.com<br>max_login_attempts: 5<br>ssh_port: 22  # We&#39;ll change this later</pre><p>⚠️ It’s not advised to keep SSH port set up to default 22, but please be carefull witch chaning it — you might lock yourself out from the server.</p><p>Encrypt this sensitive file:</p><pre>ansible-vault encrypt host_vars/your-llm-server.yml<br># You&#39;ll be prompted for a vault password - remember it!</pre><h3>5. Creating Your First Security Hardening Playbook</h3><p>Let’s create a comprehensive security playbook:</p><h4>playbooks/01-initial-security-setup.yml</h4><pre>---<br>- name: Initial Server Security Hardening for LLM Deployment<br>  hosts: llm_servers<br>  become: yes<br>  <br>  vars:<br>    security_ssh_port: 2200<br>    security_ssh_protocol: 2<br>    security_ssh_permit_root_login: &#39;no&#39;<br>    security_ssh_password_authentication: &#39;no&#39;<br>    <br>  tasks:<br>    - name: Update system packages<br>      apt:<br>        update_cache: yes<br>        upgrade: dist<br>        autoremove: yes<br>        autoclean: yes<br>      register: system_update<br>      <br>    - name: Install essential security packages<br>      apt:<br>        name:<br>          - fail2ban<br>          - ufw<br>          - unattended-upgrades<br>          - logwatch<br>          - rkhunter<br>          - chkrootkit<br>          - aide<br>        state: present<br>        update_cache: yes<br>        <br>    - name: Create security user with sudo privileges<br>      user:<br>        name: &quot;{{ ansible_user }}&quot;<br>        groups: sudo<br>        append: yes<br>        shell: /bin/bash<br>        createhome: yes<br>        <br>    - name: Configure SSH hardening<br>      lineinfile:<br>        dest: /etc/ssh/sshd_config<br>        regexp: &quot;{{ item.regexp }}&quot;<br>        line: &quot;{{ item.line }}&quot;<br>        state: present<br>        backup: yes<br>      with_items:<br>        - { regexp: &#39;^Port&#39;, line: &#39;Port {{ security_ssh_port }}&#39; }<br>        - { regexp: &#39;^Protocol&#39;, line: &#39;Protocol {{ security_ssh_protocol }}&#39; }<br>        - { regexp: &#39;^PermitRootLogin&#39;, line: &#39;PermitRootLogin {{ security_ssh_permit_root_login }}&#39; }<br>        - { regexp: &#39;^PasswordAuthentication&#39;, line: &#39;PasswordAuthentication {{ security_ssh_password_authentication }}&#39; }<br>        - { regexp: &#39;^X11Forwarding&#39;, line: &#39;X11Forwarding no&#39; }<br>        - { regexp: &#39;^MaxAuthTries&#39;, line: &#39;MaxAuthTries 3&#39; }<br>        - { regexp: &#39;^ClientAliveInterval&#39;, line: &#39;ClientAliveInterval 300&#39; }<br>        - { regexp: &#39;^ClientAliveCountMax&#39;, line: &#39;ClientAliveCountMax 2&#39; }<br>      notify: restart ssh<br>      <br>    - name: Configure automatic security updates<br>      copy:<br>        content: |<br>          APT::Periodic::Update-Package-Lists &quot;1&quot;;<br>          APT::Periodic::Download-Upgradeable-Packages &quot;1&quot;;<br>          APT::Periodic::AutocleanInterval &quot;7&quot;;<br>          APT::Periodic::Unattended-Upgrade &quot;1&quot;;<br>        dest: /etc/apt/apt.conf.d/20auto-upgrades<br>        backup: yes<br>        <br>  handlers:<br>    - name: restart ssh<br>      service:<br>        name: ssh<br>        state: restarted</pre><h3>6. Implementing Fail2Ban Protection</h3><p>Create a dedicated fail2ban configuration playbook:</p><h4>playbooks/02-configure-fail2ban.yml</h4><pre>---<br>- name: Configure Fail2Ban for Enhanced Security<br>  hosts: llm_servers<br>  become: yes<br>  <br>  tasks:<br>    - name: Install fail2ban<br>      apt:<br>        name: fail2ban<br>        state: present<br>        <br>    - name: Create fail2ban local configuration<br>      copy:<br>        content: |<br>          [DEFAULT]<br>          # Ban hosts for one hour:<br>          bantime = 3600<br>          <br>          # Override /etc/fail2ban/jail.d/00-firewalld.conf:<br>          banaction = iptables-multiport<br>          <br>          # A host is banned if it has generated &quot;maxretry&quot; during the last &quot;findtime&quot;<br>          findtime = 600<br>          maxretry = 5<br>          <br>          # &quot;ignoreip&quot; can be a list of IP addresses, CIDR masks or DNS hosts<br>          ignoreip = 127.0.0.1/8 ::1<br>          <br>          # Email configuration<br>          destemail = {{ fail2ban_destemail | default(&#39;root@localhost&#39;) }}<br>          sender = {{ fail2ban_sender | default(&#39;fail2ban@localhost&#39;) }}<br>          mta = sendmail<br>          <br>          [sshd]<br>          enabled = true<br>          port = ssh<br>          filter = sshd<br>          logpath = /var/log/auth.log<br>          maxretry = 3<br>          bantime = 1800<br>          <br>          [nginx-http-auth]<br>          enabled = true<br>          filter = nginx-http-auth<br>          port = http,https<br>          logpath = /var/log/nginx/error.log<br>          maxretry = 3<br>          <br>          [nginx-dos]<br>          enabled = true<br>          filter = nginx-dos<br>          port = http,https<br>          logpath = /var/log/nginx/access.log<br>          maxretry = 200<br>          findtime = 300<br>          bantime = 600<br>          <br>        dest: /etc/fail2ban/jail.local<br>        backup: yes<br>      notify: restart fail2ban<br>      <br>    - name: Create custom nginx-dos filter<br>      copy:<br>        content: |<br>          [Definition]<br>          # Fail2Ban filter for nginx DoS attacks<br>          failregex = ^&lt;HOST&gt; -.*&quot;(GET|POST).*HTTP.*&quot; (4|5)\d\d <br>          ignoreregex =<br>        dest: /etc/fail2ban/filter.d/nginx-dos.conf<br>      notify: restart fail2ban<br>      <br>    - name: Start and enable fail2ban service<br>      service:<br>        name: fail2ban<br>        state: started<br>        enabled: yes<br>        <br>  handlers:<br>    - name: restart fail2ban<br>      service:<br>        name: fail2ban<br>        state: restarted</pre><h3>7. Moving DNS to Cloudflare for Enhanced Protection</h3><p>Before configuring your firewall, it’s wise to move your DNS to Cloudflare. This provides an additional layer of protection through their proxy service and DDoS protection.</p><h4>Why Cloudflare?</h4><p>Cloudflare acts as a reverse proxy, hiding your server’s real IP address from potential attackers. It also provides:</p><ul><li>DDoS protection</li><li>Bot mitigation</li><li>Web Application Firewall (WAF)</li><li>SSL/TLS termination</li><li>Global CDN capabilities</li></ul><h4>Setting Up Cloudflare DNS</h4><ol><li>Create a Cloudflare account at <a href="https://dash.cloudflare.com/sign-up">https://dash.cloudflare.com/sign-up</a></li></ol><p>2. Add your domain to Cloudflare:</p><ul><li>Click “Add a Site”</li><li>Enter your domain name</li><li>Choose the Free plan (sufficient for most LLM setups)</li></ul><p>3. Copy your DNS records:</p><ul><li>Cloudflare will scan your existing DNS records</li><li>Verify all important records are detected</li><li>Add any missing records manually</li></ul><p>4. Update nameservers:</p><ul><li>Cloudflare will provide two nameservers (e.g., luna.ns.cloudflare.com)</li><li>Update these in your domain registrar’s control panel</li><li>Wait 24–48 hours for propagation</li></ul><p>5. Configure proxy settings:</p><ul><li>Enable the orange “Proxied” cloud for your web records (A, AAAA, CNAME)</li><li>Keep email records (MX) and direct access records as “DNS only” (grey cloud)</li></ul><p>⚠️ Important: Once proxied, only Cloudflare IP ranges should access your server’s HTTP/HTTPS ports.</p><h3>8. UFW Firewall Configuration for LLM Servers</h3><p>Now we’ll configure UFW to work with Cloudflare’s proxy service:</p><h4>playbooks/03-configure-firewall.yml</h4><pre>---<br>- name: Configure UFW Firewall for LLM Server with Cloudflare<br>  hosts: llm_servers<br>  become: yes<br>  <br>  vars:<br>    security_ssh_port: &quot;{{ ansible_port | default(2200) }}&quot;<br>    llm_api_port: &quot;8000&quot;  # Adjust as needed<br>      <br>  tasks:<br>    - name: Install UFW<br>      apt:<br>        name: ufw<br>        state: present<br>        <br>    - name: Reset UFW to defaults<br>      ufw:<br>        state: reset<br>        <br>    - name: Set UFW default policies<br>      ufw:<br>        default: deny<br>        direction: &quot;{{ item }}&quot;<br>      loop:<br>        - incoming<br>        - outgoing<br>        - routed<br>        <br>    - name: Allow outgoing traffic<br>      ufw:<br>        default: allow<br>        direction: outgoing<br>        <br>    - name: Allow SSH before enabling UFW<br>      ufw:<br>        rule: allow<br>        port: &quot;{{ security_ssh_port }}&quot;<br>        proto: tcp<br>        comment: SSH access<br>        <br>    - name: Allow internal LLM API access<br>      ufw:<br>        rule: allow<br>        port: &quot;{{ llm_api_port }}&quot;<br>        proto: tcp<br>        src: &quot;127.0.0.1&quot;<br>        comment: Internal LLM API access<br>        <br>    - name: Enable UFW<br>      ufw:<br>        state: enabled<br>        logging: on<br>        <br>    - name: Set UFW log level to low<br>      ufw:<br>        logging: low</pre><h3>9. Automated Cloudflare IP Updates for UFW</h3><p>Since Cloudflare regularly updates their IP ranges, we need to automate the UFW rules to ensure only Cloudflare can access your HTTP/HTTPS ports.</p><h4>Creating the Cloudflare UFW Update Script</h4><p>First, let’s create the automation script:</p><h4>playbooks/05-cloudflare-ufw-automation.yml#</h4><pre>---<br>- name: Setup Cloudflare UFW Automation<br>  hosts: llm_servers<br>  become: yes<br>  <br>  tasks:<br>    - name: Create scripts directory<br>      file:<br>        path: /home/{{ ansible_user }}/scripts/logs/cloudflare-ufw<br>        state: directory<br>        owner: &quot;{{ ansible_user }}&quot;<br>        group: &quot;{{ ansible_user }}&quot;<br>        mode: &#39;0755&#39;<br>        recurse: yes<br>        <br>    - name: Install required packages for Cloudflare automation<br>      apt:<br>        name:<br>          - curl<br>          - parallel<br>        state: present<br>        <br>    - name: Create Cloudflare UFW update script<br>      copy:<br>        content: |<br>          #!/bin/bash<br>          <br>          # --- Logging Setup ---<br>          LOG_DIR=&quot;/home/{{ ansible_user }}/scripts/logs/cloudflare-ufw&quot;<br>          LOG_FILE=&quot;$LOG_DIR/update-$(date +%Y-%m-%d_%H-%M-%S).log&quot;<br>          <br>          # Create log directory if it doesn&#39;t exist<br>          mkdir -p &quot;$LOG_DIR&quot;<br>          <br>          # Set up logging: both to file and stdout<br>          exec &gt; &gt;(tee -a &quot;$LOG_FILE&quot;) 2&gt;&amp;1<br>          <br>          # --- Script Content ---<br>          echo &quot;=== Cloudflare UFW Update Started: $(date) ===&quot;<br>          <br>          # URLs for Cloudflare IP lists<br>          CF_IPv4=&quot;https://www.cloudflare.com/ips-v4&quot;<br>          CF_IPv6=&quot;https://www.cloudflare.com/ips-v6&quot;<br>          <br>          # Temporary files to store IPs<br>          TMP_IPv4=$(mktemp)<br>          TMP_IPv6=$(mktemp)<br>          <br>          # Function to clean up temp files and exit<br>          cleanup() {<br>            rm -f &quot;$TMP_IPv4&quot; &quot;$TMP_IPv6&quot;<br>            exit<br>          }<br>          trap cleanup EXIT INT TERM<br>          <br>          # Function to fetch and validate Cloudflare IP list<br>          fetch_ips() {<br>            echo &quot;Fetching Cloudflare IP lists...&quot;<br>            if ! curl -s -f &quot;$CF_IPv4&quot; -o &quot;$TMP_IPv4&quot;; then<br>              echo &quot;ERROR: Failed to download Cloudflare IPv4 list from $CF_IPv4&quot; &gt;&amp;2<br>              cleanup<br>            fi<br>            if ! curl -s -f &quot;$CF_IPv6&quot; -o &quot;$TMP_IPv6&quot;; then<br>              echo &quot;ERROR: Failed to download Cloudflare IPv6 list from $CF_IPv6&quot; &gt;&amp;2<br>              cleanup<br>            fi<br>            if ! grep -qE &#39;^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]{1,2}</pre><h3>10. System Monitoring and Log Management</h3><p>Essential monitoring for your LLM server:</p><h4>playbooks/04-monitoring-setup.yml</h4><pre>---<br>- name: Setup System Monitoring and Logging<br>  hosts: llm_servers<br>  become: yes<br>  <br>  tasks:<br>    - name: Install monitoring tools<br>      apt:<br>        name:<br>          - htop<br>          - iotop<br>          - nethogs<br>          - logwatch<br>          - rsyslog<br>          - logrotate<br>          - goaccess  # Web log analyzer<br>        state: present<br>        <br>    - name: Configure logrotate for application logs<br>      copy:<br>        content: |<br>          /var/log/llm-server/*.log {<br>              daily<br>              missingok<br>              rotate 7<br>              compress<br>              delaycompress<br>              notifempty<br>              copytruncate<br>          }<br>        dest: /etc/logrotate.d/llm-server<br>        <br>    - name: Create log directory for LLM application<br>      file:<br>        path: /var/log/llm-server<br>        state: directory<br>        owner: www-data<br>        group: www-data<br>        mode: &#39;0755&#39;<br>        <br>    - name: Create reports directory for monitoring<br>      file:<br>        path: /home/{{ ansible_user }}/reports<br>        state: directory<br>        owner: &quot;{{ ansible_user }}&quot;<br>        group: &quot;{{ ansible_user }}&quot;<br>        mode: &#39;0755&#39;<br>        <br>    - name: Configure rsyslog for security events<br>      lineinfile:<br>        dest: /etc/rsyslog.d/50-security.conf<br>        line: &quot;{{ item }}&quot;<br>        create: yes<br>      with_items:<br>        - &quot;auth,authpriv.*    /var/log/auth.log&quot;<br>        - &quot;*.info;mail.none;authpriv.none;cron.none    /var/log/messages&quot;<br>      notify: restart rsyslog<br>      <br>  handlers:<br>    - name: restart rsyslog<br>      service:<br>        name: rsyslog<br>        state: restarted</pre><h3>11. Advanced Security Monitoring Scripts</h3><p>Let’s add some powerful monitoring scripts for ongoing security management:</p><h4>playbooks/06-advanced-monitoring-scripts.yml</h4><pre>---<br>- name: Deploy Advanced Security Monitoring Scripts<br>  hosts: llm_servers<br>  become: yes<br>  <br>  tasks:<br>    - name: Create banned IP checker script<br>      copy:<br>        content: |<br>          #!/bin/bash<br>          echo &quot;========== BANNED IP CHECK ===========&quot;<br>          for jail in $(sudo fail2ban-client status | grep &quot;Jail list&quot; | cut -d: -f2 | tr &#39;,&#39; &#39; &#39;); do<br>            banned_ips=$(sudo fail2ban-client status &quot;$jail&quot; | grep &quot;Banned IP list&quot; | cut -d: -f2)<br>            if [[ -n &quot;$banned_ips&quot; ]]; then<br>              echo &quot;Jail: $jail&quot;<br>              echo &quot;Banned IPs:$banned_ips&quot;<br>              echo &quot;--------------------&quot;<br>            fi<br>          done<br>          echo &quot;========== BANNED IP CHECK: DONE ==========&quot;<br>        dest: /home/{{ ansible_user }}/scripts/check-banned-ips.sh<br>        owner: &quot;{{ ansible_user }}&quot;<br>        group: &quot;{{ ansible_user }}&quot;<br>        mode: &#39;0755&#39;<br>        <br>    - name: Create fail2ban filter checker script<br>      copy:<br>        content: |<br>          #!/bin/bash<br>          # fail2ban_batch_filter_check.sh<br>          # Usage: ./fail2ban_batch_filter_check.sh /etc/fail2ban/filter.d /var/log/nginx/access.log /tmp/fail2ban_filters_check.log<br>          FILTER_DIR=&quot;$1&quot;<br>          ACCESS_LOG=&quot;$2&quot;<br>          LOG_FILE=&quot;$3&quot;<br>          <br>          # Overwrite log file each run<br>          : &gt; &quot;$LOG_FILE&quot;<br>          <br>          export ACCESS_LOG<br>          export LOG_FILE<br>          <br>          find &quot;$FILTER_DIR&quot; -maxdepth 1 -type f -name &#39;nginx*.conf&#39; | parallel --jobs 4 --no-notice --halt soon,fail=1 --linebuffer &#39;<br>            FILTER={}<br>            FILTER_NAME=$(basename &quot;$FILTER&quot;)<br>            START=$(date +%s)<br>            RESULT=$(timeout 20s fail2ban-regex &quot;$ACCESS_LOG&quot; &quot;$FILTER&quot; | grep -E &quot;Lines: [0-9]+ lines, [0-9]+ ignored, [0-9]+ matched, [0-9]+ missed&quot; || echo &quot;TIMEOUT or ERROR&quot;)<br>            END=$(date +%s)<br>            DURATION=$((END-START))<br>            if [ $DURATION -ge 20 ]; then<br>              RESULT=&quot;TIMEOUT (&gt;$DURATION sec)&quot;<br>            fi<br>            TS=$(date &quot;+%Y-%m-%d %H:%M:%S&quot;)<br>            echo &quot;$TS | $FILTER_NAME | $RESULT&quot; &gt;&gt; &quot;$LOG_FILE&quot;<br>          &#39;<br>        dest: /home/{{ ansible_user }}/scripts/fail2ban_batch_filter_check.sh<br>        owner: &quot;{{ ansible_user }}&quot;<br>        group: &quot;{{ ansible_user }}&quot;<br>        mode: &#39;0755&#39;<br>        <br>    - name: Create GoAccess web analytics script<br>      copy:<br>        content: |<br>          #!/bin/bash<br>          # Generate real-time web analytics report<br>          REPORT_DIR=&quot;/home/{{ ansible_user }}/reports&quot;<br>          <br>          # Ensure nginx access log exists<br>          if [[ ! -f /var/log/nginx/access.log ]]; then<br>            echo &quot;ERROR: Nginx access log not found at /var/log/nginx/access.log&quot;<br>            exit 1<br>          fi<br>          <br>          echo &quot;Generating GoAccess report...&quot;<br>          goaccess /var/log/nginx/access.log -o &quot;$REPORT_DIR/report.html&quot; --real-time-html \<br>            --log-format=COMBINED \<br>            --date-format=%d/%b/%Y \<br>            --time-format=%T<br>          <br>          echo &quot;Report generated: $REPORT_DIR/report.html&quot;<br>          echo &quot;Access it via: http://YOUR_SERVER_IP:8080/report.html (if you set up a web server)&quot;<br>        dest: /home/{{ ansible_user }}/scripts/generate-web-report.sh<br>        owner: &quot;{{ ansible_user }}&quot;<br>        group: &quot;{{ ansible_user }}&quot;<br>        mode: &#39;0755&#39;<br>        <br>    - name: Create daily security check script<br>      copy:<br>        content: |<br>          #!/bin/bash<br>          # Daily security check script<br>          <br>          LOG_FILE=&quot;/home/{{ ansible_user }}/scripts/logs/daily-security-$(date +%Y-%m-%d).log&quot;<br>          <br>          echo &quot;=== Daily Security Check: $(date) ===&quot; | tee -a &quot;$LOG_FILE&quot;<br>          <br>          # Check fail2ban status<br>          echo &quot;--- Fail2ban Status ---&quot; | tee -a &quot;$LOG_FILE&quot;<br>          sudo fail2ban-client status | tee -a &quot;$LOG_FILE&quot;<br>          <br>          # Check UFW status  <br>          echo &quot;--- UFW Status ---&quot; | tee -a &quot;$LOG_FILE&quot;<br>          sudo ufw status verbose | tee -a &quot;$LOG_FILE&quot;<br>          <br>          # Check for security updates<br>          echo &quot;--- Available Security Updates ---&quot; | tee -a &quot;$LOG_FILE&quot;<br>          apt list --upgradable 2&gt;/dev/null | grep -i security | tee -a &quot;$LOG_FILE&quot;<br>          <br>          # Check system resources<br>          echo &quot;--- System Resources ---&quot; | tee -a &quot;$LOG_FILE&quot;<br>          df -h | tee -a &quot;$LOG_FILE&quot;<br>          free -h | tee -a &quot;$LOG_FILE&quot;<br>          <br>          # Check recent auth failures<br>          echo &quot;--- Recent Authentication Failures ---&quot; | tee -a &quot;$LOG_FILE&quot;<br>          grep &quot;authentication failure&quot; /var/log/auth.log | tail -10 | tee -a &quot;$LOG_FILE&quot;<br>          <br>          echo &quot;=== Daily Security Check Complete ===&quot; | tee -a &quot;$LOG_FILE&quot;<br>        dest: /home/{{ ansible_user }}/scripts/daily-security-check.sh<br>        owner: &quot;{{ ansible_user }}&quot;<br>        group: &quot;{{ ansible_user }}&quot;<br>        mode: &#39;0755&#39;<br>        <br>    - name: Setup daily security check cron job<br>      cron:<br>        name: &quot;Daily security check&quot;<br>        minute: &quot;0&quot;<br>        hour: &quot;8&quot;<br>        job: &quot;/home/{{ ansible_user }}/scripts/daily-security-check.sh&quot;<br>        user: &quot;{{ ansible_user }}&quot;<br>        <br>    - name: Create monitoring alias shortcuts<br>      lineinfile:<br>        dest: /home/{{ ansible_user }}/.bashrc<br>        line: &quot;{{ item }}&quot;<br>        create: yes<br>      with_items:<br>        - &quot;alias checkbans=&#39;/home/{{ ansible_user }}/scripts/check-banned-ips.sh&#39;&quot;<br>        - &quot;alias seccheck=&#39;/home/{{ ansible_user }}/scripts/daily-security-check.sh&#39;&quot;<br>        - &quot;alias webreport=&#39;/home/{{ ansible_user }}/scripts/generate-web-report.sh&#39;&quot;<br>        - &quot;alias ufwlog=&#39;sudo tail -f /var/log/ufw.log&#39;&quot;<br>        - &quot;alias authlog=&#39;sudo tail -f /var/log/auth.log&#39;&quot;</pre><h3>12. Complete Security Playbook</h3><p>Here’s how to tie everything together:</p><h4>playbooks/complete-llm-security.yml</h4><pre>---<br>- import_playbook: 01-initial-security-setup.yml<br>- import_playbook: 02-configure-fail2ban.yml  <br>- import_playbook: 03-configure-firewall.yml<br>- import_playbook: 04-monitoring-setup.yml<br>- import_playbook: 05-cloudflare-ufw-automation.yml<br>- import_playbook: 06-advanced-monitoring-scripts.yml<br><br>- name: Final Security Verification<br>  hosts: llm_servers<br>  become: yes<br>  <br>  tasks:<br>    - name: Run security audit with Lynis<br>      command: lynis audit system --quick<br>      register: lynis_result<br>      ignore_errors: yes<br>      <br>    - name: Display security score<br>      debug:<br>        msg: &quot;Security audit completed. Check /var/log/lynis.log for detailed results&quot;<br>        <br>    - name: Verify services are running<br>      service_facts:<br>      <br>    - name: Check critical services status<br>      debug:<br>        msg: &quot;{{ item }} is {{ ansible_facts.services[item][&#39;state&#39;] }}&quot;<br>      loop:<br>        - fail2ban<br>        - ufw<br>        - ssh<br>      when: item in ansible_facts.services<br>        <br>    - name: Display monitoring shortcuts<br>      debug:<br>        msg: |<br>          Security setup complete! Available monitoring commands:<br>          - checkbans: Check fail2ban banned IPs<br>          - seccheck: Run daily security check<br>          - webreport: Generate web analytics report  <br>          - ufwlog: Monitor UFW firewall logs<br>          - authlog: Monitor authentication logs</pre><h3>13. Running Your Security Playbooks</h3><p>Execute your security hardening:</p><pre># Test connectivity first<br>ansible all -i inventory.ini -m ping --ask-vault-pass<br><br># Run the complete security setup<br>ansible-playbook playbooks/complete-llm-security.yml -i inventory.ini --ask-vault-pass<br><br># Run individual components if needed<br>ansible-playbook playbooks/05-cloudflare-ufw-automation.yml -i inventory.ini --ask-vault-pass</pre><h4>Testing Your Setup</h4><p>Verify everything works:</p><pre># Check fail2ban status and banned IPs<br>checkbans  # or /home/username/scripts/check-banned-ips.sh<br><br># Check UFW status with Cloudflare rules  <br>sudo ufw status numbered<br><br># Check SSH configuration<br>sudo sshd -t<br><br># View recent security logs<br>authlog  # or sudo tail -f /var/log/auth.log<br><br># Generate web analytics report (if you have nginx logs)<br>webreport  # or /home/username/scripts/generate-web-report.sh<br><br># Run comprehensive security check<br>seccheck  # or /home/username/scripts/daily-security-check.sh</pre><h3>14. Essential Commands for Ongoing Management</h3><p>Keep these commands handy for daily security management:</p><pre># Advanced fail2ban management<br>sudo fail2ban-client status sshd<br>sudo fail2ban-client set sshd unbanip YOUR_IP<br>sudo fail2ban-client reload  # Reload all jails<br><br># UFW management with Cloudflare<br>sudo ufw status numbered | grep Cloudflare<br>sudo ufw delete [rule_number]  # Remove specific rule<br>/home/username/scripts/cloudflare-ufw_update.sh  # Manual Cloudflare IP update<br><br># Log analysis<br>sudo tail -f /var/log/ufw.log | grep -E &quot;(BLOCK|ALLOW)&quot;<br>sudo grep &quot;Failed password&quot; /var/log/auth.log | tail -20<br>sudo journalctl -u fail2ban.service -f  # Follow fail2ban logs<br><br># Security auditing<br>sudo lynis audit system<br>sudo rkhunter --check --skip-keypress  # Rootkit scan<br>sudo chkrootkit  # Alternative rootkit check<br><br># System monitoring<br>htop  # Interactive process viewer<br>iotop  # I/O monitoring<br>nethogs  # Network usage per process<br><br># Filter testing (after setting up nginx)<br>/home/username/scripts/fail2ban_batch_filter_check.sh /etc/fail2ban/filter.d /var/log/nginx/access.log /tmp/filter_results.log<br>cat /tmp/filter_results.log  # View filter test results<br><br># Check for security updates<br>sudo unattended-upgrade --dry-run<br>sudo apt list --upgradable | grep -i security</pre><h3>15. What’s Next?</h3><p>You’ve now got a properly hardened server with enterprise-level security ready for LLM deployment! Your setup includes:</p><p>✅ Multi-layered Security: fail2ban, UFW with Cloudflare integration, SSH hardening</p><p>✅ Comprehensive Monitoring: Real-time log analysis, ban tracking, web analytics</p><p>✅ Automated Updates: Cloudflare IP ranges, system security patches</p><p>✅ Production-Ready Scripts: Daily security checks, filter testing, automated reporting</p><p>In the next article, we’ll cover:</p><ul><li>Setting up Nginx as a reverse proxy with SSL/TLS</li><li>Implementing rate limiting for your LLM API</li><li>Container security with Docker and proper isolation</li><li>Advanced threat detection with Wazuh SIEM</li><li>Backup and disaster recovery strategies</li><li>Performance monitoring for LLM workloads</li></ul><p>Your server is now significantly more secure than a default installation and includes professional-grade monitoring capabilities.</p><p>#Ansible #LLM #Server #Linux #Security #WAF #Fail2Ban #UFW #GoAccess #webhosting</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1d495b9c5df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run SearxNG Locally To Keep Your AI Data Private & Free  — Create Custom Agentic Tools]]></title>
            <link>https://medium.com/@gabrielrodewald/run-searxng-locally-to-keep-your-ai-data-private-free-create-custom-agentic-tools-e8f4b5592082?source=rss-6f32802fcc06------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8f4b5592082</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[serpapi]]></category>
            <dc:creator><![CDATA[Gabriel Rodewald]]></dc:creator>
            <pubDate>Thu, 19 Jun 2025 15:28:47 GMT</pubDate>
            <atom:updated>2025-06-19T20:25:08.215Z</atom:updated>
            <content:encoded><![CDATA[<h3>Run SearxNG Locally To Keep Your AI Data Private &amp; Free 🚀 — Create Custom Agentic Tools</h3><p>✅ All traffic stays local<br> ✅ You can configure which engines are queried<br> ✅ You can throttle, rate-limit, or cache as needed<br> ✅ You own it</p><p>When building agents or RAG pipelines, developers often reach for commercial search APIs like SerpAPI or Bing Search. They’re powerful, yes — but they’re also metered, rate-limited, and most importantly: external.</p><p>In an age where local LLMs are becoming the norm, your search infrastructure should live close to your models.</p><p>In this post, I’ll walk you through setting up a local <a href="https://github.com/searxng/searxng">SearxNG</a> container — an open-source metasearch engine — so your apps can perform real-time web search without ever leaking a single token to the outside world. I’ll also show how to consume the data directly from Python, so your agents and LLMs can use it securely, offline, and efficiently.</p><p>Click here to go directly to the code solution: <a href="https://github.com/pyautoml/local_agents/tree/main">repository</a>🔗</p><h3>Why not SerpAPI?</h3><p>SerpAPI and similar services are:</p><ul><li><strong>Expensive</strong> — You pay per query or need a subscription.</li><li><strong>Limited</strong> — You depend on their quota, endpoints, and uptime.</li><li><strong>Not private</strong> — Queries are sent to a third-party service. This breaks the local-first privacy model.</li><li><strong>Opaque</strong> — You don’t really know what’s being filtered or tracked.</li></ul><p>If you’re already running local LLMs like <strong>Ollama</strong>, there’s no reason your retrieval pipeline should still rely on remote search APIs.</p><h3>Meet SearxNG: Open-Source Metasearch</h3><p>SearxNG is a privacy-respecting search engine that aggregates results from multiple providers (Google, Bing, Brave, Wikipedia, etc.) and gives you a clean, customizable JSON API.</p><p>Here’s how to run it in Docker.</p><h4>🐳 Step 1: Spin up SearxNG with Docker</h4><p>Save the following docker-compose-searxng.yml file:</p><pre>services:<br>  searxng:<br>    image: searxng/searxng:latest<br>    restart: unless-stopped<br>    ports:<br>      - &quot;0.0.0.0:8089:8080&quot;  # Access via http://localhost:8089<br>    networks:<br>      - app_network<br>    volumes:<br>      - ${SEARXNG_DATA}:/etc/searxng:rw<br>      - ${SEARXNG_SETTINGS}:/etc/searxng/settings.yml:ro <br>    environment:<br>      - BASE_URL=http://localhost:8080<br>      - REDIS_URL=redis://host.docker.internal:6379/0<br>      - UWSGI_WORKERS=4<br>      - UWSGI_THREADS=4<br>    cap_drop: [&quot;ALL&quot;]<br>    cap_add: [&quot;CHOWN&quot;, &quot;SETGID&quot;, &quot;SETUID&quot;]<br>    ulimits:<br>      nofile:<br>        soft: 65535<br>        hard: 65535<br>networks:<br>  app_network:<br>    external: true</pre><p>You can run the code via GUI like VSCode by clicking on the file &gt; Copose Up or via CMD:</p><pre># create docker network if not exists: <br>docker network create --driver bridge app_network<br># run the container<br>docker-compose up -d</pre><p>Use curl to check if the container is ON:</p><pre># from host<br>curl http://localhost:8089/search?q=rag+agents&amp;format=json<br># or curl from inside of the container<br># curl http://host.docker.internal:8089/search</pre><p>Use your webbrowser to open it on the host machine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2pzS631JZKdnowfC0mwCg.png" /></figure><h4>🔍 Step 2: Access from Python</h4><p>Below is a simple async wrapper that fetches multiple pages of results and returns them as structured data for your agent pipelines or LLM inputs:</p><p>Code (avaialable <a href="https://github.com/pyautoml/local_agents/blob/main/webui_llm_tools/search/serp_search.py">here</a> 🔗):</p><pre># Author: https://github.com/pyautoml/<br># License: CC BY-NC<br><br>import os<br>import httpx<br>import asyncio<br>from datetime import datetime<br>from pydantic import BaseModel, Field<br>from typing import List, Optional, Union<br><br><br>class WebsiteData(BaseModel):<br>    &quot;&quot;&quot;Represents structured data extracted from a website.&quot;&quot;&quot;<br><br>    url: str<br>    title: Optional[str] = None<br>    snippet: Optional[str] = None<br>    content: Optional[str] = None<br>    author: Optional[str] = None<br>    date: Optional[str] = None<br>    language: Optional[str] = None<br>    engine: Optional[str] = None<br>    engines: Optional[List[str]] = None<br>    score: Optional[float] = None<br>    category: Optional[str] = None<br>    published_date: Optional[str] = None<br>    extracted_at: Optional[str] = None<br>    success: bool = True<br><br><br>class WebsiteError(BaseModel):<br>    &quot;&quot;&quot;Represents an error encountered during website data extraction.&quot;&quot;&quot;<br><br>    query: str<br>    error: str<br>    extracted_at: datetime = Field(default_factory=datetime.now)<br>    success: bool = False<br><br><br>class WebsiteSearch(BaseModel):<br>    &quot;&quot;&quot;Performs website search and result extraction using a SearxNG instance.&quot;&quot;&quot;<br><br>    class Config:<br>        arbitrary_types_allowed = True<br><br>    async def _fetch_page(<br>        self,<br>        client: httpx.AsyncClient,<br>        base_url: str,<br>        query: str,<br>        page: int,<br>        timeout: int,<br>    ):<br>        &quot;&quot;&quot;<br>        Fetch a single page of search results from the SearxNG instance.<br><br>        :param client: httpx.AsyncClient instance for making HTTP requests.<br>        :param base_url: Base URL of the SearxNG search endpoint.<br>        :param query: Search query string.<br>        :param page: Page number to fetch.<br>        :param timeout: Timeout in seconds for the HTTP request.<br>        :return: A list of search result items or an error message string.<br>        :rtype: Union[List[dict], str]<br>        &quot;&quot;&quot;<br>        try:<br>            params = {&quot;q&quot;: query, &quot;format&quot;: &quot;json&quot;, &quot;pageno&quot;: page}<br>            response = await client.get(base_url, params=params, timeout=timeout)<br>            response.raise_for_status()<br>            page_json = response.json()<br>            return page_json.get(&quot;results&quot;, [])<br>        except Exception as e:<br>            return f&quot;Page {page} failed: {e}&quot;<br><br>    async def _async_search(<br>        self,<br>        query: str,<br>        max_page_number: int,<br>        timeout: int,<br>        max_results: Optional[int],<br>        output_for_llm: bool,<br>    ) -&gt; Union[List[WebsiteData] | str, WebsiteError | str]:<br>        &quot;&quot;&quot;<br>        Perform an asynchronous search across multiple pages and return structured results.<br><br>        :param query: Search query string.<br>        :param max_page_number: Number of result pages to fetch.<br>        :param timeout: Timeout in seconds for each HTTP request.<br>        :param max_results: Maximum number of results to return (after sorting by score).<br>        :param output_for_llm: Whether to format results as newline-separated JSON strings.<br>        :return: A list of WebsiteData or a WebsiteError, or formatted string if output_for_llm is True.<br>        :rtype: Union[List[WebsiteData], str, WebsiteError]<br>        :raises ValueError if SEARXNG_BASE_URL is not set.<br>        &quot;&quot;&quot;<br>        base_url: str = os.getenv(&quot;SEARXNG_BASE_URL&quot;)<br>        if not base_url:<br>            raise ValueError(&quot;SEARXNG_BASE_URL environment variable is not set.&quot;)<br><br>        all_data: List[WebsiteData] = []<br><br>        async with httpx.AsyncClient() as client:<br>            tasks = [<br>                self._fetch_page(client, base_url, query, page, timeout)<br>                for page in range(1, max_page_number + 1)<br>            ]<br>            pages_results = await asyncio.gather(*tasks)<br><br>        for result in pages_results:<br>            if isinstance(result, str):<br>                return (<br>                    result<br>                    if output_for_llm<br>                    else WebsiteError(query=query, error=result)<br>                )<br><br>            for item in result:<br>                all_data.append(<br>                    WebsiteData(<br>                        url=item.get(&quot;url&quot;),<br>                        title=item.get(&quot;title&quot;),<br>                        snippet=item.get(&quot;snippet&quot;),<br>                        content=item.get(&quot;content&quot;),<br>                        author=item.get(&quot;author&quot;),<br>                        date=f&quot;{item.get(&#39;date&#39;)}&quot;,<br>                        language=item.get(&quot;language&quot;),<br>                        engine=item.get(&quot;engine&quot;),<br>                        engines=item.get(&quot;engines&quot;),<br>                        score=item.get(&quot;score&quot;),<br>                        category=item.get(&quot;category&quot;),<br>                        published_date=f&quot;{item.get(&#39;published_date&#39;)}&quot;,<br>                        extracted_at=datetime.now().isoformat(),<br>                        success=True,<br>                    )<br>                )<br><br>        if max_results:<br>            all_data.sort(<br>                key=lambda d: d.score if d.score is not None else 0, reverse=True<br>            )<br>            all_data = all_data[:max_results]<br><br>        if output_for_llm:<br>            return &quot;\n&quot;.join(d.model_dump_json() for d in all_data)<br><br>        return all_data<br><br>    def search(<br>        self,<br>        query: str,<br>        timeout: int = 10,<br>        max_page_number: int = 5,<br>        output_for_llm: bool = False,<br>        max_results: Optional[int] = None<br>    ) -&gt; Union[List[WebsiteData] | str, WebsiteError | str]:<br>        &quot;&quot;&quot;<br>        Synchronously performs a search query using asyncio and returns results.<br><br>        :param query: Search query string.<br>        :param max_page_number: Number of result pages to retrieve (default is 5).<br>        :param timeout: Timeout in seconds for each request (default is 10).<br>        :param max_results: Maximum number of results to return (optional).<br>        :param output_for_llm: If True, returns newline-separated JSON strings for LLM input.<br>        :return: A list of WebsiteData, or WebsiteError on failure; or formatted string if output_for_llm is True.<br>        :rtype: Union[List[WebsiteData], str, WebsiteError]<br>        &quot;&quot;&quot;<br>        return asyncio.run(<br>            self._async_search(<br>                query, max_page_number, timeout, max_results, output_for_llm<br>            )<br>        )</pre><pre>result = WebsiteSearch().search(query=&quot;RAG for agents&quot;, output_for_llm=True, max_results=2)<br>print(result)</pre><p>Expected code output (if prettyfied) sorted by score results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wv_hyjgPtS9m_aiFusEdnw.png" /></figure><p>Behind the scenes, this runs multiple paged requests to your local SearxNG instance, wraps the data with pydantic, and formats it either as JSON objects or newline-separated strings—perfect for feeding to LLMs.</p><h3>When to Use This</h3><p>This setup is ideal if you’re:</p><ul><li>Running <strong>LLMs locally (e.g., via Ollama or LM Studio)</strong></li><li>Building <strong>RAG or retrieval-augmented agents</strong></li><li>Prototyping tools with <strong>tight privacy requirements</strong></li><li>Sick of SerpAPI rate limits</li></ul><h3>Final Thoughts</h3><p>Modern AI workflows should respect developer privacy, control, and cost-efficiency. While SerpAPI and others may be useful for prototyping, they’re ultimately a crutch. With SearxNG, you can eliminate that dependency entirely.</p><p>It’s open, fast, hackable, and runs beautifully next to your local models.</p><p>🛠️ Build the full pipeline. Local models. Local data. Total control.</p><h3>➡️ <strong>Next</strong></h3><p>In the next article, we’ll integrate OpenWebUI with local Ollama models and expose custom tools — like this search wrapper — as native functions usable by models such as LLaMA 3.2. All local. No API costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMR_Ss7HX09hfURHB4Gp3g.png" /></figure><h3>📣 Stay Tuned</h3><p>If you’re interested in a deeper dive into integrating this setup with tools like LangChain or Ollama, stay tuned for my next post.</p><p>You can also follow me <a href="https://medium.com/@gabrielrodewald">@gabrielrodewald</a> for more LLM ops and open-source AI workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8f4b5592082" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Craft Custom Tools for Agents in Ollama, OpenAI, and More ]]></title>
            <link>https://medium.com/@gabrielrodewald/craft-custom-tools-for-agents-in-ollama-openai-and-more-d13103cf1bab?source=rss-6f32802fcc06------2</link>
            <guid isPermaLink="false">https://medium.com/p/d13103cf1bab</guid>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Gabriel Rodewald]]></dc:creator>
            <pubDate>Thu, 28 Nov 2024 21:06:38 GMT</pubDate>
            <atom:updated>2024-11-30T10:36:20.607Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOwbtm2ROva9cS5tDIj5Nw.jpeg" /><figcaption>A llama equipped with tools.</figcaption></figure><h4>Introduction</h4><p>Today, I’ll share a solution I’ve developed that provides an easy method for integrating custom tools ⚙️ without relying on popular third-party libraries.</p><p>This is necessary because <strong>agents</strong>, which are models equipped with tools, <strong>cannot retrieve new data on their own</strong>. As a result, their knowledge scope is limited unless they are provided with new information from the internet. By implementing custom functions, we can effectively expand the capabilities of these agents, allowing them to access and utilize real-time data to enhance their performance and decision-making processes.</p><p><a href="https://ollama.com/blog/functions-as-tools">Ollama </a>has recently enhanced its capabilities by introducing a new feature that allows function calling directly from Python methods. This makes it a good moment to understand better how custom functions can be integrated into models.</p><p>By following along, you’ll see how straightforward it is to implement these tools in your projects, enabling you to focus on building applications without getting bogged down by complex setups or dependencies.</p><h4>Code</h4><p>If you want to run the code, you can access if via GitHub here: <a href="https://github.com/pyautoml/Artificial-Intelligence/tree/main/tutorials/agents_with_tools">Agents with tools</a></p><h3><strong>Requirements</strong></h3><p>The first step is to install the necessary libraries. The Python version used is 3.12. Save the data below as requirements.txt:</p><pre>httpx==0.27.2<br>ollama==0.4.1<br>openai==1.55.1<br>pydantic==2.9.2<br>python-dotenv==1.0.1</pre><p>and then run the following command:</p><pre>pip install -r requirements.txt</pre><p>Next, go to <a href="https://ollama.com/download">https://ollama.com/download</a> and install Ollama locally. Once this step is done, open CMD and type command below to install llama3.2 model:</p><pre>ollama pull llama3.2</pre><p>If you need a different configuration or would like to redirect locally saved models into another driver, please go through this article: <a href="https://medium.com/@gabrielrodewald/running-models-with-ollama-step-by-step-60b6f6125807">Running models with Ollama step by step</a></p><p>To check if the model is properly installed, enter in the CMD:</p><pre>ollama list</pre><h3>The Core Components</h3><p>The solution consists of three main classes:</p><ul><li>BaseChatModel: The foundation class that handles common functionality</li><li>OllamaChatModel: Implementation for Ollama models</li><li>OpenAIChatModel: Implementation for OpenAI models</li></ul><p>Let’s break down how it works.</p><h3>1. Building a Solid Foundation: The BaseChatModel Class</h3><p>The BaseChatModel class serves as this essential backbone, providing the core functionalities that enable seamless communication between users and AI. Let’s dive deeper into its structure and features like memory management and message formatting:</p><pre>class BaseChatModel:<br>    def __init__(<br>        self,<br>        client: Any,<br>        model: str,<br>        temperature: float = 0.0,<br>        keep_alive: int = -1,<br>        format: Optional[str] = None,<br>        max_stored_memory_messages: int = 50,<br>    ) -&gt; None:<br>        self.client = client<br>        self.model = model<br>        self.format = format<br>        self.temperature = temperature<br>        self.memory = BaseMemory(max_size=max_stored_memory_messages)</pre><ul><li><strong>client</strong>: This parameter represents the connection to the underlying language model API, allowing the class to send and receive messages.</li><li><strong>model</strong>: The specific model being utilized (e.g., Ollama or OpenAI), which determines the capabilities and responses of the chat.</li><li><strong>temperature</strong>: A float value that influences the randomness of the model’s responses. Lower values yield more deterministic outputs, while higher values introduce variability.</li><li><strong>keep_alive</strong>: An integer that specifies how long to maintain the connection with the client, ensuring efficient communication without unnecessary overhead.</li><li><strong>format</strong>: An optional string that can define how messages are formatted before being sent or displayed. if you decide to change the output format to json remember to adjust rest of the code to handle agent’s responses by requested key.</li><li><strong>max_stored_memory_messages</strong>: This integer sets a limit on how many past messages can be stored in memory, facilitating context retention during conversations.</li></ul><p>One of the features of the BaseChatModel is its built-in memory management system. By initializing a BaseMemory instance with a specified maximum size, the model can effectively remember previous interactions, enhancing its ability to provide relevant responses based on context.</p><p>To guide the AI’s behavior during interactions, a predefined system message is included:</p><pre>self.system = &quot;&quot;&quot;You are a helpful AI assistant. When using tools, always provide a natural, complete response using the information gathered.<br>Format your response as a short, coherent sentence.&quot;&quot;&quot;</pre><p>This instruction helps shape how the AI formulates its replies, ensuring that they are not only informative but also presented in a user-friendly manner.</p><p>The BaseChatModel also includes a method for formatting messages exchanged between users and the AI:</p><pre>def message(self, human: str, ai: str) -&gt; ChatMessage:<br>    return ChatMessage(message={&quot;human&quot;: human, &quot;ai&quot;: ai})</pre><p>This method encapsulates human and AI messages into a structured format, making it easier to manage and display conversation history.</p><h3>2. Ollama Implementation</h3><h4>Class Initialization</h4><p>The OllamaChatModelclass is an extension of the BaseChatModel, designed to facilitate interactions with Ollama’s language models providing a structured way to manage tools and responses. Let’s explore its features and functionalities in detail.</p><pre>class OllamaChatModel(BaseChatModel):<br>    &quot;&quot;&quot;http://localhost:11434 is the default Ollama port serving API.&quot;&quot;&quot;<br><br>    def __init__(self, tools: list[dict], model: str = &quot;llama3.2&quot;) -&gt; None:<br>        self.model = model<br>        self.tools = tools<br>        self.client = ollama.Client(host=&quot;http://localhost:11434&quot;)<br>        super().__init__(client=self.client, model=self.model)</pre><ul><li><strong>model</strong>: The model parameter allows users to specify which version of the Ollama model to utilize, defaulting to &quot;llama3.2&quot;.</li><li><strong>tools</strong>: The tools parameter accepts a list of custom tools that can be invoked during chat sessions, enhancing the model&#39;s functionality.</li><li><strong>client</strong>: The clientis initialized to connect to the Ollama API, which operates on a specified host and port, ensuring that all requests are directed correctly. If you are running Ollama within a <strong>Docker </strong>container, you can easily configure the Ollama host to point to the appropriate network settings.</li></ul><p>One of the features of the OllamaChatModelis its ability to extract and execute tool calls dynamically. Extracting multiple tool calls allows us to give the agent a chance to make multiple tool calls per user request.</p><pre>def extract(self, tool_call) -&gt; list:<br>    &quot;&quot;&quot;Extract and execute tool call&quot;&quot;&quot;<br>    data = []<br><br>    if not isinstance(tool_call, list):<br>        tool_call = [tool_call]<br><br>    for tool in tool_call:<br>        func_name = tool.function.name<br>        if isinstance(tool.function.arguments, str):<br>            func_arguments = json.loads(tool.function.arguments)<br>        else:<br>            func_arguments = tool.function.arguments<br>        result = run_callable(func_name, func_arguments)<br>        data.append(result)<br>    return data</pre><p>This flexibility allows developers to create rich interactions where the model can perform actions based on user input.</p><h4>Generating Responses</h4><p>The response method is crucial for generating model replies based on user prompts:</p><pre>def response(self, user_prompt: str, system_message: str = None) -&gt; ollama.ChatResponse:<br>    messages = [<br>        {<br>            &quot;role&quot;: &quot;system&quot;,<br>            &quot;content&quot;: system_message if system_message else self.system,<br>        }<br>    ]<br><br>    for msg in self.memory.get():<br>        if isinstance(msg, ChatMessage):<br>            messages.extend(<br>                [<br>                    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: msg.human},<br>                    {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: msg.ai},<br>                ]<br>            )<br><br>    messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_prompt})<br><br>    return self.client.chat(<br>        model=self.model,<br>        messages=messages,<br>        format=self.format,<br>        keep_alive=self.keep_alive,<br>        tools=self.tools,<br>    )</pre><p>This method constructs a message history that includes both system instructions and previous interactions. It sends this context to the Ollama client to generate a coherent response based on the current user prompt.</p><h4>Interactive Chat Functionality</h4><p>The chat method provides an interactive loop for users to engage with the model. It handles user inputs in real-time and processes any necessary tool calls before generating and displaying responses. The ability to save chat as .json files history adds an extra layer of functionality for users who wish to revisit previous conversations.</p><pre>def chat(self, system_message: str = None, save_chat: bool = False) -&gt; None:<br>    system_message = system_message if system_message else self.system<br><br>    while True:<br>        print(&quot;current memory: &quot;, self.memory.get(), &quot;\n\n&quot;)<br><br>        user_prompt = input(&quot;User: &quot;)<br>        if user_prompt == &quot;bye&quot;:<br>            self.memory.add(self.message(human=user_prompt, ai=&quot;Bye&quot;))<br>            if save_chat:<br>                self.memory.save(model_name=str(self.model))<br>            self.memory.clear()<br>            print(&quot;AI: Bye&quot;)<br>            break<br><br>        response = self.response(user_prompt, system_message)<br><br>        # If there are tool calls, process them and get final response<br>        if hasattr(response.message, &quot;tool_calls&quot;) and response.message.tool_calls:<br>            collected_data = {}<br><br>            for tool_call in response.message.tool_calls:<br>                result = self.extract(tool_call)<br>                collected_data[tool_call.function.name] = result<br><br>            final_prompt = (<br>                f&quot;Based on the following information:\n&quot;<br>                f&quot;{collected_data}&quot;<br>                f&quot;Please provide a natural response to the original question: &#39;{user_prompt}&#39;&quot;<br>            )<br><br>            final_response = self.client.chat(<br>                model=self.model,<br>                messages=[<br>                    {<br>                        &quot;role&quot;: &quot;system&quot;,<br>                        &quot;content&quot;: &quot;Sum up your response before sending back. Make it short and concise&quot;<br>                        + &quot; &quot;<br>                        + system_message,<br>                    },<br>                    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: final_prompt},<br>                ],<br>            )<br>            response_content = final_response.message.content<br>        else:<br>            # If no tool calls, use the original response<br>            response_content = response.message.content<br><br>        if response_content:<br>            print(f&quot;AI: {response_content}&quot;, end=&quot;\n\n&quot;)<br>            self.memory.add(self.message(human=user_prompt, ai=response_content))</pre><h3>3. OpenAI Implementation</h3><p>The class OpenAIChatModel`is very similar to OllamaChatModeland contains the same functions. We will not discuss them, but will focus only on the differences that led to a separate implementation.</p><p><strong>API Key vs. Client</strong>: The OpenAIChatModel requires an api_key as part of its initialization, which is essential for authenticating requests to the OpenAI API. In contrast, the OllamaChatModel connects to a local instance of the Ollama server without requiring an API key.</p><pre># OpenAIChatModel initialization<br>self.client = openai.OpenAI(api_key=api_key, timeout=timeout, max_retries=max_retries)<br><br># OllamaChatModel initialization<br>self.client = ollama.Client(host=&quot;http://localhost:11434&quot;)</pre><p><strong>Tool Call Extraction:</strong> The extract method in both models processes tool calls, but the OpenAIChatModel directly parses tool call arguments from a JSON string format, while the OllamaChatModel checks if the input is a list and handles it accordingly.</p><pre># OpenAIChatModel extract method<br>func_arguments = json.loads(tool_call.function.arguments)<br><br># OllamaChatModel extract method<br>if not isinstance(tool_calls, list):<br>    tool_call = [tool_calls]</pre><p><strong>Response Method:</strong> The way responses are generated differs between the two models. The OpenAIChatModel uses self.client.chat.completions.create() to generate responses, whereas the OllamaChatModel calls self.client.chat().</p><pre># OpenAIChatModel response method<br>return self.client.chat.completions.create(model=self.model, messages=messages, tools=self.tools)<br><br># OllamaChatModel response method<br>return self.client.chat(model=self.model, messages=messages)</pre><p><strong>Final Prompt Handling:</strong> Both models construct a final prompt for generating a concise response based on collected data from tool calls. However, they differ in how they format and send this prompt back to their respective clients.</p><h3>4. Expanding custom tools</h3><p>Additionally, we utilize two modules: memory.py, where we find a simplified implementation of the memory passed to our agents, and tools.py, where we keep our tools.</p><p>At the beginning of the file, we have 2 functions responsible for global registration of all used tools. If you’d like to serve tools from file different than tools.py, remember to adjust changes in:</p><pre>module = importlib.import_module(&quot;tools&quot;) # &lt;- replace with the module name storing tools</pre><pre>registered_functions = {}<br><br>def register_function(func) -&gt; Callable:<br>    registered_functions[func.__name__] = func<br>    return func<br><br><br>def run_callable(name: str, arguments: dict) -&gt; Callable | dict:<br>    try:<br>        module = importlib.import_module(&quot;tools&quot;)<br>        func = getattr(module, name, None)<br>        func = registered_functions.get(name)<br><br>        if func and callable(func):<br>            return func(**arguments)<br>        else:<br>            return {&quot;error&quot;: f&quot;Function &#39;{name}&#39; is not callable or not found&quot;}<br>    except Exception as e:<br>        traceback.print_exc()<br>        return {&quot;error&quot;: f&quot;Error executing {name}: {str(e)}&quot;}</pre><h4>How to add a new tool</h4><p>Go to tools.py, create and register a new function. I provide simple methods, but you can incorporate more robust solutions, such as paid APIs like [SerpApi](<a href="https://serpapi.com/">https://serpapi.com/</a>)or experiment with free ones like the [CatFacts Api] (<a href="https://alexwohlbruck.github.io/cat-facts/">https://alexwohlbruck.github.io/cat-facts/</a>).</p><pre>@register_function<br>def say_hello(name: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Greeets a user by their name.<br><br>    Returns:<br>    str: user greeting<br>    &quot;&quot;&quot;<br>    return f&quot;Hello {name}!&quot;</pre><p>Each function requires a second, descriptive part. You can choose any name for the dictionary variable, but <strong>the value associated with the key “name” must exactly match the name of the called function</strong>. This revision clarifies that while the dictionary name is flexible, the value for “name” must correspond precisely to the function it represents.</p><pre>say_hello_tool = {<br>    &quot;type&quot;: &quot;function&quot;,<br>    &quot;function&quot;: {<br>        &quot;name&quot;: &quot;say_hello&quot;,<br>        &quot;description&quot;: &quot;Greet the user by their name.&quot;,<br>        &quot;parameters&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {&quot;name&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;User&#39;s name&quot;}},<br>            &quot;required&quot;: [&quot;name&quot;],<br>        },<br>    },<br>}</pre><p>Because we pass a parameter to the function, it is essential to specify which fields are required.</p><p>Now, let’s expand the toolset in the agents_with_tools.py file:</p><pre>tools = [today_is_tool, weather_tool, day_of_week_tool, say_hello_tool]</pre><h4>Replacing memory</h4><p>In memory.py, we use custom classes to handle communication between the user and the AI, as well as to store historical data. This functionality could be simplified by utilizing LangChain memory types; however, I opted not to do so to help you better understand how it works from scratch. Feel free to implement your own memory for your agents :)</p><p>The ChatMessage class offers a straightforward communication interface, ensuring that the passed data always contains the expected keys: human and ai.:</p><pre>class ChatMessage(BaseModel):<br>    message: Dict[str, str] = Field(<br>        ..., description=&quot;A dictionary containing &#39;human&#39; and &#39;ai&#39; messages.&quot;<br>    )<br><br>    @property<br>    def human(self) -&gt; str:<br>        &quot;&quot;&quot;Return the human message.&quot;&quot;&quot;<br>        return self.message.get(&quot;human&quot;, &quot;&quot;)<br><br>    @property<br>    def ai(self) -&gt; str:<br>        &quot;&quot;&quot;Return the AI message.&quot;&quot;&quot;<br>        return self.message.get(&quot;ai&quot;, &quot;&quot;)<br><br>    def cleanup(memory: Any):<br>        memory.clear()<br><br>    def __str__(self) -&gt; str:<br>        &quot;&quot;&quot;Custom string representation for ChatMessage.&quot;&quot;&quot;<br>        return json.dumps({&quot;human&quot;: self.human, &quot;ai&quot;: self.ai}, ensure_ascii=False)</pre><p>BaseMemory is a deque structure that ensures you store a maximum of N messages. This is important for two reasons:</p><ol><li>Sending too many tokens to paid LLMs is expensive.</li><li>Most LLMs have medium to large token windows, but it’s easy to forget about this and exceed the limit.</li></ol><p>Additionally, the efficiency of LLMs decreases if we send too much historical information.</p><pre>class BaseMemory:<br>    def __init__(self, max_size=100):<br>        &quot;&quot;&quot;Initialize the memory with a maximum size.&quot;&quot;&quot;<br>        self.memory = deque(maxlen=max_size)<br><br>    def add(self, message: ChatMessage):<br>        &quot;&quot;&quot;Add an item to the memory.&quot;&quot;&quot;<br>        self.memory.append(message)<br><br>    def peek(self) -&gt; str:<br>        if self.memory:<br>            return str(self.memory[-1])<br>        return None<br><br>    def get(self):<br>        &quot;&quot;&quot;Retrieve all items in memory.&quot;&quot;&quot;<br>        return list(self.memory)<br><br>    def get_as_str(self):<br>        &quot;&quot;&quot;Retrieve all items in memory.&quot;&quot;&quot;<br>        return &quot;;&quot;.join(f&quot;{x}&quot; for x in list(self.memory))<br><br>    def get_max(self, limit: int):<br>        &quot;&quot;&quot;Retrieve all items in memory.&quot;&quot;&quot;<br>        if self.memory:<br>            return list(self.memory)[:limit]<br>        return None<br><br>    def clear(self):<br>        &quot;&quot;&quot;Clear all items from memory.&quot;&quot;&quot;<br>        self.memory.clear()<br><br>    def save(self, model_name: str = None, file_path: str = None):<br>        &quot;&quot;&quot;Dump all memory contents to a local JSON file.&quot;&quot;&quot;<br><br>        if not file_path or not os.path.exists(file_path):<br>            file_path = Path(<br>                os.path.abspath(os.path.join(os.path.dirname(__file__)))<br>            ).as_posix()<br><br>        if self.memory:<br>            timestamp = (<br>                str(datetime.now().replace(microsecond=0))<br>                .replace(&quot;:&quot;, &quot;&quot;)<br>                .replace(&quot; &quot;, &quot;&quot;)<br>                .replace(&quot;-&quot;, &quot;&quot;)<br>                .replace(&quot;_&quot;, &quot;&quot;)<br>            )<br>            name = (<br>                f&quot;chat_{model_name.replace(&quot;-&quot;,&quot;&quot;)}_{timestamp}.json&quot;<br>                if model_name<br>                else f&quot;chat_{timestamp}.json&quot;<br>            )<br>            with open(<br>                os.path.join(file_path, name), &quot;w&quot;, encoding=&quot;utf-8&quot;<br>            ) as json_file:<br>                json.dump([msg.message for msg in self.memory], json_file, indent=4)<br><br>    def __str__(self):<br>        &quot;&quot;&quot;String representation of the memory.&quot;&quot;&quot;<br>        if self.memory:<br>            return f&quot;Memory({list(self.memory)})&quot;<br>        return None</pre><h3>Running the script 🎉</h3><p>Choose your preferred model and simply run the script to start chatting with the agent! :)</p><pre>def load_model(model: str = None) -&gt; OllamaChatModel | OpenAIChatModel:<br>    tools = [today_is_tool, weather_tool, day_of_week_tool]<br>    match model:<br>        case &quot;ollama&quot;:<br>            return OllamaChatModel(tools=tools)<br>        case &quot;openai&quot;:<br>            return OpenAIChatModel(api_key=os.environ.get(&quot;openai_apikey&quot;), tools=tools)<br>        case _:<br>            return OllamaChatModel(tools=tools)<br><br><br>def main():<br>    model = load_model(&quot;openai&quot;) # choose the model<br>    model.chat(save_chat=True)   # decide if save the chat or not<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>To exit the chat, simply type bye</p><p>The expected output of the chat is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uaJVaxpADTGkvqbqZuBL_w.png" /><figcaption>The expected output of the chat.</figcaption></figure><p>Chat saved as a JSON file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHROukZiCGUHdW10W8VGyg.png" /><figcaption>Chat saved as a JSON file.</figcaption></figure><p>What will you build today? ⭐</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d13103cf1bab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Basic Counts to Contextual Embeddings: A Journey Through Text Vectorization (Part 1)]]></title>
            <link>https://medium.com/@gabrielrodewald/from-basic-counts-to-contextual-embeddings-a-journey-through-text-vectorization-part-1-98f94a086622?source=rss-6f32802fcc06------2</link>
            <guid isPermaLink="false">https://medium.com/p/98f94a086622</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[vectorization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Gabriel Rodewald]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 22:34:59 GMT</pubDate>
            <atom:updated>2024-11-18T19:07:24.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Plush llama scientist against a background of statistical charts. Image source: https://www.bing.com/images" src="https://cdn-images-1.medium.com/max/1024/1*HRsYFO9PooUBxQeuPoFToQ.jpeg" /></figure><h3>Introduction: Why Vectorize Text?</h3><p>Have you ever wondered how a computer can grasp the meaning of a phrase to generate an appropriate response? I bet you already used LLMs-base services like ChatGPT or Perplexity, which rely on advanced algorithms to understand context, meaning, and intent, allowing them <br>to respond in ways that seem almost human. But the process behind how these models interpret and generate language is far more complex than <br>it might appear at first glance.</p><p>Bridging the gap between language and machine intelligence involves <strong>vectorization </strong>i.e. converting text into numerical representations that machines can compute. This series will teach you text vectorization starting from basic word counts to advanced embeddings.</p><p>In this first part, we lay the groundwork for what will become machine-readable vectors from text. You will also find additional, reliable reading resources to expand scope oy current knowledge.</p><p>We will talk about the advantages and disadvantages of each technique, <br>and where possible, show examples of use through code implementation.</p><p>Step by step, we will go through basic vectorization using:</p><ol><li><strong>Bag of Words</strong> (BoW): atechnique representing text as word collections, converting documents into frequency-based vectors, ignoring grammar and word order.</li><li><strong>Term-Frequency Inverse Document Frequency</strong> (TF-IDF): it enhances BoW by weighting word frequency against overall occurrence, highlighting words significant to specific documents. We’ are starting from this step.</li><li><strong>One-Hot Encoding</strong>: represents words as binary vectors, with one “1” indicating presence, ignoring semantic relationships between words.</li><li><strong>Word Embeddings</strong> (Dense Vector Representations like Word2Vec, GloVe, FastText): encode words in vectors, capturing semantics and context for meaningful relationships.</li><li><strong>Doc2Vec</strong>: extends Word2Vec, creating document-level embeddings using models like Distributed Memory (DM) and Distributed Bag of Words (DBOW).</li><li><strong>Transformer models</strong> (BERT, Sentence-BERT): generate contextualized embeddings, capturing meaning nuances; Sentence-BERT extends this to sentences or passages.</li><li><strong>Contextualized embeddings</strong>: adapt to word context, enhancing NLP tasks like sentiment analysis; examples include ELMo and GPT models.</li></ol><h3>Why to bother?</h3><p>While LLM-based online services can be useful, they often fall short of meeting our specific needs — whether for personal or business purposes.</p><p>In this first part, we will establish a solid foundation for understanding how text is converted into machine-readable vectors. By the end of this journey, you will gain insights into how these techniques drive applications such as spam detection, sentiment analysis, and search engines.</p><p>Our primary focus will be on building a system using PyTorch and Scikit-Learn to classify emails as spam or not. This hands-on experience will provide practical applications of text processing. To ensure our data is meaningful, we will utilize an email spam dataset from Kaggle. Let’s transform spam emails into a format that our machines can understand and filter out!</p><blockquote>From time to time, you will encounter separators in the text, such as:<br>- — — Done so far — — -<br>These separators summarize the steps, helping you focus on aggregated knowledge for better retention.</blockquote><h3>Resources</h3><p><strong>Data:</strong></p><ol><li>Email Spam Dataset from Kaggle (credits: _w1998): <a href="https://www.kaggle.com/datasets/jackksoncsie/spam-email-dataset">https://www.kaggle.com/datasets/jackksoncsie/spam-email-dataset</a></li></ol><p><strong>Reading resources (clickable links):</strong></p><ol><li><a href="https://machinelearningmastery.com/random-oversampling-and-undersampling-for-imbalanced-classification">MachineLearningMastery — Resampling strategies</a> (website)</li><li><a href="https://web.stanford.edu/class/datasci112/lectures/lecture9.pdf">Stanford University — Textual Data: Vector Space Model and TF-IDF</a> (PDF)</li><li><a href="https://nlp.stanford.edu/IR-book/html/htmledition/tf-idf-weighting-1.html">Stanford University — Tf-idf weighting</a> (website)</li><li><a href="https://web.stanford.edu/class/cs276/19handouts/lecture6-tfidf-1per.pdf">Stanford University — Introduction to Information Retrieval</a> (PDF)</li></ol><p><strong>Code:</strong></p><p>Source code (.py): can be downloaded directly from my GitHub repository: <a href="https://github.com/pyautoml/Machine-Learning/blob/main/NLP/Text-Vectorization-Techniques/TF-IDF.py">ML_TFIDF (in Python)</a> (.ipynb version will be added soon).</p><p>Code provided below is copied from a python notebook (<strong>.ipynb </strong>file). It saves you time to run all the code each time from beginning, so you can focuse only on the most important parts.</p><p>You can run it from Google Colab or copie &amp; paste to your local notebook. If you want to run it from a standard .py file, please remember to adjust it.</p><p>You may find useful to read terms stated below that are often used in this article before jumping to code (and comments, referring to these terms).</p><p><strong>Glossary </strong>(in context of this article):</p><ol><li>term: a word that has a meaning (e.g. is not a stopword)</li><li>document: email subject and content</li><li>corpus: (similar to linguistic corpora) unique words across all documents (in this case, all emails)</li></ol><h3><strong>1. Installation and libraries</strong></h3><p>To run the code, you need to install python version 3.9 or newest. You can install libraries in a dedidated venv:</p><pre># windows: pip or pip3<br>pip install python3-venv<br><br># You should see a folder named Scripts<br>activate <br><br># unix<br># sudo apt install python3-venv</pre><p>Libraries to install:</p><p>We use ` — quiet` to hide additional information in the terminal shown during installation. It’s not necessary and can be removed from the command.</p><pre>pip install numpy pandas  seaborn  kagglehub wordcloud  imbalanced-learn --quiet</pre><p>At the top of the file, add all necessary imports:</p><pre>import os<br>import nltk<br>import math<br>import torch<br>import numpy as np<br>import pandas as pd<br>import seaborn as sns<br>from pathlib import Path<br>import matplotlib.pyplot as plt<br>from wordcloud import WordCloud<br>from nltk.corpus import stopwords<br>from scipy.sparse import csr_matrix<br>from nltk.tokenize import word_tokenize<br>from nltk.stem import WordNetLemmatizer<br>from imblearn.over_sampling import SMOTE<br>from typing import Callable, List, Tuple<br>from sklearn.metrics import accuracy_score<br>from collections import defaultdict, Counter<br>from nltk.stem.snowball import EnglishStemmer<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br>from imblearn.under_sampling import RandomUnderSampler<br>from sklearn.feature_extraction.text import TfidfVectorizer<br><br># uncomment if you&#39;d like to use stemmer<br># from nltk.stem.snowball import EnglishStemmer<br><br># Download the necessary NLTK resources - you need to do this only once<br># nltk.download(&#39;punkt&#39;)<br># nltk.download(&#39;punkt_tab&#39;)<br># nltk.download(&#39;stopwords&#39;)<br># nltk.download(&#39;wordnet&#39;)</pre><h3><strong>2. Defining globals</strong></h3><p>The next part is adding some global variables wich allows us to skip passing those values as arguments each time.</p><pre># global variables and functions<br>SMOTE_= SMOTE(random_state=42)<br>LEMMATIZER = WordNetLemmatizer()<br>TFIDF_VECTORIZER = TfidfVectorizer()<br>STOPWORDS =  set(stopwords.words(&#39;english&#39;))<br>STEMMER = EnglishStemmer(ignore_stopwords=True)<br>UNDERSAMPLER = RandomUnderSampler(random_state=42)<br><br>WORD_DOC_FREQ = defaultdict(int)<br>VOCABULARY = None<br>WORD_TO_IDX = None<br>NUM_TRAIN_DOCS = 0<br>LOG_N = 0</pre><p><strong>‘42’</strong> is a seed value, ensuring reproducibility of your results. You can change it to any other int value as long as you do so in other parts ot the code.</p><h3><strong>3. Loading email spam dataset</strong></h3><p>Let’s import the aforementioned dataset. If you want to serve file from local directory, make sure to download it <a href="https://www.kaggle.com/datasets/jackksoncsie/spam-email-dataset"><strong>here</strong></a><strong> </strong>and replace in the code below this part ‘’./data/emails.csv’’ to your directory.</p><pre># load the dataset<br>def load_dataset(locally: bool = False) -&gt; pd.DataFrame:<br>    &quot;&quot;&quot;<br>    Download Kaggle&#39;s dataset.<br><br>    :param locally: (bool) False by default. Is set to True, make sure<br>    to provide proper path to your local CSV file.<br>    :returns pd.DataFrame: a Pandas data frame.<br>    &quot;&quot;&quot;<br>    if locally:<br>        # provide emails.csv file in a preferreed directory<br>        return pd.DataFrame(pd.read_csv(&#39;./data/emails.csv&#39;))<br>    else:<br>        import kagglehub<br>        download_path = kagglehub.dataset_download(<br>            &quot;jackksoncsie/spam-email-dataset&quot;, <br>            force_download=False<br>        )<br>        return pd.read_csv(Path(<br>            os.path.join(download_path, &#39;emails.csv&#39;)<br>            ).as_posix()<br>        )<br><br>dataset = load_dataset()<br>print(f&#39;-&gt; Data sample:\n{dataset.head()}&#39;, end=&#39;\n\n&#39;)</pre><p>You should expect such data to be printed in the console / terminal:</p><pre>-&gt; Data sample:<br>                                                text  spam<br>0  Subject: naturally irresistible your corporate...     1<br>1  Subject: the stock trading gunslinger  fanny i...     1<br>2  Subject: unbelievable new homes made easy  im ...     1<br>3  Subject: 4 color printing special  request add...     1<br>4  Subject: do not have money , get software cds ...     1</pre><p>— — — Done so far — — —</p><ul><li>Installed the necessary libraries.</li><li>Downloaded and loaded the dataset from Kaggle.</li><li>Taken a glimpse at the data in the dataset.</li></ul><h3><strong>4. Adding helper functions</strong></h3><p>The first step is to build some<strong> helper functions</strong> that we’re going to use later in the code. We’re using closures to keep things in a local neighbourhood for better understanding.</p><blockquote>Python closure is a nested <a href="https://www.programiz.com/python-programming/function">function</a> that allows us to access <a href="https://www.programiz.com/python-programming/variables-constants-literals">variables</a> of the outer function even after the outer function is closed. (source: <a href="https://www.programiz.com/python-programming/closure">https://www.programiz.com/python-programming/closure</a>)</blockquote><p>Let’s break it down into parts and explain what’s going on here.</p><h3><strong>4a. Resampling</strong></h3><p><strong>Why is resampling necessary?</strong> Consider a scenario where our dataset contains 10,000 emails, but only 1,000 of them are labeled as spam. Training a model on such imbalanced data can lead to inefficiencies and potential issues down the line. To address this, we need to resample the dataset to balance the two categories: spam and not spam. By ensuring that both labels have a similar number of instances, we can create a more effective training set before passing it to the model. This revision clarifies the reasoning behind resampling and improves the overall flow of the text.</p><p>This part informs what data we’re expecting to get. Because in later chapters we’re going to use PyTorch and Scikit-Learn, we need to vectorize the data and turn it into tensors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*IRHzOTzNwc145P079U6Gmw.png" /><figcaption>Different data representation based on dimension. Source: <a href="https://dev.to/mmithrakumar/scalars-vectors-matrices-and-tensors-with-tensorflow-2-0-1f66">dev.to</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*t6rjkRppvQoRQfgUplxDjA.jpeg" /><figcaption>Graphical tensor representation. Source: <a href="https://dev.to/mmithrakumar/scalars-vectors-matrices-and-tensors-with-tensorflow-2-0-1f66">dev.to</a></figcaption></figure><p>To grasp the differences between scalars, vectors, matrices, and tensors, please read the article ‘’<a href="https://dev.to/mmithrakumar/scalars-vectors-matrices-and-tensors-with-tensorflow-2-0-1f66">Scalars, Vectors, Matrices and Tensors with Tensorflow 2.0</a>&#39;’.</p><p>You need to provide a value for sampling_category, is a string that should have one of the following values: oversample, undersample, or combined.</p><p>Later, you will see that the dataset is not balanced and we have more data labelled as 0 (proper emails class) than 1 (spam emails). Before passing data to the model, we need to decide how to balance the dataset.</p><p>The code needs to know if it shoukd focuse on reducing the data from the majority class</p><pre>def resampling(<br>        X_train: torch.Tensor, <br>        y_train: torch.Tensor, <br>        sampling_category: str, <br>    ) -&gt; Tuple[torch.Tensor, torch.Tensor]:</pre><ol><li>Oversampling: a technique used to balance an imbalanced dataset by <strong>reducing </strong>the number of instances <strong>in the majority class</strong>.</li></ol><blockquote><strong>Pros</strong>: Reduces the size of the dataset, making it faster to train models.</blockquote><blockquote><strong>Cons</strong>: You might lose important information from the majority class. Can lead to underfitting if too much data is removed.</blockquote><p>2. Oversampling: a technique used to balance an imbalanced dataset by <strong>increasing </strong>the number of instances <strong>in the minority class</strong>.</p><blockquote><strong>Pros</strong>: Retains all the information from the original dataset. Can improve model performance by providing more examples of the minority class.</blockquote><blockquote><strong>Cons</strong>: Increases the size of the dataset, making it slower to train models. Synthetic samples might not be as informative as real ones.</blockquote><p>2. Combined: a technique that uses both undersampling and oversampling to balance the dataset.</p><blockquote><strong>Pros</strong>: Balances the dataset effectively. Retains important information from both classes.</blockquote><blockquote><strong>Cons</strong>: More complex to implement. Can still lead to larger datasets and longer training times.</blockquote><p>For more insights, please go through this great article: <a href="https://machinelearningmastery.com/random-oversampling-and-undersampling-for-imbalanced-classification">MachineLearningMastery — Resampling strategies</a> (website)</p><p>Full part of the code:</p><pre># helper functions<br>def resampling(<br>        X_train: torch.Tensor, <br>        y_train: torch.Tensor, <br>        sampling_category: str, <br>    ) -&gt; Tuple[torch.Tensor, torch.Tensor]:    <br>    &quot;&quot;&quot;Use resampling techniques to balance datasets.&quot;&quot;&quot;<br><br>    def oversample_minority_class(<br>            X_train: torch.Tensor, <br>            y_train: torch.Tensor<br>        ) -&gt; Tuple[np.ndarray, np.ndarray]:<br>        &quot;&quot;&quot;SMOTE - Synthetic Minority Over-sampling Technique&quot;&quot;&quot;<br>        return SMOTE_.fit_resample(X_train, y_train)<br><br>    def undersample_majority_class(<br>            X_train: torch.Tensor, <br>            y_train: torch.Tensor<br>        ) -&gt; Tuple[np.ndarray, np.ndarray]:<br>        return UNDERSAMPLER.fit_resample(X_train, y_train)<br><br>    def combined_resampling(<br>            X_train: torch.Tensor, <br>            y_train: torch.Tensor, <br>            sampling_strategy: float | str | dict = &#39;auto&#39;<br>        ) -&gt; Tuple[np.ndarray, np.ndarray]:<br>        &quot;&quot;&quot;<br>        Use resampling techniques to balance datasets.<br><br>        Parameters:<br>        X_train (np.ndarray): Training features.<br>        y_train (np.ndarray): Training labels.<br>        sampling_category (str): The resampling technique to use. Options are &#39;oversample&#39;, &#39;undersample&#39;, or &#39;combined&#39;.<br>        undersample_strategy (float): The ratio of the number of samples in the minority class to the number of <br>        in the majority class after undersampling. Must be in the range (0.0, 1.0].<br><br>        Returns:<br>        Tuple[torch.Tensor, torch.Tensor]: Resampled training features and labels as PyTorch tensors.<br>        &quot;&quot;&quot;<br>        # Step 1: Undersample the majority class<br>        undersampler = RandomUnderSampler(sampling_strategy=sampling_strategy, random_state=42)<br>        X_undersampled, y_undersampled = undersampler.fit_resample(X_train, y_train)<br>        <br>        # Step 2: Oversample the minority class<br>        smote = SMOTE(random_state=42)<br>        return smote.fit_resample(X_undersampled, y_undersampled)<br><br>    match sampling_category:<br>        case &#39;oversample&#39;:<br>            X_resampled, y_resampled = oversample_minority_class(X_train, y_train)<br>        case &#39;undersample&#39;:<br>            X_resampled, y_resampled = undersample_majority_class(X_train, y_train)<br>        case &#39;combined&#39;:<br>            X_resampled, y_resampled = combined_resampling(X_train, y_train)<br>        case _:<br>            raise ValueError(&quot;Invalid sampling category. Use &#39;oversample&#39;, &#39;undersample&#39; or &#39;combined&#39;.&quot;)<br>    return torch.tensor(X_resampled, dtype=torch.float32), torch.tensor(y_resampled, dtype=torch.int32)<br><br>def extract_tokens(document: str, lemmatize: bool = True) -&gt; dict:<br>    &quot;&quot;&quot;Extract tokens from a document.&quot;&quot;&quot;<br>    tokens = word_tokenize(document.lower())<br><br>    if lemmatize:<br>        filtered_tokens = [LEMMATIZER.lemmatize(word) for word in tokens if word.isalnum() and word not in STOPWORDS]<br>    else:<br>        filtered_tokens = [word for word in tokens if word.isalnum() and word not in STOPWORDS]<br>    return dict(Counter(filtered_tokens))<br><br>def corpus(documents: np.ndarray) -&gt; List[dict]:<br>    &quot;&quot;&quot;Create a list of token dictionaries for each document.&quot;&quot;&quot;<br>    all_texts = []<br>    for document in documents:<br>        all_texts.append(extract_tokens(document))<br>    return all_texts<br><br>def count_tf(document: dict) -&gt; List[float]:<br>    &quot;&quot;&quot;Calculate term frequency for each term in a document.&quot;&quot;&quot;<br>    all_keys = sum(document.values())<br>    return [document[k] / all_keys for k in document.keys()]<br><br>def count_idf(document: dict, corpus: dict) -&gt; List[int]:<br>    &quot;&quot;&quot;Calculate document frequency for each term in the corpus.&quot;&quot;&quot;<br>    return [corpus.get(k, 0) for k in document.keys()]<br><br>def tf_idf(tf: List[float], df: List[int], n: int) -&gt; List[float]:<br>    &quot;&quot;&quot;Calculate TF-IDF values for terms in a document.&quot;&quot;&quot;<br>    return [t * math.log(n / (d + 1)) for t, d in zip(tf, df)]<br><br></pre><p>— — — Done so far — — —</p><ul><li>You can name differences between scalars, vectors, matrices, and tensors.</li><li>You understand why we need to convert data to a tensor form for data processing in machine learning.</li><li>You know what it resampling.</li><li>You know why we need it in terms of providing balanced datasets.</li></ul><p>Great!</p><h3><strong>4b. Coding TF-IDF (almost) from scratch</strong></h3><p>TF-IDF is a technique used to determine which words in a dataset are more important or rare, helping the computer focus on the most meaningful data while filtering out statistical noise.</p><p>In this article, we will explore two different approaches to calculating TF-IDF. We’ll implement a basic version of TF-IDF ourselves and also use Scikit-Learn’s built-in tools to achieve the same result.</p><p>To better understand this, imagine the following scenario: you have a collection of documents on different topics, and you want to identify which words are most relevant to each topic. Some words, like “the,” “and,” or “is,” are used so frequently that they provide little information about the content. In contrast, words that appear less often but are specific to a particular topic can reveal important insights. TF-IDF helps to assign higher weights to these rarer, more informative words, while down-weighting common words that don’t contribute much to the unique meaning of a document.</p><p>To calculate TF-IDF we need to perform serveral steps:</p><ol><li>Term Frequency (TF)</li></ol><p>Measures how often a specific word appears in a document compared to the total number of words in that document. We implemented it as `<strong>def count_tf(document: dict)</strong>` in the code below.</p><p>Formula:</p><ul><li>t: term</li><li>d: document</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*IudUZsfLu5CsS_fsLUMDOg.png" /><figcaption>Source: Image generated in LaTeX</figcaption></figure><p>2. Inverse Document Frequency (IDF)</p><p>Measures how important a term is throughout the entire corpus (all documents combined together). We implemented it as `<strong>def count_idf(document: dict)</strong>` in the code below.</p><ul><li>t: term</li><li>N: corpus</li></ul><p>Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*J59m89y0WhTQ1-jHP8L4bQ.png" /><figcaption>Source: Image generated in LaTeX</figcaption></figure><p>3. Term-Frequency Inverse Document Frequency (TD-IDF)</p><p>Evaluates the importance of a term within a document relative to a collection of documents (the corpus) to provide a balanced representation of how significant a term is in a specific document while considering its prevalence across all documents.</p><ul><li>t: term</li><li>d: document</li><li>N: corpus</li></ul><p>Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*UGNk-8kBAS9whGOpmoP7_w.png" /><figcaption>Source: Image generated in LaTeX</figcaption></figure><p>4. Additionally (not include within the scope of this article), we can add weights to the TF-IDF based on custom criteria.</p><p>Each term gets added a proper weight based on how frequent it appeard across documents (how rare it is).</p><ul><li>Heighest weight: term can be found many times but only in a few documents.</li><li>Medium weight: term can be found fewer times in a document or can be found in many documents.</li><li>Low weight: Can be found frequently across all documents.</li><li>t: term</li><li>d: document</li><li>N: corpus</li><li>W: weight</li></ul><p>Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*BTGHDFI39S3gBKKVVWIH7g.png" /><figcaption>Source: Image generated in LaTeX</figcaption></figure><ul><li>t: term</li><li>d: document</li><li>N: corpora</li></ul><p>Two other things you might spotted in the code consider lemmatization and semming (EnglishStemmer, WordNetLemmatizer). This code uses lemmatization, but you can add stemming if this is your preferred option. To do this, uncomment STEMMER in globals and replace lemmatizer with STEMMER.stem(data).</p><p><strong>Stemming </strong>is the process of reducing words to their root form by removing prefixes and suffixes, often resulting in non-dictionary forms (e.g., “running” to “run”). It is faster but can be less accurate.</p><p><strong>Lemmatization </strong>reduces words to their base or dictionary form while considering meaning and context (e.g., “better” to “good”). It is more accurate but also more computationally intensive.In summary, stemming prioritizes speed, while lemmatization emphasizes accuracy.</p><pre>def extract_tokens(document: str, lemmatize: bool = True) -&gt; dict:<br>    &quot;&quot;&quot;Extract tokens from a document.&quot;&quot;&quot;<br>    tokens = word_tokenize(document.lower())<br><br>    if lemmatize:<br>        filtered_tokens = [LEMMATIZER.lemmatize(word) for word in tokens if word.isalnum() and word not in STOPWORDS]<br>    else:<br>        filtered_tokens = [word for word in tokens if word.isalnum() and word not in STOPWORDS]<br>    return dict(Counter(filtered_tokens))<br><br>def corpus(documents: np.ndarray) -&gt; List[dict]:<br>    &quot;&quot;&quot;Create a list of token dictionaries for each document.&quot;&quot;&quot;<br>    all_texts = []<br>    for document in documents:<br>        all_texts.append(extract_tokens(document))<br>    return all_texts<br><br>def count_tf(document: dict) -&gt; List[float]:<br>    &quot;&quot;&quot;Calculate term frequency for each term in a document.&quot;&quot;&quot;<br>    all_keys = sum(document.values())<br>    return [document[k] / all_keys for k in document.keys()]<br><br>def count_idf(document: dict, corpus: dict) -&gt; List[int]:<br>    &quot;&quot;&quot;Calculate document frequency for each term in the corpus.&quot;&quot;&quot;<br>    return [corpus.get(k, 0) for k in document.keys()]<br><br>def tf_idf(tf: List[float], df: List[int], n: int) -&gt; List[float]:<br>    &quot;&quot;&quot;Calculate TF-IDF values for terms in a document.&quot;&quot;&quot;<br>    return [t * math.log(n / (d + 1)) for t, d in zip(tf, df)]</pre><p>— — — Done so far — — —</p><ul><li>You recognize process of stemming and lemmatization.</li><li>You can explain why we need to use TF-IDF, and not just TF or IDF.</li><li>You know what is a document and a corpora in terms of text vectorization.</li></ul><h3>Data Exploration</h3><p>In this data exploration phase, we begin by conducting a thorough analysis of the dataset downloaded from Kaggle. Our initial steps include identifying and handling any missing values, followed by reviewing the data’s statistical properties for accuracy.</p><p>We then assess the balance between the classes, specifically examining the distribution of spam and non-spam emails.</p><p>To better understand any class imbalances, we calculate the ratio of minority to majority classes. Further, we visualize the class distribution and perform a detailed analysis of the text length across emails.</p><p>Finally, we create a word cloud for the non-spam emails, offering valuable insights into their common language patterns.</p><p>Steps shown in the code below:</p><ol><li>Checking for missing values.</li></ol><p>2. Verifying data statistics</p><p>3. Verify that data distribution is balanced between classes (spam / not spam).</p><p>4. Calculating minority-majority difference ratio between classes.</p><p>5. Class distribution visualization.</p><p>6. Text length analysis.</p><p>7. Word cloud for non-spam emails.</p><pre># Ad. 1<br>print(f&#39;-&gt; Missing data:\n{dataset.isnull().sum()}&#39;, end=&#39;\n\n&#39;)<br><br># Ad. 2<br>print(f&#39;-&gt; Summary statistics:\n{dataset.describe()}&#39;, end=&#39;\n\n&#39;)<br><br># Ad. 3<br>spam_counts = dataset[&#39;spam&#39;].value_counts()<br>print(f&#39;-&gt; Spam classicifaction:\n{spam_counts}&#39;, end=&#39;\n\n&#39;)<br><br># Ad. 4<br>spam = spam_counts[1]<br>not_spam = spam_counts[0]<br>min_max_ration = spam / not_spam<br>print(f&#39;-&gt; Ratio of spam to not spam: {min_max_ration:.4f}&#39;, end=&#39;\n\n&#39;)<br># output: 0.31 which means that the dataset is imbalanced<br><br># Ad. 5<br>plt.figure(figsize=(8, 6))<br>sns.countplot(x=&#39;spam&#39;, data=dataset)<br>plt.title(&#39;Class Distribution&#39;)<br>plt.xlabel(&#39;0 - not spam, 1 - spam&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.show()<br><br># Ad. 6<br>spam_emails = &#39; &#39;.join(dataset[dataset[&#39;spam&#39;] == 1][&#39;text&#39;])<br>wordcloud = WordCloud(width=800, height=400, background_color=&#39;white&#39;).generate(spam_emails)<br>plt.figure(figsize=(10, 5))<br>plt.imshow(wordcloud, interpolation=&#39;bilinear&#39;)<br>plt.axis(&#39;off&#39;)<br>plt.title(&#39;Word Cloud for Spam Emails&#39;)<br>plt.show()<br><br># Ad. 7<br>non_spam_emails = &#39; &#39;.join(dataset[dataset[&#39;spam&#39;] == 0][&#39;text&#39;])<br>wordcloud = WordCloud(width=800, height=400, background_color=&#39;white&#39;).generate(non_spam_emails)<br>plt.figure(figsize=(10, 5))<br>plt.imshow(wordcloud, interpolation=&#39;bilinear&#39;)<br>plt.axis(&#39;off&#39;)<br>plt.title(&#39;Word Cloud for Non-Spam Emails&#39;)<br>plt.show()</pre><p>Text that will be generated in the terminal look like this.</p><p>We can observe that:</p><ul><li>data is complete (no missing values in row/columns)</li><li>dataset offers labels named 0 and 1, representing non-spam emails and spam emails</li><li>ration spam / not-spam equals 31% (which means the data is not balanced, as number of items groupped by label are not equal).</li></ul><pre>-&gt; Missing data:<br>text    0<br>spam    0<br>dtype: int64<br><br>-&gt; Summary statistics:<br>              spam<br>count  5728.000000<br>mean      0.238827<br>std       0.426404<br>min       0.000000<br>25%       0.000000<br>50%       0.000000<br>75%       0.000000<br>max       1.000000<br><br>-&gt; Spam classicifaction:<br>spam<br>0    4360<br>1    1368<br>Name: count, dtype: int64<br><br>-&gt; Ratio of spam to not spam: 0.3138</pre><p>Images generated by this part of the code:</p><p>It’s now clear that the dataset is imbalanced, and we’ll need to address this before feeding the data into our spam filtering model. The class distribution between spam and non-spam emails is as follows: label 1 (spam) is 0.31% less than label 0 (non-spam).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*KE1BYPAE6jxlqvKi6ifo4Q.png" /><figcaption>Imbalanced dataset. We have 0.31% more non-spam emails than spam ones. Source: Image generated by code.</figcaption></figure><p>We did not perform any data removal from the email contents.</p><p>Most common words in the spam emails:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*m0KzhCA21yaMpJxoRrikWA.png" /><figcaption>Most common words in the spam emails content. The bigger the word the more frequently found in the dataset. Source: Image generated by code.</figcaption></figure><p>Most common words in the non-spam emails:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*bJaHWBnKORwKf_SJJzOz5Q.png" /><figcaption>Most common words in the non-spam emails content. The bigger the word the more frequently found in the dataset. Source: Image generated by code.</figcaption></figure><p>Now we can fully understand the initial need of providing resampling :)</p><h3>Splitting data</h3><p>After reviewing the data, we begin by splitting it into two separate parts:</p><ul><li><strong>Emails</strong> — the data that will later serve as input for the model.</li><li><strong>Labels</strong> — our target variable, which will be used for model fitting and to help measure the model’s loss during training.</li></ul><pre># split data by columns<br>emails = dataset.iloc[:, 0].values<br>labels = dataset.iloc[:, 1:].values</pre><p>— — — Done so far — — —</p><ul><li>You now how to perform a basic data check.</li><li>You can recognize an imbalanced dataset.</li><li>You know how to split this particular dataset into separate chunks.</li></ul><h3>TF-IDF implementation</h3><p>We can use scikit-learn library to use from <strong>TfidfVectorizer </strong>(from Scikit-Learn)<strong> </strong>or code the solution from scratch.</p><p>First, let’s implement TF-IDF using inbuilt Scikit-Learn functions.</p><pre>def tf_idf_vectorization(emails: np.ndarray, fit: bool = True) -&gt; torch.Tensor:<br>    &quot;&quot;&quot;Use predefined Sklearn functions to vectorize data.<br>       :param emails: (np.ndarray) Input text data<br>       :param fit: (bool) If True, fit and transform the vectorizer, else transform.<br>       :returns torch.Tensor: Vectorized text data.<br>    &quot;&quot;&quot;<br>    # vectorize data using TF-IDF<br>    if fit:<br>        tfidf_matrix = TFIDF_VECTORIZER.fit_transform(emails)<br>    else:<br>        tfidf_matrix = TFIDF_VECTORIZER.transform(emails)<br>    <br>    df_tfidf = pd.DataFrame(<br>        tfidf_matrix.toarray(), <br>        columns=TFIDF_VECTORIZER.get_feature_names_out()<br>    )<br><br>    # convert data to PyTorch tensor format<br>    emails_tensor = torch.tensor(df_tfidf.values, dtype=torch.float32).float()<br>    return emails_tensor</pre><p>Now, let’s create our own version. The docstrings within the functions will provide a detailed, step-by-step guide to help you understand the process.</p><pre><br>def tf_idf_from_scratch(<br>        emails: np.ndarray, fit: bool = True, <br>        lemmatize: bool = True<br>    ) -&gt; torch.Tensor:<br>    &quot;&quot;&quot;<br>    Optimized TF-IDF calculation from scratch.<br>    1. Extract_tokens function tokenizes the document, removes stopwords, and optionally lemmatizes the tokens.<br>    2, Corpus function creates a list of words for each document.<br>    3. The count_tf function calculates the term frequency for each term in a document.<br>    4. The count_idf function calculates the document frequency for each term in the corpus.<br>    5. The tf_idf function calculates the TF-IDF values for each term in a document.<br>    5. The TF-IDF values are calculated for each document in the corpus and printed.<br><br>    :param: emails (np.ndarray): Array of email documents<br>    :param fit: (bool) If True, fit and transform the vectorizer. If False, only transform.<br>    :returns torch.Tensor: TF-IDF emails tensor<br>    &quot;&quot;&quot;<br>    global WORD_DOC_FREQ, VOCABULARY, WORD_TO_IDX, NUM_TRAIN_DOCS, LOG_N<br>    <br>    if fit:<br>        # Reset globals<br>        WORD_DOC_FREQ = defaultdict(int)<br>        NUM_TRAIN_DOCS = len(emails)<br>        <br>        # First pass: Build vocabulary and document frequencies<br>        word_doc_count = defaultdict(lambda: defaultdict(int))<br>        <br>        for doc_idx, doc in enumerate(emails):<br>            tokens = extract_tokens(doc, lemmatize=lemmatize)<br>            <br>            for word in tokens:<br>                if word_doc_count[doc_idx][word] == 0:<br>                    WORD_DOC_FREQ[word] += 1<br>                word_doc_count[doc_idx][word] += 1<br>        <br>        # Create vocabulary list and mapping<br>        VOCABULARY = sorted(WORD_DOC_FREQ.keys())<br>        WORD_TO_IDX = {word: idx for idx, word in enumerate(VOCABULARY)}<br>        LOG_N = np.log(NUM_TRAIN_DOCS)<br>    <br>    # Transform phase (runs for both fit=True and fit=False)<br>    vocab_size = len(VOCABULARY) if VOCABULARY else 0<br>    num_docs = len(emails)<br>    <br>    rows = []<br>    cols = []<br>    values = []<br>    <br>    for doc_idx, doc in enumerate(emails):<br>        # Process document<br>        tokens = extract_tokens(doc, lemmatize=lemmatize)<br>        token_counts = Counter(tokens)<br>        doc_length = sum(token_counts.values())<br>        <br>        if doc_length == 0:<br>            continue<br>            <br>        for word, count in token_counts.items():<br>            if word in WORD_TO_IDX:<br>                tf = count / doc_length<br>                idf = LOG_N - np.log(WORD_DOC_FREQ[word] + 1)<br>                tfidf = tf * idf<br>                <br>                if tfidf != 0:<br>                    rows.append(doc_idx)<br>                    cols.append(WORD_TO_IDX[word])<br>                    values.append(tfidf)<br>    <br>    # Create sparse matrix and convert to dense tensor<br>    sparse_matrix = csr_matrix(<br>        (values, (rows, cols)),<br>        shape=(num_docs, vocab_size),<br>        dtype=np.float32<br>    )<br>    <br>    # Convert to PyTorch tensor<br>    emails_tensor = torch.from_numpy(sparse_matrix.toarray()).float()<br>    return emails_tensor</pre><p>— — — Done so far — — —</p><ul><li>You can implement TF-IDF text vectorization using Scikit-Learn.</li><li>You also can do it almost from scratch by providing custom implementation.</li></ul><p><strong>Balanced / Imbalanced dataset &amp; Resampling</strong></p><p>Previously, we explained data balancing by implementing helper functions. Now, it’s time to add this part into the code solution.</p><blockquote>In this step you need to choose the TF-IDF, the one offered by scikit-learn or our custom one.</blockquote><blockquote>! You change it once only in this piece of the code.</blockquote><pre># 1. First split the raw text data and labels<br>X_train_raw, X_test_raw, y_train, y_test = train_test_split(<br>    emails,  # raw text data<br>    labels, <br>    test_size=0.2, <br>    random_state=42<br>)<br><br># 2. Fit and transform TF-IDF on training data only<br># or tf_idf_from_scratch(X_train_raw, fit=True)<br>X_train = tf_idf_vectorization(X_train_raw, fit=True) <br><br># 3. Transform test data using the fitted vectorizer<br># or tf_idf_from_scratch(X_test_raw, fit=False)<br>X_test = tf_idf_vectorization(X_test_raw, fit=False)<br><br># 4. Convert labels to tensors<br>y_train = torch.tensor(y_train, dtype=torch.int32)<br>y_test = torch.tensor(y_test, dtype=torch.int32)<br><br># Ratio is 0.31, and the fixed threshold is set to 0.05. We should balance the data in the next step.<br>if min_max_ratio &gt; 0.05:<br>    X_train, y_train = resampling(<br>        X_train=X_train, <br>        y_train=y_train, <br>        sampling_category=&#39;oversample&#39;<br>    )<br>    print(f&#39;Classes count after resampling:\n{pd.Series(y_train).value_counts()}&#39;)</pre><p>You can copare the initial emails’ content with the one that has been vectorized:</p><pre># examples<br>print(&quot;X_train: &quot;, X_train)<br>print(&quot;y_train: &quot;, y_train)</pre><p>which gives result similar to:</p><pre>X_train:  tensor([[0.0000e+00, 0.0000e+00, 0.0000e+00,  ..., 0.0000e+00, 0.0000e+00,<br>         0.0000e+00],<br>        [0.0000e+00, 0.0000e+00, 0.0000e+00,  ..., 0.0000e+00, 0.0000e+00,<br>         0.0000e+00],<br>        [0.0000e+00, 0.0000e+00, 0.0000e+00,  ..., 0.0000e+00, 0.0000e+00,<br>         0.0000e+00],<br>        ...,<br>        [2.4393e-03, 1.7632e-03, 2.6521e-03,  ..., 0.0000e+00, 0.0000e+00,<br>         0.0000e+00],<br>        [5.1898e-05, 2.5849e-03, 3.8881e-03,  ..., 0.0000e+00, 0.0000e+00,<br>         0.0000e+00],<br>        [0.0000e+00, 0.0000e+00, 0.0000e+00,  ..., 0.0000e+00, 0.0000e+00,<br>         0.0000e+00]])<br>y_train:  tensor([0, 0, 0,  ..., 1, 1, 1], dtype=torch.int32)</pre><p>The next steps are to create a classifier and a model. Let’s find out what is the accuracy.</p><p>Classifier:</p><pre># Create an instance of LogisticRegression<br>classifier = LogisticRegression()<br><br># Train the classifier on the training data<br>classifier.fit(X_train, y_train)<br><br># Make predictions on the testing data<br>y_pred = classifier.predict(X_test)<br><br># Calculate the accuracy of the classifier<br>accuracy = accuracy_score(y_test, y_pred)<br>print(f&quot;Accuracy: {accuracy * 100:.2f}%&quot;)</pre><p>Model:</p><pre># Create an instance of LogisticRegression<br>model = LogisticRegression(max_iter=10000)<br>model.fit(X_train, y_train)<br><br># Make predictions<br>predictions = model.predict(X_test)<br><br># Evaluate accuracy<br>accuracy = accuracy_score(y_test, predictions)<br>print(f&quot;Accuracy: {accuracy * 100:.2f}%&quot;)</pre><p>The final step is to test the model on a brand new data. Because we implemented TF-IDF of two types, let’s split also the usage functions.</p><p>Scikit-Learn based TF-IDF (classify_text) and custom TF-IDF (classify_text_custom):</p><pre>def classify_text(model, new_text: str) -&gt; tuple:<br>    &quot;&quot;&quot;Classify a new text message as spam or not spam.&quot;&quot;&quot;<br>    # Transform new text using the same vectorizer (don&#39;t fit)<br>    new_text_tensor = tf_idf_vectorization(np.array([new_text]), fit=False)<br>    <br>    # Make prediction<br>    prediction = model.predict(new_text_tensor)<br>    probabilities = model.predict_proba(new_text_tensor)<br>    <br>    # Interpret the prediction<br>    label = &quot;Spam&quot; if prediction[0] == 1 else &quot;Not Spam&quot;<br>    proba = probabilities[0][prediction[0]]<br>    return label, proba<br><br>def classify_text_custom(model, new_text: str) -&gt; tuple:<br>    &quot;&quot;&quot;Classify a new text message as spam or not spam.&quot;&quot;&quot;<br>    new_text_tensor = tf_idf_from_scratch(np.array([new_text]), fit=False)<br><br>    prediction = model.predict(new_text_tensor)<br>    probabilities = model.predict_proba(new_text_tensor)<br>    <br>    label = &quot;Spam&quot; if prediction[0] == 1 else &quot;Not Spam&quot;<br>    proba = probabilities[0][prediction[0]]<br>    return label, proba</pre><p>To choose between scikit-learn and custom TF-IDF go to ‘<strong>Balanced / Imbalanced dataset &amp; Resampling’ </strong>and change the function.</p><p>Provide own data:</p><pre># Example usage:<br>new_message = &quot;great offer buy now bitcoins!!!!!!&quot; # insert your data<br>label, probability = classify_text(model, new_message)<br>print(f&quot;Classification: {label}&quot;)<br>print(f&quot;Probability: {probability:.2f}&quot;)<br></pre><p>Result:</p><pre>Classification: Spam<br>Probability: 0.88</pre><h3>Conclusions</h3><p>In this first part of our text vectorization journey, we’ve successfully built a foundation for understanding and implementing text-to-vector conversion techniques.</p><p>We started with basic data exploration, implemented TF-IDF vectorization using both Scikit-Learn and a custom approach, and created a working spam detection system. Through hands-on implementation, we learned how to handle imbalanced datasets using resampling techniques, process text data using lemmatization, and convert raw text into machine-readable vectors.</p><p>The resulting model can effectively classify new emails with probability scores, demonstrating practical application of these concepts. In the next part of this series, we’ll explore more advanced embedding techniques and how they can improve our text classification capabilities.</p><p>Whether you’re building a spam filter or working on other NLP tasks, the fundamentals covered here provide a solid starting point for more complex text processing applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98f94a086622" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents in Action: Boosting Revenue for Startups through Strategic Implementation ]]></title>
            <link>https://medium.com/@gabrielrodewald/ai-agents-in-action-boosting-revenue-for-startups-through-strategic-implementation-3ce08f9da728?source=rss-6f32802fcc06------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ce08f9da728</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Gabriel Rodewald]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 21:05:50 GMT</pubDate>
            <atom:updated>2024-08-12T21:05:50.546Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this series of short &amp; fun articles, we’re diving headfirst into the world of open-source AI tools and their potential to impact revenue generation for startups. But hold onto your keyboards, folks — we’re not just talking about your run-of-the-mill SaaS products or IT services.</p><p>To follow up, you can find a short list of useful concepts linked at the end of this article.</p><figure><img alt="A plush llama against a background of charts. Source: https://www.bing.com/images/create" src="https://cdn-images-1.medium.com/max/1024/1*VfejDC3ICEiRVipa9Qwjog.jpeg" /><figcaption>Llama 3.1 as a leading open-source LLM. Source: Generated by Bing (<a href="https://www.bing.com/images/create">https://www.bing.com/images/create</a>)</figcaption></figure><h3>Hypotheses and assumptions</h3><p>Let’s kick things off with two hypotheses that would make even the most seasoned data scientist’s heart race:</p><p>👉 H0: The Null Hypothesis: Open-source tools and their AI offspring are ready for their commercial debut.<br>👉 H1: The Alternative Hypothesis: LLM-based agents aren’t quite ready for their moment in the spotlight… yet.</p><p><strong>What is your bet? </strong>💡(share it in the comments :)</p><p>To keep our investigation as rigorous as a double-blind study (but way more exciting), we’ll adhere to the following ground rules:</p><ul><li>We’re only using publicly available data (don’t worry, we’ll keep it anonymous and categorized — no trade secrets spilled here!).</li><li>Our AI agents are specialized fine-tuned models having access to the Internet and vectorstores updated by agents, built on the shoulders of open-source LLM’s (Llama3.1, fine-tuned with RAG access agents).</li></ul><p>Measuring success with metrics:<br>a) How closely our AI-generated content matches the engagement levels of human-created commercial posts. (Naively assuming high engagement equals high ROI — hey, we’re optimists!)<br>b) The agents’ reasoning prowess in supporting business decisions. We’ll create a mini economic sandbox and see if our AI friends can navigate it like seasoned Wall Street traders.<br>c) Can agents be part-time developers? Let’s try to pass on to them some less-favored responsibilities like reading and updating documentation, finding bugs, checking databases for expected results, preselecting important emails, or even managing our calendars for scheduling meetings.</p><p>Evaluation criteria are based on:</p><ul><li>Custom mini-benchmarks checking the non-parametrizied agent’s behaviour.</li><li>Analytical accuracy (Can they think like a CEO?)<br>Predictive power (How well do their insights match historical data they’ve never seen?)</li><li>The impact of specialized tools and domain-specific agents (Starting with a coin flip and improving with each iteration)</li></ul><h3>Real-world use cases</h3><p>Now, taking this AI-powered business ride to the next level with six case studies we will check tests results aiming at:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PP01fNvfF-kCBb9r28BKlg.jpeg" /><figcaption>Business-oriented Agentic approach for emerging startups. Source: Generated by Bing (<a href="https://www.bing.com/images/create">https://www.bing.com/images/create</a>)</figcaption></figure><p>[1] Developer’s Personal Assistant — We’ll show you how to go from idea to code faster than ever, doing less but achieving more.</p><p>[2]: Social Media Content Creator — Learn how to create, schedule, and run a year’s worth of content for clients on autopilot. We’ll share the secret sauce for keeping your social media game strong 24/7.</p><p>[3]: Competition Research — Stay ahead of the curve by being the first to notice market changes and update your product portfolio. We’ll demonstrate how AI agents can be your eyes and ears in the digital marketplace.</p><p>[4]: Client Satisfaction Index — Dive deep into understanding your clients by analyzing real-time data with AI support. We’ll show you how to scrutinize documents, find flaws in meeting summaries, and monitor live data to suggest the best possible products.</p><p>[5]: Tame Data Chaos — Build customized data pipelines that deliver only the most crucial daily updates. Watch as AI agents curate information scopes built on your personal data, turning information overload into actionable insights.</p><p>[6]: Building a custom Benchmark for LLM Agents — Create private benchmarks and delegate only the best agents for specialized tasks.</p><h3>What can you expect?</h3><p>By the end of the series, we’ll see how our AI agents fare in today’s economic landscape. Will they emerge as the next tech unicorns, or will they need to go back to machine learning school? One thing’s for sure — this ride through the AI-powered business world is about to get wild, and you’ll have data to prove it!</p><h3>Reader’s corner 📖</h3><p>1. MMLU: <a href="https://arxiv.org/pdf/2009.03300">https://arxiv.org/pdf/2009.03300</a> &amp; <a href="https://paperswithcode.com/sota/multi-task-language-understanding-on-mmlu">https://paperswithcode.com/sota/multi-task-language-understanding-on-mmlu</a><br>2. HellaSwag: <a href="https://arxiv.org/pdf/1905.07830">https://arxiv.org/pdf/1905.07830</a><br>3. Markov Model: <a href="https://en.wikipedia.org/wiki/Markov_model">https://en.wikipedia.org/wiki/Markov_model</a><br>4. Llama 3.1: <a href="https://ollama.com/library/llama3.1">https://ollama.com/library/llama3.1</a><br>5. What is ROI: <a href="https://www.forbes.com/advisor/investing/roi-return-on-investment">https://www.forbes.com/advisor/investing/roi-return-on-investment</a></p><p>See you in the next one! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ce08f9da728" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running models with Ollama step-by-step]]></title>
            <link>https://medium.com/@gabrielrodewald/running-models-with-ollama-step-by-step-60b6f6125807?source=rss-6f32802fcc06------2</link>
            <guid isPermaLink="false">https://medium.com/p/60b6f6125807</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[quantization]]></category>
            <dc:creator><![CDATA[Gabriel Rodewald]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 23:17:28 GMT</pubDate>
            <atom:updated>2024-09-28T18:35:21.318Z</atom:updated>
            <content:encoded><![CDATA[<p>Looking for a way to quickly test LLM without setting up the full infrastructure? That’s great because that’s exactly what we’re about to do in this short article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldg0Ik98J-Zaej1iIRiNQw.jpeg" /><figcaption>Llama2:70B-chat from Meta visualization. Image created using <a href="https://www.bing.com/images/create">https://www.bing.com/images/create</a> ☘️</figcaption></figure><p>You can skip to a specific paragraph if you’ve had previous experience with Ollama. What you can find in this article:</p><ol><li>What is Ollama?</li><li>Installing Ollama on Windows.</li><li>Running Ollama [cmd].</li><li>Downloading models locally.</li><li>Different models for different purposes.</li><li>Running models [cmd].</li><li>CPU-friendly quantized models.</li><li>Integrating models from other sources.</li><li>Ollama-powered (Python) apps to make devs life easier.</li><li>Summary.</li></ol><h3>1. What is Ollama?</h3><p>Ollama is an open-souce code, ready-to-use tool enabling seamless integration with a language model locally or from your own server. This allows you to avoid using paid versions of commercial APIs, especially now that Meta has made Llama2 models available for commercial use — perfect for further training on your own datasets.</p><p>➡️ GitHub respository: <a href="https://github.com/ollama/ollama">https://github.com/ollama/ollama</a></p><p>➡️ Ollama official webpage: <a href="https://ollama.com/">https://ollama.com</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*W1NzH5PMt-LD8uArjcoOnw.png" /><figcaption>Image source: <a href="https://ollama.com/">https://ollama.com</a></figcaption></figure><h3>2. Installing Ollama on Windows</h3><p>Ollama seamlessly works on Windows, Mac, and Linux. This quick tutorial walks you through the installation steps specifically for Windows 10. After installation, the program occupies around 384 MB. However, keep in mind that downloaded models may not be as lightweight.</p><p>If you prefer to run Ollama in a Docker container, skip the description below and go to</p><p>➡️ <a href="https://ollama.com/blog/ollama-is-now-available-as-an-official-docker-image">https://ollama.com/blog/ollama-is-now-available-as-an-official-docker-image</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*rhX863Jg3lEx6Fb2d0R3wg.png" /></figure><p>➡️ Go to Ollama and download .exe file: <a href="https://ollama.com/">https://ollama.com</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*O34D3TrdLJseB3ttyDnUxQ.png" /></figure><p>Download Ollama and install it on Windows. You have the option to use the default model save path, typically located at:</p><pre>C:\Users\your_user\.ollama</pre><p>However, if space is limited on the C: partition, it’s recommended to switch to an alternative directory. If you have another partition like D:\, simply:</p><ol><li>Right-click on the computer icon on your desktop.</li><li>Choose <strong>Properties</strong>, then navigate to “Advanced system settings”.</li><li>Click <strong>Environment variables</strong>.</li><li>In <strong>User variables for … </strong>insert the absolute path to the directory where you plan to store all models. For example:</li></ol><pre>Variable: OLLAMA_MODELS<br>Value: D:\your_directory\models</pre><p>Do not rename <strong>OLLAMA_MODELS</strong> because this variable will be searched for by Ollama exactly as follows.</p><p>An Ollama icon will appear on the bottom bar in Windows. If the program doesn’t initiate, search for it in Windows programs and launch it from there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/89/1*VoYAZ2aGcYmJmVfeyoBb5A.png" /><figcaption>Ollama running in background on Windows 10</figcaption></figure><p>Now you are ready torun Ollama and download some models :)</p><h3>3. Running Ollama [cmd]</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*7PuDoKv9O5Df-DKEoEx92A.png" /><figcaption>Ollama communicates via pop-up messages.</figcaption></figure><p>Once Ollama is set up, you can open your cmd (command line) on Windows and pull some models locally.</p><p>Ollama local dashboard (type the url in your webbrowser):</p><pre>http://localhost:11434/api/</pre><p>Running Ollama is simple as that. Later you will see how to utilize it both via CMD and from Python code.</p><p>A few key commands:</p><p>To check which models are locally available, type in cmd:</p><pre>ollama list</pre><p>To check which SHA file applies to a particular model, type in cmd (e.g. for instance, checking llama2:7b model):</p><pre>ollama show --modelfile llama2:7b</pre><p>To remove a model:</p><pre>ollama rm llama2:7b</pre><p>To server models:</p><pre>ollama serve</pre><h3>4. Downloading models locally.</h3><p>On the website ➡️ <a href="https://ollama.com/library">https://ollama.com/library</a>, you’ll find numerous models ready for download, available in various parameter sizes.</p><p>Before downloading a model locally, check if your hardware has sufficient memory for loading it. For testing, it’s advisable to use small models labeled as 7B — they are adequate for integrating the model into applications.</p><p>⚠️ It is strongly recommended to have at least one GPU for smooth model operation.</p><p>Below, you’ll find several models I’ve tested and recommend. Copy and paste the commands into your command prompt to pull the specified model locally.</p><p>👉<strong>Llama2 models from Meta</strong></p><p>A set of generative text models optimized for dialogue scenarios. Like many models on Ollama, Llama2 is offered in various configurations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5k4XVkC5XpkCExw_m56eA.png" /><figcaption>Image source: <a href="https://ollama.com/library/llama2:chat">https://ollama.com/library/llama2:chat</a></figcaption></figure><p>Below are just a few examples of how to pull such models:</p><p>Standard model:</p><pre>ollama pull llama2</pre><p>Uncensored version:</p><pre>ollama pull llama2-uncensored:7b</pre><p>Chat 7B model:</p><pre>ollama pull llama2:7b-chat</pre><p>➡️ Read more: <a href="https://llama.meta.com/llama2">https://llama.meta.com/llama2</a></p><p>👉<strong>Gemma from Google</strong></p><p>An open-source model delivering robust performance comparable to leading 7B weight models.</p><pre>ollama pull gemma:7b</pre><p>➡️ Read more: <a href="https://blog.google/technology/developers/gemma-open-models/">https://blog.google/technology/developers/gemma-open-models/</a></p><p>👉LL<strong>aVa from </strong>Haotian Liu et al.</p><p>A multimodal model that excels in handling image-to-text descriptions while providing robust support for both vision and language models.</p><pre>ollama pull llava</pre><p>➡️ Read more: <a href="https://llava-vl.github.io/">https://llava-vl.github.io/</a></p><p>5. Different models for different purposes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*myCiaJNBrhSGeBq8qxuaYg.jpeg" /><figcaption>Llama2:70B-chat from Meta visualization. Image created using <a href="https://www.bing.com/images/create">https://www.bing.com/images/create</a> ☘️</figcaption></figure><p>Some models were trained on specific datasets, making them better suited for particular tasks such as code completion, conversation, or image-to-text processing. On Ollama, you’ll find models designed for various purposes.</p><p>The first group is focused on facilitating conversations, text completion, summarizations, including models like <strong>Gemma</strong>, <strong>Llama2</strong>, <strong>Falcon</strong>, or <strong>OpenChat</strong>.</p><p>Some examples:</p><p>➡️ <a href="https://ollama.com/library/falcon">https://ollama.com/library/falcon</a></p><p>➡️ <a href="https://ollama.com/library/gemma">https://ollama.com/library/gemma</a></p><p>➡️ <a href="https://ollama.com/library/openchat">https://ollama.com/library/openchat</a></p><p>The next group comprises multimodal models capable of engaging in conversations, acting as chatbots, describing images (vision models), summarizing texts, and powering Question-Answer (Q/A) applications.</p><p>Some examples:</p><p>➡️ <a href="https://ollama.com/library/llava">https://ollama.com/library/llava</a></p><p>➡️ <a href="https://ollama.com/library/bakllava">https://ollama.com/library/bakllava</a></p><p>The last, highly specialized group supports developers’ work, featuring models available on Ollama like <strong>codellama</strong>, <strong>doplhin-mistral</strong>, <strong>dolphin-mixtral</strong> (‘’<em>fine-tuned model based on the Mixtral mixture of experts model that excels at coding tasks’’</em>) , and many more continuously added by creators.</p><p>Some examples:</p><p>➡️ <a href="https://ollama.com/library/codellama">https://ollama.com/library/codellama</a></p><p>➡️ <a href="https://ollama.com/library/dolphin-mistral">https://ollama.com/library/dolphin-mistral</a></p><p>➡️ <a href="https://ollama.com/library/dolphin-mixtral">https://ollama.com/library/dolphin-mixtral</a></p><h3><strong>6. Running models [cmd]</strong></h3><p>To run downloaded model, simply type <em>ollama run model_name:params “your prompt” </em>, for instance:</p><pre>ollama run llama2:7b &quot;your prompt&quot;</pre><p>Multimodal models allow you to include files, paths to local images, and more, extending beyond a basic prompt.</p><h3>6. CPU-friendly quantized models</h3><p>Quantization is all about reducing the weights of costs of loosing model’s precision. Detailed explanation can be found in this great article that leads users step by step helping to build up intuition laying behind the process:</p><p>📃 <strong>What are Quantized LLMs? </strong>(by Miguel Carreira Neves) :</p><p>➡️ <a href="https://www.tensorops.ai/post/what-are-quantized-llms">https://www.tensorops.ai/post/what-are-quantized-llms</a></p><p>Additional reading:</p><p>📃 <strong>Extreme Compression of Large Language Models via Additive Quantization</strong>:</p><p>➡️ <a href="https://arxiv.org/html/2401.06118v2">https://arxiv.org/html/2401.06118v2</a></p><p>📃<strong>SmoothQuant: Accurate and Efficient Post-Training Quantization for Large Language Models</strong>:</p><p>➡️ <a href="https://arxiv.org/pdf/2211.10438.pdf">https://arxiv.org/pdf/2211.10438.pdf</a></p><p>📃 <strong>BiLLM: Pushing the Limit of Post-Training Quantization for LLMs</strong>:</p><p>➡️ <a href="https://arxiv.org/pdf/2402.04291.pdf">https://arxiv.org/pdf/2402.04291.pdf</a></p><p>In simple terms, <strong>quantization adjusts weight precision, decreases model size, and allows running on less powerful hardware</strong> without significant accuracy loss.</p><p>In the image accompanying this article, you can observe that post-quantization, the models occupy considerably less space than in their original version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghUm8kngNeB00YlmBcGArw.png" /><figcaption>Image source: <a href="https://www.tensorops.ai/post/what-are-quantized-llms">https://www.tensorops.ai/post/what-are-quantized-llms</a></figcaption></figure><p>Ollama supports quantized models, relieving you from the burden of processing them independently.</p><h3>7. Integrating models from other sources</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*p1qKFkZOYB8z5q4a5bUWLw.png" /><figcaption>Llama2:70B-chat from Meta visualization. Image created using <a href="https://www.bing.com/images/create">https://www.bing.com/images/create</a> ☘️</figcaption></figure><p>Although the models on Ollama offer versatility, not all of them are currently accessible. However, integrating your own model locally is a straightforward process. Let’s explore how to incorporate a new model into our local Ollama.</p><p>Numerous quantized models are available on The Bloke’s HuggingFace account. For medical papers, we can conveniently opt for the medicine-chat-GGUF model at:</p><p>➡️<a href="https://huggingface.co/TheBloke/medicine-chat-GGUF">https://huggingface.co/TheBloke/medicine-chat-GGUF</a></p><p>Open the aforementioned link and click <strong>Files and versions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sB0gDBPS7MKjT9q6ilC3Nw.png" /><figcaption>Image source: <a href="https://huggingface.co/TheBloke/medicine-chat-GGUF/tree/main">https://huggingface.co/TheBloke/medicine-chat-GGUF/tree/main</a></figcaption></figure><p>Download model that you would like to include to Ollama models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*_zhNbcKKa3se-TazukWrBw.png" /><figcaption>Image source: <a href="https://huggingface.co/TheBloke/medicine-chat-GGUF/tree/main">https://huggingface.co/TheBloke/medicine-chat-GGUF/tree/main</a></figcaption></figure><p>Generate an empty file named <strong>Modelfile</strong> and insert the specified data below (ensure to substitute the path with the absolute path where the downloaded model is stored, for instance). The example is fundamental and can be expanded with multiple options such as the model’s temperature, system message, and numerous others. If necessary, eliminate the ‘#’ from the file to activate those options.</p><pre>FROM D:\...\medicine-chat.Q4_0.gguf<br># PARAMETER temperature 0.6<br># SYSTEM &quot;&quot;&quot;You are a helpful medicine assistant.&quot;&quot;&quot;</pre><p>Save the <strong>Modelfile. </strong>Then type in cmd:</p><pre>ollama create model_name -f Modelfile</pre><h3>9. Ollama-powered (Python) apps to make devs life easier</h3><p>Ollama running in background is accessible as any regular REST API. Therefore it is easy to integrate it withing an application using libraries like requests, or a bit more developed frameworks like FastAPI, Flask or Django.</p><p>Easy pip install for Ollama python package from</p><p>➡️ <a href="https://pypi.org/project/ollama/0.1.3/">https://pypi.org/project/ollama/0.1.3</a>:</p><pre>pip install ollama</pre><p>Generating embedding directly from Python code:</p><pre>import ollama<br><br>embedding = ollama.embeddings(model=&quot;llama2:7b&quot;, prompt=&quot;Hello Ollama!&quot;)</pre><p>By using simply CURL:</p><pre>curl http://localhost:11434/api/embeddings -d &#39;{<br>  &quot;model&quot;: &quot;llama2:7b&quot;,<br>  &quot;prompt&quot;: &quot;Here is an article about llamas...&quot;<br>}&#39;</pre><p>To read more about Ollama endpoints, please visit:</p><p>➡️ <a href="https://github.com/ollama/ollama/blob/main/docs/api.md">https://github.com/ollama/ollama/blob/main/docs/api.md</a></p><p>Ollama has been seamlessly integrated into the Langchain framework, streamlining our coding efforts and making our work on the technical side even more straightforward:</p><p>➡️ <a href="https://python.langchain.com/docs/integrations/llms/ollama">https://python.langchain.com/docs/integrations/llms/ollama</a></p><p>Let’s appreciate the simplicity of creating an embedding:</p><pre># pip install langchain_community<br>from langchain_community.embeddings import OllamaEmbeddings<br><br><br>embed = OllamaEmbeddings(model=&quot;llama2:7b&quot;)<br>embedding = embed.embed_query(&quot;Hello Ollama!&quot;)</pre><h3>10. Summary</h3><p>This article guides you through running models with Ollama step-by-step, offering a seamless way to test LLM without a full infrastructure setup.</p><p>Ollama, an open-source tool, facilitates local or server-based language model integration, allowing free usage of Meta’s Llama2 models. The installation process on Windows is explained, and details on running Ollama via the command line are provided.</p><p>The article explores downloading models, diverse model options for specific tasks, running models with various commands, CPU-friendly quantized models, and integrating external models. Additionally, Ollama-powered Python applications are highlighted for developers’ convenience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60b6f6125807" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>