<?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 Cuelark on Medium]]></title>
        <description><![CDATA[Stories by Cuelark on Medium]]></description>
        <link>https://medium.com/@cuelarkofficial?source=rss-5c51d478fcf1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*prqKAHP_rg5pzD1pS9NZuQ.png</url>
            <title>Stories by Cuelark on Medium</title>
            <link>https://medium.com/@cuelarkofficial?source=rss-5c51d478fcf1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:36:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cuelarkofficial/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[How to Extract Pages from a PDF (Mac, Windows, Acrobat, Command Line, or Browser)]]></title>
            <link>https://medium.com/@cuelarkofficial/how-to-extract-pages-from-a-pdf-mac-windows-acrobat-command-line-or-browser-9fbd90cfa1fd?source=rss-5c51d478fcf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fbd90cfa1fd</guid>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[mac]]></category>
            <dc:creator><![CDATA[Cuelark]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 06:38:48 GMT</pubDate>
            <atom:updated>2026-11-30T06:38:48.279Z</atom:updated>
            <content:encoded><![CDATA[<p>How to Extract Pages from a PDF (Mac, Windows, Acrobat, Command Line, or Browser)</p><p>Pull pages like 1, 3–4 and 7 into one new PDF, keep the original untouched, and know which method keeps links and form fields.</p><p>To extract pages from a PDF, select the pages you want (say 1, 3–4 and 7) and save only those as a new file. On a Mac, Command-click their thumbnails in Preview and drag them to the desktop; on Windows, print the PDF from Edge or Chrome to Save as PDF with a custom page range, or use Acrobat Pro, qpdf, or a browser tool.</p><p>This guide is about pulling chosen pages, even ones that aren’t next to each other, into one new PDF. If you want to cut a file into several smaller files instead, see our guide on <a href="https://medium.com/@cuelarkofficial/how-to-split-a-pdf-into-separate-pages-or-page-ranges-45c952d3191c">splitting a PDF into separate pages</a>. We ran the browser tool and every command below on a 10-page sample PDF and checked the pages in each result.</p><h3>Option 1: In your browser, without uploading</h3><p>Our <a href="https://tools.cuelark.com/extract-pdf-pages">extract PDF pages tool</a> reads the file inside the browser tab. While we used it, the only outgoing request was an 834-byte analytics ping, far too small to carry the PDF.</p><ol><li>Drop a PDF on the page, or try the 3-page sample. A thumbnail of every page appears.</li><li>Click the pages you want, or type a range such as 1, 3-4, 7 and press <strong>Select range</strong>. An open end like 8- means page 8 to the last page.</li><li>Click <strong>Extract pages</strong>, then <strong>Download PDF</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ujIB4c0mbBnEjt9f9V-FgA.png" /></figure><p><em>Four of ten pages selected. The download is named report-extracted.pdf.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1keidjsSfewlLrFuIa960w.png" /></figure><p><em>The downloaded file contains exactly the four selected pages.</em></p><p>Pages are copied, not turned into images, so the text stayed selectable in our test. Two limits: the new file always keeps the original order (typing 7, 1 still gave us page 1, then page 7), and password-protected or edit-restricted files have to be saved as an unlocked copy first.</p><h3>Option 2: Mac Preview</h3><p>Preview is built into macOS. Following Apple’s guides to <a href="https://support.apple.com/guide/preview/add-delete-or-move-pdf-pages-prvw11793/mac">moving PDF pages</a> and <a href="https://support.apple.com/guide/preview/combine-pdfs-prvw43696/mac">combining PDFs</a>:</p><ol><li>Open the PDF in Preview and choose View &gt; Thumbnails.</li><li>Click the first page you want, then Command-click each of the others.</li><li>Drag the selected thumbnails out of the sidebar onto the desktop. Preview creates a new PDF containing just those pages.</li></ol><p>Dragging thumbnails inside the sidebar rearranges the open file instead, and Apple warns that Preview saves changes automatically. If you plan to delete or move pages, choose File &gt; Duplicate first.</p><h3>Option 3: Windows with Edge or Chrome</h3><p>Windows has no separate page extractor, but the print dialog in Edge or Chrome does the job.</p><ol><li>Open the PDF in Microsoft Edge or Google Chrome.</li><li>Press Ctrl+P.</li><li>Choose <strong>Save as PDF</strong> as the printer. <strong>Microsoft Print to PDF</strong> also works; <a href="https://www.adobe.com/acrobat/hub/save-one-page-of-a-pdf.html">Adobe’s own guide</a> uses it with Edge.</li><li>Under <strong>Pages</strong>, choose <strong>Custom</strong> and type the pages, such as 1-3, 7. Microsoft&#39;s <a href="https://support.microsoft.com/en-us/edge/print-in-microsoft-edge">Edge print help</a> says Custom takes ranges like 1-5 or pages separated by commas. In Chrome, the box shows the hint &quot;e.g. 1-5, 8, 11-13&quot; (<a href="https://github.com/chromium/chromium/blob/main/chrome/app/printing_strings.grdp">Chromium source</a>; <a href="https://support.google.com/chrome/answer/1069693">Chrome Help</a>).</li><li>Click Save (or Print), then pick a name and folder.</li></ol><p>This route prints the pages into a new file instead of copying them, so if the pages have links or fillable fields, open the result and check that they still work.</p><h3>Option 4: Adobe Acrobat (paid desktop, free online)</h3><p>In Acrobat Pro or Standard on the desktop, choose All tools &gt; Organize pages, select the pages (or type them in the Pages selected field), then choose Extract pages. Leave both boxes, Delete pages after extracting and Extract pages as separate files, unchecked to get one new PDF and keep the original intact. Adobe says extracted pages keep their content, form fields, comments and links, but not bookmarks or article threads (<a href="https://helpx.adobe.com/acrobat/desktop/edit-documents/organize-pages/extract-pages.html">Adobe Help</a>).</p><p>The free Acrobat Reader can’t extract pages, as <a href="https://www.adobe.com/acrobat/hub/save-one-page-of-a-pdf.html">Adobe notes</a>. Adobe’s free <a href="https://www.adobe.com/acrobat/online/extract-pdf-pages.html">online Extract PDF pages tool</a> uploads your file, asks you to sign in, and accepts PDFs up to 500 pages and 100 MB.</p><h3>Option 5: Command line and Python</h3><p>qpdf copies the pages as they are. The . stands for the input file, and the <a href="https://qpdf.readthedocs.io/en/stable/cli.html">page range syntax</a> takes lists, ranges and z for the last page:</p><pre>qpdf report.pdf --pages . 1,3-4,7 -- extracted.pdf</pre><p>Unlike our browser tool, qpdf keeps the order you type, so 7,1 puts page 7 first. Its docs note that document-level data such as bookmarks comes from the primary input, and bookmarks pointing at pages you left out will stop working. Use --empty in place of the input file to drop that data.</p><p>With <a href="https://www.pdflabs.com/docs/pdftk-man-page/">pdftk</a>, separate the ranges with spaces:</p><pre>pdftk report.pdf cat 1 3-4 7 output extracted-pdftk.pdf</pre><p>In Python, <a href="https://pypdf.readthedocs.io/en/stable/user/merging-pdfs.html">pypdf’s</a> append takes a list of page indexes, which start at 0:</p><pre>from pypdf import PdfWriter</pre><pre>writer = PdfWriter()<br># pages 1, 3, 4, 7 are indexes 0, 2, 3, 6<br>writer.append(&quot;report.pdf&quot;, [0, 2, 3, 6])<br>writer.write(&quot;extracted-pypdf.pdf&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*QQf78yG6lYckpbPN7R1IHw.png" /></figure><p><em>Real output with qpdf 12.2.0, pdftk-java 3.3.3 and pypdf 7.2.0. The “pages in file” lines read each page’s label with pdftotext.</em></p><h3>Other online tools</h3><p>Smallpdf has an <a href="https://smallpdf.com/extract-pdf-pages">Extract PDF Pages</a> tool that saves your selection as one PDF or as separate files. It’s free with usage limits, and Smallpdf says uploaded files are deleted after one hour. iLovePDF handles extraction inside <a href="https://www.ilovepdf.com/blog/how-to-extract-pages-from-pdf">Split PDF</a>: pick Extract pages, select pages, and tick the box to merge them into one PDF. Its free plan has limited processing, and Premium is $5 a month billed annually or $9 monthly (<a href="https://www.ilovepdf.com/pricing">pricing</a>). Both upload your file to their servers, which is fine for most documents but worth a thought for contracts or medical records.</p><h3>FAQ</h3><p><strong>Does extracting pages change the original PDF?</strong> Not with any method here, unless you tick Delete pages after extracting in Acrobat or delete pages in Preview’s sidebar.</p><p><strong>Can I extract pages in a different order?</strong> Yes with qpdf, pdftk or pypdf, which follow the order you type. Our browser tool keeps the original order, so reorder the new file afterward if you use it.</p><p><strong>Why does my page number not match the page I get?</strong> qpdf, pdftk, pypdf and our tool count pages from the start of the file, not by the numbers printed on them. A document with a roman-numeral front section can be off by several pages, so check the thumbnails.</p><p><strong>How do I extract pages from a locked PDF?</strong> You need the password. qpdf accepts it with --password. In Acrobat, Adobe suggests checking File &gt; Document Properties &gt; Security for restrictions before you start.</p><p><strong>Can I do this on a phone?</strong> Yes. A browser tool that processes files on the device, such as our <a href="https://tools.cuelark.com/extract-pdf-pages">extract PDF pages tool</a>, works in a mobile browser.</p><p><em>Cuelark Team</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fbd90cfa1fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mid-conversation system reminders with Claude in a React chat: the AI SDK fix that keeps them in…]]></title>
            <link>https://medium.com/@cuelarkofficial/mid-conversation-system-reminders-with-claude-in-a-react-chat-the-ai-sdk-fix-that-keeps-them-in-6abfc4308495?source=rss-5c51d478fcf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6abfc4308495</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Cuelark]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 04:50:23 GMT</pubDate>
            <atom:updated>2026-11-29T04:55:48.181Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mid-conversation system reminders with Claude in a React chat: the AI SDK fix that keeps them in place</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JW6ZZ1qkGkPvvwNP.png" /></figure><p><em>By the Cuelark Team. Sources: AI SDK release notes, PR and docs, and Anthropic’s API docs, checked 29 November 2026. We didn’t call Claude: everything ran against a fake Anthropic endpoint on </em><em>ai@7.0.184 with </em><em>@ai-sdk/anthropic@4.0.111 (and </em><em>4.0.110 for comparison), so it shows the request your app sends, not model output.</em></p><p>Claude can take a role: &quot;system&quot; message in the middle of messages. Prompt caching hashes tools, then system, then messages, and a hit needs that prefix to match byte for byte. Edit the top-level system mid-chat and you lose the cache for everything after it. Append a system message where the new rule applies and the cached prefix stays the same.</p><p>The AI SDK supports this with allowSystemInMessages: true, but until this week one common case misbehaved.</p><h3>What changed in @ai-sdk/anthropic 4.0.111</h3><p>The patch (November 27 UTC) fixes two cases that silently drop a cache breakpoint:</p><ol><li><strong>No leading system message.</strong> With no instructions at the start, the provider promoted the first system message to top-level system, even after user and assistant turns. That&#39;s deliberate for models that reject mid-conversation system messages, but it moves your reminder and its cacheControl to the front, so the breakpoint covers almost nothing.</li><li><strong>Tool-change-only system messages.</strong> A system message with only toolChanges and no text lost its cacheControl, though Anthropic accepts it on tool_addition and tool_removal blocks.</li></ol><p>The fix adds providerOptions.anthropic.midConversationSystemMessages (default false). When true, a later system message stays where you put it. A tool-changes-only message now puts its cacheControl on its last tool change.</p><p>Anthropic lists mid-conversation system messages for Claude Fable 5.2, Mythos 5.2, Fable 5.1, Mythos 5.1, Fable 5, Mythos 5, Opus 5.5, Opus 5, Opus 4.8, Sonnet 5.5 and Haiku 5.5. Claude Sonnet 5 doesn’t. Only enable the option for listed models.</p><h3>Seeing the difference</h3><p>Same history through both versions: user, assistant, user, then a system reminder with cacheControl.</p><pre>const history = [<br>  { role: &#39;user&#39;, content: &#39;Here is our style guide... (long)&#39; },<br>  { role: &#39;assistant&#39;, content: &#39;Got it.&#39; },<br>  { role: &#39;user&#39;, content: &#39;Rewrite the intro.&#39; },<br>  {<br>    role: &#39;system&#39;,<br>    content: &#39;Reply in US English. Keep it under 120 words.&#39;,<br>    providerOptions: { anthropic: { cacheControl: { type: &#39;ephemeral&#39; } } },<br>  },<br>];<br><br>await generateText({<br>  model: anthropic(&#39;claude-opus-5-5&#39;),<br>  allowSystemInMessages: true,<br>  messages: history,<br>  providerOptions: { anthropic: { midConversationSystemMessages: true } },<br>});</pre><p>What the endpoint received:</p><ul><li><strong>4.0.110, with or without the option:</strong> the reminder moved into top-level system, breakpoint and all; messages was user &gt; assistant &gt; user. The unknown option raised no error.</li><li><strong>4.0.111, option off:</strong> same as above. The default didn’t change.</li><li><strong>4.0.111, option on:</strong> no top-level system; messages was user &gt; assistant &gt; user &gt; system, breakpoint on the reminder, so the whole history precedes it.</li></ul><p>For the tool case, a system message containing only toolChanges: [{ type: &#39;tool_addition&#39;, toolName: &#39;exportPdf&#39; }] plus cacheControl. had no breakpoint on 4.0.110. On 4.0.111 it sent {&quot;type&quot;:&quot;tool_addition&quot;,&quot;tool&quot;:{&quot;type&quot;:&quot;tool_reference&quot;,&quot;name&quot;:&quot;exportPdf&quot;},&quot;cache_control&quot;:{&quot;type&quot;:&quot;ephemeral&quot;}}.</p><h3>Wiring it into a useChat app</h3><p>A reminder must sit in the same position on every request, or the prefix stops matching. useChat UI messages don&#39;t include system messages, so</p><pre>// app/api/chat/route.ts<br>import { anthropic } from &#39;@ai-sdk/anthropic&#39;;<br>import { streamText, convertToModelMessages, type UIMessage, type ModelMessage } from &#39;ai&#39;;<br><br>export type ChatMessage = UIMessage&lt;{ reminder?: string }&gt;;<br><br>const cache = { anthropic: { cacheControl: { type: &#39;ephemeral&#39; as const } } };<br><br>export async function POST(req: Request) {<br>  const { messages }: { messages: ChatMessage[] } = await req.json();<br><br>  const modelMessages: ModelMessage[] = [];<br>  for (const m of messages) {<br>    modelMessages.push(...(await convertToModelMessages([m])));<br>    // Put the reminder back right after its user turn on every request.<br>    if (m.role === &#39;user&#39; &amp;&amp; m.metadata?.reminder) {<br>      modelMessages.push({ role: &#39;system&#39;, content: m.metadata.reminder });<br>    }<br>  }<br><br>  // One breakpoint on the newest message covers the whole history.<br>  const last = modelMessages.at(-1)!;<br>  last.providerOptions = { ...last.providerOptions, ...cache };<br><br>  const result = streamText({<br>    model: anthropic(&#39;claude-opus-5-5&#39;),<br>    allowSystemInMessages: true,<br>    messages: modelMessages,<br>    providerOptions: { anthropic: { midConversationSystemMessages: true } },<br>  });<br><br>  return result.toUIMessageStreamResponse();<br>}we store the reminder as metadata on its user message and rebuild it on the server each turn.</pre><p>On the client, a composer checkbox attaches the reminder:</p><pre>const { messages, sendMessage, status } = useChat&lt;ChatMessage&gt;();<br><br>sendMessage({<br>  text: input,<br>  metadata: usEnglish ? { reminder: &#39;Reply in US English from here on.&#39; } : undefined,<br>});</pre><p>We called this handler twice against a fake streaming endpoint, like two useChat turns. On 4.0.111, turn 1 sent user &gt; system with the breakpoint on the reminder; turn 2 sent user &gt; system &gt; assistant &gt; user with the breakpoint on the newest user message. Ignoring cache_control, turn 1&#39;s messages were an exact prefix of turn 2&#39;s, and both streamed back through toUIMessageStreamResponse. On 4.0.110 the reminder moved into top-level system, which also changes its meaning: it now applies to the whole chat, earlier turns included.</p><h3>Honest limits</h3><ul><li><strong>No real model, no real cache.</strong> We checked request shapes, not cache_read_input_tokens. Short chats fall under Anthropic&#39;s minimum cacheable length anyway.</li><li><strong>Use the same setting on every request.</strong> The AI SDK docs warn that toggling midConversationSystemMessages mid-conversation moves the message between system and messages, missing the cache and possibly breaking Anthropic&#39;s prefix check for earlier thinking blocks.</li><li><strong>Placement rules still apply.</strong> Anthropic returns a 400 if a system message doesn’t directly follow a user turn (or an assistant turn ending in a server tool result), or sits between a tool_use and its tool_result.</li><li><strong>Don’t edit sent reminders.</strong> Changing or removing one invalidates the cache from that point. Append a new one instead.</li><li><strong>No browser click-through.</strong> The code type-checks against @ai-sdk/react@4.0.189; we called the handler directly.</li></ul><h3>Sources</h3><ul><li>@ai-sdk/anthropic@4.0.111 release notes: <a href="https://github.com/vercel/ai/releases/tag/%40ai-sdk%2Fanthropic%404.0.111">https://github.com/vercel/ai/releases/tag/%40ai-sdk%2Fanthropic%404.0.111</a></li><li>vercel/ai PR #25551, keep cache control on mid-conversation system messages: <a href="https://github.com/vercel/ai/pull/25551">https://github.com/vercel/ai/pull/25551</a></li><li>AI SDK Anthropic provider docs, Mid-Conversation System Controls: <a href="https://ai-sdk.dev/providers/ai-sdk-providers/anthropic#mid-conversation-system-controls">https://ai-sdk.dev/providers/ai-sdk-providers/anthropic#mid-conversation-system-controls</a></li><li>Anthropic docs, Mid-conversation system messages: <a href="https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages">https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages</a></li><li>Anthropic docs, Models overview: <a href="https://platform.claude.com/docs/en/about-claude/models/overview">https://platform.claude.com/docs/en/about-claude/models/overview</a></li></ul><p>To skip building the chat UI, <a href="https://ui.cuelark.com/">Cuelark UI</a> has shadcn-style chat components that fit this setup.</p><p><em>Originally published at </em><a href="https://dev.to/cuelark/mid-conversation-system-reminders-with-claude-in-a-react-chat-the-ai-sdk-fix-that-keeps-them-in-4j73"><em>https://dev.to</em></a><em> on November 29, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6abfc4308495" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why did my AI chat stop? Using stoppedBy from AI SDK 7 in a React chat]]></title>
            <link>https://medium.com/@cuelarkofficial/why-did-my-ai-chat-stop-using-stoppedby-from-ai-sdk-7-in-a-react-chat-935421ecd009?source=rss-5c51d478fcf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/935421ecd009</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Cuelark]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 04:52:40 GMT</pubDate>
            <atom:updated>2026-11-27T04:59:03.707Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n8NlCpbB-s3QwN8l.png" /></figure><p><em>By the Cuelark Team. Details come from the Vercel AI SDK release notes and docs, checked on 27 November 2026. We didn’t call a real model. Everything below ran against </em><em>MockLanguageModelV4 from </em><em>ai/test on </em><em>ai@7.0.183, so this tests the wiring your app sees, not how any model behaves.</em></p><p>A tool-calling chat can end for very different reasons. The model gave its answer. Your step limit kicked in halfway through a task. A tool is waiting for the user to approve it. Or the model called a tool that only the browser can run. Until now you had to guess which one happened from finishReason, and that field only describes the last model call. A loop that hits its step limit still says tool-calls.</p><p>ai@7.0.181, published November 23 (UTC), adds stoppedBy to the generateText and streamText results, the onEnd callback, and the final finish stream part. Per the AI SDK loop control docs it has four values:</p><ul><li>model: the model finished without tool calls that keep the loop going. Check finishReason to tell stop from length.</li><li>stop-condition: a stopWhen condition was met, such as isStepCount(3).</li><li>tool-without-execute: a tool call needs a result from a tool with no execute function.</li><li>approval: a tool call needs approval.</li></ul><p>The same release adds a per-call onWarning callback. The docs say WorkflowAgent and HarnessAgent don&#39;t report stoppedBy yet.</p><h3>Getting it to the browser</h3><p>stoppedBy lives on the server-side stream. The UI message stream&#39;s finish chunk that useChat reads carries finishReason and messageMetadata, but not stoppedBy. So pass it through message metadata:</p><pre>// app/api/chat/route.ts<br>import { openai } from &#39;@ai-sdk/openai&#39;;<br>import {<br>  streamText, convertToModelMessages, tool, isStepCount,<br>  type UIMessage, type StoppedBy, type FinishReason,<br>} from &#39;ai&#39;;<br>import { z } from &#39;zod&#39;;<br><br>export type ChatMessage = UIMessage&lt;{ stoppedBy?: StoppedBy; finishReason?: FinishReason }&gt;;<br><br>const tools = {<br>  searchDocs: tool({<br>    description: &#39;Search the docs&#39;,<br>    inputSchema: z.object({ query: z.string() }),<br>    execute: async ({ query }) =&gt; ({ hits: [`result for ${query}`] }),<br>  }),<br>  deleteDraft: tool({<br>    description: &#39;Delete a draft&#39;,<br>    inputSchema: z.object({ id: z.string() }),<br>    needsApproval: true,<br>    execute: async ({ id }) =&gt; ({ deleted: id }),<br>  }),<br>  askUser: tool({<br>    description: &#39;Ask the user a clarifying question&#39;,<br>    inputSchema: z.object({ question: z.string() }),<br>    // no execute: the browser answers this one<br>  }),<br>};<br><br>export async function POST(req: Request) {<br>  const { messages }: { messages: ChatMessage[] } = await req.json();<br><br>  const result = streamText({<br>    model: openai(&#39;gpt-6.2-sol&#39;),<br>    messages: await convertToModelMessages(messages),<br>    tools,<br>    stopWhen: isStepCount(3),<br>    onWarning: ({ warnings }) =&gt; console.warn(&#39;model warnings&#39;, warnings),<br>  });<br><br>  return result.toUIMessageStreamResponse&lt;ChatMessage&gt;({<br>    messageMetadata: ({ part }) =&gt;<br>      part.type === &#39;finish&#39;<br>        ? { stoppedBy: part.stoppedBy, finishReason: part.finishReason }<br>        : undefined,<br>  });<br>}</pre><p>On the client, useChat&lt;ChatMessage&gt;() gives you message.metadata.stoppedBy on the last assistant message. Only two cases need new UI:</p><pre>export function LoopStatus({ message, onContinue }: { message: ChatMessage; onContinue: () =&gt; void }) {<br>  const { stoppedBy, finishReason } = message.metadata ?? {};<br>  if (stoppedBy === &#39;stop-condition&#39;) {<br>    return &lt;p&gt;Paused after the step limit. &lt;button onClick={onContinue}&gt;Keep going&lt;/button&gt;&lt;/p&gt;;<br>  }<br>  if (stoppedBy === &#39;model&#39; &amp;&amp; finishReason === &#39;length&#39;) {<br>    return &lt;p&gt;The answer hit the length limit and may be cut off.&lt;/p&gt;;<br>  }<br>  return null; // approval and client-side tools already show up as tool parts<br>}</pre><p>We wire onContinue to sendMessage({ text: &#39;Continue where you left off.&#39; }). The approval and client-side tool cases already appear as tool parts in approval-requested and input-available states, so those parts can render their own buttons.</p><h3>What the test showed</h3><p>We ran six scripted scenarios through the route handler above (with the mock model swapped in) and read each response the way useChat does, using parseJsonEventStream and readUIMessageStream.</p><pre>Scenario                    Model calls  stoppedBy             finishReason<br>Plain answer                1            model                 stop<br>Cut off by max tokens       1            model                 length<br>Three searches, limit of 3  3            stop-condition        tool-calls<br>Delete needs approval       1            approval              tool-calls<br>askUser (no execute)        1            tool-without-execute  tool-calls</pre><p>The last three rows are the point. finishReason is the same in all three, while stoppedBy tells them apart. The metadata arrived on the client every time.</p><p>The sixth scenario had the mock return a provider warning. With onWarning set, the callback got {&quot;type&quot;:&quot;unsupported&quot;,&quot;feature&quot;:&quot;temperature&quot;} and nothing was printed. Without it, the same warning went to the global warning logger. That matches the streamText reference, which says warnings skip that logger when onWarning is set.</p><h3>The other change: a 64 MiB cap per streamed event</h3><p>@ai-sdk/provider-utils@5.0.84 (November 25, UTC) fixed a crash risk. Before, parseJsonEventStream buffered a server-sent event with no size limit, so a stream that never finished an event could use up memory. Now a single event is capped at 67,108,864 characters. Per the release notes, this cap also covers the streams useChat and useCompletion read. 5.0.85 a day later let the OpenAI and xAI Responses models accept events of up to 512 MiB, because response.completed repeats every output item, including base64 images.</p><p>We pushed one SSE event through parseJsonEventStream with the UI message chunk schema:</p><ul><li>A 10 MiB text delta parsed fine.</li><li>A 70 MiB delta failed with ParseError: Buffered data exceeded max buffer size of 67108864 characters.</li><li>The same 70 MiB delta passed with maxEventSize raised to 128 MiB.</li></ul><p>For a chat app, the practical rule is to keep big payloads out of single events. If a tool returns a generated file, send a URL in the tool output instead of base64. In ai@7.0.183, we found no maxEventSize option on DefaultChatTransport, so you can&#39;t raise the cap from useChat.</p><h3>Honest limits</h3><ul><li><strong>No real model.</strong> These results show what the SDK sends and reports. They don’t show how often a real model hits your step limit.</li><li><strong>The browser UI wasn’t exercised.</strong> The route and the React components type-check against @ai-sdk/react@4.0.188, and the stream was read with the same parser useChat uses. We didn&#39;t click through a rendered page.</li><li><strong>“Keep going” is a new turn.</strong> It sends another user message, which costs another model call with the full history.</li><li><strong>Patch-level features.</strong> stoppedBy is optional in the types, so treat undefined as &quot;unknown&quot; if you share code with older versions or agents that don&#39;t report it yet.</li></ul><h3>Sources</h3><p>If you’d rather not build the message list and tool-status rows yourself, <a href="https://ui.cuelark.com/">Cuelark UI</a> has shadcn-style AI chat components that fit this setup.</p><p><em>Originally published at </em><a href="https://dev.to/"><em>https://dev.to</em></a><em> on November 27, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=935421ecd009" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What does a 100 KB or 1 MB cap do to a PDF? We tested text, photos and scans (Nov 2026)]]></title>
            <link>https://medium.com/@cuelarkofficial/what-does-a-100-kb-or-1-mb-cap-do-to-a-pdf-we-tested-text-photos-and-scans-nov-2026-97e85374be92?source=rss-5c51d478fcf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/97e85374be92</guid>
            <category><![CDATA[ghostscript]]></category>
            <category><![CDATA[compression]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[file-size]]></category>
            <category><![CDATA[web-performance]]></category>
            <dc:creator><![CDATA[Cuelark]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 04:22:36 GMT</pubDate>
            <atom:updated>2026-11-27T04:22:36.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Source tulip crop versus the 100 KB cap" src="https://cdn-images-1.medium.com/max/1000/1*mTQeuOZpwL6xXm9GqH2tCA.png" /></figure><p><em>By the Cuelark Team. Measured on 27 November 2026, between 08:44:42 and 09:09:39 AM IST (Asia/Calcutta). Disclosure: we make Cuelark Tools, including a </em><a href="https://tools.cuelark.com/compress-pdf-to-100kb"><em>browser-based PDF compressor that aims at a 100 KB cap</em></a><em>. This study measures Ghostscript on the command line, not our website and not other online tools. Every number comes from the run described below.</em></p><p>Job portals, university forms and many mail systems still ask for a PDF under 100 KB, 200 KB, 500 KB or 1 MB. Those caps are easy to state and hard to meet once a file contains photographs or a scan. The usual advice is to pick a Ghostscript preset — /screen for “screen quality,” /ebook for a smaller reading file, /printer if you still need print. We wanted a measured answer to a tighter question: at a fixed byte budget, what happens to page quality, and does that depend on whether the PDF is text, photographs, a mix, or a scan?</p><p>We built four A4 PDFs and compressed each one with three Ghostscript distiller presets and with a size-aware search aimed at 100,000, 200,000, 500,000 and 1,000,000 bytes. Quality was scored with SSIM (structural similarity) on 150 DPI page rasters. We also checked whether pdftotext could still read the same words after compression.</p><p>This is the original write-up of that run. The citable tables, charts, method and a download of the measurements live on <a href="https://tools.cuelark.com/guides/pdf-quality-at-size-caps">the Cuelark Tools data page</a>.</p><h3>The short answer</h3><ul><li><strong>A text-only PDF was already under every cap we tested.</strong> Our 12-page text file was 14,958 bytes. Copying it beat compressing it: /printer actually made it larger (31,550 bytes). Every preset kept selectable text and a mean SSIM of 0.993 (worst page 0.976).</li><li><strong>On a photo PDF, a size-aware 100 KB pick beat Ghostscript </strong><strong>/screen on both size and worst-page quality.</strong> The 100,000-byte search produced a 78,881-byte file with mean SSIM 0.909 and worst-page SSIM 0.872. /screen was 266,395 bytes — over the 100 KB and 200 KB caps — with a worse worst-page SSIM of 0.838.</li><li><strong>Mean SSIM on a mixed file hides the photo pages.</strong> At the 100 KB cap our mixed text-and-photo PDF scored a mean SSIM of 0.974, but the two photo pages scored 0.947 and 0.872 (mean 0.909) — the same, to three decimals, as the photos-only file. The six text pages stayed at 0.996 mean (worst 0.977). If you only look at the document average, you will think the photographs survived better than they did.</li><li><strong>A 200 DPI image-only scan would not fit in 100 KB or 200 KB.</strong> The smallest file in our grid was 268,921 bytes, with mean SSIM 0.838 and worst-page SSIM 0.796. /screen fitted a 500 KB cap (502,083 bytes, mean SSIM 0.893) but not a 200 KB cap. /ebook and /printer barely recompressed the already-JPEG pages and stayed near 3.8 MB with SSIM 1.000.</li></ul><p>In this article, 1 KB is 1,000 bytes and 1 MB is 1,000,000 bytes. SSIM is reported to three decimals. 1.000 means the 150 DPI rasters are identical.</p><h3>What we compressed</h3><pre>Text<br>  Pages: 12<br>  Source size: 14,958 B<br>  Words (pdftotext): 1,902<br>  What it is: Selectable text, no photographs</pre><pre>Photos<br>  Pages: 4<br>  Source size: 18,408,857 B<br>  Words (pdftotext): 62<br>  What it is: Two CC BY-SA 4.0 photographs, each used twice, plus short captions</pre><pre>Mixed<br>  Pages: 8<br>  Source size: 18,421,507 B<br>  Words (pdftotext): 3,016<br>  What it is: Text pages plus the same two photographs on pages 3 and 6</pre><pre>Scan<br>  Pages: 8<br>  Source size: 4,717,826 B<br>  Words (pdftotext): 0<br>  What it is: Image-only 200 DPI JPEGs of the mixed file, no text layer</pre><p>The photographs are Frank Schulenburg’s Golden Gate Bridge picture and Elena.laps’ tulips at Keukenhof, both <a href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a>. They are the same source files as in our 25 November 2026 100 KB image-quality study. Hashes and links are in the dataset’s sources.json. reportlab wraps JPEGs as ASCII85+DCT, so the photo and mixed PDFs are larger than the JPEGs alone; the sizes above are the PDF sources we actually compressed.</p><h3>File size after compression</h3><figure><img alt="Log-scale bar chart of compressed PDF sizes for text, photos, mixed and scan fixtures, with 100 KB and 1 MB reference lines" src="https://cdn-images-1.medium.com/max/1024/1*uuOjGZ4soPEn4YR4mOYhig.png" /><figcaption>Compressed size for each fixture and method. The axis is logarithmic. Dashed lines mark 100 KB and 1 MB. Methods that miss a cap are still plotted at their real size.</figcaption></figure><p>The text file is a flat line near 15 KB. The photo and mixed files are almost the same size as each other: the photographs dominate the byte count. The scan starts smaller than the photo PDF (the page images are already 200 DPI JPEGs) but it does not shrink as willingly. /ebook and /printer leave it close to the source.</p><h3>Quality after compression</h3><figure><img alt="Bar chart of mean SSIM for each fixture and method, with dots for the worst page" src="https://cdn-images-1.medium.com/max/1024/1*3Z7C5SWEy6UFbiYeacm08g.png" /><figcaption>Mean SSIM at 150 DPI for each fixture and method. The dot on each bar is the worst page. Higher is better.</figcaption></figure><h3>Ghostscript presets</h3><pre>Text<br>  /screen: 14,388 B, SSIM 0.993 (min 0.976)<br>  /ebook: 14,288 B, SSIM 0.993 (min 0.976)<br>  /printer: 31,550 B, SSIM 0.993 (min 0.976)</pre><pre>Photos<br>  /screen: 266,395 B, SSIM 0.898 (min 0.838)<br>  /ebook: 1,218,451 B, SSIM 0.942 (min 0.936)<br>  /printer: 7,480,073 B, SSIM 0.979 (min 0.959)</pre><pre>Mixed<br>  /screen: 276,055 B, SSIM 0.972 (min 0.838)<br>  /ebook: 1,228,073 B, SSIM 0.983 (min 0.936)<br>  /printer: 7,498,607 B, SSIM 0.992 (min 0.959)</pre><pre>Scan<br>  /screen: 502,083 B, SSIM 0.893 (min 0.858)<br>  /ebook: 3,775,981 B, SSIM 1.000 (min 1.000)<br>  /printer: 3,779,207 B, SSIM 1.000 (min 1.000)</pre><p>/screen is the only preset that gets the photo PDF near a form-upload budget, and it still misses 100 KB and 200 KB. /ebook on the photo file is already over 1 MB (1,218,451 bytes). /printer on the text file is <em>larger</em> than the source, because the distiller rewrote a small, already-efficient file.</p><h3>Size-aware caps</h3><p>For each cap we ran a grid of Ghostscript colour-image resolutions (300, 200, 150, 100, 72 DPI) and JPEG QFactor values (0.15, 0.30, 0.50, 1.00, 1.50, 2.00; a smaller QFactor is higher JPEG quality). We kept the candidate that fitted the cap with the highest mean SSIM, breaking ties in favour of the larger file. If nothing fitted, we copied the smallest grid file and marked the cap as a miss.</p><pre>Text<br>  ≤100 KB: 14,958 B (copy), SSIM 1.000<br>  ≤200 KB: same copy<br>  ≤500 KB: same copy<br>  ≤1 MB: same copy</pre><pre>Photos<br>  ≤100 KB: 78,881 B, SSIM 0.909 (min 0.872)<br>  ≤200 KB: 158,055 B, SSIM 0.947 (min 0.929)<br>  ≤500 KB: 403,016 B, SSIM 0.970 (min 0.960)<br>  ≤1 MB: 947,600 B, SSIM 0.975 (min 0.972)</pre><pre>Mixed<br>  ≤100 KB: 88,539 B, SSIM 0.974 (min 0.872)<br>  ≤200 KB: 167,713 B, SSIM 0.984 (min 0.929)<br>  ≤500 KB: 412,674 B, SSIM 0.990 (min 0.960)<br>  ≤1 MB: 957,258 B, SSIM 0.991 (min 0.972)</pre><pre>Scan<br>  ≤100 KB: did not fit (268,921 B, SSIM 0.838, min 0.796)<br>  ≤200 KB: did not fit (same 268,921 B file)<br>  ≤500 KB: 376,781 B, SSIM 0.850 (min 0.812)<br>  ≤1 MB: 972,115 B, SSIM 0.901 (min 0.874)</pre><p>The photo 100 KB file came from grid settings r100 and QFactor 1.50. The 1 MB photo file came from r200 and QFactor 0.15. The scan’s smallest grid file was r72 and QFactor 2.00 — the roughest cell in the grid — and it was still 268,921 bytes. The scan file that fitted 500 KB came from r72 and QFactor 1.00; the 1 MB scan file came from r100 and QFactor 0.50.</p><p>Word counts survived on every text, photo and mixed method in the tables: 1,902/1,902, 62/62 and 3,016/3,016. The scan has no text layer, so there was nothing for pdftotext to recover (both counts were zero). If you need words from a scan, you need OCR, not a more generous JPEG QFactor. <a href="https://tools.cuelark.com/pdf-to-text">Cuelark’s PDF-to-text tool</a> extracts already-selectable text; it will not invent a text layer on a scan like this one.</p><h3>Mean scores hide the photo pages</h3><p>The mixed 100 KB row looks excellent if you only read the mean: 0.974. Split by page type, it is a different file. The six text pages have mean SSIM 0.996 (worst 0.977). The two photo pages have mean SSIM 0.909 and worst-page SSIM 0.872 — the same, to three decimals, as the photos-only file at the same settings. The 1 MB mixed file shows the same pattern: overall mean 0.991, photo-page mean 0.975 (min 0.972).</p><p>That is why we published per-page scores. A mixed “average quality” figure is mostly a count of how many text pages you have.</p><h3>What the photographs look like</h3><p>The crops below are from page 2 of the photos fixture, Elena.laps’ tulips at Keukenhof (<a href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a>). The two tulip pages were consistently the weaker pages; the Golden Gate pages held up better. At the 100 KB cap, the bridge pages scored SSIM 0.947 and the tulip pages scored 0.872.</p><figure><img alt="Side-by-side crops of the tulip photo: the source PDF, a 1 MB cap, a 100 KB cap, and Ghostscript /screen" src="https://cdn-images-1.medium.com/max/1024/1*1uBV84I33unwIV6upVecqA.png" /><figcaption>Tulip photo, page 2 of the photos fixture, left to right: the source PDF; the ≤1 MB pick (947,600 B, this page SSIM 0.972); the ≤100 KB pick (78,881 B, this page SSIM 0.872); and Ghostscript /screen (266,395 B, this page SSIM 0.838). Photograph by Elena.laps, CC BY-SA 4.0.</figcaption></figure><p>The 1 MB cap is close to the source at a normal reading size. The 100 KB cap is softer and flatter, but it is still a clearer crop than /screen, and it is less than a third of /screen’s size. /screen is the wrong default if the cap is 100 KB: it misses the cap and damages the hardest page more than a search that is aimed at the cap.</p><p>The 100 KB photo file is 233.4 times smaller than the 18,408,857-byte source (18,408,857 ÷ 78,881). That is a real saving. It is also a real quality loss. We would not call SSIM 0.872 “visually lossless.”</p><h3>Method</h3><p>We measured this on 27 November 2026, from 08:44:42 to 09:09:39 AM IST (Asia/Calcutta), on one Linux machine.</p><ul><li><strong>Encoder:</strong> Ghostscript 10.05.1 (GPL), pdfwrite device. Presets were -dPDFSETTINGS=/screen, /ebook and /printer. The size-cap grid set ColorImageResolution and Distiller QFactor through setdistillerparams. (The JPEGQ switch is not accepted by this Ghostscript build.)</li><li><strong>Caps:</strong> 100,000, 200,000, 500,000 and 1,000,000 bytes. For each cap, every grid file at or under the cap was a candidate. We chose the highest mean SSIM, then the largest file if two means tied. If nothing fitted, we copied the smallest grid file and recorded fits=false.</li><li><strong>Viewing size:</strong> each page of the source and of the compressed file was rasterised with Poppler 25.03.0 pdftoppm at 150 DPI. Pages were forced to the same pixel size, then compared with ImageMagick 7.1.1-43 magick compare for SSIM and PSNR. We report mean SSIM across pages and the worst page.</li><li><strong>Text survival:</strong> pdftotext word counts on the source and on the compressed file. We counted a file as having survived if the ratio was at least 0.95, or if both counts were zero.</li><li><strong>Fixtures:</strong> built with reportlab 5.1.0. The scan is a 200 DPI JPEG image of each mixed page, wrapped as a PDF with pikepdf 10.17.0, with no text layer.</li></ul><p>PSNR is in the raw CSV, but it is not the headline metric. On this ImageMagick build, two identical rasters print 0 (0) rather than inf, and a Ghostscript rewrite of a text page can show a PSNR around 25 dB even when SSIM is 0.977–1.000, because font rasterisation shifts slightly. SSIM did not have that problem, so we ranked and published on SSIM. The notes file in the dataset spells this out.</p><h3>Limits of this run</h3><p>This is one encoder, one grid, four fixtures, one viewing resolution. We did not test other tools, other Ghostscript versions, jbig2 or color-to-gray conversions, or a human rater. A different photograph, a sharper scan, or a cap of 50 KB could change the winner. The scan result is not a claim that “no scan can fit in 200 KB”; it is a claim that <em>this</em> 200 DPI, eight-page, colour JPEG scan did not fit in our grid.</p><p>We also did not score “will this file be accepted by a particular portal.” Some portals recode what you upload. Some count 1 KB as 1,024 bytes. Our caps are 1,000-byte kilobytes.</p><h3>Dataset</h3><p>You can download the measurements, the encoder versions, the fixture manifest, and text.pdf from <a href="https://tools.cuelark.com/guides/pdf-quality-at-size-caps">the data page</a>. The photo and mixed source PDFs are large and rebuildable from the credited photographs with the scripts in that zip.</p><p><em>Cuelark Tools is a set of browser-based file tools. If you need to aim a PDF at a 100 KB cap in the browser, that tool is </em><a href="https://tools.cuelark.com/compress-pdf-to-100kb"><em>compress-pdf-to-100kb</em></a><em>. This article is about the Ghostscript measurements above, not a benchmark of that page.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97e85374be92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Invert the Colors of an Image (Online, Photoshop, GIMP, or Code)]]></title>
            <link>https://medium.com/@cuelarkofficial/how-to-invert-the-colors-of-an-image-online-photoshop-gimp-or-code-bc3233d81528?source=rss-5c51d478fcf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc3233d81528</guid>
            <category><![CDATA[photography]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[photoshop]]></category>
            <category><![CDATA[image-editing]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Cuelark]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 06:39:28 GMT</pubDate>
            <atom:updated>2026-11-26T06:39:28.065Z</atom:updated>
            <content:encoded><![CDATA[<p>Make a true negative, keep transparency, flip a chart to dark without wrecking its colors, and know why film scans need more than Invert.</p><p>To invert an image, every red, green and blue value becomes 255 minus its old value, so white turns black, red turns cyan and blue turns yellow. You can do it in a browser tool, in Photoshop (Image &gt; Adjustments &gt; Invert), in GIMP (Colors &gt; Invert), or with one line of ImageMagick or Python.</p><p>Below are the steps for each, plus three cases where a plain invert gives the wrong result: transparent PNGs, screenshots you want in dark mode, and scanned film negatives.</p><h3>What “invert” actually does</h3><p>Adobe’s <a href="https://helpx.adobe.com/photoshop/using/applying-special-color-effects-images.html">Photoshop help</a> describes it as converting each pixel’s brightness to the opposite value on the 0 to 255 scale: 255 becomes 0, and 5 becomes 250. <a href="https://docs.gimp.org/3.2/en/gimp-filter-invert-perceptual.html">GIMP’s documentation</a> adds that hues are replaced by their complementary colors.</p><p>That math is exact, so inverting twice gets you back to the start, as long as the file is lossless. We inverted a PNG chart twice with ImageMagick and got back identical pixels. We did the same with a JPG saved at quality 90 after each step, and 31% of pixels came back slightly different (by up to 39 levels). Invert a PNG or your original, not a JPG that’s been saved over and over.</p><h3>Option 1: In your browser</h3><p>Our <a href="https://tools.cuelark.com/invert-image">invert image tool</a> runs in the browser tab, so nothing is uploaded. We watched the network requests while converting and saw no image data leave the page.</p><ol><li>Drop in one or more images (JPG, PNG, WebP, HEIC, AVIF, GIF or BMP), or paste one.</li><li>Keep <strong>Invert colors</strong> selected. The preview updates right away.</li><li>Optional: lower the strength, or untick Red, Green or Blue to invert only some channels.</li><li>Click <strong>Download PNG</strong> (JPG and WebP are also offered), or download all images as a ZIP.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*xSZB9IeWjr45OaVW7isUcg.png" /></figure><p><em>Two test files loaded. The chart has been inverted at 100% strength on all three channels.</em></p><p>We checked the downloaded PNG against our own 255-minus-value calculation and it matched pixel for pixel.</p><h3>Option 2: Photoshop or GIMP</h3><p><strong>Photoshop.</strong> Choose Layer &gt; New Adjustment Layer &gt; Invert, or click the Invert icon in the Adjustments panel. Image &gt; Adjustments &gt; Invert also works, but Adobe notes it changes the layer directly instead of adding an adjustment you can switch off (<a href="https://helpx.adobe.com/photoshop/using/applying-special-color-effects-images.html">Adobe help</a>).</p><p><strong>GIMP (free).</strong> Use Colors &gt; Invert. GIMP also has Colors &gt; Linear Invert, which inverts in linear light and leaves the alpha channel alone (<a href="https://docs.gimp.org/3.2/en/gimp-filter-invert-linear.html">GIMP docs</a>). The difference shows in the midtones: for an sRGB image, mid-gray (128) becomes 127 with Invert but about 229 with Linear Invert, by the standard sRGB conversion math. Try both and keep the one that looks right.</p><h3>Option 3: Command line and code</h3><p>ImageMagick’s <a href="https://imagemagick.org/command-line-options/#negate">-negate</a> replaces each pixel with its complementary color:</p><pre>magick input.jpg -negate output.jpg</pre><p>For transparent PNGs, add -channel RGB. In our test with ImageMagick 7.1.1-43, plain -negate also flipped the alpha channel, so the logo vanished and the empty background turned solid white:</p><pre>magick logo.png -channel RGB -negate logo-inverted.png</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*SwqhlKw3dXSPbBRyZGbcCQ.png" /></figure><p><em>Same transparent PNG, two commands. Only the second keeps the transparency.</em></p><p>In Python, Pillow’s ImageOps.invert works on RGB and grayscale images. The <a href="https://pillow.readthedocs.io/en/stable/reference/ImageOps.html">ImageOps docs</a> warn that most of its operators only work on L and RGB images, and on Pillow 13.0.0 an RGBA image raised OSError: not supported for mode RGBA. Split off the alpha channel first:</p><pre>from PIL import Image, ImageOps<br><br>im = Image.open(&quot;logo.png&quot;).convert(&quot;RGBA&quot;)<br>r, g, b, a = im.split()<br>rgb = ImageOps.invert(Image.merge(&quot;RGB&quot;, (r, g, b)))<br>Image.merge(&quot;RGBA&quot;, (*rgb.split(), a)).save(&quot;logo-inverted.png&quot;)</pre><p>On a web page, CSS filter: invert(1) inverts an element on screen without touching the file. MDN lists it as widely available across browsers since September 2016, and values between 0 and 100% give a partial invert (<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/invert">MDN</a>).</p><h3>When a plain invert is the wrong tool</h3><h3>Screenshots and charts for a dark page</h3><p>A plain negative changes every hue. On our sample chart, the blue line turned orange, the green line turned magenta and the red bars turned teal, so the legend and any text that names a color no longer match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7iG-v-eVgYbCInG1TQrxhA.png" /></figure><p><em>Left to right: original, plain invert, and a lightness flip that keeps each hue.</em></p><p>The fix is to flip only lightness and keep hue and saturation (an HSL lightness flip). The browser tool calls this <strong>Dark mode (keep colors)</strong>. If you made the chart yourself, re-exporting it with a dark theme usually looks best.</p><h3>Scanned color film negatives</h3><p>Color negative film has an orange base. Adobe states that, because of this orange mask, the Invert adjustment can’t make accurate positives from scanned color negatives. Here’s what that looks like on a simulated negative we made from a <a href="https://commons.wikimedia.org/wiki/File:Commodore_Grace_M._Hopper,_USN_(covered).jpg">public domain portrait of Grace Hopper</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRGSxN-Ma_Jed6BeT8lrbQ.png" /><figcaption>Plain invert leaves a blue cast. Stretching each channel on its own removes most of it.</figcaption></figure><p>After a plain invert, the average blue level was more than twice the red level. Stretching each channel separately (we clipped the darkest and brightest 0.5%) brought the averages back within about 0.01 of the original photo. The browser tool’s <strong>Film negative to photo</strong> effect does this kind of per-channel stretch. Crop off the film border first, because the bright rebate skews the balance. For a serious archive, use your scanner software’s color negative mode, which is what Adobe recommends.</p><h3>Screen invert is not the same thing</h3><p>Invert settings on your computer change the display, not the file. On a Mac, System Settings &gt; Accessibility &gt; Display &gt; Invert colors has a Smart mode, which skips images and video, and a Classic mode, which inverts everything (<a href="https://support.apple.com/guide/mac-help/adjust-the-display-colors-mchl11ddd4b3/mac">Apple Support</a>). Windows has Settings &gt; Accessibility &gt; Color filters &gt; Inverted, and Magnifier can invert with Ctrl+Alt+I (<a href="https://support.microsoft.com/en-us/accessibility/windows/use-color-and-contrast-for-accessibility-in-microsoft-365">Microsoft Support</a>). They’re good for reading at night, but the picture you save or send keeps its original colors.</p><h3>FAQ</h3><p><strong>Is inverting an image reversible?</strong> Yes, a full invert of a lossless file is its own opposite. Partial strengths, lightness flips and film conversions aren’t exactly reversible, so keep the original.</p><p><strong>Why did my transparent PNG turn into a white box?</strong> Either the tool inverted the alpha channel too (ImageMagick without -channel RGB), or you saved as JPG, which has no transparency. Save as PNG or WebP.</p><p><strong>How do I invert just part of an image?</strong> Select the area first in Photoshop or GIMP, then run Invert. Only the selection changes.</p><p><strong>Can I invert a photo on my phone without an app?</strong> Yes. A browser tool that processes files on your device, like our <a href="https://tools.cuelark.com/invert-image">invert image tool</a>, works in a mobile browser. The phone’s accessibility invert setting only changes the screen.</p><p><strong>What’s the difference between Invert and Linear Invert in GIMP?</strong> Invert flips the stored pixel values, while Linear Invert flips them in linear light and leaves alpha untouched. Linear Invert makes midtones much lighter, so a gray photo looks washed out rather than dark.</p><p><em>Cuelark Team</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc3233d81528" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What does a 100 KB cap do to image quality? We tested JPEG, WebP, AVIF and JPEG XL (Nov 2026)]]></title>
            <link>https://medium.com/@cuelarkofficial/what-does-a-100-kb-cap-do-to-image-quality-we-tested-jpeg-webp-avif-and-jpeg-xl-nov-2026-927e054a723e?source=rss-5c51d478fcf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/927e054a723e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[compression]]></category>
            <category><![CDATA[jpeg]]></category>
            <dc:creator><![CDATA[Cuelark]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 05:51:58 GMT</pubDate>
            <atom:updated>2026-11-25T05:58:01.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Golden Gate Bridge cover image for the 100 KB image quality study" src="https://cdn-images-1.medium.com/max/1000/1*iqYrJ5HINF1tp7ZuX-MdJw.png" /></figure><p><em>By the Cuelark Team. Measured on 25 November 2026, between 11:05 and 11:11 AM IST. Disclosure: we make Cuelark Tools, including a browser-based compressor that aims at a file-size cap. This study measures command-line encoders, not our website and not other online tools. Every number comes from the run described below.</em></p><p>Job portals, exam forms and many mail systems still ask for a photo under 100 KB. That is a tight budget: a 2,400-pixel picture as a PNG is several megabytes, so 100 KB is often a 50-to-1 cut. The usual advice is “just lower the quality.” We wanted a measured answer to a fairer question: <strong>at the same 100,000-byte cap, which format and which strategy keep the most quality, and does that depend on the picture?</strong></p><p>We compressed five pictures — two photographs, a screenshot, a flat graphic and a text form — with JPEG, WebP, AVIF, JPEG XL and lossless PNG. We used two strategies: change quality only, and allow a resize first. Quality was scored with SSIM (and PSNR) at a shared 800-pixel viewing width.</p><h3>The short answer</h3><figure><img alt="Best SSIM at or under 100,000 bytes for each format and picture" src="https://cdn-images-1.medium.com/max/1024/1*mCTWifV1piNLHFC8WkQvsA@2x.png" /></figure><ul><li><strong>On both photographs, shrinking the picture and then raising quality beat crushing quality at full size, in every format.</strong> The gap was largest for JPEG on the tulip photo: SSIM 0.756 at full size (quality 4) versus 0.864 after a resize to 1,200 px.</li><li><strong>No single format won every picture.</strong> On the bridge photo, JPEG XL after a resize to 800 px kept the most quality (SSIM 0.980). On the tulip close-up, AVIF won (0.912); JPEG XL (0.863) was level with JPEG (0.864).</li><li><strong>If a lossless PNG already fits, use it.</strong> Our screenshot was 90.7 KB as PNG and our graphic was 55.1 KB, both with SSIM 1.000. Lossy compression is unnecessary there. JPEG XL at quality 100 also produced a pixel-identical copy of the screenshot, in 43.8 KB — about half the PNG.</li><li><strong>Lossless PNG is a poor way to force a photo under 100 KB.</strong> The bridge photo only fitted as PNG at 300 px (SSIM 0.833). The tulip photo needed 200 px (SSIM 0.553). The form needed 300 px (SSIM 0.734). All three scores are well below the best lossy results.</li></ul><h3>Results table</h3><p>The cap is <strong>100,000 bytes</strong> (100 KB, not 102,400). “Best under the cap” is the resize-and-quality search described in the method: we try several widths, at each width we take the highest encoder quality that still fits, and we keep the candidate with the highest SSIM at 800 px wide. SSIM is shown to three decimals; bytes are exact.</p><h3>Best result at or under 100,000 bytes</h3><pre>Bridge photo<br>  JPEG: 0.954, 99,902 B, 800×450, q=90<br>  WebP: 0.964, 93,594 B, 800×450, q=92<br>  AVIF: 0.969, 99,456 B, 1,000×563, q=76<br>  JPEG XL: 0.980, 93,833 B, 800×450, q=92 (best)<br>  PNG: Did not fit at 400 px or larger</pre><pre>Tulip photo<br>  JPEG: 0.864, 99,693 B, 1,200×975, q=18<br>  WebP: 0.899, 99,358 B, 800×650, q=43<br>  AVIF: 0.912, 97,187 B, 800×650, q=46 (best)<br>  JPEG XL: 0.863, 99,559 B, 800×650, q=71<br>  PNG: Did not fit at 400 px or larger</pre><pre>Screenshot<br>  JPEG: 0.996, 99,423 B, 1,400×788, q=90<br>  WebP: 0.998, 98,336 B, 1,920×1,080, q=99<br>  AVIF: 0.998, 71,475 B, 1,920×1,080, q=100<br>  JPEG XL: 1.000 (lossless), 43,839 B, 1,920×1,080, q=100 (best)<br>  PNG: 1.000, 90,674 B, 1,920×1,080 (best)</pre><pre>Graphic<br>  JPEG: 0.986, 99,956 B, 1,400×1,050, q=66<br>  WebP: 0.994, 98,632 B, 1,600×1,200, q=94<br>  AVIF: 0.996, 43,701 B, 1,600×1,200, q=100<br>  JPEG XL: 0.996, 92,172 B, 800×600, q=98<br>  PNG: 1.000, 55,109 B, 1,600×1,200 (best)</pre><pre>Form page<br>  JPEG: 0.891, 96,990 B, 1,240×1,754, q=29<br>  WebP: 0.914, 98,398 B, 1,240×1,754, q=45<br>  AVIF: 0.915, 93,857 B, 848×1,200, q=70 (best)<br>  JPEG XL: 0.898, 96,292 B, 848×1,200, q=80<br>  PNG: Did not fit at 400 px or larger</pre><p>(best) marks the highest SSIM for that picture. For the screenshot, JPEG XL and PNG are both lossless; JPEG XL is just smaller. For the graphic, PNG is the only lossless result and the highest SSIM.</p><h3>Quality only, at the original size</h3><p>This is the “lower the quality slider and leave the pixels alone” path.</p><pre>Bridge photo<br>  JPEG: 0.901, 99,498 B, q=11<br>  WebP: 0.942, 99,216 B, q=8<br>  AVIF: 0.959, 97,212 B, q=29<br>  JPEG XL: 0.962, 97,562 B, q=19<br>  PNG: 4,708,142 B, does not fit</pre><pre>Tulip photo<br>  JPEG: 0.756, 81,642 B, q=4<br>  WebP: 0.810, 91,746 B, q=0<br>  AVIF: 0.888, 94,154 B, q=13<br>  JPEG XL: 0.812, 96,028 B, q=3<br>  PNG: 8,759,866 B, does not fit</pre><pre>Screenshot<br>  JPEG: 0.995, 99,703 B, q=68<br>  WebP: 0.998, 98,336 B, q=99<br>  AVIF: 0.998, 71,475 B, q=100<br>  JPEG XL: 1.000, 43,839 B, q=100<br>  PNG: 90,674 B, fits</pre><pre>Graphic<br>  JPEG: 0.981, 99,933 B, q=51<br>  WebP: 0.994, 98,632 B, q=94<br>  AVIF: 0.996, 43,701 B, q=100<br>  JPEG XL: 0.994, 98,376 B, q=79<br>  PNG: 55,109 B, fits</pre><pre>Form page<br>  JPEG: 0.891, 96,990 B, q=29<br>  WebP: 0.914, 98,398 B, q=45<br>  AVIF: 0.906, 89,362 B, q=50<br>  JPEG XL: 0.879, 99,672 B, q=50<br>  PNG: 781,946 B, does not fit</pre><p>The tulip JPEG at quality 4 is already under the cap (81,642 bytes) and still looks poor. Spending the leftover bytes would have meant a higher quality, but quality 5 was over 100,000 bytes, so 4 was the highest setting that fitted.</p><h3>What the pictures look like</h3><p>The cover and the bridge-photo crops use Frank Schulenburg’s Golden Gate photograph, <a href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a>. The tulip crops use Elena.laps’ Keukenhof photograph, same licence. Links are in the method.</p><figure><img alt="Tulip photo crops: original, full-size JPEG at quality 4, resized JPEG, and resized AVIF" src="https://cdn-images-1.medium.com/max/1024/1*eqJBa1E73vd1jNoYx17_iw.png" /></figure><p>On the tulip photo, full-size JPEG at quality 4 smears the petals and the grass. Resizing to 1,200 px and encoding at quality 18 is clearly cleaner, and AVIF at 800 px is cleaner still. Even the best result (SSIM 0.912) is a long way from perfect: 100 KB is a hard budget for this picture.</p><figure><img alt="Bridge photo crops: original, full-size JPEG at quality 11, resized JPEG, and resized JPEG XL" src="https://cdn-images-1.medium.com/max/1024/1*u8pV0DAwdoR9t6FaO7hNnw.png" /></figure><p>On the bridge photo the differences are quieter but still visible. Full-size JPEG at quality 11 softens the cables and adds banding in the sky. The 800 px JPEG at quality 90 is sharper. JPEG XL at the same width is closest to the original (SSIM 0.980) and used 93,833 bytes, so it had a little room left under the cap.</p><figure><img alt="On both photos, shrinking first beat crushing quality at full size" src="https://cdn-images-1.medium.com/max/1024/1*hgQ3oEAe7D5fYLk1ESi1EA@2x.png" /></figure><p>The strategy chart is the most repeatable result in the study. For every lossy format on both photographs, the resize-and-quality search beat quality-only. The lift was about 0.05 SSIM for JPEG on the bridge photo (0.901 → 0.954) and about 0.11 for JPEG on the tulip photo (0.756 → 0.864). AVIF gained less, because it was already stronger at full size, but it still gained.</p><p>The form was a partial exception: JPEG and WebP already did their best at the original 1,240×1,754 size. AVIF and JPEG XL improved slightly after a shrink to 1,200 px on the long side. On the form, WebP at full size (0.914) was almost even with the best AVIF (0.915). JPEG XL was behind both.</p><h3>When PNG is the right answer, and when it isn’t</h3><p>A lossless PNG of the screenshot (90,674 bytes) and of the graphic (55,109 bytes) already fitted the cap, with SSIM 1.000. In both cases that is the quality winner. You would only pick a lossy format if you needed a still smaller file, or a format a form will not accept.</p><p>Two JPEG XL results are worth separating from that. At quality 100, the encoder switched to a lossless mode (the file shrank from 81,098 bytes at quality 99 to 43,839 bytes at quality 100). We decoded that screenshot file and compared it to the original, pixel for pixel: the maximum difference was 0. So JPEG XL can, on this kind of image, beat PNG on size without giving up a single pixel. The graphic did not go lossless: the best JPEG XL result was SSIM 0.996 at 92,172 bytes, still behind the 55,109-byte PNG.</p><p>The photographs and the form never fitted as PNG at 400 px or larger. After the main run we tried 350, 300, 250 and 200 px on the long side, with the same Lanczos filter and maximum PNG compression:</p><pre>Bridge photo<br>  Smallest long side we tried that fitted: 300×169<br>  Size: 81,033 B<br>  SSIM at 800 px: 0.833</pre><pre>Tulip photo<br>  Smallest long side we tried that fitted: 200×163<br>  Size: 79,391 B<br>  SSIM at 800 px: 0.553</pre><pre>Form page<br>  Smallest long side we tried that fitted: 212×300<br>  Size: 74,944 B<br>  SSIM at 800 px: 0.734</pre><p>Those SSIM scores are far below the best lossy results. A 200-pixel photo also fails most form dimension rules. For a photograph that must be under 100 KB, a lossy format is the practical choice.</p><p>A side note on sharp screenshots: when we resized the 90.7 KB screenshot PNG to 1,600 px, the new PNG grew to 192 KB and no longer fitted. Lanczos resampling of sharp text introduces new intermediate colours, which a lossless PNG has to store. Shrinking a screenshot is not a free way to save bytes.</p><h3>How we measured</h3><p><strong>When and where.</strong> 25 November 2026, 11:05:44 to 11:10:56 AM IST, on one Linux machine. The extra PNG size-threshold checks and the AVIF 4:4:4 footnote were run immediately after, around 11:11–11:12 AM IST.</p><p><strong>The cap.</strong> 100,000 bytes. Some systems treat “100 KB” as 102,400 bytes (100 KiB). We used the tighter figure and say so.</p><p><strong>The pictures.</strong> Two photographs from Wikimedia Commons, converted to 8-bit sRGB PNG and resized so the long side is 2,400 px (Lanczos), which is still a large image:</p><ol><li><em>Bridge photo</em> — <a href="https://commons.wikimedia.org/wiki/File:Golden_Gate_Bridge_as_seen_from_Marshall%E2%80%99s_Beach,_March_2018.jpg">Golden Gate Bridge as seen from Marshall’s Beach, March 2018</a> by Frank Schulenburg, <a href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a>. Reference: 2,400×1,350.</li><li><em>Tulip photo</em> — <a href="https://commons.wikimedia.org/wiki/File:Tulips_and_tree_at_Keukenhof_gardens.jpg">Tulips and tree at Keukenhof gardens</a> by Elena.laps, <a href="https://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a>. Reference: 2,400×1,950.</li></ol><p>And three pictures we generated, so they can be rebuilt bit for bit from the script:</p><ol><li><em>Screenshot</em> — 1,920×1,080 synthetic desktop-app window, with a table, a bar chart and 11-pixel footnotes.</li><li><em>Graphic</em> — 1,600×1,200 flat poster: bold type, thin 1-pixel lines, solid colour blocks.</li><li><em>Form page</em> — 1,240×1,754 synthetic A4 form at 150 dpi, with body text and a light paper grain.</li></ol><p><strong>Formats and encoders.</strong> Quality is always an integer 0–100. We used each encoder’s reference (or standard) command-line tool, at its documented default effort/speed unless noted:</p><ul><li>JPEG: <a href="https://libjpeg-turbo.org/">libjpeg-turbo</a> 2.1.5 cjpeg -optimize -quality Q</li><li>WebP: <a href="https://developers.google.com/speed/webp">libwebp</a> 1.5.0 cwebp -m 4 -q Q (-m 4 is the documented default)</li><li>AVIF: <a href="https://github.com/AOMediaCodec/libavif">libavif</a> 1.2.1 with <a href="https://aomedia.googlesource.com/aom/">libaom</a> v3.12.1, avifenc --codec aom --speed 6 --yuv 420 -q Q (--speed 6 is the documented default)</li><li>JPEG XL: <a href="https://jpeg.org/jpegxl/">libjxl</a> 0.11.2 cjxl --effort 7 -q Q (--effort 7 is the documented default)</li><li>PNG: the original reference file, or a Lanczos resize written with ImageMagick at PNG compression level 9. There is no quality slider.</li></ul><p>We decoded each result with the matching official decoder (djpeg/ImageMagick, dwebp, avifdec, djxl) before measuring.</p><p><strong>Two strategies.</strong></p><ol><li><em>Quality only.</em> Keep the original pixels. Binary-search quality for the highest setting whose file is ≤ 100,000 bytes. If quality 0 still overflows, it does not fit.</li><li><em>Resize, then quality.</em> For long sides of 2,400, 2,000, 1,600, 1,400, 1,200, 1,000, 800, 600 and 400 px (only those no larger than the original), resize with Lanczos, then repeat the quality search. Among the files that fit, keep the one with the highest SSIM at 800 px; ties go to more pixels, then to more bytes (closer to the cap).</li></ol><p><strong>Quality metric.</strong> ImageMagick 7.1.1–43 compare -metric SSIM and compare -metric PSNR. For every comparison we resized both the reference and the decoded file to 800 px wide with Lanczos (or to the original width if it was already narrower). That matches the size a form or an article typically displays a photo. SSIM of 1 means the two 800 px images are identical; higher PSNR (dB) is also better. On the lossless JPEG XL screenshot, ImageMagick printed PSNR as 0 (0) for identical images; we compared the pixels directly, found no difference, and recorded PSNR as infinity.</p><p><strong>AVIF 4:2:0.</strong> All AVIF numbers in the tables use 4:2:0 chroma, which is the usual setting for web photos. That means even quality 100 cannot be mathematically lossless, because half the colour samples are discarded. As a check, we also encoded the screenshot and the graphic at quality 100 with --yuv 444. Neither was pixel-identical (the screenshot file was 89,236 bytes, with a maximum per-channel difference of 2; the graphic was 47,835 bytes, with a maximum difference of 1). Those two files are not in the table.</p><h3>Limits of the test</h3><ul><li><strong>These are encoders, not websites.</strong> We did not run TinyPNG, Squoosh, iLoveIMG or any other online tool. A website may preprocess, pick different defaults, or use another encoder build. A different --speed, --effort or -m would also change the bytes and the SSIM. We used each tool’s documented default effort so the run is repeatable in a few minutes.</li><li><strong>Five pictures are not the whole world.</strong> The tulip photo is a hard case (fine detail, saturated colour). The bridge photo is easier (smooth sky and water). Other photos will land between them, or outside.</li><li><strong>SSIM is a useful score, not a verdict from a human.</strong> We published crops so you can look. On the form page, AVIF’s best SSIM (0.915) was slightly above its full-size score (0.906), while PSNR went down (37.3 dB → 34.8 dB). We ranked candidates by SSIM, as decided before the run, and we report both numbers in the raw data.</li><li><strong>We did not test colour profiles in the output, animation, transparency or metadata.</strong> References were 8-bit sRGB with metadata stripped. Real camera files may behave differently.</li><li><strong>We make a compressor.</strong> That is why the method, the scripts, the encoder versions and the raw files are published with this post. If you repeat the test and get a different result, tell us and we will update the table with the date.</li></ul><p>If you want to do a resize-and-quality search in a browser, for a size cap such as 100 KB, 50 KB or 20 KB, we have a tool that does that on <a href="https://tools.cuelark.com/compress-image-to-100kb">Cuelark’s compress-to-100 KB page</a>. It was not one of the encoders in this test.</p><p><em>Cuelark Team</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=927e054a723e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gemini file slicing in a React chat: let the model pick the pages]]></title>
            <link>https://medium.com/@cuelarkofficial/gemini-file-slicing-in-a-react-chat-let-the-model-pick-the-pages-f4836923c05b?source=rss-5c51d478fcf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4836923c05b</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Cuelark]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 04:52:26 GMT</pubDate>
            <atom:updated>2026-11-25T05:06:22.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6O8jfhbPOrxh34oQ.png" /></figure><p><em>By the Cuelark Team. Feature details come from Google’s launch post, the Gemini API docs, and the Vercel AI SDK docs and release notes, all checked on 25 November 2026. We didn’t call Gemini. The code ran against a local mock of the Interactions API that records each request, so this is a wiring test. It tells you what your app sends, not how well the model reads your PDF.</em></p><p>On November 23, Google added <strong>file slicing controls</strong> to the Gemini API. When you pass a PDF, an Office file, a spreadsheet, audio or video, you can now ask for specific pages, cell ranges or time segments, and choose which layer the model gets: extracted text or rendered page images for documents; data, formulas or a visual snapshot for sheets. Google slices the file on its side and bills tokens only for the slice it sends to the model. The same launch added native upload for Word, PowerPoint, Excel and OpenDocument files.</p><p>The launch post says slicing works on all Gemini 4 models. The docs say the options work on Gemini 3 and Gemini 4+ models.</p><p>The part that matters for a chat app is that slices can go inside a <strong>function result</strong>. Your tool returns a file URI plus a page range, and the model decides what to look at. According to the docs, the model also gets the file’s total page count and worksheet names, so it can ask for more on a later turn.</p><p>The Vercel AI SDK added support in @ai-sdk/google 4.0.125 (November 23) and 4.0.126 a day later removed the early-access model IDs from its suggestions, noting that regular IDs like gemini-4-hydrogen work.</p><h3>Why bother</h3><p>Per the docs, a page image costs about 280 tokens at low, 560 at medium (the default) and 1,120 at high. Send a 40-page report as images on every turn and that&#39;s around 22,400 tokens at the default before anyone asks a question. Google&#39;s suggested pattern is to skim as text, then render only the pages with charts or dense layouts at high resolution.</p><h3>The route</h3><p>Upload the PDF once with the Files API ( ai.files.upload in @google/genai) and pass the URI to the chat. Then give the model one tool:</p><pre><br>// app/api/chat/route.ts<br>import { createGoogleGenerativeAI, type GoogleInteractionsFileOptions } from &#39;@ai-sdk/google&#39;;<br>import { streamText, convertToModelMessages, tool, isStepCount, type UIMessage } from &#39;ai&#39;;<br>import { z } from &#39;zod&#39;;<br>// GEMINI_BASE_URL is unset in production; our test points it at a local mock.<br>const google = createGoogleGenerativeAI({ baseURL: process.env.GEMINI_BASE_URL });<br>export async function POST(req: Request) {<br>  // fileUri: a Files API URI you got from uploading the PDF once.<br>  const { messages, fileUri }: { messages: UIMessage[]; fileUri: string } = await req.json();<br>  const readPages = tool({<br>    description:<br>      &#39;Load pages of the attached PDF. Use detail &quot;text&quot; to skim many pages, &#39; +<br>      &#39;then &quot;image&quot; for the few pages with charts or tables.&#39;,<br>    inputSchema: z.object({<br>      startPage: z.number().int().min(1),<br>      endPage: z.number().int().min(1),<br>      detail: z.enum([&#39;text&#39;, &#39;image&#39;]),<br>    }),<br>    execute: async (input) =&gt; {<br>      if (input.endPage &lt; input.startPage) throw new Error(&#39;endPage must be &gt;= startPage&#39;);<br>      if (input.detail === &#39;image&#39; &amp;&amp; input.endPage - input.startPage &gt; 4) {<br>        throw new Error(&#39;Render at most 5 pages as images per call&#39;);<br>      }<br>      return input;<br>    },<br>    toModelOutput: ({ output }) =&gt; ({<br>      type: &#39;content&#39;,<br>      value: [<br>        {<br>          type: &#39;file&#39;,<br>          data: { type: &#39;url&#39;, url: new URL(fileUri) },<br>          mediaType: &#39;application/pdf&#39;,<br>          providerOptions: {<br>            google: {<br>              resolution: output.detail === &#39;image&#39; ? &#39;high&#39; : &#39;low&#39;,<br>              processing: {<br>                type: &#39;static&#39;,<br>                pageOptions: {<br>                  startPage: output.startPage,<br>                  endPage: output.endPage,<br>                  contentLayers: [output.detail === &#39;image&#39; ? &#39;page_image&#39; : &#39;page_text&#39;],<br>                },<br>              },<br>            } satisfies GoogleInteractionsFileOptions,<br>          },<br>        },<br>      ],<br>    }),<br>  });<br>  const result = streamText({<br>    model: google.interactions(&#39;gemini-4-hydrogen&#39;),<br>    system: &#39;Answer from the attached PDF. Skim with text first, then zoom in on specific pages.&#39;,<br>    messages: await convertToModelMessages(messages),<br>    tools: { readPages },<br>    stopWhen: isStepCount(6),<br>  });<br>  return result.toUIMessageStreamResponse();<br>}</pre><p>On the client, useChat with new DefaultChatTransport({ api: &#39;/api/chat&#39;, body: { fileUri } }) is enough. Each call shows up as a tool-readPages part, so you can render a small &quot;Read pages 12-12 as image&quot; line. It&#39;s a handy way to show what the model actually looked at.</p><h3>What the test showed</h3><p>We scripted the mock to skim pages 1–40 as text, zoom into page 12 as an image, then answer.</p><ul><li><strong>The wire format matches the docs.</strong> The skim went out as a top-level function_result holding {&quot;type&quot;:&quot;document&quot;,&quot;uri&quot;:&quot;.../files/abc123&quot;,&quot;resolution&quot;:&quot;low&quot;,&quot;processing&quot;:{&quot;type&quot;:&quot;static&quot;,&quot;page_options&quot;:{&quot;start_page&quot;:1,&quot;end_page&quot;:40,&quot;content_layers&quot;:[&quot;page_text&quot;]}}}. The SDK converts camelCase to snake_case for you, and the zoom call carried &quot;resolution&quot;:&quot;high&quot; with [&quot;page_image&quot;].</li><li><strong>Earlier slices are resent.</strong> By default the SDK sends the full history on each step and no previous_interaction_id. The three requests carried 0, 1 and 2 document blocks. The skim from step one rides along on every later step. We couldn&#39;t measure what that costs without a real key, so check usage on your own account before you assume the skim is a one-time charge.</li><li><strong>Don’t shortcut that with </strong><strong>previousInteractionId.</strong> We tried passing the last interaction ID in prepareStep to make the SDK trim history. In our mock run, the newest function_result was dropped from the next request, so the model would never see the pages it asked for. Stick with the default unless you&#39;ve tested your own setup.</li><li><strong>Bad ranges come back as tool errors.</strong> A reversed range, a 40-page image request, or page 0 all went back to the model as function_result with is_error: true, so the request never reached Gemini with bad options. That matters because the docs say a start_page of 0 or less returns 400 INVALID_ARGUMENT.</li><li><strong>Tools are sent every time.</strong> The docs warn that tool declarations aren’t stored with the interaction. The SDK included readPages on every request, so that&#39;s handled.</li></ul><h3>Honest limits</h3><ul><li><strong>We didn’t run Gemini.</strong> Nothing here measures answer quality, latency or real token counts.</li><li><strong>Text skims aren’t free.</strong> The docs give per-page numbers for images, not for the page_text layer. Expect it to be cheaper, but check your own usage numbers.</li><li><strong>File limits still apply to the whole file.</strong> That means 50 MB per file, 1,000 pages per PDF, 2,000 pages or slides per Office file and 50,000 cells per sheet, even if you only ask for one page.</li><li><strong>Edge behavior.</strong> Per the docs, a start_page past the end returns an empty slice, while an end_page past the end is clamped. If you get an empty slice back, the model asked for pages that don&#39;t exist.</li><li><strong>Office page numbers follow rendered layout.</strong> The AI SDK docs note this, so “page 12” of a Word file may not match what the author sees in their editor.</li></ul><p>The same processing object handles spreadsheets ( spreadsheetOptions with sheetIndex, visibleCells and data/ formulas/ visual layers) and audio or video clips, so the tool shape above carries over.</p><h3>Sources</h3><p>If you’d rather not build the message list and tool-status rows yourself, <a href="https://ui.cuelark.com/">Cuelark UI</a> has shadcn-style AI chat components that fit this setup.</p><p><em>Originally published at </em><a href="https://dev.to/cuelark/gemini-file-slicing-in-a-react-chat-let-the-model-pick-the-pages-19n"><em>https://dev.to</em></a><em> on November 25, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4836923c05b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Convert a GIF to MP4 (ffmpeg, Clipchamp, or in Your Browser)]]></title>
            <link>https://medium.com/@cuelarkofficial/how-to-convert-a-gif-to-mp4-ffmpeg-clipchamp-or-in-your-browser-24c1d0a3c940?source=rss-5c51d478fcf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/24c1d0a3c940</guid>
            <category><![CDATA[video-editing]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[gif]]></category>
            <category><![CDATA[ffmpeg]]></category>
            <category><![CDATA[videos]]></category>
            <dc:creator><![CDATA[Cuelark]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 06:39:23 GMT</pubDate>
            <atom:updated>2026-11-23T06:39:23.693Z</atom:updated>
            <content:encoded><![CDATA[<p>To convert a GIF to MP4, run it through a video encoder: ffmpeg on the command line, a free editor like Clipchamp, or a browser-based converter. With ffmpeg, the one command most people need is ffmpeg -i input.gif -movflags +faststart -pix_fmt yuv420p -vf &quot;scale=trunc(iw/2)*2:trunc(ih/2)*2&quot; output.mp4, and the MP4 is usually a fraction of the GIF&#39;s size.</p><p>Below is each method, what we measured on test files, and where things break.</p><h3>Why MP4 is smaller, and why sites ask for it</h3><p>A GIF stores every frame as 8-bit indexed color, with at most 256 colors per palette, compressed losslessly with LZW (<a href="https://developer.mozilla.org/en-US/docs/Web/Media/Guides/Formats/Image_types">MDN image format guide</a>). H.264 video is lossy, and video compression works by comparing frames and storing only what changed from the previous one (<a href="https://developer.mozilla.org/en-US/docs/Web/Media/Guides/Formats/Video_codecs">MDN video codec guide</a>). An animation where most of the picture stays still is close to the best case for video.</p><p>Here’s what we measured. We made a 4-second, 480×270 animated GIF with 80 frames and converted it with ffmpeg 7.1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JqCajyiNJL5whV_PA2QWeg.png" /></figure><p><em>Sizes measured on our test file. CRF is ffmpeg’s quality setting for H.264: lower means better quality and a bigger file.</em></p><p>The GIF was 515.5 KB. The default MP4 was 25.2 KB, about 95% smaller. A real-world GIF shrank less but still a lot: the <a href="https://commons.wikimedia.org/wiki/File:Rotating_earth_%28large%29.gif">rotating Earth animation on Wikimedia Commons</a> (400×400, 44 frames, CC BY-SA 3.0) went from 1,001.7 KB to 136.7 KB, 86% smaller. Google’s <a href="https://web.dev/articles/replace-gifs-with-videos">web.dev guide on replacing GIFs with video</a> reports a similar jump, 3.7 MB of GIF to a 551 KB MP4, and Lighthouse flags large GIFs with the audit “Use video formats for animated content.”</p><p>Upload rules are the other reason. YouTube’s <a href="https://support.google.com/youtube/troubleshooter/2888402?hl=en">list of supported file formats</a> includes MP4, MOV, WebM and others, but not GIF.</p><h3>Option 1: ffmpeg (Windows, Mac, Linux)</h3><p>ffmpeg is free and gives you full control. Get it from <a href="https://ffmpeg.org/download.html">ffmpeg.org/download</a>, which links Windows builds, or on a Mac with Homebrew (brew install ffmpeg, see the <a href="https://formulae.brew.sh/formula/ffmpeg">formula page</a>).</p><ol><li>Open a terminal in the folder with your GIF.</li><li>Run the command below, then check the MP4 in a browser or on your phone before you share it.</li></ol><pre>ffmpeg -i input.gif -movflags +faststart -pix_fmt yuv420p \<br>  -vf &quot;scale=trunc(iw/2)*2:trunc(ih/2)*2&quot; output.mp4</pre><p>What each part does:</p><ul><li>-movflags +faststart moves the MP4&#39;s metadata (its index of all the frames) to the start of the file &quot;for better playback&quot; (<a href="https://ffmpeg.org/ffmpeg-formats.html">ffmpeg formats docs</a>), so a browser can start playing before the whole file has downloaded.</li><li>-pix_fmt yuv420p sets the standard color format. MDN notes that most H.264 profiles use 4:2:0 chroma subsampling, which is what this flag gives you.</li><li>The scale filter rounds width and height down to even numbers.</li></ul><p>Add -crf 28 for a smaller file or -crf 18 for a sharper one. In our test, leaving -crf out produced a byte-identical file to -crf 23.</p><h3>The two ffmpeg gotchas</h3><p><strong>Gotcha 1: the default color format.</strong> We ran plain ffmpeg -i sample.gif naive.mp4. ffmpeg picked yuv444p and the &quot;High 4:4:4 Predictive&quot; H.264 profile. MDN notes that most H.264 profiles use 4:2:0, with 4:4:4 only in advanced profiles. Google&#39;s own GIF conversion command in the web.dev guide sets -pix_fmt yuv420p explicitly, and so should you.</p><p><strong>Gotcha 2: odd dimensions.</strong> With yuv420p, the libx264 encoder needs even width and height. Our 481×271 test GIF failed with:</p><pre>[libx264] width not divisible by 2 (481x271)<br>Conversion failed!</pre><p>The scale=trunc(iw/2)*2:trunc(ih/2)*2 filter fixed it, producing a 480×270 MP4. The web.dev guide uses a crop filter with the same math, which cuts off a single pixel row or column instead of resizing.</p><h3>Option 2: Clipchamp (Windows or any browser)</h3><p>Microsoft’s Clipchamp video editor has a free tier, and Microsoft says its drag-and-drop import <a href="https://support.microsoft.com/en-au/topic/how-to-add-images-to-video-dd35dea8-e203-4abe-afeb-0c31e9016698">works on Windows, Mac, and Linux</a>.</p><ol><li>Import the GIF in the media tab and drag it to the timeline (<a href="https://support.microsoft.com/en-us/clipchamp/how-to-add-gifs-to-videos">Microsoft’s GIF guide</a>).</li><li>Click <strong>Export</strong> and pick 480p, 720p or 1080p.</li></ol><p>Exports are MP4 at 30 fps, and 480p to 1080p are free (<a href="https://support.microsoft.com/en-us/clipchamp/what-format-is-my-video-exported-in">Microsoft support</a>). It’s a good pick if you also want to trim the clip or add text. The trade-off is timing: every frame has to land on a 30 fps grid, so a GIF with uneven delays may play slightly differently.</p><h3>Option 3: In the browser</h3><p>Our free <a href="https://tools.cuelark.com/gif-to-mp4">GIF to MP4 converter</a> runs entirely in your browser using its built-in video encoder (WebCodecs), so the GIF is never uploaded. It keeps each frame’s own delay, lets you pick a background color for transparent areas, can repeat a short loop until the video reaches 3, 10 or 15 seconds, and converts batches to a ZIP. Output is H.264 MP4 with even dimensions and fast-start. Limits: 100 MB, 3,000 frames and 16 megapixels per GIF, and it needs a browser with the H.264 video encoder: Chrome, Edge, Safari 16.4+ or desktop Firefox 130+ (<a href="https://developer.mozilla.org/en-US/docs/Web/API/VideoEncoder">MDN VideoEncoder compatibility</a>). Firefox on Android doesn’t have it yet.</p><p>Two well-known alternatives:</p><ul><li><a href="https://ezgif.com/gif-to-mp4">Ezgif</a> takes files up to 200 MB. Uploads are deleted after an hour, and it also offers a local-processing mode.</li><li><a href="https://cloudconvert.com/pricing">CloudConvert</a> converts on its own servers. The free plan gives 10 conversion credits a day, with a 1 GB file limit.</li></ul><h3>Limits to know</h3><ul><li><strong>No transparency.</strong> yuv420p has no alpha channel (ffmpeg -pix_fmts lists it with three components), so transparent pixels become a solid color.</li><li><strong>No built-in loop.</strong> A GIF can loop forever on its own. An MP4 loops only if the player or site does it. On your own site, use &lt;video autoplay loop muted playsinline&gt;, the pattern web.dev recommends. MDN documents the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/video">loop attribute</a>.</li><li><strong>No sound.</strong> GIFs have no audio track, so the MP4 is silent.</li><li><strong>Slight quality loss.</strong> H.264 is lossy. At the default CRF 23 we couldn’t see a difference at normal size (SSIM 0.997 against the GIF, where 1.0 is identical). At CRF 32, color bled around the hard edges, as the zoom below shows.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aO6mZwUvyAiZH-ntMW2tlA.png" /></figure><p><em>The same frame from the GIF and two MP4s, with a 4× zoom on the sun’s edge.</em></p><h3>FAQ</h3><p><strong>Will the MP4 always be smaller than the GIF?</strong> Not always. A tiny 64×64 GIF with three frames went from 428 bytes to 1,739 bytes as an MP4. For anything bigger than an icon, expect real savings: our two test files came out 86% and 95% smaller.</p><p><strong>Why won’t my converted MP4 play on my phone or in a browser?</strong> Check the pixel format first. If ffmpeg wrote yuv444p, re-run the conversion with -pix_fmt yuv420p.</p><p><strong>Why does ffmpeg say “width not divisible by 2”?</strong> Your GIF has an odd width or height. Add the scale (or crop) filter shown above.</p><p><strong>Can I convert GIF to MP4 on an iPhone?</strong> Yes, in Safari 16.4 or later with a converter that encodes in the browser.</p><p><strong>Does converting keep the GIF’s speed?</strong> ffmpeg and our converter keep each frame’s delay. We tested ffmpeg with a GIF whose last frame holds for one second, and the MP4 held it too. Editors that export at a fixed 30 fps, like Clipchamp, resample it, which can make the timing slightly uneven.</p><p><em>Cuelark Team</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24c1d0a3c940" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inkling 2 Mini in a React chat: wiring reasoning effort through the Vercel AI SDK]]></title>
            <link>https://medium.com/@cuelarkofficial/inkling-2-mini-in-a-react-chat-wiring-reasoning-effort-through-the-vercel-ai-sdk-3a44ae230487?source=rss-5c51d478fcf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a44ae230487</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Cuelark]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 04:52:48 GMT</pubDate>
            <atom:updated>2026-11-23T04:56:37.759Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lSa_tNYbC9zyaPyu.png" /></figure><p><em>By the Cuelark Team. Model details come from Thinking Machines Lab’s launch post and model card and from Hugging Face’s release post, all checked on 23 November 2026. We didn’t run the model itself. The checkpoint is about 20GB and our test box has 15GB of RAM. The code ran against a local mock of an OpenAI-compatible server, and we rendered the model’s official chat template against the requests the SDK actually sent. Read this as a wiring test, not a quality review.</em></p><p>Thinking Machines Lab released <strong>Inkling 2 Mini</strong> on November 20 with open weights under Apache 2.0. It’s a Mixture-of-Experts model with 26.4B total parameters and 3.4B active. Of its 24 layers, the middle 12 run three times per token, which brings it to about 5.4B effective active parameters. It takes text and images, outputs text, and supports a context window of up to 1M tokens. The checkpoint is about 20GB in mixed NVFP4 and MXFP8. The model card recommends Apple silicon with 32GB or more, a DGX Spark, or a GPU with 32GB or more of VRAM.</p><p>The launch post says it leads open-weights models under 100B total parameters on DeepSWE v1.1 (48.2%) and Vals Index v2.2 (46.5%). Those are the lab’s own numbers, and we didn’t check them.</p><p>For a chat app, one setting matters more than anything else: reasoning effort. Here’s how to wire it from a React dropdown to the model, plus two things in the chat template worth knowing first.</p><h3>Serving it</h3><p>Hugging Face’s post gives two commands. For local GGUF:</p><pre>llama serve -hf ggml-org/Inkling-2-Mini-GGUF:IQ4_NL</pre><p>And for SGLang on datacenter hardware (trimmed; the post has the full flags and notes it needs SM103):</p><pre>python -m sglang.launch_server --model-path thinkingmachines/Inkling-2-Mini \ --served-model-name inkling --host 0.0.0.0 --port 30000</pre><p>The post says Llama App, built on llama.cpp, exposes a local OpenAI-compatible API, and SGLang serves /v1/chat/completions. SGLang&#39;s example request passes &quot;reasoning_effort&quot;: &quot;low&quot; in the body, so the Vercel AI SDK&#39;s generic OpenAI-compatible provider is enough.</p><h3>The route</h3><p>On the client, useChat sends the effort with each message: sendMessage({ text: input }, { body: { effort } }). Reasoning arrives as reasoning parts, which you can render in a collapsible &lt;details&gt; above the answer.</p><h3>What the test showed</h3><p>AI SDK 7’s top-level reasoning option accepts none, minimal, low, medium, high, xhigh and max. That&#39;s the same list of names Inkling&#39;s chat template uses. In our mock run, each one reached the server unchanged as reasoning_effort. provider-default leaves the field out. Streamed reasoning_content deltas showed up as a reasoning part in the UI message, and the usage chunk filled in the token counts.</p><p>Then we ran the official chat_template.jinja from the Hugging Face repo against those requests. A few things stood out:</p><ul><li><strong>Names map to numbers.</strong> none is 0, minimal 0.1, low 0.2, medium 0.7, high 0.9 and both xhigh and max 0.99. If you leave the field out, you get 0.9, so the default is close to the top. With this template, an xhigh and a max option in your UI do the same thing.</li><li><strong>Numbers work in the template, but not in the SDK option.</strong> The template accepts any value from 0.0 to 0.99. The provider’s reasoningEffort option only takes a string, so passing 0.35 failed before any request was sent. Passing a raw reasoning_effort: 0.35 under providerOptions.inkling got through unchanged. We didn&#39;t confirm that SGLang or llama serve accept a number there.</li><li><strong>Unknown names throw.</strong> &quot;turbo&quot; raised Unknown reasoning_effort. Validate the dropdown value on the server.</li><li><strong>Old reasoning is resent.</strong> By default the SDK sends earlier reasoning back as reasoning_content, and the template renders each one into the prompt as a thinking block. With six tiny fake thoughts, the rendered prompt grew from 1,102 to 1,681 characters. Real reasoning is much longer, so in a long chat this fills context fast. That&#39;s why the route strips it unless keepThoughts is set. We don&#39;t know whether keeping it helps answer quality.</li><li><strong>Tool calls need parsed arguments.</strong> The SDK sends tool_calls[].function.arguments as a JSON string, like the OpenAI API. The raw template rejects that (&quot;must be a parsed object, not a JSON string&quot;). After JSON.parse, the same history rendered fine. Your server may parse it first. Test one tool round trip on yours before building an agent on it.</li></ul><h3>Honest limits</h3><ul><li><strong>We didn’t run the model.</strong> Everything above covers the request and the template. None of it measures speed or answer quality.</li><li><strong>The lab lists its own weak spots.</strong> It isn’t the strongest small model for multi-turn chat or for instructions with many constraints. It scores 50.0% on MultiChallenge and 33.4% on ComplexConstraints v1.1, both behind Qwen3.8–27B.</li><li><strong>none isn&#39;t off.</strong> The model card says the minimum reasoning effort doesn&#39;t fully disable reasoning. Because the middle layers run three times, compute per token is also higher than 3.4B active parameters suggests.</li><li><strong>Agent safety.</strong> The model card warns that the model may delete or overwrite files without asking. It recommends a sandbox and confirmation for destructive actions.</li><li><strong>Local runtimes are new.</strong> Per the model card, support for looped models in local runtimes is new, and speed varies by runtime and hardware.</li></ul><p>If you want to experiment, a research checkpoint, TML-d24-varloop-research, lets you change the number of loop passes. Fewer passes are faster, but answers may be a little worse.</p><h3>Sources</h3><p>If you’d rather not build the reasoning toggle and message list yourself, <a href="https://ui.cuelark.com/">Cuelark UI</a> has shadcn-style AI chat components that work with this setup.</p><p><em>Originally published at </em><a href="https://dev.to/cuelark/inkling-2-mini-in-a-react-chat-wiring-reasoning-effort-through-the-vercel-ai-sdk-3gg3"><em>https://dev.to</em></a><em> on November 23, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a44ae230487" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gemini 4 Neon in a React chat: going past 64K output without breaking your token meter]]></title>
            <link>https://medium.com/@cuelarkofficial/gemini-4-neon-in-a-react-chat-going-past-64k-output-without-breaking-your-token-meter-950c97fd2187?source=rss-5c51d478fcf1------2</link>
            <guid isPermaLink="false">https://medium.com/p/950c97fd2187</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Cuelark]]></dc:creator>
            <pubDate>Sat, 21 Nov 2026 05:04:54 GMT</pubDate>
            <atom:updated>2026-11-23T15:43:44.972Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By the Cuelark Team. Every model detail below comes from Google’s launch post and Gemini API docs, and the SDK details come from the Vercel AI SDK’s release notes and published package, all checked on 21 November 2026. The code ran on our machine against a local mock of the documented </em><em>streamGenerateContent stream. We had no Gemini API key for this test, so read it as a wiring test, not a quality review.</em></p><p>Google released <strong>Gemini 4 Neon</strong> (gemini-4-neon) on November 18. It sits between Hydrogen and Carbon in the Gemini 4 family and is aimed at complex coding, knowledge work and science. The launch post leads with benchmark rankings. We didn&#39;t check those, so we&#39;ll skip them.</p><p>The part that matters for a chat UI is quieter. Neon can produce up to 1M tokens in a single answer, but changing the model ID alone doesn’t enable that. Any one request still stops at 65,536 tokens of thinking plus output. Here’s how the longer answers work with the AI SDK, and two things we only noticed once we ran it.</p><h3>What the docs say</h3><p>From <a href="https://aistudio.google.com/docs/whats-new-gemini-4-neon">What’s new in Gemini 4 Neon</a> and the <a href="https://ai.google.dev/gemini-api/docs/changelog">release notes</a>:</p><ul><li><strong>Price:</strong> $3.00 per 1M input tokens and $15.00 per 1M output tokens, thinking included, flat across the window. Cached input is $0.15 per 1M (a 95% discount from implicit caching).</li><li><strong>Paid tier only.</strong> Unlike Hydrogen, there’s no free tier.</li><li><strong>Thinking levels:</strong> low, medium, high (the default) and xhigh. minimal is rejected.</li><li><strong>One shared window:</strong> input, thinking and output share 1,048,576 tokens.</li></ul><p>The <a href="https://ai.google.dev/gemini-api/docs/long-decode">long decode guide</a> explains the rest. Generation runs in hops of up to 64K tokens. If a hop hits that cap and budget is left, the response ends with finishReason: CONTINUATION and an encrypted continuationToken. You send the same request again with that token and don&#39;t add the partial output to contents, because the token carries the state. When the whole max_output_tokens budget is used, the response ends with MAX_TOKENS instead.</p><p>Google is also clear about when this is worth it. Chat, Q&amp;A and summaries finish well under 32K tokens and don’t need it. It’s for hard reasoning and “write the whole thing” jobs like a full migration spec. So we made it a per-message toggle, not the default.</p><h3>SDK support</h3><p><a href="https://github.com/vercel/ai/releases/tag/%40ai-sdk%2Fgoogle%404.0.123">@ai-sdk/google 4.0.123</a> (November 20) added the gemini-4-neon ID with xhigh. Long decode support itself landed earlier, in <a href="https://github.com/vercel/ai/releases/tag/%40ai-sdk%2Fgoogle%404.0.95">4.0.95</a>: the provider continues CONTINUATION hops for you, sums usage, and exposes initialPromptTokenCount. We used ai@7.0.179 and @ai-sdk/google@4.0.124.</p><h3>The route</h3><pre>// app/api/chat/route.ts<br>import { streamText, convertToModelMessages, type UIMessage } from &#39;ai&#39;;<br>import { google } from &#39;@ai-sdk/google&#39;;<br><br>export const maxDuration = 900; // hops can take minutes; check your host&#39;s limit<br><br>export type ChatMeta = {<br>  finishReason?: string;<br>  contextTokens?: number;     // what the conversation actually occupies<br>  billedInputTokens?: number; // summed over every hop, for cost only<br>  continuationToken?: string;<br>};<br><br>export async function POST(req: Request) {<br>  const { messages, long = false, continuationToken }: {<br>    messages: UIMessage[]; long?: boolean; continuationToken?: string;<br>  } = await req.json();<br><br>  const result = streamText({<br>    model: google(&#39;gemini-4-neon&#39;),<br>    messages: await convertToModelMessages(messages),<br>    // Above 65,536 the provider runs the 64K hops for you<br>    maxOutputTokens: long ? 262_144 : undefined,<br>    providerOptions: {<br>      google: {<br>        thinkingConfig: { thinkingLevel: long ? &#39;high&#39; : &#39;medium&#39;, includeThoughts: true },<br>        ...(continuationToken &amp;&amp; { continuationToken }),<br>      },<br>    },<br>  });<br><br>  return result.toUIMessageStreamResponse&lt;UIMessage&lt;ChatMeta&gt;&gt;({<br>    sendReasoning: true,<br>    messageMetadata: ({ part }) =&gt; {<br>      if (part.type !== &#39;finish-step&#39;) return;<br>      const g = part.providerMetadata?.google as<br>        { initialPromptTokenCount?: number; continuationToken?: string } | undefined;<br>      const input = part.usage.inputTokens ?? 0;<br>      const output = part.usage.outputTokens ?? 0;<br>      return {<br>        finishReason: part.finishReason,<br>        billedInputTokens: input,<br>        contextTokens: (g?.initialPromptTokenCount ?? input) + output,<br>        continuationToken: g?.continuationToken,<br>      };<br>    },<br>  });<br>}</pre><h3>What the test showed</h3><p>Our mock replaces fetch and streams SSE chunks shaped like the docs&#39; examples. It isn&#39;t a captured Gemini response. We drove the route the way useChat does.</p><ol><li><strong>Without </strong><strong>maxOutputTokens, the answer just stops.</strong> One request, finishReason: &#39;length&#39;, half a spec. The UI shows it as finished unless you check.</li><li><strong>With 262,144, the hops are invisible.</strong> Three requests went out. The second and third carried the previous continuationToken, and contents was identical each time. The first hop was all thinking with empty text, which the docs call normal. The client got one reasoning block and one text block, as if it were a single response.</li><li><strong>usage.inputTokens is not your context size.</strong> It came back as 199,608, the sum of each hop&#39;s input (1,000 + 66,536 + 132,072), because every hop re-reads everything generated so far. The real context was 162,072. The docs warn about this. If your app trims or summarises history when a token count gets close to the limit, feed it initialPromptTokenCount plus output, not inputTokens, or it&#39;ll compact far too early.</li></ol><p>For the cut-off case we added a Continue button. It sends the original prompt plus the token and a bigger budget. regenerate already drops the partial answer from the request, which is what Google asks for:</p><pre>{status === &#39;ready&#39; &amp;&amp; meta?.finishReason === &#39;length&#39; &amp;&amp; meta.continuationToken &amp;&amp; (<br>  &lt;button onClick={() =&gt; {<br>    setCarry(carry + textOf(last!)); // the new message holds only the rest<br>    regenerate({ body: { long: true, continuationToken: meta.continuationToken } });<br>  }}&gt;<br>    Hit the token limit. Continue<br>  &lt;/button&gt;<br>)}</pre><p>The rest of the component is a normal useChat list with a details block for reasoning. We type-checked it and ran this flow through the AI SDK Chat class: one user message went out, the token reached Gemini, and the displayed text joined up.</p><h3>Honest limits</h3><ul><li><strong>We didn’t call the real API.</strong> Before you ship, run one real long request and compare the hop count and usage with what you log.</li><li><strong>Dropped streams don’t resume from checkpoints.</strong> After the first 64K on Neon, the stream sends a checkpoint token about every 5,000 tokens, and Google’s REST loop resumes from the last one. In our test, a stream cut after a checkpoint ended as finishReason: &#39;interrupted&#39; with no token in the metadata, and the text after the checkpoint stayed in the message. With this SDK version you resend the request instead.</li><li><strong>The resumed message is only the tail.</strong> Our carry fixes the display, but the stored history holds just the second part. Merge them before the next turn.</li><li><strong>Time limits.</strong> Google suggests HTTP timeouts of at least 15 minutes, and the server closes a stream after 20. Check your host’s function time limit before relying on maxDuration. For truly long jobs, Google recommends background execution on the Interactions API, which this route doesn&#39;t use.</li><li><strong>Cost.</strong> Every hop is billed, including thinking-only hops. Repeated input in each hop gets the 95% cache discount, but if the model uses the whole 262,144-token budget, that’s about $3.90 of output for one answer.</li></ul><h3>Sources</h3><ul><li><a href="https://blog.google/innovation-and-ai/models-and-research/gemini-models/introducing-gemini-4-neon/">Introducing Gemini 4 Neon, Google</a></li><li><a href="https://aistudio.google.com/docs/whats-new-gemini-4-neon">What’s new in Gemini 4 Neon</a></li><li><a href="https://ai.google.dev/gemini-api/docs/changelog">Gemini API release notes</a></li><li><a href="https://ai.google.dev/gemini-api/docs/long-decode">Long decode</a> and <a href="https://ai.google.dev/gemini-api/docs/long-decode?generate-content=true">long decode with generateContent</a></li><li><a href="https://github.com/vercel/ai/releases/tag/%40ai-sdk%2Fgoogle%404.0.123">@ai-sdk/google 4.0.123</a> and <a href="https://github.com/vercel/ai/releases/tag/%40ai-sdk%2Fgoogle%404.0.95">4.0.95</a></li></ul><p>If you’d rather not hand-build the reasoning block and message list, <a href="https://ui.cuelark.com/">Cuelark UI</a> has shadcn-style components for AI chat that work with this setup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=950c97fd2187" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>