<?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 Gilvandro Neto on Medium]]></title>
        <description><![CDATA[Stories by Gilvandro Neto on Medium]]></description>
        <link>https://medium.com/@gilvandrofneto?source=rss-ffa97aee7956------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VNo7ar1I54Ho3zRzHOsn-Q@2x.jpeg</url>
            <title>Stories by Gilvandro Neto on Medium</title>
            <link>https://medium.com/@gilvandrofneto?source=rss-ffa97aee7956------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 14:57:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gilvandrofneto/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[Construí uma plataforma pra corredores brasileiros com um agente de IA]]></title>
            <link>https://gilvandrofneto.medium.com/constru%C3%AD-uma-plataforma-pra-corredores-brasileiros-com-um-agente-de-ia-62ccecb25504?source=rss-ffa97aee7956------2</link>
            <guid isPermaLink="false">https://medium.com/p/62ccecb25504</guid>
            <category><![CDATA[youtube]]></category>
            <category><![CDATA[world-marathon-majors]]></category>
            <category><![CDATA[runners]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[garmin]]></category>
            <dc:creator><![CDATA[Gilvandro Neto]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 22:45:04 GMT</pubDate>
            <atom:updated>2026-11-24T22:45:04.278Z</atom:updated>
            <content:encoded><![CDATA[<h4>Um painel de maratonas e um canal no YouTube desenhado em Python. Quatro meses construindo em público, com o código e os números</h4><p>No dia 13 de julho de 2026 eu fiz o primeiro commit de um projeto pessoal chamado Painel Majors. A ideia era um painel: datas, formas de entrada e custo real das World Marathon Majors, em português, pra corredor brasileiro como eu.</p><p>Hoje o repositório tem 70 commits. O site manda e-mail quando abre a janela de inscrição, converte custo com câmbio que ele mesmo atualiza e tem um simulador de índice. E tem um canal no YouTube com sete vídeos longos, 17 Shorts e 4,4 mil visualizações desde o primeiro vídeo, em 2 de novembro.</p><p>Boa parte disso foi construída num ciclo com um agente de IA: o Claude, rodando no meu computador, com acesso ao repositório, a um terminal, ao meu navegador e a um serviço de voz. Eu decido o que fazer e quando está bom. O agente pesquisa, escreve, programa, renderiza, sobe e confere o próprio trabalho.</p><p>Este post é a história inteira, com o código que importou e os números como eles estão hoje. A stack ganha uma seção aqui; ela merece um post só dela.</p><h3>Por que correr uma Major é um problema de planejamento</h3><p>Eu trabalho com software e corro nos fins de semana. Quem corre sabe o que são as Majors; o que pouca gente sabe é o tamanho do trabalho pra chegar numa delas saindo do Brasil:</p><ul><li>Oito janelas de inscrição espalhadas pelo ano, cada uma num site diferente, quase sempre só em inglês</li><li>Quatro portas de entrada, com regras que mudam toda temporada: sorteio, índice, filantropia ou pacote de operadora</li><li>Custo em moeda que não é a sua. Quando eu fiz a conta pela primeira vez, só Berlim passou de R$ 10 mil em voo, hotel e inscrição. Sydney chega perto de R$ 15 mil</li></ul><p>O índice parecia a porta justa: treinar, correr uma maratona oficial, bater a marca e entrar. Aí, na área de chegada de uma prova de 14 km, uma corredora me contou que conhecia gente com índice pra Boston que tinha ficado de fora. Boston aceita todo mundo abaixo da marca e depois corta dos mais lentos pros mais rápidos. Tóquio também tem porta por tempo, com 25 vagas pro mundo inteiro.</p><p>A informação certa existia, espalhada em oito sites oficiais. Ninguém tinha juntado em português, com o custo em real e as datas num lugar só. Essa foi a primeira versão do Painel Majors.</p><h3>A plataforma: HTML estático, um banco SQL e o GitHub como relógio</h3><p>O primeiro dia já tinha o núcleo: um painel com as próximas Majors, uma página de planos de treino e uma opção paga de gerar um plano personalizado pela API do Claude. As duas semanas seguintes transformaram a página num produto:</p><ul><li><strong>22 de julho:</strong> um robô que manda e-mail quando a janela da prova que você escolheu está pra abrir, e uma área logada</li><li><strong>23 de julho:</strong> um banco SQL pra dados de pessoas (usuários, alertas, provas escolhidas) e uma calculadora que compara o sorteio com a compra de pacote</li><li><strong>24 de julho:</strong> conteúdo como código. Uma notícia é um arquivo JSON com data de publishAt; um job agendado publica e manda a newsletter</li><li><strong>26 de julho:</strong> uma página por prova, com a altimetria do percurso</li><li><strong>Agosto e setembro:</strong> o simulador de índice e o câmbio mensal do Banco Central Europeu, commitado de volta no repositório por um robô</li></ul><p>A stack é chata de propósito e quase de graça:</p><ul><li>HTML, CSS e JavaScript puros no Cloudflare Pages. Sem framework e sem build: o deploy é git push</li><li>Pages Functions pra API, um arquivo por rota em functions/api/</li><li>D1 (o SQLite da Cloudflare) pra tudo que é de pessoa; KV pra configuração, sessão e a base de datas e custos</li><li>Resend pro e-mail e GitHub Actions como cron</li></ul><p>Uma notícia é assim:</p><pre>{<br>  &quot;publishAt&quot;: &quot;2026-11-29&quot;,<br>  &quot;newsletter&quot;: true,<br>  &quot;slug&quot;: &quot;dezembro-mes-de-resultado&quot;,<br>  &quot;title&quot;: &quot;Dezembro é mês de resultado: Berlim dia 3, Chicago dia 8&quot;,<br>  &quot;category&quot;: &quot;majors&quot;,<br>  &quot;body&quot;: &quot;&lt;p&gt;Dezembro decide 2027. ...&lt;/p&gt;&quot;<br>}</pre><p>O robô que publica roda às 06h17, e não às 06h00. O GitHub Actions pode atrasar job agendado na hora cheia, quando o cron de todo mundo dispara junto, e um minuto quebrado é a correção mais barata que existe.</p><p>O único custo fixo até agora é o domínio. A API do Claude é a única coisa cobrada por uso: roda quando alguém pede um plano de treino gerado, ou quando eu peço um rascunho de notícia.</p><h3>Trabalhando com um agente de IA</h3><p>A configuração é menos exótica do que parece. O Claude roda no app de desktop do Claude com quatro coisas: a pasta do projeto, um Linux isolado com Python e ffmpeg, o meu Chrome por uma extensão e um conector do ElevenLabs pras vozes. Minhas mensagens costumam ter uma linha. “Veja como estamos hoje” foi uma delas, de verdade, e voltou com os números do canal e a proposta de uma série nova.</p><p>O que fica comigo:</p><ul><li><strong>Direção.</strong> O que vem a seguir e o tom: o canal é história primeiro, com a dica dentro da história</li><li><strong>Gosto.</strong> Eu reviso o que sai, e algumas peças voltam mais de uma vez. O vídeo do Marílson saiu na versão três</li><li><strong>A minha voz.</strong> Os primeiros vídeos usaram um clone da minha voz feito no ElevenLabs. Hoje eu gravo a narração</li><li><strong>Tudo que não tem volta.</strong> O agente pergunta antes de baixar arquivo ou apagar qualquer coisa pública, e nunca digita senha</li></ul><p>O resto é do agente: pesquisa com fonte, roteiro, o Python que desenha cada cena, o som, os uploads, o agendamento e um relatório no fim de cada sessão.</p><p>O que eu não esperava era a memória. Toda sessão começa do zero, então o repositório virou o cérebro compartilhado. Cada pasta de vídeo tem um arquivo de publicação com título, descrição e status. O AGENDA.md guarda o calendário e a PAUTA.md, as ideias. O agente lê tudo isso primeiro e atualiza por último. É o projeto mais bem documentado que eu já tive, e eu escrevi muito pouco dessa documentação.</p><p>A regra que mais importou é a mesma que o site já seguia: nada de dado inventado. O commit de 2 de novembro no primeiro post de história diz “tira afirmações que as fontes não sustentam”. Um parágrafo bem escrito não passou na conferência com as fontes e saiu. Todo roteiro passa por isso antes de eu gravar.</p><h3>A fábrica de conteúdo: vídeos do YouTube desenhados por código</h3><p>Em outubro o site funcionava, e pouca gente sabia que ele existia. Busca demora pra domínio novo, então eu fui pra onde o corredor já passa a noite: o YouTube. O primeiro vídeo saiu em 2 de novembro. Hoje são sete vídeos longos e 17 Shorts públicos, mais quatro vídeos agendados até 2 de dezembro e um calendário fechado até o fim do ano.</p><p>Não tem editor de vídeo nesse processo. Cada quadro é desenhado em Python com Pillow e mandado pro ffmpeg. A identidade visual é um bonequinho correndo, o mesmo que corre pelo site, e uma versão em Python lê a geometria da passada direto do JavaScript do site. Mudou o corredor.js, mudam os vídeos.</p><p>Um vídeo é uma pasta com uma linha de produção numerada:</p><pre># 1. limpa a narração gravada e alinha com o roteiro<br>python3 _ferramentas/alinha_voz.py 10-berlim-ronaldo-da-costa/9-producao gravacao.m4a<br># 2. tempo das palavras -&gt; tempo das cenas, legenda (.srt) e o áudio final<br>python3 _ferramentas/tempos_auto.py 10-berlim-ronaldo-da-costa/9-producao<br># 3. trilha sintetizada, whoosh nas trocas de cena, música que abaixa sob a voz<br>python3 _ferramentas/trilha.py 10-berlim-ronaldo-da-costa/9-producao natural<br># 4. desenha cada cena, quadro a quadro<br>python3 10-berlim-ronaldo-da-costa/9-producao/render.py<br># 5. corta os Shorts listados no cortes.json<br>python3 _ferramentas/shorts.py 10-berlim-ronaldo-da-costa</pre><p>O passo de que eu mais gosto é o primeiro. O alinha_voz.py sincroniza uma narração gravada com o roteiro sem serviço de transcrição nenhum:</p><ol><li>Acha os trechos de fala pelas pausas da gravação</li><li>Divide o roteiro em frases e estima quanto cada uma dura, pela contagem de sílabas e pela velocidade de quem gravou</li><li>Casa trechos com frases por programação dinâmica. Trecho que não casa com nada (começo falso, frase repetida) é marcado como erro e sai do áudio</li><li>Confirma cada corte comparando o som dele com o trecho seguinte, porque frase repetida soa parecido com a anterior</li></ol><p>Um segundo script, o acha_repeticoes.py, pega repetição sem pausa no meio usando uma matriz de autossimilaridade do áudio: frase falada duas vezes aparece como uma diagonal. Na prática eu gravo o roteiro inteiro de uma vez, gaguejo algumas vezes e as ferramentas tiram as gaguejadas. A saída usa o mesmo formato de tempo por palavra do ElevenLabs, então o clone e a minha voz de verdade passam pelo mesmo caminho.</p><p>A música também é sintetizada: quatro acordes em lá menor, bumbo e chimbal, gerados em NumPy. Não tem direito autoral de ninguém, e abaixa sozinha quando entra a voz.</p><p>Cada pasta de vídeo tem ainda um fontes.md com a fonte de cada afirmação do roteiro. Num canal de história da corrida, data certa é o que faz quem assiste confiar no próximo vídeo.</p><h3>Os números, e o que eu diria pra mim em julho</h3><p>Os números até 22 de novembro:</p><ul><li><strong>YouTube, últimos 28 dias:</strong> 4,1 mil visualizações e 58 horas assistidas. 93% das visualizações vieram da página inicial e das recomendações do próprio YouTube</li><li><strong>O vídeo que carregou o canal:</strong> Marílson Gomes dos Santos, o brasileiro que venceu a Maratona de Nova York duas vezes, com 3.325 visualizações, uns 80% de tudo</li></ul><p>O que eu diria pra mim em julho:</p><ol><li><strong>Dê ao agente uma memória que ele consiga ler.</strong> Um README por pasta, um calendário, um diário do que funcionou. Escrito durante o trabalho, custa minutos, e toda sessão nova começa de onde a anterior parou</li><li><strong>Peça pro agente conferir o resultado de verdade.</strong> O vídeo renderizado, a página publicada, o que o servidor respondeu. É essa conferência que deixa delegar sem medo</li><li><strong>História ganha de dica.</strong> Eu planejei um canal de conselho prático. A história de um corredor brasileiro fez uns 80% das visualizações</li><li><strong>Mídia feita por código é barata de mudar.</strong> Data errada é uma constante e um novo render, não uma tarde no editor</li><li><strong>Mantenha a regra de não inventar dado quando quem escreve é uma IA.</strong> Um arquivo de fontes por vídeo, conferido antes de eu gravar, é o que me deixa assinar o roteiro</li></ol><h3>O que vem agora</h3><p>O calendário do YouTube está fechado até o fim do ano. O sinal mais claro dos números foi que história de brasileiro é o que o YouTube mais distribui, então isso virou série: “Brasileiros que pararam o mundo da corrida”. Chicago sai em 6 de dezembro, o Vanderlei Cordeiro de Lima em Atenas 2004 no dia 9, Tóquio no 13, a Carmem de Oliveira no 16, Londres no 20 e a São Silvestre no 27. A série “Tecnologia a favor do corredor” começa em 27 de novembro, ligando um Garmin numa IA. O processo está estável o bastante pra que um vídeo novo seja quase só roteiro, gravação e revisão.</p><p>A lição maior é sobre a divisão do trabalho. O agente tornou possível uma pessoa com emprego tocar ao mesmo tempo um site e um canal. As decisões continuam minhas. O que mudou é que agora cabe na semana tudo o que eu decido fazer.</p><p><em>O Painel Majors está no ar em </em><a href="https://painelmajors.com.br/"><em>painelmajors.com.br</em></a><em>, de graça. O canal é </em><a href="https://www.youtube.com/@painelmajors"><em>Painel Majors no YouTube</em></a><em>. Eu construo isso nos fins de semana; comentário e sugestão são muito bem-vindos.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62ccecb25504" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I built it with AI.]]></title>
            <link>https://gilvandrofneto.medium.com/i-built-it-with-ai-5c1b5ca0ff57?source=rss-ffa97aee7956------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c1b5ca0ff57</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[connection]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[runners]]></category>
            <category><![CDATA[garmin]]></category>
            <dc:creator><![CDATA[Gilvandro Neto]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 02:18:25 GMT</pubDate>
            <atom:updated>2026-11-24T02:18:25.413Z</atom:updated>
            <content:encoded><![CDATA[<h3>I built it with AI. Then I put three AIs on reviewing it, and 7 of 10 planted bugs went green through my tests.</h3><p><em>I had 147 green tests and a product I used every day. Then I asked an AI to plant bugs on purpose in my code and run my suite.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QzZ1XBOaf60sN30YSvziAg.png" /><figcaption>The ten bugs planted in the race-plan module, and the seven that passed green</figcaption></figure><p><em>Written in November 2026.</em></p><p>In the <a href="https://gilvandrofneto.medium.com/i-stopped-screenshotting-my-runs-now-the-ai-writes-the-workout-straight-onto-my-watch-dd800b93fcc1">first post</a> I explained how I built Runner LLM, an MCP server that connects my Garmin to ChatGPT and Claude. I built it with AI in a few days, and it was already live and running every day on my wrist.</p><p>This one is about what happened when I stopped building and started hunting for defects. If you only read one line: test coverage doesn’t mean the tests catch anything. It took 147 green tests for me to learn that.</p><h3>The first review found a bug from two weeks earlier</h3><p>I’d shipped the strength-training part and asked for a review of the new code. The reviewer found eight real problems, and the worst wasn’t even in the new code. It was in a function from two weeks before:</p><pre>with contextlib.suppress(Exception):<br>    sleep = g.get_sleep_data(day)</pre><p>Swallowing everything looks defensive. In practice, when Garmin was down the week came back with sleep, HRV and readiness null and with no warning, identical to an athlete who didn’t sleep with the watch on. The model read that, concluded “no recovery data” and kept proposing hard training.</p><p>I had written a whole degraded mode for this case, with a plain-language warning. The suppress made it unreachable, and the degraded-mode test passed because it tested the wrong function. The pattern repeated in every round after that: the worst finding was always in the code that already looked good. I look at new code with suspicion and at two-week-old code with fondness.</p><h3>The infinite loop I had written the day before</h3><p>In the next round I did it properly: three independent reviews at the same time, each with a closed scope and forbidden to edit files. One looked at the new code, one at the whole application, one at the documentation against the code. The least glamorous, the documentation one, found 17 claims the code contradicted. Wrong documentation is worse than missing documentation, because people trust it.</p><p>The new-code reviewer found this:</p><pre>tool build_race_plan() -&gt; 9.6 km, goal 1:08:24<br>real 0m20.012s   exit=124   (killed by timeout, never returned)</pre><p>The tool that splits a race goal into pace per segment went into an infinite loop for certain combinations. The algorithm adjusts the pace one second at a time until the sum closes, and it stopped like this:</p><pre>if abs(leftover) &lt;= smallest.km / 2:   # changing 1 s/km would make it worse<br>    break</pre><p>When the leftover was exactly half a distance, 0.6000000000000227 was never &lt;= 0.6. The adjustment went up a second, down a second, up again, forever.</p><p>Instead of widening the tolerance, I changed the question the criterion asks, from “is it good enough?” to “does this step improve things?”. That way the leftover shrinks on every pass and the loop ends by construction. I had written that loop the day before, with tests, and the tests passed.</p><h3>My tests had no teeth</h3><p>The reviewer didn’t stop there. It did what I asked: planted ten bugs on purpose in the module and ran my suite. Seven passed green. One of them computed the split from the average pace instead of each block’s pace, which makes km 10 come out 45 seconds off in a negative split, exactly the error that module exists to prevent. My 54 tests for that file didn’t notice.</p><p>They were written like this:</p><pre>expected = race._time_between(0, 10, blocks)   # the same function the code uses<br>assert plan[&quot;checkpoints&quot;][1][&quot;cumulative_s&quot;] == expected</pre><p>A test that calls the same helper that produced the answer agrees with the code even when both are wrong together. It doesn’t check the arithmetic, it only checks that the function gives the same result twice. I rewrote them: in an arithmetic module the test redoes the arithmetic, written out again inside it. Now each of the ten planted bugs breaks at least one test.</p><p>This goes beyond AI, but it weighs more with AI. The model writes the code and the tests in the same session, with the same head, and if the test imports the code’s helper, both share the same mistake. It’s test inbreeding.</p><h3>Planting bugs became routine</h3><p>After the 7 of 10, planting bugs became part of closing a version. The recipe fits in twenty lines: I copy the code out, apply one change at a time, run only that module’s tests and demand that all of them die. When one passes green, the problem is my test, and “that case doesn’t matter” doesn’t count as an answer.</p><p>The mutants I picked myself all died, of course, since they were the ones I had already thought of. When the outside reviewer planted 116, 73 passed. The next round, 112 planted and 50 passed.</p><h3>What no review found</h3><p>The reviewers looked at the whole code. The defects that bothered me most came from me using the product and finding what it said odd.</p><p>The first was a parameter with a default value. ChatGPT sent me a workout of “36 minutes, 5.4 km”. I was coming back from an injury and that was 5 blocks of 2 minutes of jogging and the rest walking, so it couldn’t be 5.4 km. The number wasn’t the model’s invention, it was mine:</p><pre>def estimated_meters(self, default_pace_s: int = 360) -&gt; int:</pre><p>360 seconds per kilometer is 6:00/km. Every step with a time duration and no pace target was converted at running pace, and walking carries no pace, so every walk was counted as a run and the error went past 50%. The root cause was my DSL having no way to say “walking”. But what I wrote in the decision log was that a parameter with a default value is a hidden decision. It went through four versions because it looked like configuration and was a claim about the athlete.</p><p>The second was a wrong finger on the watch. I opened the load history and read “Pullover: −14 kg”, on an exercise I’ve done without fail since July. Right below, “Row: +16 kg”. The two numbers almost mirrored each other, and the loads were swapped: on July 18 I typed one exercise’s weight into the other. The product read the first point of the series against the last, so one odd day at the start flipped the whole reading. I switched to comparing the median of the first sessions with the median of the last, and Pullover now says +2 kg, which is what happened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HqJgzWCvDgz-xLaSLGW3gw.png" /><figcaption>The two load series crossing on July 18, the day I typed one exercise’s weight into the other</figcaption></figure><p>The third was the week that showed up twice. I opened the page for a week that crossed two months and every workout appeared twice. Each month’s code was right, the sum was only wrong at the crossover, which is why no review tripped on it. The same wrong number reached the model, which also read 6 km on a 3 km day.</p><p>In all three I looked at a number and found it odd. On the other side, one of the reviews found a problem that gave no symptom at all, nothing broken and no wrong number, and that using the product would never have shown. So neither replaces the other: using the product finds what review can’t see, and review finds what use doesn’t show.</p><h3>What I’d do differently from the start</h3><p>A test for an arithmetic module redoes the arithmetic, and never calls from inside it the helper that produced the answer. A loop’s stop criterion with floats is “does this step improve things?”, with a cap on iterations in reserve. Transport errors have to go up to the caller while missing data can be silence, and “Garmin didn’t answer” has to come out differently from “that day has no sleep logged”. Every default that looks like configuration deserves the question of whether it’s a setting or a claim about the world nobody revisited. And an outside mutant finds the inside mutant’s blind spot: ask someone who didn’t write the code to plant their own bugs, and treat every survivor as a weak test.</p><p>To run this on your project, use three reviewers in parallel, with closed scopes, forbidden to edit. Require the new-code reviewer to plant bugs and run your suite, because instead of a list of findings you get a measure of how much your safety net catches. Give the whole-application reviewer an explicit priority order (data loss before style). Check every finding by hand before changing anything, because they’re good but they’re not oracles. After all that, use the product, on your phone, on the couch, in real life.</p><p>Today Runner LLM has 39 tools and 1,512 tests, and it still costs R$ 0 a month. I stopped assuming that “passed” means “correct”.</p><p><em>Runner LLM uses the unofficial </em><em>python-garminconnect library with the athlete&#39;s own account. It has no relation to Garmin, OpenAI or Anthropic.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c1b5ca0ff57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I stopped screenshotting my runs. Now the AI writes the workout straight onto my watch.]]></title>
            <link>https://gilvandrofneto.medium.com/i-stopped-screenshotting-my-runs-now-the-ai-writes-the-workout-straight-onto-my-watch-dd800b93fcc1?source=rss-ffa97aee7956------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd800b93fcc1</guid>
            <category><![CDATA[connection]]></category>
            <category><![CDATA[garmin]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[runners]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Gilvandro Neto]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 02:16:37 GMT</pubDate>
            <atom:updated>2026-11-24T02:16:37.499Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I built an MCP server that connects Garmin, ChatGPT and Claude. It writes workouts to my watch, remembers me between conversations and builds playlists around my cadence.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ip2Ioiw6a3Q1vu0Vr-hdmA.png" /><figcaption>How the conversation reaches the watch</figcaption></figure><p><em>Written in November 2026.</em></p><p>I run half marathons and I’ve been using ChatGPT as a coach for a while. Its answers were never the problem. Getting to them was the work: open Garmin Connect, screenshot the run, paste it into the chat, type “what do you think”. Then, for the workout it planned to reach my wrist, open Garmin again and type it in step by step. Every week, by hand.</p><p>There was a worse part. If I opened the same conversation in Claude, it knew nothing about me. My history was stuck inside ChatGPT.</p><p>The intelligence was fine, the plumbing was what failed. So I stopped taking screenshots and built an MCP server, together with an AI. Today it has 39 tools, a memory that works in both assistants, workouts that land straight on the watch and playlists that line up with the race kilometer.</p><p>Here’s how it works and where I got it wrong.</p><h3>Why MCP</h3><p>MCP (Model Context Protocol) is the open standard ChatGPT and Claude use to talk to external tools. You run a server that exposes functions, each with a name, a description and parameters. The client discovers them on its own and the model decides when to call each one.</p><p>I could have built a REST API with a custom GPT on top. I went with MCP for three reasons. The protocol handles discovery, so I don’t write “if the user asks X, call Y”, I write a good description (and I spent more time on descriptions than on functions). It’s portable: the same server serves both assistants and whatever shows up next. And the boring part of plugging a remote server into the client already comes solved.</p><p>I also decided early on that I wasn’t building a coach. The intelligence already exists and it’s good. What was missing was a reliable pipe between the conversation and the watch.</p><h3>What every tool has to do</h3><p>Of the 39, five rules ended up mattering for all of them.</p><p>Return little. Garmin’s raw response for one activity has hundreds of fields, and dumping that on the model burns context and confuses it. Each tool cleans up and returns only what matters.</p><p>Treat errors as conversation. If the model sends an impossible pace, it reads “pace must be between 2:30 and 12:00 per km” and fixes it on the next call. That cut a lot of back and forth.</p><p>Never write before showing. There’s even a tool that only validates, so the model has something to show the plan with.</p><p>Survive repeats. Running twice doesn’t duplicate a workout: everything the system creates carries a per-date mark, and anything I put on the watch myself is never touched.</p><p>And don’t break when Garmin goes down. An exception in the middle of a conversation makes the model lose the thread. The tool retries, falls back to what it has stored and returns the week with a plain-language warning about what didn’t come back. That way the model doesn’t see an empty week and conclude I didn’t train.</p><h3>A small language for workouts</h3><p>Garmin’s workout format is full of numeric codes, and asking the model to build it directly is asking for errors. I put a layer in the middle, a small DSL any model can fill in without thinking:</p><pre>{&quot;name&quot;: &quot;Tempo 3x10min&quot;, &quot;steps&quot;: [<br>  {&quot;type&quot;: &quot;warmup&quot;,   &quot;duration&quot;: {&quot;km&quot;: 2},  &quot;target&quot;: {&quot;hr_zone&quot;: 2}},<br>  {&quot;type&quot;: &quot;repeat&quot;,   &quot;count&quot;: 3, &quot;steps&quot;: [<br>    {&quot;type&quot;: &quot;interval&quot;, &quot;duration&quot;: {&quot;min&quot;: 10}, &quot;target&quot;: {&quot;pace&quot;: &quot;6:30-6:40&quot;}},<br>    {&quot;type&quot;: &quot;recovery&quot;, &quot;duration&quot;: {&quot;min&quot;: 2},  &quot;target&quot;: {&quot;hr_zone&quot;: 1}}]},<br>  {&quot;type&quot;: &quot;cooldown&quot;, &quot;duration&quot;: {&quot;km&quot;: 1}}]}</pre><p>Everything is validated before it becomes Garmin’s format, so the model can only write things that exist. What it can’t express never reaches the watch. The flow is always the same: it reads the grammar, builds the workout, asks for a preview that saves nothing, shows me, I say ok, and only then does it schedule.</p><p>One gotcha cost me a night. Garmin’s calendar returns distance in centimeters and duration in milliseconds, while the activities API uses meters and seconds. The workout showed up with a hundred times the right distance and I assumed the bug was mine.</p><h3>The gym program comes in as a screenshot</h3><p>My gym’s app has no integration and no export. I used to open the program on my phone and retype it exercise by exercise into Garmin, three times a month. Now I send the screenshot into the conversation, the model reads the image, builds the list and creates the strength workout.</p><p>Transcribing is easy. Vocabulary is hard: Garmin doesn’t accept “Pull Down Polia”, it wants a pair from a closed list. So I keep a translation table that started with what I already used and grows by itself, because every translation I confirm goes into it. If an exercise has no translation, the whole program is rejected, since half a program saved causes more trouble than none.</p><p>I learned not to trust the library’s table and to look at the format in the real account. The library I use declares two codes that, in the 13 programs already saved in my account, mean something else. I found out by downloading the JSON of what Garmin itself had accepted from me. When a third party’s constant and what the server accepted yesterday disagree, I go with the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*tBh0el22gvdOXgMi3Dd7pg.png" /><figcaption>The Gym tab on the iPhone, with the program already transcribed</figcaption></figure><h3>The arithmetic the model can’t do</h3><p>A 2:25 half marathon goal is 6:52 per km on paper. But with a negative split you need two paces that close exactly on the goal, plus the split for every kilometer so you know at km 15 whether you’re on plan. It’s the kind of arithmetic an LLM gets wrong with total confidence, and you find out mid-race.</p><p>It became a tool, and one that only calculates. It returns the blocks with a pace range, the splits per kilometer and a ready workout for the watch. Writing still goes through the usual path, after my ok. The strategy can say “first half 1.2% slower” and the blocks are rescaled so the sum closes on the goal. Whatever is left from rounding to the second is declared instead of hidden.</p><h3>The average that never happened</h3><p>I’m coming back from an injury, which means alternating walking and running. That’s when I saw my own product was telling me half the truth.</p><p>A Sunday workout showed up as 8.01 km, 1h14, average pace 9:16/km. The math is right, but it says nothing. Lap by lap it was 5 km of running at around 8:00/km and 3 km of walking at around 11:00/km, and at no point in that workout was I at 9:16. The average merged two different things into a third that never existed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jtst4NWdirHbcMGBbE0yQ.png" /><figcaption>Pace per lap in a walk-run session: the average-pace line lands between walking and running, where I never ran</figcaption></figure><p>The number that matters coming back from an injury isn’t even distance, it’s how long you can run without stopping. That showed up nowhere. The workout was called “Longuinho 8 km” and my longest running stretch was 8.4 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQNFpe0m2Y4_tBRoApSkKw.png" /><figcaption>Three sessions with walking separated from running, and the longest continuous block alongside</figcaption></figure><p>So a tool came in that separates walking from running inside each session. It looks at each lap’s cadence and not its pace, because a jog uphill hits 11:00/km, same as walking on the flat. Cadence also wins over the workout’s intent: the plan may say run for 5 minutes and I may have walked the last one, and what counts is what the body did. A lap right at the cutoff gets declared. One lap at 141 steps per minute, one step above the cutoff, changes my longest continuous block from 11.9 to 21.1 minutes, so the number comes with the reason written next to it.</p><h3>I almost built what already existed</h3><p>I wanted to log food and cross it with training. I spent a good while designing an input of my own and a mirror into a third-party app that would have needed a lot of hacks. Before writing a line, I ran a ten-minute test to answer one question: does Garmin return the food diary through its API?</p><p>It does, and all of it: macros, micronutrients, per meal and per item. I’d been logging food in the Garmin app for two months without realizing it was a database I could read. I canceled the plan. Food came in read-only, and what’s left of value is what nobody does, crossing what I ate with what I trained.</p><p>Two decisions apply to anything that reads health data. The target that counts is the adjusted one: on long-run day Garmin raises the calorie target by the workout’s burn, and comparing against the base target was off by 655 calories. And an incomplete log isn’t fasting. One day the diary showed 99 calories because I logged breakfast and stopped. Every response now carries a partial-log warning, and the model is told to ask instead of conclude.</p><h3>Music that follows the cadence</h3><p>I run to music at about 160 steps per minute and wanted the AI to build the playlists. That became ten tools. What has run on my real account: reading playlists, looking up BPM, analyzing my running playlist and planning the order by race or workout. What I hadn’t seen yet when I wrote this: creating, editing and deleting a playlist on the real account, and the music playing on the road at the right moment. That code passes its tests against a fake Apple I wrote myself, and that doesn’t count as proof.</p><p>The cadence math fits in one line. A song follows 160 steps per minute if its BPM, times 2, times 1 or times 0.5, lands within 3% of 160, so near 80, 160 or 320. The answer also warns that BPM detectors get half-time wrong on about 20% of tracks, and half-time is one of those three harmonics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nl5hmCChGa8E-Njkyfg_1A.png" /><figcaption>When a song follows 160 steps per minute: the ±3% bands around 80, 160 and 320 BPM</figcaption></figure><p>The oldest request on the list was “at km 20, Linkin Park starts”. The physical limit comes before the code: nothing connects the watch’s kilometer to the iPhone’s player. So the math runs backwards. The predicted time of each mark comes from the race plan, and the tool picks, among the playlist’s songs, the set whose durations add up closest to it. If I run off plan, the anchor drifts, and the answer says so.</p><h3>Prompts and resources</h3><p>Almost everyone who writes an MCP stops at tools, but the protocol has two more cheap things. Resources are content the client attaches on its own, without spending a call. Prompts are ready-made conversations that show up as commands. Mine became four shortcuts I use all the time: review the week, plan the next one, “can I train today?” and analyze the last run. That’s where I put the discipline I don’t want to repeat every time, like confirming before saving and noting the lesson at the end.</p><h3>The memory stays outside the model</h3><p>I hadn’t planned this part and it ended up being the heart of the project.</p><p>ChatGPT’s memory is good, but it stays stuck in ChatGPT: Claude knew nothing about me, and switching tools meant losing everything. I took the memory out of the model and put it in the application, as structured, versioned data: focus race, past races and what I learned in them, injuries, preferences and a current status with an expiry date. Once the date passes, the status drops out of the briefing on its own, which keeps the AI from thinking you’re still hurt three months later.</p><p>In practice, I say “in my last race I fell apart at km 17, but my heart rate stayed low, it was legs, not lungs”, and the model saves the lesson. The next week, in another chat and with another AI, it’s already shaping the plan.</p><p>The test that convinced me was silly. I asked ChatGPT to save to memory everything it already knew about me. It did. Claude read it and picked up where the other left off. I switched assistants in two clicks without losing context, and I’m the one holding the data.</p><p>Since the model writes for real, to the watch and to the memory, there’s an undo tool that looks at what happened last and reverts it. It lets me leave the AI writing without fear, because “that wasn’t it” costs one sentence.</p><h3>Security: what stays out</h3><p>A server on the internet holding my health data has to treat access as a day-one requirement. I did, and I ran the code through independent reviews. I won’t detail the front door, the authentication or the infrastructure, for obvious reasons. If I can offer one piece of advice: design access before features and ask an outsider to try to break it. The next post is about that kind of review.</p><p>What I can say: it runs on free cloud tiers, costs R$ 0 a month, and the same code runs on my PC and in the cloud, with the suite passing on both. Deploy is a git push that runs the tests before publishing.</p><p>Two cheap habits apply to any MCP. One is contract testing: freeze the list of tools and the keys of each response, because when the contract breaks the model doesn’t complain, it starts inventing on top of what disappeared. The other is measuring which tools get called. A good part of mine never was, and a tool nobody calls takes up context and gets in the model’s way when it chooses.</p><h3>What I cut</h3><p>I had promised an automatic Sunday-night routine that reviews the week and proposes the next one. I cut it. The product already does that at any hour, and a fixed cadence pushes toward a generic plan, the opposite of what the memory is there to prevent. A good week adjusts when pain, travel or a full calendar shows up, and for that I need to be able to show up on Wednesday and not wait for Sunday. The food mirror went too, and it’s the cut I’m proudest of, because it came from ten minutes of testing and not from opinion.</p><p>This is the first of two posts. In the second, I put three AI reviewers on top of the code I built with AI. They found an infinite loop I had written the day before and showed that 7 of 10 bugs planted on purpose passed green through my test suite.</p><p><em>Runner LLM uses the unofficial </em><em>python-garminconnect library with the athlete&#39;s own account. It has no relation to Garmin, OpenAI or Anthropic.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd800b93fcc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Construí com IA.]]></title>
            <link>https://gilvandrofneto.medium.com/constru%C3%AD-com-ia-2b8c69bf61e0?source=rss-ffa97aee7956------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b8c69bf61e0</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[garmin]]></category>
            <category><![CDATA[runners]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[connection]]></category>
            <dc:creator><![CDATA[Gilvandro Neto]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 02:15:20 GMT</pubDate>
            <atom:updated>2026-11-24T02:15:20.234Z</atom:updated>
            <content:encoded><![CDATA[<h3>Construí com IA. Depois botei três IAs pra revisar, e 7 de 10 bugs plantados passaram pelos meus testes.</h3><p><em>Eu tinha 147 testes verdes e um produto que usava todo dia. Aí pedi pra uma IA plantar bugs de propósito no meu código e rodar a minha suíte.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vuvGAzseOQrqwXYnlp9Hdw.png" /><figcaption>Os dez bugs plantados no módulo do plano de prova e os sete que passaram verdes</figcaption></figure><p><em>Escrito em novembro de 2026.</em></p><p>No <a href="https://gilvandrofneto.medium.com/parei-de-tirar-print-das-minhas-corridas-agora-a-ia-escreve-o-treino-direto-no-meu-rel%C3%B3gio-970e1876a0a6">primeiro post</a> contei como construí o Runner LLM, um servidor MCP que liga meu Garmin ao ChatGPT e ao Claude. Fiz em par com IA, em poucos dias, e ele já estava no ar e rodando todo dia no meu pulso.</p><p>Este aqui é sobre o que aconteceu quando parei de construir e comecei a caçar defeito. Se você só ler uma linha: cobertura de teste não quer dizer que o teste pega alguma coisa. Precisei de 147 testes verdes pra aprender isso.</p><h3>A primeira revisão achou um bug de duas semanas antes</h3><p>Tinha acabado de lançar a parte de musculação e pedi uma revisão do código novo. O revisor achou oito problemas reais, e o pior nem estava no código novo. Estava numa função de duas semanas atrás:</p><pre>with contextlib.suppress(Exception):<br>    sono = g.get_sleep_data(dia)</pre><p>Engolir tudo parece defensivo. Na prática, quando a Garmin estava fora do ar a semana voltava com sono, HRV e prontidão nulos e sem aviso nenhum, igualzinho a um atleta que não dormiu com o relógio. O modelo lia aquilo, concluía “sem dado de recuperação” e continuava propondo treino forte.</p><p>Eu tinha escrito um modo degradado inteiro pra esse caso, com aviso em português. O suppress deixava ele inalcançável, e o teste do modo degradado passava porque testava a função errada. O padrão se repetiu nas rodadas seguintes: o achado mais grave estava sempre no código que já parecia bom. Código novo eu olho desconfiado, o de duas semanas atrás eu olho com carinho.</p><h3>O laço infinito que eu tinha escrito no dia anterior</h3><p>Na rodada seguinte fiz direito: três revisões independentes ao mesmo tempo, cada uma com escopo fechado e proibida de editar arquivo. Uma olhava o código novo, outra a aplicação inteira, outra a documentação contra o código. A menos glamourosa, a da documentação, achou 17 afirmações que o código contradizia. Documentação errada é pior que documentação faltando, porque as pessoas confiam nela.</p><p>O revisor do código novo achou isto:</p><pre>tool build_race_plan() -&gt; 9.6 km, meta 1:08:24<br>real 0m20.012s   exit=124   (matado pelo timeout, nunca voltou)</pre><p>A ferramenta que divide a meta de prova em ritmo por trecho entrava em laço infinito pra certas combinações. O algoritmo ajusta o ritmo de 1 em 1 segundo até a soma fechar, e parava assim:</p><pre>if abs(sobra) &lt;= menor.km / 2:   # trocar 1 s/km pioraria<br>    break</pre><p>Quando a sobra dava exatamente meia distância, o 0.6000000000000227 nunca ficava &lt;= 0.6. O ajuste subia um segundo, descia um segundo, subia de novo, pra sempre.</p><p>Em vez de aumentar a tolerância, troquei a pergunta do critério: de “já está bom o bastante?” pra “este passo melhora?”. Assim a sobra diminui a cada volta e o laço termina por construção. Eu tinha escrito aquele laço no dia anterior, com testes, e os testes passavam.</p><h3>Os meus testes não tinham dente</h3><p>O revisor não parou aí. Fez o que eu pedi: plantou dez bugs de propósito no módulo e rodou a minha suíte. Sete passaram verdes. Um deles calculava o parcial pelo ritmo médio em vez do ritmo de cada bloco, o que faz o km 10 sair 45 segundos errado num negative split, justamente o erro que aquele módulo existe pra impedir. Meus 54 testes do arquivo não viram.</p><p>Eles estavam escritos assim:</p><pre>esperado = race._tempo_entre(0, 10, blocos)   # a mesma função que o código usa<br>assert plano[&quot;checkpoints&quot;][1][&quot;cumulative_s&quot;] == esperado</pre><p>Um teste que chama o mesmo ajudante que produziu a resposta concorda com o código até quando os dois estão errados juntos. Ele não confere a conta, só confere que a função dá o mesmo resultado duas vezes. Reescrevi: num módulo de aritmética o teste refaz a conta, escrita de novo dentro dele. Agora cada um dos dez bugs plantados derruba pelo menos um teste.</p><p>Vale além de IA, mas com IA pesa mais. O modelo escreve o código e os testes na mesma sessão, com a mesma cabeça, e se o teste importa o ajudante do código os dois têm o mesmo engano. É consanguinidade de teste.</p><h3>Plantar bug virou rotina</h3><p>Depois do 7 de 10, plantar bug virou parte de fechar uma versão. A receita cabe em vinte linhas: copio o código pra fora, aplico uma mudança por vez, rodo só o teste daquele módulo e exijo que todos morram. Quando um passa verde, o problema é o meu teste, e “ah, esse caso não importa” não vale como resposta.</p><p>Os mutantes que eu mesmo escolhia morriam todos, claro, porque eram os que eu já tinha pensado. Quando o revisor de fora plantou 116, 73 passaram. Na rodada seguinte, 112 plantados e 50 passaram.</p><h3>O que revisão nenhuma achou</h3><p>Os revisores olharam o código inteiro. Os defeitos que mais me incomodaram vieram de mim usando o produto e estranhando o que ele dizia.</p><p>O primeiro foi um parâmetro com valor padrão. O ChatGPT me mandou um treino de “36 minutos, 5,4 km”. Eu estava voltando de lesão e aquilo eram 5 blocos de 2 minutos de trote e o resto caminhando, não tinha como dar 5,4 km. O número não era invenção do modelo, era meu:</p><pre>def estimated_meters(self, default_pace_s: int = 360) -&gt; int:</pre><p>360 segundos por quilômetro é 6:00/km. Todo passo com duração em tempo e sem alvo de ritmo era convertido a ritmo de corrida, e caminhada não carrega ritmo, então toda caminhada era contada como corrida e o erro passava de 50%. A causa raiz era a minha DSL não ter como dizer “caminhando”. Mas o que anotei no registro de decisões foi que um parâmetro com valor padrão é uma decisão escondida. Atravessou quatro versões porque parecia configuração e era uma afirmação sobre o atleta.</p><p>O segundo foi um dedo errado no relógio. Abri o histórico de carga e li “Pullover: −14 kg”, num exercício que faço sem falhar desde julho. Logo abaixo, “Remada: +16 kg”. Os dois números quase se espelhavam, e eram cargas trocadas: em 18 de julho eu digitei o peso de um exercício no outro. O produto lia o primeiro ponto da série contra o último, então um dia atípico no começo invertia a leitura inteira. Passei a comparar a mediana das primeiras sessões com a das últimas, e o Pullover agora diz +2 kg, que é o que aconteceu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqaD-VNXWmeRI0MMPyRJjA.png" /><figcaption>As duas séries de carga se cruzando em 18/07, o dia em que digitei o peso de um exercício no outro</figcaption></figure><p>O terceiro foi a semana em dobro. Abri a página de uma semana que cruzava dois meses e cada treino aparecia duas vezes. O código de cada mês estava certo, a soma só errava na virada, e por isso nenhuma revisão tropeçou. O mesmo número errado chegava ao modelo, que também lia 6 km num dia de 3.</p><p>Nos três casos eu olhei um número e achei estranho. Do outro lado, uma das revisões achou um problema que não dava sintoma nenhum, nada quebrado e nenhum número errado, e que usar o produto jamais mostraria. Então uma coisa não substitui a outra: usar acha o que a revisão não enxerga, e a revisão acha o que o uso não mostra.</p><h3>O que eu faria diferente desde o começo</h3><p>Teste de módulo de conta refaz a conta, e nunca chama de dentro dele o ajudante que produziu a resposta. Critério de parada de laço com float é “este passo melhora?”, com um teto de voltas de reserva. Erro de transporte tem que subir pra quem chamou, enquanto dado ausente pode ser silêncio, e “a Garmin não respondeu” precisa sair diferente de “esse dia não tem sono registrado”. Todo default que parece configuração merece a pergunta se é um ajuste ou uma afirmação sobre o mundo que ninguém revisou. E mutante de fora acha o ponto cego do mutante de dentro: peça a quem não escreveu o código que plante os bugs dele, e trate cada sobrevivente como teste fraco.</p><p>Pra rodar isso no seu projeto, use três revisores em paralelo, escopos fechados, proibidos de editar. Exija que o revisor do código novo plante bugs e rode a sua suíte, porque em vez de uma lista de achados você recebe uma medida de quanto a sua rede de segurança realmente pega. Dê uma ordem de prioridade explícita ao revisor da aplicação (perda de dado antes de estilo). Confira cada achado à mão antes de mexer, porque eles são bons mas não são oráculos. Depois de tudo isso, use o produto no celular, no sofá, na vida real.</p><p>Hoje o Runner LLM tem 39 tools e 1.512 testes, e ainda custa R$ 0 por mês. Eu só parei de achar que “passou” quer dizer “está certo”.</p><p><em>O Runner LLM usa a biblioteca não oficial </em><em>python-garminconnect com a conta do próprio atleta. Não tem nenhuma relação com Garmin, OpenAI ou Anthropic.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b8c69bf61e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parei de tirar print das minhas corridas. Agora a IA escreve o treino direto no meu relógio.]]></title>
            <link>https://gilvandrofneto.medium.com/parei-de-tirar-print-das-minhas-corridas-agora-a-ia-escreve-o-treino-direto-no-meu-rel%C3%B3gio-970e1876a0a6?source=rss-ffa97aee7956------2</link>
            <guid isPermaLink="false">https://medium.com/p/970e1876a0a6</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[connection]]></category>
            <category><![CDATA[runners]]></category>
            <category><![CDATA[garmin]]></category>
            <dc:creator><![CDATA[Gilvandro Neto]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 02:09:17 GMT</pubDate>
            <atom:updated>2026-11-24T02:09:17.300Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Construí um servidor MCP que liga Garmin, ChatGPT e Claude. Ele grava treino no relógio, lembra de mim entre as conversas e monta playlist pela cadência.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GjD6HRgHZUMlAHQbjkB7QA.png" /><figcaption>Como a conversa chega no relógio</figcaption></figure><p><em>Escrito em novembro de 2026.</em></p><p>Corro meia maratona e faz tempo que uso o ChatGPT como treinador. A resposta dele nunca foi o problema. O trabalho era chegar até ela: abrir o Garmin Connect, tirar print da corrida, colar no chat, escrever “avalia aí”. E pro treino que ele montava chegar no meu pulso, abrir o Garmin de novo e digitar passo por passo. Toda semana, no braço.</p><p>Ainda tinha o pior. Se eu abrisse a mesma conversa no Claude, ele não sabia nada de mim. Meu histórico estava preso dentro do ChatGPT.</p><p>A inteligência estava ótima, o que falhava era o encanamento. Então parei de tirar print e construí um servidor MCP, junto com uma IA. Hoje ele tem 39 ferramentas, guarda uma memória que vale nos dois assistentes, manda treino direto pro relógio e monta playlist que encaixa no quilômetro da prova.</p><p>Vou contar como funciona e onde eu errei.</p><h3>Por que MCP</h3><p>MCP (Model Context Protocol) é o padrão aberto que o ChatGPT e o Claude usam pra falar com ferramentas externas. Você sobe um servidor que expõe funções, cada uma com nome, descrição e parâmetros. O cliente descobre tudo sozinho e o modelo decide quando chamar.</p><p>Dava pra ter feito uma API REST com um GPT customizado por cima. Fui de MCP por três motivos. Quem escolhe qual função chamar é o protocolo, então eu não escrevo “se o usuário perguntar X, chame Y”, só escrevo uma boa descrição (e gastei mais tempo com descrição do que com função). Ele é portátil: o mesmo servidor atende os dois assistentes e o que aparecer depois. E a parte chata de plugar um servidor remoto no cliente já vem pronta.</p><p>Decidi também, logo de cara, que não ia construir um treinador. A inteligência já existe e é boa. Faltava um cano confiável entre a conversa e o relógio.</p><h3>O que toda ferramenta precisa fazer</h3><p>Das 39, cinco regras pesaram em todas.</p><p>Devolver pouco. A resposta crua da Garmin pra uma atividade vem com centenas de campos, e despejar isso no modelo queima contexto e deixa ele confuso. Cada ferramenta limpa e entrega só o que interessa.</p><p>Tratar erro como conversa. Se o modelo manda um ritmo impossível, ele lê “ritmo precisa estar entre 2:30 e 12:00 por km” e corrige na chamada seguinte. Isso cortou um monte de vai e volta.</p><p>Nunca gravar sem mostrar antes. Existe até uma ferramenta só pra validar sem gravar, pra o modelo ter onde mostrar o plano.</p><p>Aguentar repetição. Rodar duas vezes não duplica treino: tudo que o sistema cria leva uma marca por data, e o que eu mesmo coloquei no relógio ele nunca toca.</p><p>E não quebrar quando a Garmin cai. Estourar exceção no meio da conversa faz o modelo perder o fio. A ferramenta tenta de novo, usa o que tem guardado e devolve a semana com um aviso em português dizendo o que não veio. Assim o modelo não vê uma semana vazia e conclui que eu não treinei.</p><h3>Uma linguagem pequena pro treino</h3><p>O formato de treino da Garmin é cheio de código numérico, e pedir pro modelo montar aquilo direto é pedir erro. Botei uma camada no meio, uma DSL pequena que qualquer modelo preenche sem pensar:</p><pre>{&quot;name&quot;: &quot;Tempo 3x10min&quot;, &quot;steps&quot;: [<br>  {&quot;type&quot;: &quot;warmup&quot;,   &quot;duration&quot;: {&quot;km&quot;: 2},  &quot;target&quot;: {&quot;hr_zone&quot;: 2}},<br>  {&quot;type&quot;: &quot;repeat&quot;,   &quot;count&quot;: 3, &quot;steps&quot;: [<br>    {&quot;type&quot;: &quot;interval&quot;, &quot;duration&quot;: {&quot;min&quot;: 10}, &quot;target&quot;: {&quot;pace&quot;: &quot;6:30-6:40&quot;}},<br>    {&quot;type&quot;: &quot;recovery&quot;, &quot;duration&quot;: {&quot;min&quot;: 2},  &quot;target&quot;: {&quot;hr_zone&quot;: 1}}]},<br>  {&quot;type&quot;: &quot;cooldown&quot;, &quot;duration&quot;: {&quot;km&quot;: 1}}]}</pre><p>Tudo passa por validação antes de virar o formato da Garmin, então o modelo só consegue escrever coisa que existe. O que ele não sabe expressar não chega no relógio. O fluxo é sempre o mesmo: ele lê a gramática, monta o treino, pede uma prévia que não grava nada, me mostra, eu dou o ok e só então agenda.</p><p>Uma pegadinha me custou uma noite. O calendário da Garmin devolve distância em centímetro e duração em milissegundo, enquanto a API de atividades usa metro e segundo. O treino aparecia com cem vezes a distância certa e eu achei que o bug era meu.</p><h3>A ficha da academia chega por print</h3><p>O app da minha academia não tem integração nem exportação. Eu abria a ficha no celular e redigitava exercício por exercício no Garmin, três vezes por mês. Agora mando o print na conversa, o modelo lê a imagem, monta a lista e cria o treino de força.</p><p>Transcrever é fácil. O difícil é o vocabulário: a Garmin não aceita “Pull Down Polia”, quer um par de uma lista fechada. Então mantenho uma tabela de tradução que começou com o que eu já usava e cresce sozinha, porque cada tradução que eu confirmo entra nela. Se um exercício não tem tradução, a ficha inteira é recusada, porque meia ficha gravada dá mais dor de cabeça que ficha nenhuma.</p><p>Aqui eu aprendi a não confiar na tabela da biblioteca e a olhar o formato na conta real. A biblioteca que eu uso declara dois códigos que, nas 13 fichas que já estavam na minha conta, querem dizer outra coisa. Descobri baixando o JSON do que a própria Garmin tinha aceitado de mim. Na dúvida entre a constante de um terceiro e o que o servidor aceitou ontem, fico com o servidor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*tBh0el22gvdOXgMi3Dd7pg.png" /><figcaption>A aba Academia no iPhone, com a ficha já transcrita</figcaption></figure><h3>A conta que o modelo não pode fazer</h3><p>Meta de 2h25 na meia dá 6:52 por km no papel. Só que com negative split você precisa de dois ritmos que fechem exatamente na meta, e do parcial de cada quilômetro pra saber, no km 15, se está no plano. É o tipo de conta que um LLM erra com a maior confiança do mundo, e você só descobre no meio da prova.</p><p>Virou ferramenta, e uma que só calcula. Devolve os blocos com faixa de ritmo, os parciais por quilômetro e um treino pronto pro relógio. Quem grava continua sendo o caminho de sempre, depois do meu ok. A estratégia pode dizer “primeira metade 1,2% mais lenta” e os blocos são reescalados pra soma fechar na meta. O que sobra do arredondamento ao segundo aparece declarado em vez de sumir.</p><h3>A média que nunca aconteceu</h3><p>Estou voltando de uma lesão, o que significa alternar caminhada e corrida. Foi aí que vi que meu próprio produto me contava meia verdade.</p><p>Um treino de domingo apareceu assim: 8,01 km, 1h14, ritmo médio de 9:16/km. A conta está certa, mas não diz nada. Volta por volta eram 5 km de corrida perto de 8:00/km e 3 km de caminhada perto de 11:00/km, e em nenhum momento do treino eu estive a 9:16. A média juntou duas coisas diferentes numa terceira que não existiu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EqKVSYmYJgRifP0yg5myFg.png" /><figcaption>Ritmo por volta numa sessão de caminhada e corrida: a linha do ritmo médio cai no vazio entre as duas</figcaption></figure><p>E o número que importa na volta de lesão nem é a distância, é quanto tempo você consegue correr sem parar. Esse não aparecia em lugar nenhum. O treino se chamava “Longuinho 8 km” e meu trecho corrido mais longo foi de 8,4 minutos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3G9fnQvg1rKVlVV4vOwpQ.png" /><figcaption>Três sessões com a caminhada separada da corrida e o bloco contínuo mais longo ao lado</figcaption></figure><p>Então entrou uma ferramenta que separa caminhada de corrida dentro de cada sessão. Ela olha a cadência de cada volta e não o ritmo, porque trote em subida dá 11:00/km igual caminhada no plano. A cadência também ganha da intenção do treino: o plano pode mandar correr 5 minutos e eu ter caminhado o último, e o que vale é o que o corpo fez. Volta no fio do corte sai declarada. Uma volta a 141 passos por minuto, um passo acima do corte, muda meu maior bloco contínuo de 11,9 pra 21,1 minutos, então o número vem com o porquê escrito do lado.</p><h3>Quase construí o que já existia</h3><p>Queria registrar alimentação e cruzar com treino. Passei um bom tempo desenhando uma entrada própria e um espelho num app de terceiros que ia dar muita gambiarra. Antes de escrever uma linha, rodei um teste de dez minutos pra responder uma pergunta: a Garmin devolve o diário de alimentos por API?</p><p>Devolve, e inteiro: macro, micronutriente, por refeição e por item. Eu registrava comida no app da Garmin fazia dois meses sem perceber que aquilo era um banco de dados que eu podia ler. Cancelei o plano. A alimentação entrou só como leitura, e o que sobrou de valor é o que ninguém faz, cruzar o que eu comi com o que eu treinei.</p><p>Duas decisões que servem pra qualquer coisa com dado de saúde. A meta que vale é a ajustada: no dia do longão a Garmin sobe a meta de caloria pelo gasto do treino, e comparar com a meta base errava a leitura em 655 calorias. E registro incompleto não é jejum. Teve um dia em que o diário mostrava 99 calorias porque eu registrei o café e parei. Agora toda resposta traz um aviso de registro parcial, e o modelo é instruído a perguntar em vez de concluir.</p><h3>Música que segue a cadência</h3><p>Corro com música a uns 160 passos por minuto e queria que a IA montasse as playlists. Viraram dez ferramentas. O que já rodou na minha conta de verdade: ler playlists, buscar BPM, analisar minha playlist de corrida e planejar a ordem pela prova ou pelo treino. O que eu ainda não tinha visto quando escrevi isto: criar, editar e apagar playlist na conta real, e a música tocando na rua na hora certa. Esse código passa nos testes contra uma Apple falsa que eu mesmo escrevi, e isso não conta como prova.</p><p>A conta da cadência cabe numa linha. Uma música segue 160 passos por minuto se o BPM dela, multiplicado por 2, por 1 ou por 0,5, fica a até 3% de 160, ou seja, perto de 80, 160 ou 320. A resposta também avisa que detector de BPM erra meio tempo em uns 20% das faixas, e meio tempo é um dos três harmônicos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dmHRO8OJ0n1Mgsm6rrZRg.png" /><figcaption>Quando uma música segue 160 passos por minuto: as faixas de ±3% em torno de 80, 160 e 320 BPM</figcaption></figure><p>O pedido mais antigo era “no km 20 começa Linkin Park”. O limite físico vem antes do código: nada liga o quilômetro do relógio ao player do iPhone. Então a conta é feita ao contrário. O horário previsto de cada marca vem do plano de prova, e a ferramenta escolhe, entre as músicas da playlist, o conjunto cuja soma de durações cai mais perto dele. Se eu correr fora do plano, a âncora desliza, e a resposta diz isso.</p><h3>Prompts e resources</h3><p>Quase todo mundo que escreve um MCP para nas ferramentas, mas o protocolo tem mais duas coisas baratas. Resources são conteúdo que o cliente anexa sozinho, sem gastar chamada. Prompts são conversas prontas que aparecem como comando. Os meus viraram quatro atalhos que uso de fato: revisar a semana, planejar a próxima, “posso treinar hoje?” e analisar a última corrida. É neles que eu coloco a disciplina que não quero repetir toda vez, tipo confirmar antes de gravar e anotar o aprendizado no fim.</p><h3>A memória fica fora do modelo</h3><p>Essa parte eu não tinha previsto e acabou virando o coração do projeto.</p><p>A memória do ChatGPT é boa, mas fica presa nele: o Claude não sabia nada de mim, e trocar de ferramenta era perder tudo. Tirei a memória de dentro do modelo e botei na aplicação, como dado estruturado e versionado: prova foco, provas feitas e o que aprendi nelas, lesões, preferências e um estado atual com validade. Passada a data, o estado some sozinho do briefing, o que evita a IA achar que você ainda está machucado três meses depois.</p><p>Na prática, eu comento “na última prova quebrei no km 17, mas a frequência cardíaca ficou baixa, foi perna e não pulmão”, e o modelo grava o aprendizado. Na semana seguinte, em outro chat e com outra IA, aquilo já está moldando o plano.</p><p>O teste que me convenceu foi bobo. Pedi pro ChatGPT “grava na memória tudo que você já sabe sobre mim”. Ele gravou. O Claude leu e continuou de onde o outro parou. Troquei de assistente em dois cliques sem perder contexto, e quem guarda o dado sou eu.</p><p>Como o modelo escreve de verdade, no relógio e na memória, tem uma ferramenta de desfazer que olha o que aconteceu por último e reverte. Com ela dá pra deixar a IA gravar sem medo, porque “não era isso” custa uma frase.</p><h3>Segurança: o que fica de fora</h3><p>Um servidor na internet com meus dados de saúde precisa tratar acesso como requisito do primeiro dia. Fiz assim e passei o código por revisões independentes. Não vou detalhar a porta de entrada, a autenticação nem a infraestrutura, por razões óbvias. Se couber um conselho: desenhe o acesso antes das funcionalidades e peça pra alguém de fora tentar quebrar. O próximo post é sobre esse tipo de revisão.</p><p>O que posso dizer: roda em planos gratuitos de nuvem, custa R$ 0 por mês, e o mesmo código roda no meu PC e na nuvem, com a suíte passando nos dois. O deploy é um git push que roda os testes antes de publicar.</p><p>Dois hábitos baratos valem pra qualquer MCP. Um é teste de contrato: congelar a lista de ferramentas e as chaves de cada resposta, porque quando o contrato quebra o modelo não reclama, ele só passa a inventar em cima do que sumiu. O outro é medir quais ferramentas são realmente chamadas. Boa parte das minhas nunca foi usada, e ferramenta que ninguém chama ocupa contexto e atrapalha o modelo na hora de escolher.</p><h3>O que eu cortei</h3><p>Eu tinha prometido uma rotina automática de domingo à noite pra revisar a semana e propor a próxima. Cortei. O produto já faz isso a qualquer hora, e cadência fixa empurra pra plano genérico, o contrário do que a memória existe pra evitar. Semana boa se ajusta quando aparece dor, viagem ou agenda cheia, e pra isso preciso poder chegar na quarta, sem esperar domingo. O espelho de alimentação também saiu, e é o corte de que mais me orgulho, porque nasceu de dez minutos de teste e não de opinião.</p><p>Esse é o primeiro de dois posts. No segundo, botei três revisores de IA em cima do código que construí com IA. Eles acharam um laço infinito que eu tinha escrito no dia anterior e mostraram que 7 de 10 bugs plantados de propósito passavam verdes pela minha suíte de testes.</p><p><em>O Runner LLM usa a biblioteca não oficial </em><em>python-garminconnect com a conta do próprio atleta. Não tem nenhuma relação com Garmin, OpenAI ou Anthropic.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=970e1876a0a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Readwise changed the way I consume content?!]]></title>
            <link>https://gilvandrofneto.medium.com/how-readwise-changed-the-way-i-consume-content-62ca6f8fad30?source=rss-ffa97aee7956------2</link>
            <guid isPermaLink="false">https://medium.com/p/62ca6f8fad30</guid>
            <category><![CDATA[highlights]]></category>
            <category><![CDATA[read]]></category>
            <category><![CDATA[content]]></category>
            <category><![CDATA[kindle]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Gilvandro Neto]]></dc:creator>
            <pubDate>Mon, 07 Jun 2021 21:01:32 GMT</pubDate>
            <atom:updated>2021-06-07T21:01:32.904Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>This is one of those services that I consider a complete change in the way I consume content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EqHgMSlNzjoFJ22fyAOlOw.png" /><figcaption>Readwise</figcaption></figure><p>Here I am, back to 2014, back to the usual way of reading physical books. And I read a lot.</p><p>Suddenly the lack of space in my life for physical books became a problem and I decided to give Amazon Kindle a try.</p><p>Then, my life changed for the first time…</p><h3>Before knowing Readwise</h3><p>In the end of 2020, after almost an entire year of the pandemic here in Brazil, I’ve read 30 books in one year with my Kindle Paperwhite (most of them written by Asimov!).</p><p>I started to notice that I highlighted most of the books, but these notes are almost inaccessible.</p><p>So, what’s the point of having to do an entire work of going through a book, taking notes, having a lot of thoughts and ideas regarding its content, only for it to stay in the deep nether of Amazon/Kindle?</p><p>More than that, I started to realize that other services that I use to consume content also have this problem, examples are:</p><ul><li>My highlights of articles in Medium;</li><li>My highlights in Pocket articles that I saved for read later.</li></ul><p>All these remain isolated and its difficult for me to remember them and use them for another purpose, whether it is to think or to produce more content later. It even impacted my productivity system — that is another concept that I have.</p><h4>My second brain</h4><p>I have to share with you what’s called the “principle of second brain” which is simply a way to realize and accept that your brain could fail and put lead you into bad situations. You cannot let your memory take care of everything you want to remember later and of course you want to keep the knowledge accessible.</p><p>Then, because of that, <strong>I take notes on everything</strong>. Therefore, if I think that such information will be useful for my future self, I will take note of that.</p><p>My choice for that is the so called “<a href="https://evernote.com/intl/pt-br/">Evernote ecosystem</a>”. But here you have a lot of possibilities:</p><ul><li>Evernote;</li><li>Notion;</li><li>Apple Notes;</li><li>Microsoft OneNote.</li></ul><p>All of these apps and products offer the user the option to create notebooks, tags, notes and share content with others.</p><blockquote>So, that’s the main point of this article: How can I integrate my “second brain” with all of these others information storage spaces that I created over the internet?</blockquote><p>And the answer for this question is: <a href="https://readwise.io/"><strong>the Readwise app/service!</strong></a></p><h3>Readwise</h3><p>Readwise is a service that connects all of these information storage spaces over the internet. I for one connected with Evernote, Medium, Amazon, Pocket and even Twitter!</p><p>Thus, the moment I highlight a content in any of these services, Readwise app will sync and create a specific Notebook in Evernote.</p><p>And since its on Evernote, it is on my second brain. So, I can use that content later, as I wish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AfUCed2NrB3EIlo1iiReaQ.png" /><figcaption>Readwise content Import</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*vr804rcUT-kUT3tD8KRgnA.png" /><figcaption>Readwise content Export</figcaption></figure><p>It’s really simple to connect a service for import or export your highlights. And the best part, Readwise create a Notebook directly on my Evernote account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*FTqqoz-vgOVQCvNk3lpSkQ.jpeg" /><figcaption>Readwise notebook on Evernote</figcaption></figure><p>And since it’s on my Evernote, I can even share for words, topics and more content that I want. And even if I write some notes with my highlights, Readwise also sync them.</p><p>So for books that I want to take notes and get some insights, I can highlight them and for sure it will be inside my second brain.</p><p>And that’s it!</p><p><strong>I do not get any money or other type of benefit from Readwise</strong>, I think that is a good solution for a problem that I had and is helping me to get mor productive.</p><p>Feel free to share your thoughts on comments and tell more about how you keep your second brain and your productive system up to date!</p><p>And also if you have any other way to do that, <a href="https://www.linkedin.com/in/gilvandroneto1991/">please share with me</a>!🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62ca6f8fad30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips and Secrets for developing a powerful API with Python + Flask]]></title>
            <link>https://medium.com/analytics-vidhya/tips-and-secrets-for-developing-a-powerful-api-with-python-flask-8c3c3ea0103?source=rss-ffa97aee7956------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c3c3ea0103</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Gilvandro Neto]]></dc:creator>
            <pubDate>Mon, 07 Sep 2020 05:50:47 GMT</pubDate>
            <atom:updated>2020-09-07T05:50:47.073Z</atom:updated>
            <content:encoded><![CDATA[<h4>I love Flask and Python. That’s love began with my need to build efficient APIs following the #MLOps. Discover some tips and secrets that made my APIs more powerful.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owKdqWEz753tY7na4LQKXw.jpeg" /><figcaption>Know how to develop better APIs</figcaption></figure><p>Python is a great programming language and it’s really powerful for the world of AI and Data Science.</p><p>Since I’ve started my career in this world, I’m trying to use the best tools for my services, microservices and projects using Python.</p><p>With that in mind, APIs are the best way to delivery Data Science projects for my clients. Also, it’s the best way to build a microservice environment inside the business and create new products using more than one service working in an integrated way.</p><p>But building an API could be difficult. Here are some tips and secrets that made my APIs more usable and improve the costumer experience.</p><p>Check it out!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o6fJamhUDoyETLQUE%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o6fJamhUDoyETLQUE%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3o6fJamhUDoyETLQUE%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="240" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7e5650683d303e4ba153ad28c8fc6cd/href">https://medium.com/media/c7e5650683d303e4ba153ad28c8fc6cd/href</a></iframe><h3>You should use environment variables. But use it better!</h3><p>Environments variables are not new and are a good way to configure your project regarding your environment of work. But a great tip to build an API is to create a method or class to call all of these variables.</p><p>Hence:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76548e7da1b4ba95fdb5b756449688f0/href">https://medium.com/media/76548e7da1b4ba95fdb5b756449688f0/href</a></iframe><p>With such, you can simply use env variables as a class in your code. It makes it easier to change anything and to keep your working across multiple OS and computers.</p><h3>Discover the Flask Monitoring Dashboard</h3><p>Building an API could be simple and fast, at least when you know how to do it — but tracking and monitoring your application could be somewhat tricky when you start to work with some Cloud and DevOps concepts. I really love Docker and Kubernetes, but it is complex to get a log or a Python output using all <em>kubectl</em> commands.</p><p>That’s why I’m using Flask Monitoring Dashboard with my APIs.</p><p><a href="https://github.com/flask-dashboard/Flask-MonitoringDashboard">GitHub - flask-dashboard/Flask-MonitoringDashboard: Automatically monitor the evolving performance of Flask/Python web services.</a></p><p>This Python lib works directly with your Flask project, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad24f5af47144e07b92fcf9d7d029f43/href">https://medium.com/media/ad24f5af47144e07b92fcf9d7d029f43/href</a></iframe><p>This lib gives you access to a bunch of information regarding your application, such as profiler, usage and performance — and it even separate by routes of your Flask API.</p><h3>Validate your Json Schema</h3><p><strong>Security is a rule these days. Period.</strong></p><p>And here I make a highlight:</p><blockquote>I am not suggesting or recommending that it be the only form of security for your application. This is just another good addition, ok?</blockquote><p>In my projects I use a lot of different forms of authentication and best practices in order to keep my APIs secure. But a simple and first security implementation could be your own Json Schema.</p><p>You could implement a function that validates your json regarding a previous schema, as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a7c287b0f42b920e03e9b7988dda7ad/href">https://medium.com/media/6a7c287b0f42b920e03e9b7988dda7ad/href</a></iframe><p>With this, you can implement a good first layer to keep away people who don’t know your requests or the schema to talk with your application.</p><h3>Use APM Insights. But also, use it better!</h3><p>Some of my application are deployed using a Cloud Service, like Azure. The place were I work uses Azure for some projects services, including the AKS — Azure Kubernetes Services. Other really great tool is the APM, Application Performance Management or just Application Insights.</p><p><a href="https://docs.microsoft.com/pt-br/azure/azure-monitor/app/app-insights-overview">O que é o Application Insights do Azure? - Azure Monitor</a></p><p>With it we can track any log or bug, the performance of our API and also any type of bad request.</p><p>APM is not new, and what did I do different or better?</p><p>I created my own lib to import in all my Flask projects, working with Python logs. It helps me a lot to keep track of my application, even when its on LAB environment. My lib gets a lot of imports for the Application Insights SDK and also configures the telemetry, handler and key management.</p><p>This could be a better way to integrante and unify efforts around development and monitoring in all environments.</p><h3>If you have a microservice, dockerize it!</h3><p>Docker, docker, docker… Everybody talks about it and for a while now everyone has commented about the power of this technology. It is great and I use it a lot. And the question is:</p><blockquote>How can you create a better Python Flask API using Docker and Kubernetes?</blockquote><p>All of my last projects were delivered using Docker + Kubernetes. Some tips are:</p><ul><li>Use a base image for your projects to keep your libraries tracked. For an API with Python and Flask , I’ve some libraries that are used all the time as Flask, Flask Monitoring, Application Insights SDK, Json Schema…;</li><li>Declare your environments variables correctly in your dockerfile;</li><li>Don’t forget to EXPOSE your port before the CMD;</li><li>Know the basics commands of kubectl, as use-context, apply, get pod, scale… This will make the difference when you have to manage your API.</li></ul><p>Here’s a great example of a simple Dockerfile:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e78e8fdc4c63f1b9ac1d067c8dd1239/href">https://medium.com/media/2e78e8fdc4c63f1b9ac1d067c8dd1239/href</a></iframe><h3>That’s it, folks!</h3><p>Building an API with Python and Flask could be a simple way to deliver your project or service to your client but some tips and secrets make the difference to implement better solutions.</p><p>These 5 are the ones that I always use in my development and have helped me a lot in the most diverse projects.</p><p>I know there could be others and even better options to deploy an API, but this is what works for me.</p><p>Do you know more options or another way to get a better result?</p><p><strong>Please, feel free to comment and tell me more about it or stay in touch on </strong><a href="https://www.linkedin.com/in/gilvandroneto1991/"><strong>LinkedIn</strong></a><strong> or </strong><a href="https://github.com/gilvandroneto"><strong>Github</strong></a><strong>!</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FFcT1BFYoHwJxu%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FFcT1BFYoHwJxu%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FFcT1BFYoHwJxu%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ae9f28b2269ba14fb02abbf37862ddb/href">https://medium.com/media/8ae9f28b2269ba14fb02abbf37862ddb/href</a></iframe><h4>If these tips helped you in any way, share!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c3c3ea0103" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/tips-and-secrets-for-developing-a-powerful-api-with-python-flask-8c3c3ea0103">Tips and Secrets for developing a powerful API with Python + Flask</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting keywords from COVID-19 news with Python]]></title>
            <link>https://medium.com/analytics-vidhya/extracting-keywords-from-covid-19-news-with-python-13249571d37b?source=rss-ffa97aee7956------2</link>
            <guid isPermaLink="false">https://medium.com/p/13249571d37b</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[articial-intelligence]]></category>
            <category><![CDATA[pos-tagging]]></category>
            <category><![CDATA[spacy]]></category>
            <dc:creator><![CDATA[Gilvandro Neto]]></dc:creator>
            <pubDate>Thu, 05 Mar 2020 18:43:57 GMT</pubDate>
            <atom:updated>2020-03-10T12:04:34.205Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Python and NLP techniques we are able to extract keywords of more than 100k articles and publications of the new infectious disease caused by coronavirus (COVID-19).</h4><figure><img alt="Keywords extracting by Python library spaCy" src="https://cdn-images-1.medium.com/max/960/1*TeTvbwj1AxGUlqbP9SAbvw.jpeg" /><figcaption>Extract keywords from a large text using Python</figcaption></figure><p>The new Coronavirus — or now called COVID-19 — are affecting the whole world as a new infectious disease. From several news of different sources we are able to apply some NLP techniques and frameworks.</p><p>In this article we going to extract the <em>keywords </em>of each article and create a dataset to use a function that applies the concept of POS tagging to identify <em>keywords</em>.</p><p>We will use spaCy and the News API, a great data source for search and retrieve live articles from all over the web. There will be some sections in this article:</p><ul><li>Setup</li><li>Coding</li><li>Conclusion</li><li>Future works</li></ul><p>Let’s go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*R0juCegH0ywti4gI.gif" /><figcaption>Let’s do some coding!</figcaption></figure><h4>Setup — Google Colab</h4><p>First let’s understand everything that’s going to be used in this article. I first created this Notebook on Google Colab — but this could be implemented with another IDE or Python Notebook. We will install the spaCy using pip and as much as I speak Brazilian Portuguese, I will use the English Language Model.</p><p>The News API also have a Python library and we can install with pip.</p><pre>!pip install spacy<br>!pip install newsapi-python</pre><p><a href="https://spacy.io/usage">Install spaCy · spaCy Usage Documentation</a></p><p>After that we can download the spaCy English Language Model in it’s largest size. The file size of this model is about 800MB and you can try download another versions as the medium and small one. We will use the code bellow:</p><pre>!python -m spacy download en_core_web_lg</pre><p>After installation you need to import the spaCy library and we going to use another libraries to help the implementation of the NLP analysis. We will also have to import the spaCy model and load it through a variable that we going to call <em>nlp_eng</em>.</p><pre>nlp_eng = en_core_web_lg.load()<br>newsapi = NewsApiClient (api_key=&#39;PLACE_HERE_YOUR_API_KEY&#39;)</pre><p>This finish our setup and after that we can do some coding.</p><h4>Coding</h4><p>The News API provide an easy way to research through a lot of different sources of articles and publications and we can get an API_KEY for free. When we send and HTTP Request, the API returns as much as 100 articles for maximum — you have to pay the dev account to get the total of results.</p><p><a href="https://newsapi.org/docs">Documentation - News API</a></p><p>These articles are divided into pages and each page have 20 articles. You have to implement some type of pagination to get the total of 100 articles for free. We also have a limitation on the maximum search date in the past which is 30 days.</p><pre>temp = newsapi.get_everything(q=&#39;coronavirus&#39;, language=&#39;en&#39;, from_param=&#39;2020-02-03&#39;, to=&#39;2020-03-03&#39;, sort_by=&#39;relevancy&#39;, page=pagina)</pre><p>As I’m using the Python Notebook on Google Colab, there is a need to save the dataset inside my Google Drive to maintain the data if anything bad happens. I used the Pickle library to save all the articles. We can create and save the .<em>pckl </em>file using these commands:</p><pre>filename = &#39;articlesCOVID.pckl&#39;<br>pickle.dump(articles, open(filename, &#39;wb&#39;))</pre><pre>filename = &#39;articlesCOVID.pckl&#39;<br>loaded_model = pickle.load(open(filename, &#39;rb&#39;))</pre><pre>filepath = &#39;/content/path/to/file/articlesCOVID.pckl&#39;<br>pickle.dump(loaded_model, open(filepath, &#39;wb&#39;))</pre><p>After that we will handle the data and transform the dictionary of articles in a Pandas DataFrame. The original JSON that we get from News API is very rich and we can clean it to use only the <em>title</em>, <em>date</em>, <em>description </em>and <em>content</em>.</p><pre>for i, article in enumerate(articles):<br>    for x in article[&#39;articles&#39;]:<br>        title = x[&#39;title&#39;]<br>        description = x[&#39;description&#39;]<br>        content = x[&#39;content&#39;]<br>        dados.append({&#39;title&#39;:titles[0], &#39;date&#39;:dates[0], &#39;desc&#39;:descriptions[0], &#39;content&#39;:content})</pre><pre>df = pd.DataFrame(dados)<br>df = df.dropna()<br>df.head()</pre><p>After we clean the data and create a Pandas DataFrame, we will create a function called <strong><em>get_keywords_eng </em></strong>that will receive the <strong><em>text </em></strong>and will handle with the spaCy model to identify the Part-of-speech tagging that match with the <em>keywords </em>of our news.</p><blockquote>POS tagging is based on the concept of marking up a word in a text or a corpus as it corresponding to a particular definition and its context. The relationship with other related words in the phrase, sentence or paragraph are also taken into account to identify the correct tag.</blockquote><p>We will extract the <em>verbs </em>(VERB), a <em>nouns </em>(NOUN) and <em>proper nouns</em> (PROPN).</p><pre>if (token.text in nlp_eng.Defaults.stop_words or token.text in punctuation):<br>  continue<br>if (token.pos_ in pos_tag):<br>  result.append(token.text)</pre><pre>return result</pre><p>With our function created, it’s time to apply that with our DataFrame. We can add a new column inside our DataFrame called <em>keywords </em>to receive the result of the function.</p><p>I’ve tested with the <em>title</em>, <em>description </em>and the <em>content </em>of the article. The best results that I’ve get are with the <em>content </em>of the article, as it’s have the major number of words.</p><pre>for content in df.content.values:<br>    results.append([(&#39;#&#39; + x[0]) for x in Counter(get_keywords_eng(content)).most_common(5)])</pre><pre>df[&#39;keywords&#39;] = results</pre><p>After that, we can insert these new data to our DataFrame and save it again into our .<em>pckl </em>file.</p><h4>Conclusion</h4><p>Now that we have a dataset with the 5 most common keywords of each article concatenate with another several articles regarding the COVID-19, it’s time to choose the best way of show our results. I’ve choose a WordCloud, a picture that show the words of a text according to it’s frequency.</p><pre>text = str(results)<br>wordcloud = WordCloud(max_font_size=50, max_words=100, background_color=&quot;white&quot;).generate(text)<br>plt.figure()<br>plt.imshow(wordcloud, interpolation=&quot;bilinear&quot;)<br>plt.axis(&quot;off&quot;)<br>plt.show()</pre><p>Below our image:</p><h4>Future work</h4><p>For sure this work can evolve and get much more applications than just create an WordCloud.</p><p>You can apply with other parts of the DataFrame or create another method to concatenate more than one field. Maybe get data from Twitter or Facebook will be great.</p><p>One of my investigations shows that we have enough dataset to train a language model with the COVID-19 news and get answers for some questions with these news. I’m trying this now with <a href="https://arxiv.org/abs/1810.04805">BERT </a>and <a href="https://openai.com/blog/better-language-models/">OpenAI GPT-2</a> — more results soon!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*sckm-D_0AGzfd-39.gif" /></figure><p>Thanks for reading and feel free to comment and share!</p><p>Contact me on <a href="https://www.linkedin.com/in/gilvandroneto1991/">LinkedIn</a> to keep in touch. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13249571d37b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/extracting-keywords-from-covid-19-news-with-python-13249571d37b">Extracting keywords from COVID-19 news with Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Afinal, o que é o #MLOps e por que é tão importante para Ciência de Dados?]]></title>
            <link>https://gilvandrofneto.medium.com/afinal-o-que-%C3%A9-o-mlops-e-por-que-%C3%A9-t%C3%A3o-importante-para-ci%C3%AAncia-de-dados-10321214e7b4?source=rss-ffa97aee7956------2</link>
            <guid isPermaLink="false">https://medium.com/p/10321214e7b4</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ciencia-de-dados]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Gilvandro Neto]]></dc:creator>
            <pubDate>Tue, 03 Dec 2019 14:49:09 GMT</pubDate>
            <atom:updated>2019-12-03T14:49:09.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpTIMx1dgoFUiu9SsN665A.jpeg" /><figcaption>Operacionalizar a Ciência de Dados é um passo importante para disseminar os benefícios da sua aplicação!</figcaption></figure><p>Primeiro fazer a engenharia do dado e o famoso <em>feature engineering</em> até ter um <em>dataset</em> bem organizado e num formato perfeito para ser utilizado num treinamento do modelo ideal, após horas de análise sobre o problema inicial do seu cliente.</p><p>E então vem o treinamento do modelo — e mesmo nos modelos tradicionais ou indo ao <em>Deep Leaning</em>, à ânsia da espera pelo resultado é a mesma. Depois de alguns ajustes e do famoso <em>fine tuning</em> do modelo o resultado chega, a acurácia é a ideal de acordo com o que foi proposto inicialmente pelo cliente e a alegria da entrega de valor é iminentemente…</p><p>Mas aí chega a grande pergunta do cliente:</p><h3>Quando entra em produção?</h3><p>E então surgem as dúvidas:</p><p>Produção? Como assim? Consigo rodar o <em>Jupyter Notebook</em> aqui na minha máquina. Posso te entregar um .<em>pickle</em> do modelo, pode ser? Ah, o <em>Keras</em> e o <em>Fast.ai</em> permitem exportar o modelo, mas no formato deles. Te atende?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*xhxJRsoe_I_ghnwN" /><figcaption>“Works on my machine!”</figcaption></figure><p>Não, claro que não atende!</p><p><strong>O cliente quer ver o modelo em produção, sendo utilizado por todas as áreas da empresa e de preferência mostrando os resultados plausíveis e agregando valor ao negócio.</strong></p><p>E aí então que se chega num termo muito importante para Ciência de Dados: o <strong>MLOps.</strong></p><h3>Conhecendo um pouco mais sobre o MLOps</h3><p>Por trás de toda a <em>hype </em>ao se agregar a sigla “Ops” ao final de alguma abreviação, tem uma grande vertente na área de Ciência de Dados que é a da preocupação por operacionalizar um modelo treinado. Em termos mais técnicos, é fazer o <em>deploy</em> dos modelos em produção, tornando-os utilizáveis de fato para a empresa.</p><p>Com isso, mais desafios passam a fazer parte da área e mostram que a Ciência de Dados deve sim ir muito além dos <em>Jupyter Notebooks</em>.</p><p>Devemos sim nos preocupar com controle de versão e passar a utilizar no dia a dia termos como ‘Git Commit -m “”’ e ‘Git Push’. Temos que ter um repositório de códigos, utilizando-os a cada projeto!</p><p>O <em>Docker </em>também é nosso aliado e sim, funciona muito bem com o <em>Flask </em>ou com o <em>Django </em>— acredite, por experiência própria nunca mais quero utilizar máquinas virtuais depois da minha primeira API em <em>Flask</em>.</p><p>Além do <em>Docker</em>, ambientes em Cloud devem ser utilizados para a orquestração e gerenciamento das nossas aplicações. O <em>Kubernetes </em>(e os seus K8s) são ideais e o Cientista de Dados passa a conhecer comandos como o incrível ‘kubectl get pod’.</p><p>E os resultados obtidos da aplicação que está operando o modelo? Como utilizá-los para uma retroalimentar este mesmo modelo afim de realizar um novo treinamento, dessa vez com dados reais de produção?</p><p>E o gerenciamento de informação? Podemos utilizar uma <em>collection </em>do <em>MongoDB</em> para isso?</p><p>Mongo? De verdade? Mesmo? Hahaha…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ib94m211h-DHRaqp" /><figcaption>O MLOps e a evolução da Ciência de Dados</figcaption></figure><h3>A evolução da Ciência de Dados passa sim pelo MLOps!</h3><p>Escalabilidade, tempo de resposta e disponibilidade da aplicação são pontos importantes que devemos nos preocupar. Para o cliente, o importante é ter a aplicação funcionando e o modelo disponível para utilização.</p><p>Portanto sim, é imprescindível que nós, Cientista de Dados, nos tornemos cada vez mais responsáveis por aquilo que criamos. Treinar um modelo pode ser considerado como somente a primeira parte para fazer com que a aplicação como um todo esteja disponível para o cliente e de verdade agregue valor para o negócio.</p><p>O <strong>MLOps </strong>deve sim se tornar mais frequente nas empresas que estão apostando e enxergando a Ciência de Dados como área transformadora dos seus negócios. E cabe a nós, Cientistas de Dados, nos preocupar com a utilização dos nossos modelos.</p><p>Do início ao fim!</p><p><a href="https://www.linkedin.com/in/gilvandroneto1991/">Converse comigo no LinkedIn</a> e conte um pouco mais do seu dia a dia como Cientista de Dados e se o #MLOps já é realidade na sua aplicação.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10321214e7b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>