<?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 bo li on Medium]]></title>
        <description><![CDATA[Stories by bo li on Medium]]></description>
        <link>https://medium.com/@agentboli?source=rss-641c46d5b4d4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KyFtCwZhwtBs-ushw6coRw.png</url>
            <title>Stories by bo li on Medium</title>
            <link>https://medium.com/@agentboli?source=rss-641c46d5b4d4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 15:09:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@agentboli/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[I Burned Through 1.4 Billion AI Tokens in Six Weeks — Here’s What Chinese Models Really Cost]]></title>
            <link>https://agentboli.medium.com/i-burned-through-1-4-billion-ai-tokens-in-six-weeks-heres-what-chinese-models-really-cost-c9526d0a70b2?source=rss-641c46d5b4d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9526d0a70b2</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[bo li]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 06:25:04 GMT</pubDate>
            <atom:updated>2026-11-03T06:25:04.889Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Every price comparison you’ve read compares list prices per token. After six weeks on a Chinese coding subscription — and a fact-check of every provider’s official pricing page — I found the real gap is much bigger than the headlines say. Just not always in the way you’d expect.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X8JLPd8PyZ4x50HS.png" /></figure><blockquote><strong><em>TL;DR:</em></strong><em> Token-price comparisons systematically overstate what you actually pay for Chinese models like GLM, Qwen and DeepSeek. Four mechanisms do the work: the same plan is often cheaper on the provider’s Chinese site than its international one; subscriptions stack quarterly and annual discounts on top; providers discount nights, weekends and Chinese public holidays on Beijing time — which is literally daytime in Europe and the US; and promotional quota boosts come and go without ever being announced in English. All prices below were verified on official pricing pages on October 22, 2026.</em></blockquote><h3>The number that started this</h3><p>Over the last six weeks or so, I pushed roughly <strong>1.4 billion tokens</strong> through a GLM coding plan — the entry-level <strong>Lite</strong> plan, on quarterly billing at the Chinese-site price of <strong>¥94 a month (about $13)</strong>. Six weeks cost me about <strong>¥140 — call it $20</strong>.</p><p>What would the same volume cost at the prices everyone quotes in comparisons? At Anthropic’s list rates for Sonnet 5.5 ($2 per million input tokens, $10 per million output, assuming a typical coding-agent mix of about three tokens in for every token out and no caching), 1.4 billion tokens come to roughly <strong>$5,600</strong> — about 280 times what I paid. Not a typo. The same workload through Z.ai’s own pay-as-you-go API would be about $3,000, still 150 times my bill.</p><p>Blended across everything I actually consumed, I paid <strong>about $0.014 per million tokens</strong> — less than one and a half cents. Two boring-sounding details made that possible, and neither appears in any price comparison: about <strong>half my traffic ran on GLM-5.3-Flash</strong>, the budget tier, and my <strong>cache hit rate sat near 90%</strong> — cached input is billed at roughly a quarter of fresh-input rates. Steering your workload between tiers and keeping the cache warm are discount levers worth more than any promo code. Z.ai’s own documentation estimates a heavy user on the top-tier Max plan pays the equivalent of <strong>$0.02–0.03 per million tokens</strong>. That is a different sport, not a different price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IPvqSI0J4ghh5-UB.png" /></figure><h3>Token-price comparisons are measuring the wrong thing</h3><p>Almost every “Chinese AI is 10x cheaper” article — including the ones I used to nod along to — compares <strong>API list prices per million tokens</strong>. That’s a real number, and it’s easy to source. But almost nobody who codes with these models daily pays list prices. We’re on subscriptions, and subscriptions are where the pricing gets interesting:</p><ul><li><strong>Z.ai GLM Coding Plan</strong> — Lite $18, Pro $80, Max $168 per month; quarterly billing takes 20% off, annual takes 30% off.</li><li><strong>Alibaba Token Plan</strong> — Lite $6, Essential $10, Standard $18, Pro $68 per month (all currently “limited-time” prices below their $8/$16/$25/$80 list).</li><li><strong>ByteDance Volcano Coding Plan</strong> — Lite ¥40 (≈$5.60), Pro ¥200 (≈$28) per month — and it serves GLM, DeepSeek, Kimi and Doubao models in one plan.</li><li><strong>Kimi (Moonshot)</strong> — $15 to $159 per month internationally; every tier is discounted against its “regular” price and cheaper again if billed annually.</li><li><strong>MiniMax M Plan</strong> — $22 to $132 per month, with “two months free” on annual billing.</li><li><strong>The US baseline</strong> — ChatGPT Plus and Claude Pro are both $20 a month, and OpenAI explicitly offers no annual billing at all. Claude Pro does — $200 a year, effectively $16.67 a month. That’s the entire discount menu: one option, 17% off, at one provider.</li></ul><p>Notice what’s already happening: the Chinese side has entry tiers below $6, quarterly and annual discounts, first-purchase promotions, referral credits, and bundle top-ups. The US side has a monthly price and, at Anthropic, a single annual price. Any comparison that stops at “GLM-5.3 is $4.40 per million output tokens vs $10 for Sonnet” is comparing the most unfavorable way to buy Chinese models with the way nobody actually buys them.</p><h3>One company, two price tags</h3><p>Here’s the part almost no comparison covers: several Chinese providers run <strong>two separate price lists for the identical product</strong> — one on the international site in dollars, one on the domestic site in yuan — and the yuan list is usually lower.</p><p>Z.ai’s coding plans cost $18/$80/$168 internationally and ¥118/¥538/¥1,078 on its Chinese site. Converted at the market rate of about 7.1 yuan per dollar, the Chinese prices work out to roughly $16.6/$75.8/$151.8 — the implied exchange rate on their own pricing is 6.4–6.7, meaning <strong>the Chinese site is 5–10% cheaper in dollar terms</strong>. On raw API access the gap is wider: GLM-5.3 is $1.40/$4.40 per million tokens internationally versus ¥8/¥28 (≈$1.13/$3.94) in China, about 10–20% cheaper.</p><p>The most extreme case I verified is Alibaba’s coding IDE: <strong>Qoder Pro is $20 a month internationally and ¥59 (≈$8.30) for the domestic version</strong> — the same product line at a 58% discount. Alibaba’s flagship API shows the same pattern: qwen3.8-max is $2/$6 per million tokens on the international platform, ¥12/¥36 (≈$1.69/$5.07) in Beijing.</p><p>But before you conclude “China always pays less” — it doesn’t. Moonshot’s Kimi Max is $79 a month internationally and ¥699 (≈$98) in China. <strong>Regional pricing is real, usually favors the Chinese site, but it’s a per-product decision, not a rule.</strong> What is a rule: the price an international comparison quotes is rarely the lowest price the product sells for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HeGxp0IWXHnFWgmj.png" /></figure><h3>The Beijing clock: discounts keyed to someone else’s office hours</h3><p>This is the mechanism that convinced me the standard comparisons are structurally broken. Chinese providers quietly price by <strong>time of day in Beijing</strong> — and the discount windows are precisely the hours when China’s own usage drops: nights, weekends, and public holidays.</p><ul><li><strong>Z.ai</strong> bills coding-plan usage in credits. During “peak” hours those credits cost full rate; off-peak they cost <strong>half</strong>. Peak is defined as Monday to Friday, 14:00–18:00 Beijing time — that’s it. Five hours a day, five days a week. Nights, early mornings and the entire weekend are off-peak. Z.ai’s own token estimates show what this means: the Pro plan’s 60,000 weekly credits buy roughly <strong>290 million tokens a week if you work Beijing office hours — and 580 million if you don’t</strong>. Same subscription, double the tokens, because the clock said so.</li><li><strong>DeepSeek</strong> now runs straight peak/off-peak API pricing: off-peak is exactly half of peak (V4-Pro output: ¥13.5 vs ¥27 per million tokens). The definition, quoted from their pricing page: peak is Beijing-time weekdays 9:00–12:00 and 14:00–18:00, <strong>excluding Chinese public holidays</strong>. Read that again — Chinese holidays are a discount trigger. When China goes on Golden Week, your API bill halves.</li><li><strong>Alibaba’s Token Plan</strong> discounts 60% of the credit cost (you pay 40%) for qwen3.8-max and qwen3.8-flash every night between <strong>22:00 and 08:00 Beijing time</strong>, with 50% off for DeepSeek models on the same plan.</li></ul><p>Now do the timezone math. A developer in New York works 9:00–18:00 local — that’s 21:00–06:00 in Beijing. <strong>The entire US workday sits inside the discount window of all three providers.</strong> A developer in Berlin works 15:00–24:00 Beijing time: the first three hours graze the afternoon peak, and everything after lands in the discount zone. The only people who consistently pay full price are the providers’ own domestic users, during Chinese office hours.</p><p>None of this is secret — it’s all on official pricing pages, usually in Chinese, usually several clicks deep. But it’s invisible to per-token comparisons, which treat a Sunday-midnight token and a Wednesday-3pm-Beijing token as the same commodity. They are not the same commodity. One is half price.</p><p>And then there’s the layer I can’t source, only report: several times around Chinese holidays — when domestic usage predictably collapses — I’ve logged in to find my effective quota boosted. No announcement, no email, nothing in the English changelogs. I’ve never seen this written down anywhere, so treat it as anecdote. But the documented mechanisms above already produce exactly this effect, on schedule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5gxQTFz62PEosAT5.png" /></figure><h3>The promo layer: first months, IDE lock-in, and the reset economy</h3><p>Beyond list discounts and time-of-day pricing, there’s a rolling carnival of promotions:</p><ul><li><strong>Volcano Engine’s coding plan</strong> is running first-two-months pricing of ¥9.9 (≈$1.40) for Lite and ¥49.9 (≈$7) for Pro against a ¥40/¥200 list — a 75–96% discount for two months, limited quota, first come first served, through November 8, 2026.</li><li><strong>MiniMax</strong> just ended a 50%-off-first-month promo on its entire M Plan lineup (it ran through October 14).</li><li><strong>Z.ai launched</strong> its coding plan in September 2025 with 50% off the first month and the slogan “1/7th the price of Claude Code plans, 3x the usage” — the origin of a thousand comparison headlines.</li><li><strong>Alibaba’s</strong> current international Token Plan prices ($6/$10/$18/$68) are all explicitly “limited-time” cuts from higher list prices.</li><li><strong>Ecosystem lock-in pays literally:</strong> Chinese subscribers who use Zhipu’s own ZCode IDE get 150% of the standard quota plus free off-peak tasks. ByteDance’s Doubao team plan is advertising “limited-time doubled points” on its pricing page right now.</li><li><strong>Referrals:</strong> Z.ai gives up to 20% back in credits; Volcano gives a 5% voucher to the inviter plus 5% off for the invitee.</li></ul><p>Even quota resets are monetized differently. In August 2026, Alibaba simply <strong>gifted</strong> all Token Plan subscribers a one-time quota reset. In October 2026, OpenAI launched the ability to <strong>buy</strong> an instant usage reset for Plus and Pro. Same problem, two philosophies: one hands out tokens when demand dips, the other installs a vending machine.</p><h3>The math that matters</h3><p>Put it together and the honest comparison isn’t “GLM is 4x cheaper than Sonnet per token.” It’s:</p><ul><li><strong>Entry cost</strong> — $6–18 a month buys a legitimate Chinese coding subscription with Claude Code-compatible endpoints. The US equivalent starts at $20.</li><li><strong>Effective price</strong> — Z.ai’s documentation advertises “up to 92% savings” versus its own pay-as-you-go API, and my real usage came in around <strong>$0.014 per million tokens</strong> blended, half of it on the budget Flash tier with a ~90% cache hit rate. Both are levers, not luck: tier steering and cache warmth are pricing decisions.</li><li><strong>Off-peak doubling</strong> — work Beijing nights and weekends, which for most readers is just “being in Europe or America,” and the same credits buy roughly twice the tokens.</li><li><strong>Multi-vendor stacking</strong> — Alibaba’s $10 Essential Token Plan doesn’t just include Qwen models; it includes <strong>GLM-5.3 and DeepSeek V4</strong> on one subscription. Volcano’s coding plan bundles GLM, DeepSeek, Kimi and Doubao. China is selling multi-model subscription bundles; the US is still selling one vendor per subscription.</li></ul><h3>The honest caveats</h3><p>This story has a counterweight, and any article that omits it is selling something:</p><ul><li><strong>List prices are rising fast.</strong> GLM Coding Pro went from $30 list (September 2025) to $72 (April 2026) to $80 (July 2026); the Chinese price went from ¥149 to ¥538 in the same window. The $15-a-month era was a subsidized land grab, and it is over. The gap is still enormous at the effective level, but it is narrowing, and these are moving targets.</li><li><strong>Volume is not capability.</strong> Whether GLM-5.3 or qwen3.8-max matches Sonnet 5.5 or GPT-6 on <em>your</em> codebase is a separate question from price — and remember, half of my own 1.4 billion tokens ran on the budget Flash tier. Benchmarks move monthly. Test on your own repository before committing.</li><li><strong>Capacity is finite.</strong> Z.ai reportedly capped new subscription sales during a demand crunch in January 2026. Cheap tokens come with queueing risk at exactly the Beijing-peak hours you’re avoiding anyway.</li><li><strong>Compliance and geopolitics.</strong> EU users should think about data residency, and Reuters reported in mid-2026 that Beijing was weighing curbs on overseas access to top Chinese models. Everything cheap can become unavailable.</li><li><strong>Promotions expire.</strong> Several prices I verified are explicitly labeled “limited-time.” The $6 Essential tier may not exist when you read this. That’s the point: in this market, the list price is a starting position, not the price.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y6z4Kxa_hJqmOdjt.png" /></figure><h3>What I do differently now</h3><p>I buy annually when a plan fits — it locks both the price and the 30% discount against the repricing wave. I let the timezone work for me: heavy agent runs that used to go anytime now go after 18:00 Beijing time, which for me is just my afternoon. I keep one multi-vendor bundle subscription alongside my main plan. And I track one number only: <strong>dollars per million tokens actually consumed</strong>. By that number, nothing on the US price list comes close right now.</p><p>The headline comparisons say Chinese models are 5–10x cheaper. My own six weeks came in at roughly <strong>280x below the US list rate</strong> for the same tokens. The difference between those two claims is the entire subject of this article — and it’s sitting in plain sight, in billing documentation, mostly in Chinese, waiting for someone to read the fine print.</p><p><strong>Sources (all checked October 22, 2026):</strong> <a href="https://z.ai/subscribe">z.ai/subscribe</a> and <a href="https://docs.z.ai/devpack/overview">docs.z.ai coding-plan docs</a>; <a href="https://bigmodel.cn/glm-coding">bigmodel.cn coding plan</a> and <a href="https://docs.bigmodel.cn/cn/guide/start/pricing">bigmodel.cn API pricing</a>; <a href="https://www.alibabacloud.com/help/en/model-studio/token-plan-personal-overview">Alibaba Cloud Token Plan</a> and <a href="https://www.alibabacloud.com/help/en/model-studio/model-pricing">Model Studio pricing</a>; <a href="https://api-docs.deepseek.com/quick_start/pricing">DeepSeek pricing</a>; <a href="https://www.kimi.com/code/en">Kimi plans</a>; <a href="https://platform.minimax.io/docs/m-plan/monthly-offer.md">MiniMax M Plan promo</a>; <a href="https://www.volcengine.com/activity/codingplan">Volcano Engine coding plan</a>; <a href="https://claude.com/pricing">claude.com/pricing</a>; <a href="https://developers.openai.com/api/docs/pricing">OpenAI API pricing</a> and <a href="https://help.openai.com/en/articles/6950777-what-is-chatgpt-plus">ChatGPT Plus help</a>. Currency converted at 7.1 CNY/USD. My token usage and the holiday-quota observation are personal data points, not vendor claims.</p><p><em>Originally published at </em><a href="https://cn-llm-pricing-2tfd.zai.site/"><em>https://cn-llm-pricing-2tfd.zai.site</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9526d0a70b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the ESP32-S3 BLE Bridge Dongle to LLM]]></title>
            <link>https://agentboli.medium.com/using-the-esp32-s3-ble-bridge-dongle-to-llm-bf8ebbcc9aa2?source=rss-641c46d5b4d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf8ebbcc9aa2</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[espclaw]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[esp32]]></category>
            <category><![CDATA[bluetooth]]></category>
            <dc:creator><![CDATA[bo li]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 08:02:25 GMT</pubDate>
            <atom:updated>2026-10-11T17:26:34.753Z</atom:updated>
            <content:encoded><![CDATA[<p>A short user’s guide: connect your BLE devices to an LLM through a USB dongle and your PC.</p><p>repository url : <a href="https://github.com/jinboagent/esp32_lua_claw">https://github.com/jinboagent/esp32_lua_claw</a></p><h3>What it does for you</h3><p>The BLE Bridge Dongle is a small USB stick with a Bluetooth radio. You plug it into your PC, and it becomes the meeting point between two worlds: your BLE devices on one side — sensors, controllers, anything that advertises or holds a GATT connection — and a cloud LLM on the other side. The dongle collects whatever your devices broadcast or serve, streams it to your PC as clean JSON lines, and the LLM reads that live data, answers your questions, and writes small Lua programs that run on the dongle itself — closing the loop back toward your device.</p><p>You do not flash anything to try new behavior, and you do not write parsers. You ask. The LLM proposes code; you approve it with a single keypress; the dongle runs it immediately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1qXER3Tz_MeR-Tk7pTlPw.png" /></figure><p><em>Figure 1. Your BLE device talks to the LLM through this chain: data flows up over the dongle’s radio, and the LLM’s Lua flows back down the same path.</em></p><h3>One session, three participants</h3><p>Whenever you use the system, three participants do the work. The dongle collects — both over-the-air advertisements and, if you connect to a device, its live GATT notifications. Your PC post-processes that stream, enriching raw radio bytes with semantics: names, deduplication, which data plane a line came from, a bounded rolling snapshot. And the LLM — which lives on the PC, one API call away — reads the result and writes the code that steers what happens next. You are the fourth participant: the human who asks the questions and holds the deploy key.</p><h3>Talk to your devices from the console</h3><p>Open any serial terminal to the dongle’s port (for example COM12 at 115200 baud). You type plain text commands; the dongle answers with one strict JSON line per command and, while scanning, a live stream of JSON events — one per advertisement. Four commands are enough to start:</p><p>STATUS -&gt; {“status”:”ok”,”state”:”idle”, …}</p><p>SCAN START -&gt; {“cmd”:”scan”,”status”:”ok”,”state”:”SCANNING”}</p><p>… advertisement JSON lines stream by …</p><p>FILTER ADD NAME Sensor_* -&gt; only matching devices stream from now on</p><p>The same console can do more when you want it: FILTER ADD RSSI -70 keeps only nearby devices, CONN TARGET plus CONN START attaches the dongle to one device as a BLE client and re-streams its notifications as “src”:”conn” lines, and POWER SLEEP ON lets the dongle light-sleep when idle. Ctrl+C always stops whatever is running — scan, script, or upload — instantly, with no Enter needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e16uJpls4Jt8l5jmqYlHLg.png" /></figure><p><em>Figure 2. What happens to the data you see: every advertisement is deduplicated, parsed, filtered, and encoded to JSON before it reaches you; the second plane streams a connected device’s notifications.</em></p><h3>Everything answers in JSON</h3><p>Every response names the command it answers, so a slow terminal or a chatty stream can never hand you a stale line by mistake. Errors are numbers, not prose — each subsystem owns its own numeric range — so scripts (and the LLM) can branch on failure precisely. And anything you or the LLM upload is checked line by line on the device itself: forbidden APIs are rejected before they ever run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3eoS5VPPeu53BNqICtMsJw.png" /></figure><p><em>Figure 3. The whole protocol: text lines in, JSON lines out, every response carrying the command it answers.</em></p><h3>Ask the LLM about your live data</h3><p>The console is the mechanical interface; the conversation is the friendly one. Start the assistant and just talk:</p><p>python host_app/assistant.py COM12</p><p>you: what devices are around me?</p><p>you: keep only my two sensors</p><p>you: is my sensor’s signal getting weaker?</p><p>The model sees a fresh snapshot of your live traffic every turn, alongside your conversation. It replies in one of four typed forms: an answer grounded in the snapshot, a clarifying question when you were ambiguous, an error report that never crashes the session, or a Lua proposal. Proposals deploy only after you answer deploy? [y/N] with y — the LLM can suggest, but you decide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cw06jyu3gx6nyTVJPp55IQ.png" /></figure><p><em>Figure 4. Your question plus the live device data go into one prompt; the reply comes back typed — an answer to you, or code through your approval gate.</em></p><h3>Let the LLM define its own tools</h3><p>Beyond one-off scripts, you can give the system a tool registry: small Lua functions the model may call by name. A tool pack is a plain Lua file — every tool takes one table argument and returns a string — loaded with a single command:</p><p>/tools load demo.lua -&gt; tools registered, callable by you and the LLM</p><p>/tools persist mytools autorun -&gt; saved to flash; alive on every boot, no PC needed</p><p>Once tools are registered, the model can go beyond answering: asked about live data, it may write a small Lua program composing those tools, execute it on the dongle, read the result, and continue — at most three executions per turn, then it must answer in words. Packs can also touch hardware through the hw.* API — GPIO pins, an ADC channel, a small persistent key-value store — and tools that mutate hardware ask for your confirmation first ( — mutating-gate).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HrscJ8piVrMHBSAUtLz8CA.png" /></figure><p><em>Figure 5. How a tool pack registers (collisions rejected before any device byte is sent) and the cap-3 loop the LLM runs.</em></p><h3>See the whole loop in one command</h3><p>The fastest way to feel what this system does needs no second device. One command turns your PC into a simulated BLE sensor — a first-order plant with a known time constant — and asks the LLM to work out that constant from the captured data alone:</p><p>python host_app/run_case.py COM12 — case first_order — tau 10 — step-at 5 — secs 60 — estimate</p><p>Your PC advertises the sensor over GATT; the dongle connects automatically and streams the measurements; the LLM receives nothing but the raw JSON samples and must answer: what is tau? The harness grades the answer against physics. In the recorded run the model estimated 9.5 against a true value of 10.0 — five percent off, derived by the model from raw data it had never seen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQuDPG1C6D4rICxm87LyDw.png" /></figure><p><em>Figure 6. The closed loop, graded: simulated plant, dongle connection, LLM estimate, physics-checked verdict.</em></p><h3>Why you can trust it</h3><p>Every claim in this guide is backed by a check that runs against real hardware — one command re-proves the whole loop after any change, from the radio up to the LLM’s estimate. The device, not the host, has the final word on what code runs: uploads are scanned per line, the sandbox is whitelist-only, and nothing deploys without your keypress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5h4_B3tbjiiyQEpQ3M3aQ.png" /></figure><p><em>Figure 7. The check inventory and the one-command hardware gate behind the product.</em></p><h3>Try it</h3><p>Clone the repository, flash the dongle (scripts\build.bat and scripts\flash.bat), and start the assistant. Any OpenAI-compatible LLM endpoint works — OpenAI, Qwen/DashScope, DeepSeek, OpenRouter, or a local Ollama; credentials live in a local .llm_env file that never leaves your machine. The 10-minute walkthrough is docs/quickstart.md, and the full architecture story lives in the companion article.</p><p>python host_app/assistant.py COM12 # start chatting with your devices</p><p>python host_app/assistant.py COM12 — no-llm # or explore without any API key</p><p>A short user’s guide: connect your BLE devices to an LLM through a USB dongle and your PC.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf8ebbcc9aa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Dongle That Writes Its Own Tools: An ESP32-S3 BLE Lab Operated by an LLM]]></title>
            <link>https://agentboli.medium.com/the-dongle-that-writes-its-own-tools-an-esp32-s3-ble-lab-operated-by-an-llm-41e5f7c9b247?source=rss-641c46d5b4d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/41e5f7c9b247</guid>
            <category><![CDATA[lua]]></category>
            <category><![CDATA[espclaw]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[esp32-s3]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <dc:creator><![CDATA[bo li]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 20:26:47 GMT</pubDate>
            <atom:updated>2026-10-11T17:27:11.772Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/jinboagent/esp32_lua_claw">https://github.com/jinboagent/esp32_lua_claw</a></p><p><em>A five-dollar ESP32-S3 dongle bridges BLE devices and a cloud LLM through your PC. The dongle collects advertisement and GATT-connection data and streams strict JSON lines over USB; the host post-processes that stream, enriching it with semantics, and an LLM reads it, answers your questions, writes Lua code, defines its own tools, and deploys them back to the dongle — closing the loop all the way to the device the data came from. Everything is sandboxed, confirm-gated, and verified live on real hardware. This article explains the system, the data flow, and — from a user’s point of view — what you can actually do with it.</em></p><p>Debugging Bluetooth Low Energy devices is oddly manual. You either buy a dedicated capture gadget, fight Wireshark captures, or write a throwaway parser script for every new device you meet. And when you want the firmware itself to filter or interpret traffic differently, you are back on the bench: rebuild, reflash, retest.</p><p>This project takes a different bet: put a <strong>Lua sandbox on a cheap radio</strong>, and put an <strong>LLM on the host side</strong> where it can extend its own instrumentation. The dongle collects; the PC gives the data meaning; the model reads that meaning and writes the code that steers what happens next — and the code ships over USB in seconds instead of a reflash cycle. The whole loop — capture, analyze, generate, deploy, observe — runs against real hardware today, and every claim in this article is backed by a check in a 300+ test harness.</p><blockquote><strong><em>TL;DR:</em></strong><em> ESP32-S3 firmware (C, ~5.7k lines + vendored Lua 5.4) turns BLE adverts into ≤512-byte JSON lines over USB CDC. Three self-contained Python tools put an OpenAI-compatible LLM in the loop: you </em><strong><em>chat with it about live traffic</em></strong><em>, it </em><strong><em>writes and deploys Lua filters</em></strong><em> behind your confirmation, it can </em><strong><em>define and run its own Lua tools on the dongle</em></strong><em>, and a physics demo proves the loop — the LLM estimates a simulated sensor’s time constant to within 5% of ground truth.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1qXER3Tz_MeR-Tk7pTlPw.png" /></figure><p>The system in one picture: your BLE device talks to the LLM through this chain — its data flows up over the dongle’s radio, and the LLM’s Lua flows back down the same path.</p><h3>One session, three participants</h3><p>It helps to name who is actually in the room when a session runs. On your side there are three participants — plus one device at the other end of the radio link:</p><ul><li><strong>The device</strong> — your sensor or controller — is where the data is born. It advertises over the air, or holds a GATT connection the dongle can join.</li><li><strong>The USB dongle</strong> collects that data in both ways — advertisements, or a live BLE connection — and streams it as strict JSON lines over USB.</li><li><strong>The PC host</strong> post-processes the stream: it improves the semantics — deduplicates repeats, names devices, tags which data plane a line came from, keeps a bounded rolling snapshot — so raw radio bytes become meaningful, model-ready context. The LLM lives here, one API call away.</li></ul><p>And you are the fourth participant: the human who asks the questions and approves the code. The session then runs as one loop. The device’s data flows up — dongle, then PC, then post-processed into the LLM’s context. The LLM replies with more than words: Lua scripts, tool programs, plain answers, follow-up questions. The code travels back down the same chain and runs <em>on the dongle</em>, meters from the device — filtering its data, transforming it, reacting to it live, driving the dongle’s own pins, holding or dropping the connection. That is the real product: <strong>the LLM controls the device through the dongle</strong>, with you watching over its shoulder and holding the deploy key.</p><h3>What it looks like from your side</h3><p>Before the internals: as a user you touch this system at exactly three places, and everything else exists to make those three good.</p><p><strong>1. You type to the dongle console</strong> (any serial terminal — PuTTY, screen, the bundled monitor). Input: plain text commands like SCAN START or FILTER ADD RSSI -70. Output: one strict-JSON line per command, plus a live stream of JSON events for every BLE advertisement — readable by you, by scripts, and by the LLM.</p><p><strong>2. You run the host tools</strong> (plain Python command lines). Input: a port name, a goal in English, case flags. Output: capture files, generated Lua scripts, graded estimates, session transcripts.</p><p><strong>3. You talk to the LLM.</strong> This is the main interface, and the reason the project exists. You type an ordinary question — <em>“which devices around me are Apple?”</em>, <em>“keep only my two sensors”</em>, <em>“what’s the average RSSI of the plant sensor?”</em> — and the model answers, asks you follow-up questions when you were ambiguous, proposes Lua code, or executes tool calls on the dongle. You approve every code deploy; tool calls within a bounded budget run autonomously.</p><p>So the contract with you is simple: <strong>text in, JSON and answers out.</strong> Everything below explains what makes that trustworthy.</p><h3>The dongle: one packet’s journey</h3><p>The firmware is an ESP-IDF v5.1 project with one component per concern, communicating only through public headers in interfaces/*_if.h — that contract layer is why parallel AI agents could extend this codebase for months without stepping on each other.</p><ul><li><strong>usb</strong> — USB-Serial/JTAG console: line I/O, Ctrl+C interrupt path</li><li><strong>ble</strong> — NimBLE observer (passive scan, dedup) + optional GATT central</li><li><strong>proto / </strong><strong>json_enc</strong> — AD-structure parsing and the JSON line encoder</li><li><strong>filter</strong> — up to 16 C filter rules evaluated on the hot path</li><li><strong>lua</strong> — Lua 5.4 sandbox on a 128 KB static pool; hooks, tool packs, hw.* bindings</li><li><strong>cli</strong> — command dispatch behind IDLE / SCANNING / SCRIPT_RUNNING state guards</li><li><strong>bridge / </strong><strong>storage / </strong><strong>power</strong> — script/pack upload scanning, LittleFS, light-sleep power management</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e16uJpls4Jt8l5jmqYlHLg.png" /></figure><p>The data flow. Every advertisement walks this pipeline left to right; the second row is the optional GATT connection plane that turns the dongle from observer into client.</p><p>Every advertisement takes the same journey: NimBLE observer (passive, continuous) → dedup (FNV-1a, ~1 s window) → AD parse → C filter engine → <em>[Lua </em><em>on_adv hook: keep/drop]</em> → JSON encode → <em>[Lua </em><em>transform hook]</em> → USB console TX. A second, optional plane connects the dongle to <strong>one</strong> GATT peer — subscribe to its notifications, or fall back to polling reads — and re-streams that data as &quot;src&quot;:&quot;conn&quot; lines on the same USB stream.</p><p>The invariants are the unglamorous part that makes the rest possible: a zero-malloc hot path, one TX mutex so lines never interleave, per-module numeric error codes, and a state machine that rejects mistimed commands with -911. Ctrl+C (0x03) is polled even inside the connection worker — no command can lock the console.</p><h3>A wire contract an LLM can trust</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3eoS5VPPeu53BNqICtMsJw.png" /></figure><p>The whole protocol: text lines in, JSON lines out. Every response names the command it answers, so stale lines are never misattributed.</p><p>The host link is USB CDC, and the protocol is almost embarrassingly simple:</p><pre>&gt; SCAN START\r<br>&lt; {&quot;cmd&quot;:&quot;scan&quot;,&quot;status&quot;:&quot;ok&quot;,&quot;state&quot;:&quot;SCANNING&quot;}</pre><pre>&gt; SCRIPT LOAD<br>&gt; print(&quot;hello from the model&quot;)<br>&gt; SCRIPT END<br>&lt; {&quot;cmd&quot;:&quot;script&quot;,&quot;status&quot;:&quot;loaded&quot;}</pre><p>Three details matter more than they look.</p><p><strong>Every response carries a </strong><strong>cmd field</strong> — when an agent interrupts a running script and fires the next command, stale response lines may still drain; the cmd field means an old answer can never be mistaken for a new one. <strong>Errors are numbers, not prose</strong> — each module owns a 100-wide negative range (Lua sandbox -6xx, CLI -9xx…), so a program — or a model — can branch on failure precisely. And <strong>uploaded code is scanned per line, fail-closed</strong>: os., io., require and friends are rejected with -612 before they ever reach the interpreter. The device, not the host, has the final word on what runs.</p><h3>The host-side LLM: the actual product</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cw06jyu3gx6nyTVJPp55IQ.png" /></figure><p>Here is the part to emphasize, because it is the reason for everything above: <strong>the LLM is not a gimmick bolted onto the side — it is the primary interface.</strong> The three Python host tools exist to give the model clean context and safe actuators.</p><p>The host-LLM loop: two inputs (device + you), one prompt, one assembled context, and four kinds of typed replies — routed to you, through the human gate, or back into the next context.</p><p><strong>What the model sees.</strong> A rolling snapshot of both data planes — the latest deduplicated advertisement lines and the latest connection-plane samples — refreshed every conversational turn, plus the tool registry (below) and your conversation. The sample is capped (20 adv + 30 conn lines) to bound token cost.</p><p><strong>What you can ask it.</strong> Anything about the live traffic: <em>“what devices are around me?”</em>, <em>“is my sensor’s signal getting weaker?”</em>, <em>“summarize the manufacturers I can see”</em>. It answers in a typed envelope:</p><ul><li>answer — a plain answer, grounded in the snapshot;</li><li>clarify — <em>you</em> were ambiguous (&quot;keep only my devices&quot; — which ones?), so it asks before acting;</li><li>lua — it proposes code: a filter, a transform, or a tool pack, deployed only after deploy? [y/N];</li><li>error — something failed (provider, device); the session survives and the failure is shown to you <em>and</em> fed back to the model as a hint.</li></ul><p><strong>What the model can do on its own.</strong> With a tool registry loaded, it can go beyond answering: given a question about live data, it may write a small Lua <em>tool program</em> composing registered tools and execute it on the dongle, read the result, and continue — up to <strong>three consecutive executions per turn</strong>, then it must answer in plain text. This “generate-and-execute” loop is what turns the dongle into a self-extending instrument.</p><p><strong>How you stay in control.</strong> Four gates, in order: strict typed-envelope parsing (one escape-focused retry); the human deploy? [y/N] gate for every script/hook deploy — and an optional --mutating-gate that extends confirmation to tool programs that mutate hardware state; the per-line sandbox scan on upload; and the on-device whitelist sandbox as the final authority. Bounded autonomy for tool calls; explicit consent for everything that changes what the pipeline does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HrscJ8piVrMHBSAUtLz8CA.png" /></figure><p>The tool registry. Top: how a pack registers (manifests fetched in chunks, collisions rejected before any device byte is sent). Bottom: the cap-3 execution loop the LLM runs.</p><p><strong>Defining tools: the Lua tool registry.</strong> A <em>tool pack</em> is a plain Lua file where every line is one complete statement ≤240 bytes (so it rides the existing single-line transport with zero firmware changes), every tool takes <strong>one table argument</strong> and returns a string, and a manifest() function advertises the API — name, doc, typed args, example, and a mutating flag:</p><pre>-- every tool: ONE table argument, returns a string<br>function mean(a)<br>  local s = 0<br>  for _, v in ipairs(a.numbers) do s = s + v end<br>  return string.format(&quot;%.3f&quot;, s / #a.numbers)<br>end</pre><pre>function manifest()<br>  return &#39;{&quot;version&quot;:1,&quot;name&quot;:&quot;demo&quot;,&quot;tools&quot;:&#39;<br>      .. &#39;[{&quot;name&quot;:&quot;mean&quot;,&quot;doc&quot;:&quot;mean of numbers&quot;,&#39;<br>      .. &#39;&quot;args&quot;:[{&quot;name&quot;:&quot;numbers&quot;,&quot;type&quot;:&quot;table&quot;}]}]}&#39;<br>end</pre><p>Load it from the assistant with /tools load demo.lua — done, the tool is callable by you and by the model. Packs can be persisted to flash and marked autorun, so your tools are alive on every boot with no PC attached. Device-side hw.* bindings (GPIO write/read, 12-bit ADC, a small persistent key-value store) let packs touch the physical world; the kv store even survives reboots.</p><h3>The interfaces you can call</h3><p>The complete user-facing surface, condensed. On the console (input → what you get back):</p><ul><li><strong>You send </strong><strong>SCAN START/STOP, </strong><strong>SCAN INTERVAL ms</strong> — you get JSON advertisement lines streaming, plus scan state</li><li><strong>You send </strong><strong>FILTER ADD NAME/UUID/RSSI/MAC …</strong> — only matching devices stream (≤16 rules, AND/OR logic)</li><li><strong>You send </strong><strong>SCRIPT LOAD → lines → SCRIPT END, then </strong><strong>SCRIPT RUN/STOP</strong> — on_adv/transform hooks join the pipeline</li><li><strong>You send </strong><strong>LUA EXEC code or </strong><strong>LUA BEGIN … LUA END</strong> — one-liner or 4 KB chunk results, immediately</li><li><strong>You send </strong><strong>PACK BEGIN name [autorun] → lines → PACK END</strong> — a tool pack stored in flash, optional boot autorun</li><li><strong>You send </strong><strong>CONN TARGET/START/STOP/INTERVAL …</strong> — one GATT peer&#39;s data arrives as &quot;src&quot;:&quot;conn&quot; lines</li><li><strong>You send </strong><strong>POWER SLEEP ON/OFF, </strong><strong>STATUS, </strong><strong>VERSION — or </strong><strong>Ctrl+C</strong> — power policy; a full health blob; a universal interrupt</li></ul><p>In the assistant session (the LLM chat):</p><ul><li><strong>Free text — any question about live traffic</strong> → an answer / clarify / lua envelope from the model</li><li><strong>y at a </strong><strong>deploy? [y/N] prompt</strong> → the proposed Lua is uploaded and run (sandbox-scanned)</li><li><strong>/tools load file.lua · </strong><strong>/tools persist name autorun</strong> → register a tool pack · persist it to flash</li><li><strong>/scan on|off · </strong><strong>/conn on|off|status · </strong><strong>/samples · </strong><strong>/history</strong> → drive both data planes without leaving the chat</li></ul><p>From the shell (batch and scripted use):</p><pre>python llm_loop.py COM12 loop --secs 8 --goal &quot;keep only my Sensor_* devices&quot;<br>python host_app/assistant.py COM12            # the interactive chat<br>python host_app/run_case.py COM12 --case first_order --estimate<br>python host_app/assistant.py COM12 --no-llm   # mechanics without any API key</pre><p>Any OpenAI-compatible endpoint works — OpenAI, Qwen/DashScope, DeepSeek, OpenRouter, local Ollama. Credentials live in a gitignored .llm_env (template: .llm_env.example); a rejected key or an Aliyun-dialect URL self-heals with an announced retry.</p><h3>The demo that makes it concrete: estimating a time constant</h3><p>The clearest answer to <em>“what can this system actually do?”</em> is the first-order plant case. One command:</p><pre>python host_app/run_case.py COM12 --case first_order --tau 10 --step-at 5 --secs 60 --estimate</pre><p>What happens, step by step:</p><ol><li><strong>Your PC becomes a BLE sensor.</strong> A GATT server (Windows WinRT) advertises a service and serves measurements of a simulated first-order plant: y&#39; = (K·u − y)/τ, with the input u stepping from 0 to 1 at t = 5 s. (In GATT, the <em>server</em> is the side that holds — here, generates — the data; the dongle connects to it as the client.) This <strong>host-side BLE simulation</strong> is a feature in its own right — reproducible radio traffic with known ground truth, no second device needed.</li><li><strong>The dongle auto-connects</strong> by the advertised service UUID and starts receiving the measurements, which it re-streams to the host as &quot;src&quot;:&quot;conn&quot; JSON lines into a capture file.</li><li><strong>The LLM gets the raw capture</strong> — just the JSONL samples, nothing else — and must answer in JSON: what is the time constant τ of this sensor?</li><li><strong>The harness grades the answer</strong> against physics, not opinions: at t = step_at + τ a first-order step response must reach 63.2% of K, and the estimate must land within ±30% of the configured truth.</li></ol><p>The recorded live run: <strong>60/60 lines captured, and the LLM’s estimate was τ̂ = 9.5 against the configured τ = 10.0</strong> — a −5% error, derived by the model from raw samples alone. A harder variant, --case first_order_poll, makes the characteristic read-only so subscribing is impossible; the dongle detects this and falls back to polling reads — and the case still passes end to end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQuDPG1C6D4rICxm87LyDw.png" /></figure><p>The closed loop, graded: PC-simulated plant → dongle connection plane → LLM estimate → physics-checked verdict.</p><p>Why this demo matters: it exercises simulation (host), radio (connect/subscribe/poll), transport (JSON lines), and intelligence (the estimate) in one measurable loop. When you change anything in the stack, this is the experiment that tells you whether the product still works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5h4_B3tbjiiyQEpQ3M3aQ.png" /></figure><h3>Trust is a test suite</h3><p>The check inventory and the one-command hardware gate: wrong firmware version stops everything, and an unexpected reboot after any suite fails the run.</p><ul><li><strong>160 Unity C tests</strong> host-built (unit + response contract + fuzz) — every documented CLI response is strict-JSON validated; the fuzzer’s first run found three real encoder defects.</li><li><strong>198 python checks</strong> across the three host tools (153 on the assistant alone), including whole-REPL sessions over a device simulator.</li><li><strong>167 hardware checks</strong> in suites driven over the real COM port, behind one command (python tests/hw/run_all_hw.py) that asserts the firmware version first, tees every transcript, and checks the chip&#39;s reset_reason after <em>each</em> suite — an unexpected reboot fails the gate.</li><li><strong>Soaks</strong>: two-hour advertisement runs watching the Lua pool, and connection soaks reconnecting every 300 s.</li></ul><p>The project is also a case study in AI-native development: a machine-facing project brief, numbered design decisions in proposals, a second model reviewing code before merges, and a branch ritual where merges are decided by the hardware gate — never by confidence.</p><h3>Roadmap, and how to try it</h3><ul><li><strong>Next for the tool registry:</strong> more hw.* bindings, richer mutating-tool workflows, native function-calling on models that support it.</li><li><strong>Portability:</strong> the firmware is plain ESP-IDF — it already runs on other ESP32-S3 boards (voice/OLED dev boards included).</li></ul><p>The repo builds with stock ESP-IDF v5.1, the C tests run host-side with gcc or MinGW, and the hardware suites need only the dongle on a COM port:</p><pre>git clone https://github.com/jinboagent/esp32_lua_llm.git<br>cd esp32_lua_llm<br>scripts\build.bat &amp;&amp; scripts\flash.bat        :: firmware<br>cmake -S tests/host -B build/host -G Ninja &amp;&amp; cmake --build build/host<br>build\host\test_runner.exe                      :: 160 C tests<br>python tests/hw/run_all_hw.py                   :: hardware gate<br>python host_app\assistant.py COM12              :: start chatting</pre><p>If you have ever wanted an LLM that doesn’t just talk about your devices but sits in the loop with them — data flowing up through a dongle, working code flowing back down — with guardrails worth trusting, this is a small, complete example of how to build one.</p><p><em>The repository: </em><a href="https://github.com/jinboagent/esp32_lua_llm"><em>github.com/jinboagent/esp32_lua_llm</em></a><em> — firmware, host tools, tests, user guides (</em><em>docs/features.zcode.md, </em><em>docs/user-guide.zcode.md, </em><em>docs/demo-first-order.zcode.md), and a 17-slide architecture deck. Thanks for reading.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41e5f7c9b247" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>