<?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 GP Sandhu on Medium]]></title>
        <description><![CDATA[Stories by GP Sandhu on Medium]]></description>
        <link>https://medium.com/@gurpartap.sandhu3?source=rss-472ef08d0073------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8tmu11JACP77m-Pn</url>
            <title>Stories by GP Sandhu on Medium</title>
            <link>https://medium.com/@gurpartap.sandhu3?source=rss-472ef08d0073------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 05:38:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gurpartap.sandhu3/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[Evals demystified — how to pick the right model for the right job]]></title>
            <link>https://medium.com/@gurpartap.sandhu3/evals-demystified-how-to-pick-the-right-model-for-the-right-job-5523e7cd0e89?source=rss-472ef08d0073------2</link>
            <guid isPermaLink="false">https://medium.com/p/5523e7cd0e89</guid>
            <category><![CDATA[eval]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <dc:creator><![CDATA[GP Sandhu]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 17:27:30 GMT</pubDate>
            <atom:updated>2026-07-23T17:27:30.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bs8lQ63Yp4WmqBIKpXl8aA.png" /></figure><p>Article: <a href="https://claude.ai/code/artifact/c20349d7-002e-4562-9cf0-e6a736892d94">https://claude.ai/code/artifact/c20349d7-002e-4562-9cf0-e6a736892d94</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5523e7cd0e89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Messages API: Streaming]]></title>
            <link>https://medium.com/@gurpartap.sandhu3/claude-messages-api-streaming-4bd16a39b085?source=rss-472ef08d0073------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bd16a39b085</guid>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[streaming]]></category>
            <dc:creator><![CDATA[GP Sandhu]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 00:49:10 GMT</pubDate>
            <atom:updated>2026-06-24T00:49:10.005Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@gurpartap.sandhu3/intro-to-anthropic-messages-api-request-response-and-models-2ea8a15dafaf">first post about Messages API</a> we sent one message and got one message back. That round trip is the foundation of everything — but it has a catch you feel the moment you build a chat interface: a real reply can take ten, twenty, even thirty seconds to generate, and for that whole time your user stares at a loading spinner with no sign anything is happening.</p><p>Streaming fixes that. With streaming on, the answer appears a few words at a time — the way it does in the Claude or ChatGPT apps — text building up on screen as Claude writes it. The wait feels shorter because there’s no single wait anymore; the response is arriving the whole time. You still send one request. But instead of one reply at the end, the response arrives as a stream of small events as Claude writes. In this post we’ll turn streaming on, watch the text flow in, look at the events underneath, and then grab the finished message at the end — so you get both a live UI and a complete reply to store.</p><h4>What streaming does</h4><p>Here’s the mental model. In the first post, client.messages.create() sent your request and then waited — quietly holding the connection open — until Claude had finished the entire reply. Only then did the SDK hand you back one complete Message object. The text was done generating before you saw a single character.</p><p>Streaming keeps the request identical and changes only the delivery. When you ask for a stream, the server doesn’t wait for the full answer. It opens a long-lived connection and pushes the reply out in pieces — using a web standard called server-sent events (SSE) — as fast as Claude generates them. Your code reads those pieces as they land and can paint each one to the screen immediately.</p><blockquote>Streaming changes how the response arrives, not what you send. It’s still one request, and the API is still stateless — you still pass the full messages history every time, exactly as before.</blockquote><p>So nothing you learned last time goes away. The inputs (model, max_tokens, messages) are the same; the model and pricing are the same; managing conversation history is still your job. The only difference is that the answer comes back as a sequence of small events instead of one finished object.</p><h4>Basic stream example</h4><p>The SDK gives you a clean helper for the common case — show the text as it arrives. Notice two changes from last time: you call client.messages.stream() instead of .create(), and you use it inside a with block.</p><pre>from anthropic import Anthropic<br><br>client = Anthropic()  # reads ANTHROPIC_API_KEY from the environment<br><br>with client.messages.stream(<br>    model=&quot;claude-opus-4-8&quot;,<br>    max_tokens=1000,<br>    messages=[<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Write a one-sentence description of a fake database.&quot;},<br>    ],<br>) as stream:<br>    for text in stream.text_stream:<br>        print(text, end=&quot;&quot;, flush=True)</pre><p>text_stream is a filtered view. Under it, the server is sending a structured sequence of typed events, and it always follows the same shape:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SC0Iz7RDeavM69rNyuciRQ.png" /><figcaption>Source: Anthropic Skilljar</figcaption></figure><p>- <strong>message_start</strong> — the opening event. It carries a Message object that looks just like a normal reply but with empty content — the shell that the rest of the stream fills in.<br>- A content block, delivered as three kinds of event:<br> — <strong>content_block_start</strong> — a new block is beginning (for a text reply, a text block).<br> — <strong>content_block_delta</strong> — one chunk of the block. For text, the delta is a text_delta carrying the next snippet of words. There are many of these.<br> — <strong>content_block_stop</strong> — that block is finished.<br>- message_delta — top-level updates to the message now that it’s wrapping up, like the final stop_reason. It also carries usage.<br>- <strong>message_stop</strong> — the very last event. The reply is complete.</p><p>A few things to notice:</p><p>- The text lives in the content_block_delta events — specifically the text_delta inside each one. That’s exactly what text_stream pulls out for you; everything else is structure.<br>- ping events can appear anywhere in the stream. They’re keep-alives with no content — ignore them.<br>- The usage counts in message_delta are cumulative, not per-chunk. Don’t add them up across events; the value you want is the total reported as the stream ends. ⚠️<br>- New event types may be added over time, so if you’re handling events yourself, ignore any type you don’t recognize rather than crashing on it.</p><p>Here are the raw events for a simple hello prompt to Claude</p><pre>event: message_start<br>data: {&quot;message&quot;:{&quot;id&quot;:&quot;msg_01TjMyrTYznnjTqZo324jyEe&quot;,&quot;content&quot;:[],&quot;model&quot;:&quot;claude-opus-4-8&quot;,&quot;role&quot;:&quot;assistant&quot;,&quot;stop_reason&quot;:null,&quot;type&quot;:&quot;message&quot;,&quot;usage&quot;:{&quot;input_tokens&quot;:9,&quot;output_tokens&quot;:8,...}},&quot;type&quot;:&quot;message_start&quot;}<br><br>event: content_block_start<br>data: {&quot;content_block&quot;:{&quot;text&quot;:&quot;&quot;,&quot;type&quot;:&quot;text&quot;},&quot;index&quot;:0,&quot;type&quot;:&quot;content_block_start&quot;}<br><br>event: content_block_delta<br>data: {&quot;delta&quot;:{&quot;text&quot;:&quot;Hello! How are you do&quot;,&quot;type&quot;:&quot;text_delta&quot;},&quot;index&quot;:0,&quot;type&quot;:&quot;content_block_delta&quot;}<br><br>event: content_block_delta<br>data: {&quot;delta&quot;:{&quot;text&quot;:&quot;ing today? Is there something I can help you with?&quot;,&quot;type&quot;:&quot;text_delta&quot;},&quot;index&quot;:0,&quot;type&quot;:&quot;content_block_delta&quot;}<br><br>event: content_block_stop<br>data: {&quot;index&quot;:0,&quot;type&quot;:&quot;content_block_stop&quot;}<br><br>event: message_delta<br>data: {&quot;delta&quot;:{&quot;stop_reason&quot;:&quot;end_turn&quot;,&quot;stop_sequence&quot;:null},&quot;type&quot;:&quot;message_delta&quot;,&quot;usage&quot;:{&quot;input_tokens&quot;:9,&quot;output_tokens&quot;:23,...}}<br><br>event: message_stop<br>data: {&quot;type&quot;:&quot;message_stop&quot;}</pre><h4>Getting the complete message</h4><p>Streaming is great for the user, but your application usually still needs the whole reply — to save it to a database, log it, or append it to the conversation history for the next turn. You don’t want to manually glue the chunks back together. The SDK does it for you: after the stream finishes, call get_final_message().</p><pre>with client.messages.stream(<br>    model=&quot;claude-opus-4-8&quot;,<br>    max_tokens=1000,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Write a one-sentence description of a fake database.&quot;}],<br>) as stream:<br>    for text in stream.text_stream:<br>        # forward each chunk to your UI as it arrives<br>        print(text, end=&quot;&quot;, flush=True)<br><br>    # after the loop, the whole reply assembled for you<br>    message = stream.get_final_message()<br><br>print()<br>print(message.content[0].text)   # the full text, reassembled<br>print(message.stop_reason)       # &quot;end_turn&quot;<br>print(message.usage.output_tokens)</pre><p>The object get_final_message() returns is the exact same Message you’d get from client.messages.create() — same content[0].text, same stop_reason, same usage. So you get the best of both worlds in one request: stream the chunks to your user for a responsive UI, and hold on to the finished Message for your own logic.</p><blockquote>Bonus reason to stream. For very long replies (a large max_tokens), the SDK actually requires streaming under the hood to avoid the HTTP connection timing out while Claude works. If you don’t care about the chunks and just want the whole answer back, .stream(…) plus get_final_message() is the safe way to request a long, non-interactive generation.</blockquote><h4>Wrapping up</h4><p>Streaming is a small change to your code with a big change to how the app feels. You still send one request with the same model, max_tokens, and messages, and the API is still stateless. The only difference is the reply comes back as a sequence of events instead of one finished object:</p><p>- Use client.messages.stream() in a with block, and loop over stream.text_stream to display the answer as it’s written.<br>- Underneath, the events run message_start → (content_block_start → content_block_delta → content_block_stop) → message_delta → message_stop, with the text living in the text_delta chunks. The SDK parses all of it for you.<br>- Call stream.get_final_message() when you need the complete Message for storage or the next turn — it’s identical to what create() returns.</p><p>We kept this to plain text on purpose. Two features stream too, and each gets its own post: tool use streams its arguments as input_json_delta events (partial JSON you accumulate), and extended thinking streams Claude’s reasoning as thinking_delta events. Same event flow you just learned — just different delta types inside it.</p><p>From here, the series continues:</p><p>- <em>Extended thinking</em> — let Claude reason through hard problems before answering, and stream that reasoning with thinking_delta.<br>- <em>Tool use</em> — let Claude call your functions and APIs, and stream the call as it forms.<br>- <em>Prompt caching</em> — cut cost and latency on repeated context.</p><p>But every one of those is built on the same request → stream of events you just learned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bd16a39b085" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI model showdown — Vision]]></title>
            <link>https://medium.com/@gurpartap.sandhu3/ai-model-showdown-vision-d7b05179fe21?source=rss-472ef08d0073------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7b05179fe21</guid>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[google-gemini]]></category>
            <category><![CDATA[xai]]></category>
            <dc:creator><![CDATA[GP Sandhu]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 03:13:00 GMT</pubDate>
            <atom:updated>2026-06-23T03:13:00.112Z</atom:updated>
            <content:encoded><![CDATA[<p>Every big AI lab now ships a model that can “see,” and on paper they all claim the same thing: hand them an image and they’ll understand it. But how good are they really, on a task that’s actually useful? I wanted to find out with something concrete and a little unglamorous — pulling nutrition information out of food photos. It turns out to be a perfect stress test for vision models, because it scales smoothly from trivial to genuinely hard: at the easy end you’ve got a nutrition label with every number printed right there, and at the hard end you’ve got a messy plate of food where the model has to identify each ingredient, guess the portions, and total it all up. So I put the most capable vision model from each of the four major providers — Anthropic’s Claude, OpenAI’s GPT, Google’s Gemini, and xAI’s Grok — head to head, then went back and asked the cheapest model from each whether you really need to pay for the flagship. Here’s how they did.</p><h4>Simple task 1— read nutrition label</h4><p>We’ll start with the easiest version of the task. I handed each model a clear photo of a nutrition label — a box of Nature’s Path organic multigrain cereal and asked it to pull out the numbers: calories, macros, the vitamins and minerals, all of it. There’s no estimation involved here and nothing to infer; every value is printed right there on the package in black and white. This is pure reading. If a vision model can’t reliably transcribe a label it’s looking straight at, nothing further down the list is going to go well, so it’s the natural place to set a baseline. To keep everyone honest I wrote out the “ideal” answer by hand first, reading the values straight off the box, and scored each model against that. We used a very lazy simple prompt to “Estimate the nutrition for item in the image” and <a href="https://medium.com/@gurpartap.sandhu3/claude-messages-api-structured-outputs-451344d7f763">asked for structured data</a> schema response for 21 marco and micronutrients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XmzCNtBPUzng1XI4dhQd9g.jpeg" /><figcaption>Can models read nutrient labels well</figcaption></figure><p>Ideal values read from the box</p><pre>{<br>  &quot;image&quot;: &quot;Cereal.jpg&quot;,<br>  &quot;product&quot;: &quot;Nature&#39;s Path organic multigrain cereal&quot;,<br>  &quot;serving_size&quot;: &quot;1 cup cereal (40g)&quot;,<br>  &quot;basis&quot;: &quot;cereal only, without milk&quot;,<br>  &quot;source&quot;: &quot;human-read from the nutrition label in the image&quot;,<br>  &quot;nutrition&quot;: {<br>    &quot;calories&quot;: 160,<br>    &quot;total_fat_g&quot;: 1.5,<br>    &quot;saturated_fat_g&quot;: 0,<br>    &quot;trans_fat_g&quot;: 0,<br>    &quot;cholesterol_mg&quot;: 0,<br>    &quot;sodium_mg&quot;: 170,<br>    &quot;total_carbohydrate_g&quot;: 31,<br>    &quot;dietary_fiber_g&quot;: 7,<br>    &quot;total_sugars_g&quot;: 5,<br>    &quot;added_sugars_g&quot;: 5,<br>    &quot;protein_g&quot;: 5,<br>    &quot;vitamin_d_mcg&quot;: 0,<br>    &quot;calcium_mg&quot;: 0,<br>    &quot;iron_mg&quot;: 2,<br>    &quot;potassium_mg&quot;: 200<br>  }<br>}</pre><p>Results with the most capable models from each lab:</p><p>All four scored 21/21 on the cereal-only values, and all correctly identified the product (Nature’s Path organic multigrain / Heritage Flakes) and transcribed the ingredient list. <em>Now that we know models can do this task well, let’s do the cost optimization by finding the cheapest one that can do this well</em></p><p>These are the models we used in the first run where all 4 got everything right from the label</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTacqG_FOMGMpdQFi8GErQ.jpeg" /></figure><p><strong>Cost optimization for simple label reading task</strong></p><p>Then we ran it again for the cheapest vision model from each provider. All of them again aced the result for this very simple task and these cost fraction of the most capable expensive models</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XjGkhULQ8BwFOpWtez_Dw.jpeg" /></figure><h4>Task 2 — Extract nutrients for wellknown fruits</h4><p>Now let’s take the label away. Instead of a box with the numbers printed on it, I just hand each model a photo of a plain apple and then a banana; and ask for the full nutrition breakdown. This is a fundamentally different test. There’s nothing to read: the model has to recognize the fruit, guess the portion (“one medium apple”) from the picture alone with no scale or reference object, and then recall the actual numbers from memory. And not just calories and the big three macros — I asked for all 21 fields, including micronutrients like manganese, folate, B6, and vitamin A that never show up on a nutrition label. So where Task 1 was really an OCR test, this one asks what the model actually knows about everyday food.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*b5EJ3qCnFpPxTqNzZSjJ9w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*rJvJRAvatWhEQAG5XPCS9w.jpeg" /></figure><p>So does the cheap tier hold up here too? Almost entirely, yes and this is where it starts to get interesting. On the two single fruits, the budget models were basically perfect as well: Gemini Flash Lite, Grok 4 Fast, and Claude Haiku all scored a flat 21 out of 21 on both, and GPT-5 Nano dropped only a fraction of a point on the apple across runs.</p><h4>Task 3 — Extract nutrients for multiple food items in one single image</h4><p>The crack only appears when I show them the third image — a single photo with both an apple and a banana in it — and ask for the combined totals. Now the model has to do two things at once: nail each fruit in the image and add them together. The flagships still aced it, 21 out of 21 across the board, but the cheap Claude and the cheap GPT slipped to about 20 out of 21, and they slipped in the same place — they undercounted the total sugars, reading roughly 25 grams instead of the correct 33. It’s a small miss, but it’s a telling one: the knowledge was there, the arithmetic of combining two items is where the smaller models started to fray. Which is a perfect setup for the next task, where everything is a combination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ryh5p9pCxOm0PoLZxhr4tQ.jpeg" /></figure><p>We were able to get the model to get this task right also but writing a better prompt to guide the models</p><pre>    &quot;Identify every distinct food item shown in this image. For each item &quot;<br>    &quot;separately, estimate its nutrition and add one entry to the items list (its &quot;<br>    &quot;name plus its nutrient values for that single item — do NOT combine or sum &quot;<br>    &quot;across items). Give your best numeric estimate for every macro- and &quot;<br>    &quot;micronutrient field, in that field&#39;s unit (grams, milligrams, or micrograms; &quot;<br>    &quot;calories in kcal). Use 0 for a nutrient that is absent or negligible.</pre><h4>Task 4— Complex mix of clear ingredients</h4><p>This is where I introduce the “multiple runs” idea, since it’s the first image where the answers start to wobble: Now we get to a real plate of food. Avocado toast topped with scrambled eggs, a scatter of diced tomato, and some cilantro — the kind of thing you’d actually photograph for a meal-tracking app. Nothing here is labeled, and crucially, nothing here is a single item. To get the nutrition right, a model has to do the whole job at once: look at the plate, break it into its components, recognize each one, estimate how much of it is there, look up the nutrition for each, and add it all together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5j7M2rIJn0N9S6liCIxZg.jpeg" /></figure><p>I ran all four budget models five times each on this plate. Grok 4 Fast was the clear winner and impressively steady — 20.4 out of 21 on average, never dipping below 19. Gemini Flash Lite was the curiosity of the group: it scored exactly 17 on all five runs, not a single point of variation, which is low but uncannily reliable. Claude Haiku landed at 17.2 on average, but that number hides a lot of thrashing — its runs ranged all the way from 11 to 21 depending on how it itemized the plate. And GPT-5 Nano brought up the rear at 14.2, dragged down by the failure mode this whole task was built to expose: on its worst run it stopped breaking the plate into ingredients and collapsed it into a single “bread slice,” scoring just 7 out of 21 and throwing away the eggs and avocado entirely. So at the budget tier, only Grok could be trusted to get a simple meal right consistently — the rest were either capped, wildly inconsistent, or both.</p><p><strong>Upgrading to the most capable models</strong></p><p>As the cheap models started to fail I ran it again, five times each, with the flagship model from every provider — and the upgrade paid off exactly where the cheap tier was weakest. GPT was the big winner: GPT-5.5 jumped five full points to 19.2 and, just as importantly, the wild swings vanished, landing within a single point every run. Gemini improved too, climbing to a class-leading 20.2 with Gemini 3.1 Pro. But paying more was not a guaranteed win across the board. Grok 4.3 actually came in slightly below its own cheaper sibling (19.6 versus 20.4), and Claude barely moved — Opus 4.8 averaged 17.4, statistically tied with budget Haiku’s 17.2, and the weakest of the four flagships on this image. What the upgrade bought Claude wasn’t a higher score but a steadier one: where Haiku careened between 11 and 21, Opus stayed in a tight 16-to-19 band every time. That’s the real pattern of this task — a bigger model mainly buys you consistency and reliable itemization. It rescues the models that are flailing, but it won’t lift one that has already settled on its answer.</p><h4>Conclusion</h4><p>Putting it all together, a clear shape emerges. The easy half of this problem is basically solved, and solved cheaply. Reading a printed label, recognizing an apple, recalling the micronutrients in a banana from nothing but a photo — every model did it, and so did the cheapest model from every provider. If your use case lives here, the flagship tier is money you don’t need to spend. The difficulty — and the entire reason to reach for a more capable model — only shows up once the food gets messy: several ingredients on one plate, no label, and portions you have to eyeball. That’s where the models have to identify, estimate, and add all at once, and that’s where they start disagreeing both with the truth and with themselves.Two lessons stood out along the way.</p><blockquote>The first is that the prompt does a surprising amount of the work. The combined apple-and-banana image tripped up the cheap models until I stopped asking for a single total and instead told them to list each item separately and let my own code do the addition — the same models that fumbled the sum got it right the moment the arithmetic was taken off their plate.</blockquote><blockquote>The second, and the one I’d underline, is that you cannot trust a single run. The same model on the same image swung by ten full points from one attempt to the next; the only honest way to measure any of these systems was to run everything five times and look at the average and the spread, not a lucky one-shot.</blockquote><p>And the headline question — do you actually need to pay for the flagship? — turned out to have a more interesting answer than I expected. Paying up mostly buys consistency, not correctness. It rescued the models that were flailing (GPT went from erratic to dependable, Gemini climbed to the top of the board) but did almost nothing for a model that had already settled on its answer (Claude scored the same at both tiers, and Grok was actually a touch better in its cheap version than its expensive one). So the practical advice is to match the model to the job: reach for the cheapest tier for labels and simple foods, and save the premium models for the messy, real-world plates where reliability is worth paying for — and even there, judge them over several runs, never just one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7b05179fe21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Messages API: Structured Outputs]]></title>
            <link>https://medium.com/@gurpartap.sandhu3/claude-messages-api-structured-outputs-451344d7f763?source=rss-472ef08d0073------2</link>
            <guid isPermaLink="false">https://medium.com/p/451344d7f763</guid>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[GP Sandhu]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 05:10:13 GMT</pubDate>
            <atom:updated>2026-06-21T05:10:13.684Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*-_pSRqXWpLcWybagetV-2Q.png" /><figcaption>Structured output from Claude Messages API</figcaption></figure><p>A string is the worst possible format for a computer to read. Yet that’s exactly what an LLM gives you by default. In the last post we got Claude to talk back to us through the Messages API — which is perfect when a human is reading the reply, and miserable the moment you want code to do something with it. If you’ve ever wrapped a model call in a try/except around json.loads(), retried on malformed output, or written a regex to fish a value out of a paragraph, you know the pain. Structured outputs fix this at the source: you hand Claude a schema, and the API constrains its output to match it. No parsing errors, no missing fields, no retries — just valid JSON every time.</p><p>In this post we’ll start with the raw <em>output_config</em> approach, then move to the cleaner Pydantic-based <em>messages.parse()</em>, and finish with how required vs. optional fields behave.</p><h4>Output_config for message.create()</h4><p>The most basic way to enable structured outputs is to add <em>output_config</em> to the same messages.create method we learned about in <a href="https://medium.com/@gurpartap.sandhu3/intro-to-anthropic-messages-api-request-response-and-models-2ea8a15dafaf">Intro to Anthropic Messages API</a>.</p><pre>client = anthropic.Anthropic()<br><br>response = client.messages.create(<br>    model=&quot;claude-opus-4-8&quot;,<br>    max_tokens=1024,<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: &quot;Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm.&quot;,<br>        }<br>    ],<br>    output_config={<br>        &quot;format&quot;: {<br>            &quot;type&quot;: &quot;json_schema&quot;,<br>            &quot;schema&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;name&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                    &quot;email&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                    &quot;plan_interest&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                    &quot;demo_requested&quot;: {&quot;type&quot;: &quot;boolean&quot;},<br>                },<br>                &quot;required&quot;: [&quot;name&quot;, &quot;email&quot;, &quot;plan_interest&quot;, &quot;demo_requested&quot;],<br>                &quot;additionalProperties&quot;: False,<br>            },<br>        }<br>    },<br>)</pre><p>In the response we see that the text is the exact schema we requested in <em>output_config</em></p><pre>{<br>    &quot;id&quot;: &quot;msg_01AdhYxgQzo2qCwAYHpiqmz3&quot;,<br>    &quot;container&quot;: null, <br>    &quot;content&quot;: [<br>      {<br>        &quot;citations&quot;: null,<br>        &quot;text&quot;: {<br>          &quot;name&quot;: &quot;John Smith&quot;,<br>          &quot;email&quot;: &quot;john@example.com&quot;,<br>          &quot;plan_interest&quot;: &quot;Enterprise&quot;,<br>          &quot;demo_requested&quot;: true<br>        },<br>        &quot;type&quot;: &quot;text&quot;<br>      }<br>    ],<br>    &quot;model&quot;: &quot;claude-opus-4-8&quot;,<br>    &quot;role&quot;: &quot;assistant&quot;,<br>    &quot;stop_details&quot;: null,<br>    &quot;stop_reason&quot;: &quot;end_turn&quot;,<br>    &quot;stop_sequence&quot;: null,<br>    &quot;type&quot;: &quot;message&quot;,<br>    &quot;usage&quot;: {<br>      &quot;cache_creation&quot;: {<br>        &quot;ephemeral_1h_input_tokens&quot;: 0,<br>        &quot;ephemeral_5m_input_tokens&quot;: 0<br>      },<br>      &quot;cache_creation_input_tokens&quot;: 0,<br>      &quot;cache_read_input_tokens&quot;: 0,<br>      &quot;inference_geo&quot;: &quot;global&quot;,<br>      &quot;input_tokens&quot;: 330,<br>      &quot;output_tokens&quot;: 41,<br>      &quot;server_tool_use&quot;: null,<br>      &quot;service_tier&quot;: &quot;standard&quot;,<br>      &quot;output_tokens_details&quot;: {<br>        &quot;thinking_tokens&quot;: 0<br>      }<br>    }<br>  }</pre><h4>Pydantic using messages.parse()</h4><p>Writing JSON Schema by hand gets old fast — it’s verbose, easy to typo, and divorced from your actual types. If you’re in Python, you already have a better way to describe a shape: a Pydantic model. The SDK’s messages.parse() lets you pass one directly as output_format. It generates the schema for you, validates the response, and hands back a typed object you can use right away — no json.loads(), no guessing at keys.</p><pre>client = anthropic.Anthropic()<br><br><br>class ContactInfo(BaseModel):<br>    name: str<br>    email: str<br>    plan_interest: str<br>    demo_requested: bool<br><br><br>response = client.messages.parse(<br>    model=&quot;claude-opus-4-8&quot;,<br>    max_tokens=1024,<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: &quot;Extract the key information from this email: John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm.&quot;,<br>        }<br>    ],<br>    output_format=ContactInfo,<br>)<br><br># Access the parsed output directly as a typed Pydantic object<br>contact = response.parsed_output<br>print(contact.name, contact.email, contact.plan_interest, contact.demo_requested)<br><br># Full response, pretty-printed<br>print(response.model_dump_json(indent=2, warnings=False))</pre><p>This is what the <em>parsed_ouput</em> for contact looks like in the response:</p><pre>ContactInfo(name=&#39;John Smith&#39;, email=&#39;john@example.com&#39;, plan_interest=&#39;Enterprise&#39;, demo_requested=True)<br><br>  As JSON (contact.model_dump_json(indent=2)):<br><br>  {<br>    &quot;name&quot;: &quot;John Smith&quot;,<br>    &quot;email&quot;: &quot;john@example.com&quot;,<br>    &quot;plan_interest&quot;: &quot;Enterprise&quot;,<br>    &quot;demo_requested&quot;: true<br>  }</pre><p><em>messages.parse() </em>returns an extra <em>parsed_output</em> object in addition to the text that <em>messages.create()</em> returns with <em>output_configs</em></p><pre>The raw object (repr(response)):<br><br>  ParsedMessage[TypeVar](id=&#39;msg_01YBo4YjtDnN8NmrbW3ACHYS&#39;, container=None, content=[ParsedTextBlock[TypeVar](citations=None, text=&#39;{&quot;name&quot;:&quot;John<br>  Smith&quot;,&quot;email&quot;:&quot;john@example.com&quot;,&quot;plan_interest&quot;:&quot;Enterprise&quot;,&quot;demo_requested&quot;:true}&#39;, type=&#39;text&#39;, parsed_output=ContactInfo(name=&#39;John Smith&#39;,<br>  email=&#39;john@example.com&#39;, plan_interest=&#39;Enterprise&#39;, demo_requested=True))], model=&#39;claude-opus-4-8&#39;, role=&#39;assistant&#39;, stop_details=None, stop_reason=&#39;end_turn&#39;,<br>  stop_sequence=None, type=&#39;message&#39;, usage=Usage(cache_creation=CacheCreation(ephemeral_1h_input_tokens=0, ephemeral_5m_input_tokens=0), cache_creation_input_tokens=0,<br>  cache_read_input_tokens=0, inference_geo=&#39;global&#39;, input_tokens=388, output_tokens=41, server_tool_use=None, service_tier=&#39;standard&#39;,<br>  output_tokens_details={&#39;thinking_tokens&#39;: 0}))<br><br>  As JSON (response.model_dump_json(indent=2, warnings=False)):<br><br>  {<br>    &quot;id&quot;: &quot;msg_01YBo4YjtDnN8NmrbW3ACHYS&quot;,<br>    &quot;container&quot;: null,<br>    &quot;content&quot;: [<br>      {<br>        &quot;citations&quot;: null,<br>        &quot;text&quot;: &quot;{\&quot;name\&quot;:\&quot;John Smith\&quot;,\&quot;email\&quot;:\&quot;john@example.com\&quot;,\&quot;plan_interest\&quot;:\&quot;Enterprise\&quot;,\&quot;demo_requested\&quot;:true}&quot;,<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;parsed_output&quot;: {<br>          &quot;name&quot;: &quot;John Smith&quot;,<br>          &quot;email&quot;: &quot;john@example.com&quot;,<br>          &quot;plan_interest&quot;: &quot;Enterprise&quot;,<br>          &quot;demo_requested&quot;: true<br>        }<br>      }<br>    ],<br>    &quot;model&quot;: &quot;claude-opus-4-8&quot;,<br>    &quot;role&quot;: &quot;assistant&quot;,<br>    &quot;stop_details&quot;: null,<br>    &quot;stop_reason&quot;: &quot;end_turn&quot;,<br>    &quot;stop_sequence&quot;: null,<br>    &quot;type&quot;: &quot;message&quot;,<br>    &quot;usage&quot;: {<br>      &quot;cache_creation&quot;: {<br>        &quot;ephemeral_1h_input_tokens&quot;: 0,<br>        &quot;ephemeral_5m_input_tokens&quot;: 0<br>      },<br>      &quot;cache_creation_input_tokens&quot;: 0,<br>      &quot;cache_read_input_tokens&quot;: 0,<br>      &quot;inference_geo&quot;: &quot;global&quot;,<br>      &quot;input_tokens&quot;: 388,<br>      &quot;output_tokens&quot;: 41,<br>      &quot;server_tool_use&quot;: null,<br>      &quot;service_tier&quot;: &quot;standard&quot;,<br>      &quot;output_tokens_details&quot;: {<br>        &quot;thinking_tokens&quot;: 0<br>      }<br>    }<br>  }</pre><h4>Required vs optional fields</h4><p>Once you’re defining schemas as Pydantic models, required vs. optional comes for free — you never write a “required” list yourself. The rule is simple: a field with no default is required, and a field with a default is optional. The SDK reads your model, puts the no-default fields in the schema’s required array, and leaves the rest out. Required fields are guaranteed in every response; optional ones get filled with a real value when the info is there, or fall back to their default when it isn’t.</p><pre>class ContactInfo(BaseModel):<br>    # required — always present in the output<br>    name: str<br>    email: str<br>    plan_interest: str<br>    demo_requested: bool<br>    # optional — may be omitted by the model; default applies on parse()<br>    demo_time: str | None = None  # nullable + omittable<br>    notes: str = &quot;&quot;  # sentinel default (cheaper than a union)</pre><blockquote>John Smith (john@example.com) is interested in our Enterprise plan and wants to schedule a demo for next Tuesday at 2pm. He mentioned his team has 50 seats.</blockquote><pre>&quot;text&quot;: &quot;{\&quot;name\&quot;:\&quot;John Smith\&quot;,\&quot;email\&quot;:\&quot;john@example.com\&quot;,\&quot;plan_interest\&quot;:\&quot;Enterprise\&quot;,\&quot;demo_requested\&quot;:true,\&quot;demo_time\&quot;:\&quot;next Tuesday at 2pm\&quot;,\&quot;notes\&quot;:\&quot;His team has 50 seats.\&quot;}&quot;,<br>&quot;type&quot;: &quot;text&quot;,<br>&quot;parsed_output&quot;: {<br>          &quot;name&quot;: &quot;John Smith&quot;,<br>          &quot;email&quot;: &quot;john@example.com&quot;,<br>          &quot;plan_interest&quot;: &quot;Enterprise&quot;,<br>          &quot;demo_requested&quot;: true,<br>          &quot;demo_time&quot;: &quot;next Tuesday at 2pm&quot;,<br>          &quot;notes&quot;: &quot;His team has 50 seats.&quot;<br>}</pre><blockquote>Jane Doe (jane@example.com) is interested in the Pro plan.</blockquote><pre>&quot;text&quot;: &quot;{\&quot;name\&quot;: \&quot;Jane Doe\&quot;, \&quot;email\&quot;: \&quot;jane@example.com\&quot;, \&quot;plan_interest\&quot;: \&quot;Pro\&quot;, \&quot;demo_requested\&quot;: false, \&quot;demo_time\&quot;: null, \&quot;notes\&quot;: \&quot;\&quot;}&quot;,<br>&quot;type&quot;: &quot;text&quot;,<br>&quot;parsed_output&quot;: {<br>          &quot;name&quot;: &quot;Jane Doe&quot;,<br>          &quot;email&quot;: &quot;jane@example.com&quot;,<br>          &quot;plan_interest&quot;: &quot;Pro&quot;,<br>          &quot;demo_requested&quot;: false,<br>          &quot;demo_time&quot;: null,<br>          &quot;notes&quot;: &quot;&quot;<br>        }</pre><h4>Conclusion</h4><p>That’s structured outputs end to end. We started by handing Claude a raw JSON Schema through output_config, then let Pydantic write that schema for us with messages.parse() and got a typed object back instead of a string to parse. Along the way we saw how required and optional fields fall out of your model definition for free. The payoff is the same no matter which style you pick: the response is valid JSON that matches your schema every time, so the model’s output drops straight into your code with no try/except, no retries, and no regex. That turns Claude from something you read into something you can build on — which is exactly what you need once you start wiring these calls into real applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=451344d7f763" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Messages API: Passing images as input]]></title>
            <link>https://medium.com/@gurpartap.sandhu3/claude-messages-api-passing-images-as-input-ca6017a48672?source=rss-472ef08d0073------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca6017a48672</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <dc:creator><![CDATA[GP Sandhu]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 21:59:03 GMT</pubDate>
            <atom:updated>2026-06-20T21:59:03.702Z</atom:updated>
            <content:encoded><![CDATA[<p>Claude can read images, not just text. In the <a href="https://medium.com/@gurpartap.sandhu3/intro-to-anthropic-messages-api-request-response-and-models-2ea8a15dafaf">Messages API intro</a> we sent Claude a plain text prompt; passing an image works the exact same way — you just add an image block to the content array next to your text. Point that block at some base64-encoded image data, and Claude treats the picture as part of the prompt: it can describe it, answer questions about it, and reason over what’s in the frame. In this blog we’ll cover how to use this <strong><em>vision</em></strong> capability from Claude, where it shines, where it quietly trips up, and how much the prompt and the model you pick impact it.</p><h4>Basic vision request response</h4><p>Using this is straightforward. Read the image off disk, base64-encode it, and pass it to client.messages.create inside an image block — media_type tells Claude what kind of file it’s looking at, and data is the encoded bytes. Then add a text block right after it with your question. Here we ask the simplest thing you can ask of a picture — <em>what do you see?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qln7c-wVy7eDv9lIjHkTfA.jpeg" /><figcaption>Input image to Claude API (<a href="https://bigshinyballs.com/cdn/shop/files/hf_20260508_185549_361f00be-18ff-4a4b-a385-0cc6cb242fee.png?v=1778553997&amp;width=1780">source</a>)</figcaption></figure><p>Here is the code snippet to use the vision capabilities and the entire response from the API:</p><pre>image1_data = base64.standard_b64encode(image_bytes).decode(&quot;utf-8&quot;)<br><br>client = anthropic.Anthropic()<br>response = client.messages.create(<br>    model=&quot;claude-opus-4-8&quot;,<br>    max_tokens=1024,<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: [<br>                {<br>                    &quot;type&quot;: &quot;image&quot;,<br>                    &quot;source&quot;: {<br>                        &quot;type&quot;: &quot;base64&quot;,<br>                        &quot;media_type&quot;: image1_media_type,<br>                        &quot;data&quot;: image1_data,<br>                    },<br>                },<br>                {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;What do you see in this image&quot;},<br>            ],<br>        }<br>    ],<br>)<br>print(response)</pre><pre>{<br>  &quot;id&quot;: &quot;msg_01Krkkq5UpPACGsEF3bNGfm9&quot;,<br>  &quot;container&quot;: null,<br>  &quot;content&quot;: [<br>    {<br>      &quot;citations&quot;: null,<br>      &quot;text&quot;: &quot;This image shows a striking display of giant soccer balls arranged on a patch of artificial green turf in what appears to be a sports stadium setting.\n\n**The soccer balls:**\n- There are several oversized soccer balls of varying sizes, from very large to medium and smaller ones\n- They feature a colorful design with the classic pentagon-hexagon pattern, but instead of the traditional black-and-white, the pentagons are colored in **red, blue, and green**\n- The largest ball in the center is the dominant focal point\n\n**The setting:**\n- A large curved **stadium** structure rises in the background with tiered seating\n- A crowd of spectators can be seen in the stands\n- A **large screen/jumbotron** on the right displays what looks like a live soccer match\n- Colorful banners and flags hang around the venue, including what appears to be FIFA World Cup-style branding\n- String lights are draped overhead, adding a festive atmosphere\n- The lighting suggests early evening or sunset\n\nThe overall scene has a celebratory, promotional feel—likely a fan zone or event installation associated with a major soccer tournament like the World Cup. The image appears to be digitally created or enhanced given the perfect arrangement and polished look.&quot;,<br>      &quot;type&quot;: &quot;text&quot;<br>    }<br>  ],<br>  &quot;model&quot;: &quot;claude-opus-4-8&quot;,<br>  &quot;role&quot;: &quot;assistant&quot;,<br>  &quot;stop_details&quot;: null,<br>  &quot;stop_reason&quot;: &quot;end_turn&quot;,<br>  &quot;stop_sequence&quot;: null,<br>  &quot;type&quot;: &quot;message&quot;,<br>  &quot;usage&quot;: {<br>    &quot;cache_creation&quot;: {<br>      &quot;ephemeral_1h_input_tokens&quot;: 0,<br>      &quot;ephemeral_5m_input_tokens&quot;: 0<br>    },<br>    &quot;cache_creation_input_tokens&quot;: 0,<br>    &quot;cache_read_input_tokens&quot;: 0,<br>    &quot;inference_geo&quot;: &quot;global&quot;,<br>    &quot;input_tokens&quot;: 1416,<br>    &quot;output_tokens&quot;: 395,<br>    &quot;server_tool_use&quot;: null,<br>    &quot;service_tier&quot;: &quot;standard&quot;,<br>    &quot;output_tokens_details&quot;: {<br>      &quot;thinking_tokens&quot;: 0<br>    }<br>  }</pre><p>Here is a visual from Anthropic on how the API request response works. The only difference is the image block in addition to the text block in the request. <em>Anthropic also supports passing URL as input</em> but I noticed it often ran into issues fetching the image due to various bot controls on domains. Fetching images with your code with proper error handling seems like the more reliable option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQK0dEZjaiWSsysOgIF3Ig.jpeg" /></figure><h4>How prompts and models impact accuracy</h4><p>Let’s test this for a task to count objects in an image. This is a practical thing that folks might want to use AI models for and it is apparently one of the of the things <a href="https://platform.claude.com/docs/en/build-with-claude/vision#using-base64:~:text=Counting%3A%20Claude%20can%20give%20approximate%20counts%20of%20objects%20in%20an%20image%20but%20may%20not%20always%20be%20precisely%20accurate%2C%20especially%20with%20large%20numbers%20of%20small%20objects">Anthropic thinks Claude isn’t great at</a>. Good task to test how prompts and models impact result accuracy. We will use the same image of large soccer balls with a simple prompt asking how many balls are in the image. Here is how Claude Opus 4.8 (most capable model available at this time due to Mythos no longer being available) does with this.</p><pre>{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;How many balls are in the image&quot;}</pre><pre>{<br>  &quot;id&quot;: &quot;msg_012ZFL8hH8MChrGZSbcJUjaQ&quot;,<br>  &quot;container&quot;: null,<br>  &quot;content&quot;: [<br>    {<br>      &quot;citations&quot;: null,<br>      &quot;text&quot;: &quot;There are **6 soccer balls** in the image. They vary in size, ranging from one very large ball in the center to several smaller ones arranged around it, all displayed on a patch of green turf in what appears to be a stadium setting.&quot;,<br>      &quot;type&quot;: &quot;text&quot;<br>    }<br>  ],<br>  &quot;model&quot;: &quot;claude-opus-4-8&quot;,<br>  &quot;role&quot;: &quot;assistant&quot;,<br>  &quot;stop_details&quot;: null,<br>  &quot;stop_reason&quot;: &quot;end_turn&quot;,<br>  &quot;stop_sequence&quot;: null,<br>  &quot;type&quot;: &quot;message&quot;,<br>  &quot;usage&quot;: {<br>    &quot;cache_creation&quot;: {<br>      &quot;ephemeral_1h_input_tokens&quot;: 0,<br>      &quot;ephemeral_5m_input_tokens&quot;: 0<br>    },<br>    &quot;cache_creation_input_tokens&quot;: 0,<br>    &quot;cache_read_input_tokens&quot;: 0,<br>    &quot;inference_geo&quot;: &quot;global&quot;,<br>    &quot;input_tokens&quot;: 1417,<br>    &quot;output_tokens&quot;: 73,<br>    &quot;server_tool_use&quot;: null,<br>    &quot;service_tier&quot;: &quot;standard&quot;,<br>    &quot;output_tokens_details&quot;: {<br>      &quot;thinking_tokens&quot;: 0<br>    }<br>  }<br>}</pre><p><em>Even the most capable model with a lazy prompt got this wrong</em>. Fundamentals of good prompts remains important with images as input too. Now let’s write a more detailed prompt that you would use in a real production use case and see if it makes a difference.</p><pre>{&quot;type&quot;: &quot;text&quot;,<br> &quot;text&quot;: &quot;&quot;&quot;<br>   Analyze this image of soccer balls and determine the exact count using this methodology:<br>   1. Begin by identifying each unique soccer one at a time. Assign each a number as you identify it.<br>   2. Verify your result by counting with a different method. Start from the bottom-left corner and work row by row, from left to right.<br><br>   What is the exact, verified number of soccer balls in this image?<br>   &quot;&quot;&quot;</pre><pre>{<br>  &quot;id&quot;: &quot;msg_01HRQxk23a8aLjtE3Vr7kPQZ&quot;,<br>  &quot;container&quot;: null,<br>  &quot;content&quot;: [<br>    {<br>      &quot;citations&quot;: null,<br>      &quot;text&quot;: &quot;# Soccer Ball Count Analysis\n\n## Method 1: Identifying Each Unique Ball\n\nLet me identify each ball one at a time:\n\n1. **Large central ball** – the giant one in the middle with red/blue/green pentagons\n2. **Large left ball** – big ball on the left with red pentagon center\n3. **Large right ball** – big ball on the right with green pentagon center\n4. **Small front-left ball** – small ball at bottom left with red center\n5. **Small front-center ball** – small ball with green center, left of the giant ball\n6. **Medium front-right ball** – ball in front of right large ball, with red pentagon\n7. **Small far-right ball** – small ball at bottom right with red center\n\n## Method 2: Verification (Bottom-Left to Right, Row by Row)\n\n**Front row (smaller balls, bottom):**\n- Bottom-left small ball (red center) → 1\n- Small green-center ball → 2\n- Medium red-center ball (right of center) → 3\n- Small far-right ball (red center) → 4\n\n**Back row (larger balls):**\n- Large left ball → 5\n- Giant central ball → 6\n- Large right ball → 7\n\n## Verified Result\n\n**There are exactly 7 soccer balls in this image.**\n\nBoth methods confirm the same count: **7 soccer balls** (3 large in back, 4 smaller in front).&quot;,<br>      &quot;type&quot;: &quot;text&quot;<br>    }<br>  ],<br>  &quot;model&quot;: &quot;claude-opus-4-8&quot;,<br>  &quot;role&quot;: &quot;assistant&quot;,<br>  &quot;stop_details&quot;: null,<br>  &quot;stop_reason&quot;: &quot;end_turn&quot;,<br>  &quot;stop_sequence&quot;: null,<br>  &quot;type&quot;: &quot;message&quot;,<br>  &quot;usage&quot;: {<br>    &quot;cache_creation&quot;: {<br>      &quot;ephemeral_1h_input_tokens&quot;: 0,<br>      &quot;ephemeral_5m_input_tokens&quot;: 0<br>    },<br>    &quot;cache_creation_input_tokens&quot;: 0,<br>    &quot;cache_read_input_tokens&quot;: 0,<br>    &quot;inference_geo&quot;: &quot;global&quot;,<br>    &quot;input_tokens&quot;: 1536,<br>    &quot;output_tokens&quot;: 448,<br>    &quot;server_tool_use&quot;: null,<br>    &quot;service_tier&quot;: &quot;standard&quot;,<br>    &quot;output_tokens_details&quot;: {<br>      &quot;thinking_tokens&quot;: 0<br>    }<br>  }<br>}</pre><p>The better prompt gets the model to identify the number of balls accurately.</p><p><strong>Model quality impact</strong></p><p>The next thing that impact the quality is the model itself. I ran the same prompt with Haiku (smaller, cheaper, faster model) and it got it wrong even with the better prompt</p><pre>{<br>  &quot;id&quot;: &quot;msg_01STG71MboeJcLCvjj9gumLG&quot;,<br>  &quot;container&quot;: null,<br>  &quot;content&quot;: [<br>    {<br>      &quot;citations&quot;: null,<br>      &quot;text&quot;: &quot;# Soccer Ball Count Analysis\n\n## Method 1: Individual Identification\nLet me identify each soccer ball from largest to smallest:\n\n1. **Large ball (center)** - Red pentagon center\n2. **Large ball (left)** - Blue pentagon center\n3. **Large ball (right)** - Green pentagon center\n4. **Medium ball (left-center)** - Green pentagon center\n5. **Medium ball (right-center)** - Red pentagon center\n6. **Small ball (far left)** - Red pentagon center\n7. **Small ball (center-left)** - White/neutral pentagon\n8. **Small ball (far right)** - Red pentagon center\n\n**Method 1 Total: 8 soccer balls**\n\n## Method 2: Bottom-Left to Right, Row by Row\n\n**Bottom Row (smallest balls):**\n- Position 1 (far left): Small ball ✓\n- Position 2 (left-center): Small ball ✓\n- Position 3 (center-right): Small ball ✓\n- Position 4 (far right): Small ball ✓\n\n**Middle Row (medium balls):**\n- Position 1 (left): Medium ball ✓\n- Position 2 (right): Medium ball ✓\n\n**Top Row (largest balls):**\n- Position 1 (left): Large ball ✓\n- Position 2 (center): Large ball ✓\n- Position 3 (right): Large ball ✓\n\n**Method 2 Total: 9 soccer balls**\n\n## Verification\n\nUpon careful recount, the correct total is **9 soccer balls** - 3 large, 2 medium, and 4 small balls arranged in a pyramidal formation.&quot;,<br>      &quot;type&quot;: &quot;text&quot;<br>    }<br>  ],<br>  &quot;model&quot;: &quot;claude-haiku-4-5-20251001&quot;,<br>  &quot;role&quot;: &quot;assistant&quot;,<br>  &quot;stop_details&quot;: null,<br>  &quot;stop_reason&quot;: &quot;end_turn&quot;,<br>  &quot;stop_sequence&quot;: null,<br>  &quot;type&quot;: &quot;message&quot;,<br>  &quot;usage&quot;: {<br>    &quot;cache_creation&quot;: {<br>      &quot;ephemeral_1h_input_tokens&quot;: 0,<br>      &quot;ephemeral_5m_input_tokens&quot;: 0<br>    },<br>    &quot;cache_creation_input_tokens&quot;: 0,<br>    &quot;cache_read_input_tokens&quot;: 0,<br>    &quot;inference_geo&quot;: &quot;not_available&quot;,<br>    &quot;input_tokens&quot;: 1509,<br>    &quot;output_tokens&quot;: 396,<br>    &quot;server_tool_use&quot;: null,<br>    &quot;service_tier&quot;: &quot;standard&quot;<br>  }<br>}</pre><p>Sonnet is the other model in the Anthropic family that sits between Opus and Haiku, it got the count right with the good prompt</p><pre>{<br>  &quot;id&quot;: &quot;msg_01DMqnkjpmNshVD21dhxT2Lj&quot;,<br>  &quot;container&quot;: null,<br>  &quot;content&quot;: [<br>    {<br>      &quot;citations&quot;: null,<br>      &quot;text&quot;: &quot;## Step-by-Step Analysis\n\n### Method 1: Identifying Each Ball Individually\n\nLet me assign numbers to each distinct soccer ball:\n\n1. **Ball #1** - Small ball, bottom-left area\n2. **Ball #2** - Medium-large ball, left side\n3. **Ball #3** - Medium ball, front-center-left\n4. **Ball #4** - Large ball, center (the biggest one)\n5. **Ball #5** - Medium-small ball, front-center-right\n6. **Ball #6** - Medium ball, right-center background\n7. **Ball #7** - Large ball, far right\n\n**Count from Method 1: 7 balls**\n\n---\n\n### Method 2: Row-by-Row, Left to Right\n\n**Back row (larger/elevated balls):**\n- Ball at left → Ball at center → Ball at right = **3 balls**\n\n**Front row (smaller/lower balls):**\n- Smallest ball (far left) → Medium ball (center-left) → Small ball (center-right) → Small ball (right) = **4 balls**\n\n**Count from Method 2: 3 + 4 = 7 balls**\n\n---\n\n## ✅ Verified Answer: **7 Soccer Balls**&quot;,<br>      &quot;type&quot;: &quot;text&quot;<br>    }<br>  ],<br>  &quot;model&quot;: &quot;claude-sonnet-4-6&quot;,<br>  &quot;role&quot;: &quot;assistant&quot;,<br>  &quot;stop_details&quot;: null,<br>  &quot;stop_reason&quot;: &quot;end_turn&quot;,<br>  &quot;stop_sequence&quot;: null,<br>  &quot;type&quot;: &quot;message&quot;,<br>  &quot;usage&quot;: {<br>    &quot;cache_creation&quot;: {<br>      &quot;ephemeral_1h_input_tokens&quot;: 0,<br>      &quot;ephemeral_5m_input_tokens&quot;: 0<br>    },<br>    &quot;cache_creation_input_tokens&quot;: 0,<br>    &quot;cache_read_input_tokens&quot;: 0,<br>    &quot;inference_geo&quot;: &quot;global&quot;,<br>    &quot;input_tokens&quot;: 1509,<br>    &quot;output_tokens&quot;: 297,<br>    &quot;server_tool_use&quot;: null,<br>    &quot;service_tier&quot;: &quot;standard&quot;<br>  }<br>}  </pre><blockquote>So quality of response for vision tasks depends on the model and the prompt</blockquote><h4>Comparing images</h4><p>Another practical thing vision unlocks is comparing images. Here is how you can do this with Claude API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qln7c-wVy7eDv9lIjHkTfA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*naMKapCEOGn_zZSsLzpz5A.jpeg" /><figcaption>Using Claude to find differences between images</figcaption></figure><pre>client = anthropic.Anthropic()<br>response = client.messages.create(<br>    model=&quot;claude-opus-4-8&quot;,<br>    max_tokens=1024,<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: [<br>                {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;Image 1:&quot;},<br>                {<br>                    &quot;type&quot;: &quot;image&quot;,<br>                    &quot;source&quot;: {<br>                        &quot;type&quot;: &quot;base64&quot;,<br>                        &quot;media_type&quot;: image1_media_type,<br>                        &quot;data&quot;: image1_data,<br>                    },<br>                },<br>                {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;Image 2:&quot;},<br>                {<br>                    &quot;type&quot;: &quot;image&quot;,<br>                    &quot;source&quot;: {<br>                        &quot;type&quot;: &quot;base64&quot;,<br>                        &quot;media_type&quot;: image2_media_type,<br>                        &quot;data&quot;: image2_data,<br>                    },<br>                },<br>                {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;How are these images different?&quot;},<br>            ],<br>        }<br>    ],<br>)<br>print(response)</pre><blockquote>“text”: “These two images share a playful theme of oversized soccer balls with colorful pentagons (in red, blue, and green), but they differ significantly in setting and composition:\n\n## Image 1 — Stadium Setting\n- **Location:** A large sports stadium with tiered seating, crowds of spectators, and a big screen showing a match\n- **Atmosphere:** Energetic, festive event vibe with string lights and colorful World Cup-style banners/flags\n- **Ball arrangement:** Six soccer balls clustered tightly together on a small patch of artificial grass, varying in size from huge to small\n- **Mood:** Vibrant, crowded, sporty celebration\n\n## Image 2 — Residential Backyard\n- **Location:** An upscale shingle-style home (Hamptons-style) with a manicured lawn and a swimming pool\n- **Atmosphere:** Calm, serene, luxurious suburban setting with hydrangeas, hedges, and trees\n- **Ball arrangement:** Six soccer balls spread out across the lawn and even floating in the pool, more spaced apart\n- **Mood:** Peaceful, elegant, leisurely\n\n## Key Difference\nThe **same decorative soccer balls** are placed in two completely contrasting environments — one a bustling public stadium and the other a private, tranquil estate.”</blockquote><p>As you can see it does a good job at identifying differences, still bad at counting without detailed prompt :)</p><h4>“I don’t know who this person is” policy</h4><p>Another interesting quirk for Claude vision capabilities is that it refuses to identify people, even some of the most easily recognizable people</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*gKu5td7sNQ5U5UYTAQQV3g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5g84xP0r5Z9xCvsiY_H5g.jpeg" /><figcaption>Images of well known people to feed to Claude API to identify</figcaption></figure><blockquote>“text”: “I can see an elderly man in this black and white photograph. He has **wild, white hair**, a **mustache**, and is wearing a **tweed jacket**. The photo appears to be a classic portrait style, likely from the **mid-20th century**.\n\nI’m not able to identify who this person is from the image alone. Could you tell me who this is?”</blockquote><blockquote>“text”: “Based on the image, I can see a footballer wearing the **Argentina national team jersey #10** with the **AFA (Asociación del Fútbol Argentino)** crest, along with a **FIFA World Cup** patch on the sleeve. The jersey also shows an **Adidas** logo.\n\nHowever, I’m not able to identify who this person is from the photo alone. Could you tell me who this is? 😊”</blockquote><p>The reason for this is that <a href="https://platform.claude.com/docs/en/build-with-claude/vision#using-url:~:text=People%20identification%3A%20Claude%20cannot%20be%20used%20to%20name%20people%20in%20images%20and%20refuses%20to%20do%20so">Anthropic intentionally doesn’t want Claude to identify people</a>. We’ll do a future blog to compare this with OpenAI, Google, and X AI models.</p><h4>Published limits and cost</h4><p><a href="https://platform.claude.com/docs/en/build-with-claude/vision">There are some limits worth knowing</a> — you can send up to 10 MB per image and up to 100 images per request (600 on models with a smaller context window), in JPEG, PNG, GIF, or WebP, up to 8000×8000 px. Images aren’t free — they count as input tokens. Claude reads an image in 28×28 pixel patches, so a picture costs roughly (width/28) × (height/28) tokens. A 1000×1000 image works out to about 1,296 tokens — on Opus 4.8 at $5 per million input tokens, that’s roughly $0.0065 per image, or about $6.50 per thousand. Anything larger than the model’s native resolution (2576 px on the long edge for Opus 4.8, 1568 px on older models) gets downscaled before processing, which caps the token cost — but also means a 4K original loses detail, so resizing thoughtfully on your end usually beats dumping in the full file.</p><h4>Conclusion</h4><p>Claude’s vision is genuinely useful — describing scenes, comparing images, pulling structure out of a picture — and it’s a one-line change from a text-only request: drop an image block into the content array. But the same two levers that govern text quality govern vision too. A lazy prompt miscounts; a careful one with an explicit method gets it right. A cheaper model trips where a stronger one holds. Not identifying people is deliberate, documented behavior — not a bug. Pick the model for the task, write the prompt like you mean it, and verify anything that has to be exact.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca6017a48672" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Anthropic messages API: Request, Response, and Models]]></title>
            <link>https://medium.com/@gurpartap.sandhu3/intro-to-anthropic-messages-api-request-response-and-models-2ea8a15dafaf?source=rss-472ef08d0073------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ea8a15dafaf</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <dc:creator><![CDATA[GP Sandhu]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 01:23:19 GMT</pubDate>
            <atom:updated>2026-06-20T01:29:55.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ce52SdSmHZCgDlvEQaaGg.jpeg" /></figure><p><strong>Your First Message to Claude: The Anthropic Messages API</strong></p><p>If you’ve never called a large language model from code before, the API can feel like a black box. It isn’t. At its core, talking to Claude is a simple round trip: <strong>You send a list of messages. You get one message back.</strong></p><p>That’s the whole idea. In this post we’ll do exactly that — send a single message and look closely at what comes back. We’ll also see how Claude’s three model “sizes” (Haiku, Sonnet, and Opus) differ in speed, cost, and capability.</p><p>We’re deliberately keeping the scope small. Streaming, extended thinking, and tool use are powerful features, but each deserves its own post. Here we focus on the fundamentals: the request, the response, and the models.</p><p><strong>1. Setup</strong></p><p>Install the official Python SDK:</p><pre>pip install anthropic</pre><p>Then you need an API key. Create one in the [Anthropic Console](https://console.anthropic.com/settings/keys) and set it as an environment variable:</p><pre>export ANTHROPIC_API_KEY=&quot;sk-ant-…&quot;</pre><p>⚠️ Never hardcode an API key in your code, and never paste one into a chat, a screenshot, or a public repo. This is a key to your account and your billing. If one is ever exposed, rotate it immediately in the Console. Keeping it in an environment variable keeps it out of your source code.</p><p>The SDK reads `ANTHROPIC_API_KEY` from the environment automatically, so creating a client takes no arguments:</p><pre>from anthropic import Anthropic<br><br>client = Anthropic() # reads ANTHROPIC_API_KEY from the environment</pre><p><strong>2. Sending your first message</strong></p><p>Here is the simplest possible program — send one message, print everything that comes back:</p><pre><br>response = client.messages.create(<br>    model=&quot;claude-sonnet-4-6&quot;,<br>    max_tokens=1000,<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: &quot;What should I search for to find the latest developments in renewable energy?&quot;,<br>        }<br>    ],<br>)<br>print(response)</pre><p>Three inputs are doing the work here:</p><p><strong>`model`</strong> — which Claude model should answer. We’ll compare the options in a moment. Use the exact model ID string (e.g. `claude-opus-4–8`); don’t add date suffixes. You can get all the models via</p><pre>client.models.list()</pre><p><strong>`max_tokens`</strong>— a cap on how long the <em>*response*</em> can be, measured in tokens (roughly, pieces of words). This limits the output, not your input.</p><p><strong>`messages`</strong> — the conversation so far, as a list of `{“role”, “content”}` objects. The role is either `”user”` (you) or `”assistant”` (Claude). The first message must always be from the `user`. Run it, and `print(response)` shows the entire response: a single structured `Message` object. Alongside the reply itself, it carries metadata about the call — which model answered, why Claude stopped, and how many tokens were used. The takeaway for now is simple: <strong>one request gives you one structured object back. </strong>We’ll walk through the fields in section 4.</p><p><strong>3. What Claude does with it</strong></p><p>Here’s the mental model. Claude reads your entire `messages` list as <strong>context </strong>and generates the most likely helpful continuation — the assistant’s next turn. That’s it. There’s no hidden state, no database of your past chats on the server. This leads to one rule that surprises beginners:</p><p><strong>The API is stateless. Claude remembers nothing between calls.</strong></p><p>If you want a back-and-forth conversation, <strong><em>you</em></strong> keep the history and send it every time. Each call includes the full transcript so far:</p><pre>messages = [<br>{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;My name is Sam.&quot;},<br>{&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;Nice to meet you, Sam!&quot;},<br>{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;What&#39;s my name?&quot;},<br>]</pre><p>Because the earlier turns are included, Claude can answer “Your name is Sam.” Drop that history and the next call has no idea who you are. Managing this history is your job as the application developer.</p><p><strong>4. What it sends back</strong></p><pre>Message(<br>    id=&#39;msg_01Syx9kz5wAsRfi6GMNVMJTL&#39;,<br>    container=None,<br>    content=[<br>        TextBlock(<br>            citations=None,<br>            text=(<br>                &#39;Here are some effective search strategies for finding latest &#39;<br>                &#39;renewable energy developments:\n&#39;<br>                &#39;\n&#39;<br>                &#39;## Search Terms to Try\n&#39;<br>                &#39;- &quot;renewable energy news 2024&quot;\n&#39;<br>                &#39;- &quot;solar energy breakthroughs&quot;\n&#39;<br>                &#39;- &quot;wind power latest developments&quot;\n&#39;<br>                &#39;- &quot;clean energy technology advances&quot;\n&#39;<br>                &#39;- &quot;energy storage innovations&quot;\n&#39;<br>                &#39;\n&#39;<br>                &#39;## Reliable Sources to Check Directly\n&#39;<br>                &#39;- **News sites**: Reuters, Bloomberg Green, The Guardian Environment\n&#39;<br>                &#39;- **Industry publications**: PV Magazine, Wind Power Monthly, Energy Monitor\n&#39;<br>                &#39;- **Government/Research**: IEA (iea.org), NREL (nrel.gov), DOE\n&#39;<br>                &#39;- **Academic**: Google Scholar for peer-reviewed research\n&#39;<br>                &#39;\n&#39;<br>                &#39;## Specific Topics Worth Searching\n&#39;<br>                &#39;- Battery storage technology\n&#39;<br>                &#39;- Green hydrogen\n&#39;<br>                &#39;- Offshore wind\n&#39;<br>                &#39;- Solar panel efficiency records\n&#39;<br>                &#39;- Grid modernization\n&#39;<br>                &#39;\n&#39;<br>                &#39;## Practical Tips\n&#39;<br>                &#39;- Use **Google News** and filter by date for recent results\n&#39;<br>                &#39;- Set up **Google Alerts** for terms like &quot;renewable energy&quot;\n&#39;<br>                &#39;- Follow relevant **hashtags** on social media (#CleanEnergy, #RenewableEnergy)\n&#39;<br>                &#39;- Check **RSS feeds** from key publications\n&#39;<br>                &#39;\n&#39;<br>                &#39;## For Technical Depth\n&#39;<br>                &#39;- Search arXiv.org for preprint research papers\n&#39;<br>                &#39;- Check Nature Energy or Science journals\n&#39;<br>                &#39;\n&#39;<br>                &#39;Would you like more specific recommendations based on a particular &#39;<br>                &#39;type of renewable energy or your specific interest level &#39;<br>                &#39;(general news vs. technical research)?&#39;<br>            ),<br>            type=&#39;text&#39;,<br>        ),<br>    ],<br>    model=&#39;claude-sonnet-4-6&#39;,<br>    role=&#39;assistant&#39;,<br>    stop_details=None,<br>    stop_reason=&#39;end_turn&#39;,<br>    stop_sequence=None,<br>    type=&#39;message&#39;,<br>    usage=Usage(<br>        cache_creation=CacheCreation(<br>            ephemeral_1h_input_tokens=0,<br>            ephemeral_5m_input_tokens=0,<br>        ),<br>        cache_creation_input_tokens=0,<br>        cache_read_input_tokens=0,<br>        inference_geo=&#39;global&#39;,<br>        input_tokens=21,<br>        output_tokens=301,<br>        output_tokens_details=None,<br>        server_tool_use=None,<br>        service_tier=&#39;standard&#39;,<br>    ),<br>)</pre><p>Here’s the gist of each, with the deeper details left for later posts:</p><p><strong>`id`</strong> — a unique identifier for this message (`msg_…`), handy for logging or for referencing a specific call later.</p><p><strong>`type`</strong>— always `”message”` for a reply. A tag that labels what kind of object this is.</p><p><strong>`stop_sequence`</strong> — the custom stop string that ended generation, if you set one; otherwise `None`.</p><p><strong>`stop_details`</strong> — extra information that’s only filled in when Claude declines a request (when `stop_reason` is `”refusal”`); `None` the rest of the time.</p><p><strong>`container`</strong> — a reference to the sandbox used by the server-side code-execution tool; `None` for an ordinary text reply.</p><p><strong>`usage`</strong> holds more than the two token counts you’ll reach for most. The extras track <strong>prompt caching</strong> (`cache_creation_input_tokens`, `cache_read_input_tokens`), <strong>extended thinking </strong>(`output_tokens_details`), <strong>server-side tools</strong> (`server_tool_use`), the <strong>service tier</strong> that handled the request, and <strong>`inference_geo`</strong> — the region where inference ran.</p><p>Each of those is a topic for its own post that we’ll cover in the future</p><p><strong>Getting just the answer</strong></p><p>The reply text lives inside `content`, which is a <strong>list of blocks</strong>. For a plain text answer there’s exactly one block, so you reach the text like this:</p><pre>print(response.content[0].text)<br><br># Hello! 👋<br>#<br># How can I help you today?</pre><p>Why a <em>list</em>, and why `[0]`? Because later features (tool use, extended thinking) can return multiple blocks of different kinds. To be safe as your code grows, filter by block type.</p><p><strong>`stop_reason` — </strong>why Claude stopped.</p><p><strong>`end_turn`</strong> — Claude finished its thought naturally. This is the normal case.</p><p><strong>`max_tokens`</strong> — Claude hit your `max_tokens` cap and got cut off. If replies look truncated, raise `max_tokens`.</p><p><strong>`stop_sequence`</strong> — Claude hit a custom stop string you provided.</p><p>You’ll also see `tool_use`, `pause_turn`, and `refusal` once you get into more advanced features — we’ll cover those in later posts.</p><p><strong>`usage` — </strong>tokens, and therefore cost</p><pre>print(response.usage.input_tokens) # tokens you sent<br>print(response.usage.output_tokens) # tokens Claude generated</pre><p>You pay per token, with input and output priced separately. That’s the perfect segue to choosing a model.</p><p><strong>5. The three model types: speed, cost, and capability</strong></p><p>Claude comes in three sizes. Switching between them is a one-line change — same request, different `model` string:</p><pre>import time<br><br>prompt = &quot;Explain what an API is in one sentence.&quot;<br><br>for model in [&quot;claude-haiku-4-5&quot;, &quot;claude-sonnet-4-6&quot;, &quot;claude-opus-4-8&quot;]:<br>    start = time.perf_counter()<br>    response = client.messages.create(<br>        model=model,<br>        max_tokens=256,<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>    )<br>    elapsed = time.perf_counter() - start<br>    text = next(b.text for b in response.content if b.type == &quot;text&quot;)<br>    print(f&quot;{model}:\n  {text}&quot;)<br>    print(f&quot;  tokens in/out: &quot;<br>          f&quot;{response.usage.input_tokens}/{response.usage.output_tokens}&quot;)<br>    print(f&quot;  latency: {elapsed:.2f}s\n&quot;)</pre><p>A run of this prints something like:</p><p>claude-haiku-4–5:</p><pre>An API is a set of rules that allows different software applications to communicate and share data with each other.<br>tokens in/out: 17/24<br>latency: 0.67s</pre><p>claude-sonnet-4–6:</p><pre>An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate and share data with each other.<br>tokens in/out: 17/31<br>latency: 1.21s</pre><p>claude-opus-4–8:</p><pre>An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate and share data with each other.<br>tokens in/out: 19/42<br>latency: 1.19s</pre><p>The three differ along a clear speed ↔ capability ↔ cost axis:</p><p><strong>Claude Haiku 4.5</strong> (`claude-haiku-4–5`) — 200K context, 64K max output. $1.00 in / $5.00 out per 1M tokens. Best for fast, cheap, simple or high-volume tasks.</p><p>-<strong>Claude Sonnet 4.6</strong> (`claude-sonnet-4–6`) — 1M context, 64K max output. $3.00 in / $15.00 out per 1M tokens. Best for a balance of speed and intelligence.</p><p><strong>Claude Opus 4.8</strong> (`claude-opus-4–8`) — 1M context, 128K max output. $5.00 in / $25.00 out per 1M tokens. Best for the hardest reasoning and agentic work.</p><p>A few things to notice:</p><p><strong>Prices are per </strong><em>million</em><strong> tokens.</strong> A short request is a tiny fraction of a cent. Haiku is the cheapest, Opus the most expensive — about 5× the input price with Sonnet in between.</p><p><strong>Context window</strong> is how much you can send in one request. Haiku holds up to 200K tokens; Sonnet and Opus hold up to 1M. (For reference, 1M tokens is roughly a few thousand pages of text.)</p><p><strong>Capability tracks price —</strong> Haiku is fast and great for simple, high-volume jobs like classification or short replies. Opus is the most capable for deep reasoning. Sonnet is the everyday middle ground.</p><p><strong>Speed is the other half of the tradeoff — </strong>The latencies above (averaged over five calls each on this one-sentence prompt) were roughly Haiku ~0.7s, Sonnet ~1.2s, and Opus ~1.2s. Haiku is clearly the quickest; on a prompt this small Sonnet and Opus land close together — the wider speed gaps show up on longer, harder tasks. Latency also swings with output length and network conditions, so treat these as ballpark figures, not benchmarks.</p><p>A good rule of thumb: start with the cheapest model that does the job well, and move up only when you need to.** You can change one string and re-run.</p><p><strong>Wrapping up</strong></p><p>That’s the whole round trip: you send a `messages` list to `client.messages.create()`, Claude reads it as context, and you get back one `Message` whose reply lives in`response.content[0].text`. The API is stateless, so you carry the conversation history yourself. And picking a model is a single-string choice along a speed/cost/capability axis.</p><p>From here, the series builds up:</p><p><strong>Working with image inputs</strong>— sending images and input to the messages API.</p><p><strong>Structured output</strong> — getting the messages API to respond with a strict schema.</p><p><strong>Streaming</strong> — show the reply token by token as it’s generated.</p><p><strong>Extended thinking</strong>— let Claude reason through hard problems before answering.</p><p><strong>Tool use</strong> — let Claude call your functions and APIs.</p><p><strong>Prompt caching</strong> — cut cost and latency on repeated context.</p><p>But every one of those is built on the simple request → response you just learned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ea8a15dafaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and submitting a Claude plugin]]></title>
            <link>https://medium.com/@gurpartap.sandhu3/building-and-submitting-a-claude-plugin-471c5ec10f53?source=rss-472ef08d0073------2</link>
            <guid isPermaLink="false">https://medium.com/p/471c5ec10f53</guid>
            <dc:creator><![CDATA[GP Sandhu]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 20:07:09 GMT</pubDate>
            <atom:updated>2026-03-01T20:07:09.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1cuvNm6PndOZhjBTLFokg.png" /></figure><p><a href="https://github.com/gpsandhu23/blogs/blob/main/plugin-tutorial-blog.md">https://github.com/gpsandhu23/blogs/blob/main/plugin-tutorial-blog.md</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=471c5ec10f53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Extensible AI: How Claude is trying to become the front door for knowledge work]]></title>
            <link>https://medium.com/@gurpartap.sandhu3/the-extensible-ai-how-claude-is-trying-to-become-the-front-door-for-knowledge-work-fe9c4ef93468?source=rss-472ef08d0073------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe9c4ef93468</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[skills]]></category>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[claude]]></category>
            <dc:creator><![CDATA[GP Sandhu]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 18:56:54 GMT</pubDate>
            <atom:updated>2026-03-01T18:56:54.176Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWIDXgMGda_PuIrwp9n-Yg.png" /></figure><p><a href="https://github.com/gpsandhu23/blogs/blob/main/Claude_extensiblity.md">https://github.com/gpsandhu23/blogs/blob/main/Claude_extensiblity.md</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe9c4ef93468" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build ChatGPT App SDK experiences in simple Python]]></title>
            <link>https://medium.com/@gurpartap.sandhu3/build-chatgpt-app-sdk-experiences-in-simple-python-db19b1d3d70e?source=rss-472ef08d0073------2</link>
            <guid isPermaLink="false">https://medium.com/p/db19b1d3d70e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[app-sdk]]></category>
            <dc:creator><![CDATA[GP Sandhu]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 23:02:58 GMT</pubDate>
            <atom:updated>2025-10-12T00:09:13.277Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*axEdVGbC4P-QjJfe.png" /></figure><h4>Introduction</h4><p>On Monday, OpenAI launced App SDK for integrating apps into ChatGPT. It is mostly Model Context Protocol (MCP) with an added React UI component being loaded in an iframe in ChatGPT. This enables developers to create create rich, interactive experiences with custom HTML widgets that render directly inside ChatGPT conversations.</p><p>In this guide, we’ll build a complete MCP server in Python that demonstrates all the key concepts: tools, HTML widgets, data injection, and real-time interactions. By the end, you’ll have a working calculator app that renders beautiful UI components within ChatGPT.</p><p>A lot of the posts and examples have been fairly complex and didn’t make it easy to digest the key priciples. In this post I’ll cover how to do this in simple Python with the MCP SDK to provide an easy intro for Python developers to build these in ChatGPT experiences.</p><h4>What We’re Building</h4><p>We’ll create a simple calculator that:</p><p>- ✅ Exposes a `add` tool that ChatGPT can call</p><p>- ✅ Renders a beautiful HTML widget showing calculation results</p><p>- ✅ Uses structured data injection for dynamic content</p><p>- ✅ Follows official OpenAI Apps SDK patterns</p><p>- ✅ Includes production-ready metadata and validation</p><p>Prerequisites</p><p>- Python 3.8+ with `uv` package manager</p><p>- Basic understanding of FastAPI and web development</p><p>- A ChatGPT account for testing</p><h4>Step 1: Project Setup</h4><p>First, let’s set up our project structure:</p><pre>mkdir chatgpt-mcp-calculator<br>cd chatgpt-mcp-calculator<br>uv init</pre><p>Add the required dependencies to `pyproject.toml`:</p><pre>[project]<br>name = &quot;chatgpt-mcp-calculator&quot;<br>version = &quot;0.1.0&quot;<br>description = &quot;Interactive calculator MCP server for ChatGPT&quot;<br>dependencies = [<br>  &quot;mcp&gt;=1.0.0&quot;,<br>  &quot;fastapi&gt;=0.104.0&quot;,<br>  &quot;uvicorn[standard]&gt;=0.24.0&quot;,<br>  &quot;pydantic&gt;=2.5.0&quot;,<br>]</pre><p>Install dependencies:</p><pre>uv install</pre><h4>Step 2: Understanding MCP Architecture</h4><p>MCP servers expose three core concepts:</p><p>1. <strong><em>Tools</em></strong> — Functions that ChatGPT can call with structured input</p><p>2. <strong><em>Resources</em></strong> — HTML templates and static assets</p><p>3. <strong><em>Structured Content</em></strong> — Data injected into widgets for dynamic rendering</p><p>The magic happens when tools return both structured data and reference HTML templates that ChatGPT renders as interactive widgets.</p><h4>Step 3: Building the Core Server</h4><p>Create `calculator_server.py`:</p><pre>from mcp.server.fastmcp import FastMCP<br>from mcp import types<br>from pydantic import BaseModel<br>import uvicorn<br>from fastapi.middleware.cors import CORSMiddleware<br><br># Initialize FastMCP with stateless HTTP for ChatGPT compatibility<br>mcp = FastMCP(<br>    name=&quot;calculator-server&quot;,<br>    sse_path=&quot;/mcp&quot;,<br>    message_path=&quot;/mcp/messages&quot;,<br>    stateless_http=True,<br>)<br><br># Input validation model<br>class AddInput(BaseModel):<br>    a: float<br>    b: float<br><br># Tool registration with enhanced metadata<br>@mcp.tool()<br>def add(a: float, b: float) -&gt; dict:<br>    &quot;&quot;&quot;Add two numbers together and return structured result.&quot;&quot;&quot;<br>    result = a + b<br>    return {<br>        &quot;content&quot;: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: f&quot;Added {a} + {b} = {result}&quot;}],<br>        &quot;structuredContent&quot;: {<br>            &quot;a&quot;: a,<br>            &quot;b&quot;: b,<br>            &quot;result&quot;: result,<br>            &quot;operation&quot;: &quot;addition&quot;,<br>            &quot;timestamp&quot;: &quot;2024–01–15T10:30:00Z&quot;<br>        },<br>        &quot;_meta&quot;: {<br>            &quot;openai/outputTemplate&quot;: &quot;ui://widget/calculator-result.html&quot;,<br>            &quot;openai/toolInvocation/invoking&quot;: &quot;Calculating…&quot;, <br>            &quot;openai/toolInvocation/invoked&quot;: &quot;Calculation complete!&quot;,<br>            &quot;openai/widgetAccessible&quot;: True,<br>            &quot;openai/resultCanProduceWidget&quot;: True<br>        }<br>    }</pre><h4>Step 4: Creating the HTML Widget</h4><p>The widget is where the magic happens. Create the HTML template that will be injected into ChatGPT:</p><pre>def create_calculator_widget():<br>    return &quot;&quot;&quot;<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;UTF-8&quot;&gt;<br>        &lt;title&gt;Calculator Result&lt;/title&gt;<br>        &lt;style&gt;<br>            .calculator-result {<br>                font-family: -apple-system, BlinkMacSystemFont, &#39;Segoe UI&#39;, sans-serif;<br>                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);<br>                border-radius: 12px;<br>                padding: 24px;<br>                color: white;<br>                text-align: center;<br>                box-shadow: 0 8px 32px rgba(0,0,0,0.1);<br>                margin: 16px 0;<br>            }<br>            .label {<br>                font-size: 14px;<br>                opacity: 0.9;<br>                margin-bottom: 8px;<br>                text-transform: uppercase;<br>                letter-spacing: 1px;<br>            }<br>            .equation {<br>                font-size: 24px;<br>                font-weight: 600;<br>                margin: 12px 0;<br>            }<br>            .result {<br>                font-size: 32px;<br>                font-weight: 700;<br>                margin-top: 16px;<br>                text-shadow: 0 2px 4px rgba(0,0,0,0.2);<br>            }<br>            .loading {<br>                text-align: center;<br>                padding: 20px;<br>                color: #666;<br>            }<br>        &lt;/style&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;div id=&quot;calculator-root&quot;&gt;<br>            &lt;div class=&quot;loading&quot;&gt;Loading calculation…&lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;script type=&quot;module&quot;&gt;<br>            function render() {<br>                const root = document.getElementById(&#39;calculator-root&#39;);<br>                // Check for structured content in multiple possible locations<br>                let data = null;<br>                if (window.openai?.toolOutput?.structuredContent) {<br>                    data = window.openai.toolOutput.structuredContent;<br>                } else if (window.openai?.structuredContent) {<br>                    data = window.openai.structuredContent;<br>                } else if (window.openai?.toolOutput &amp;&amp; window.openai.toolOutput.a !== undefined) {<br>                    data = window.openai.toolOutput;<br>                }<br><br>                if (data &amp;&amp; data.a !== undefined &amp;&amp; data.b !== undefined &amp;&amp; data.result !== undefined) {<br>                    const { a, b, result } = data;<br>                    root.innerHTML = `<br>                        &lt;div class=&quot;calculator-result&quot;&gt;<br>                            &lt;div class=&quot;label&quot;&gt;Calculation Result&lt;/div&gt;<br>                            &lt;div class=&quot;equation&quot;&gt;${a} + ${b}&lt;/div&gt;<br>                            &lt;div class=&quot;result&quot;&gt;= ${result}&lt;/div&gt;<br>                        &lt;/div&gt;<br>                    `;<br>                } else {<br>                    // Debug mode - shows what data is available<br>                    root.innerHTML = `<br>                        &lt;div class=&quot;calculator-result&quot;&gt;<br>                            &lt;div class=&quot;label&quot;&gt;Debug Mode&lt;/div&gt;<br>                            &lt;div style=&quot;font-size: 12px; margin-top: 10px;&quot;&gt;<br>                                Available data: ${JSON.stringify(window.openai, null, 2)}<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    `;<br>                }<br>            }<br>            // Initialize and listen for updates<br>            render();<br>            window.addEventListener(&#39;message&#39;, render);<br>            window.addEventListener(&#39;load&#39;, render);<br>        &lt;/script&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;<br>&quot;&quot;&quot;</pre><p>Register the resource widget</p><pre>@mcp.resource()<br>async def calculator_widget():<br>    &quot;&quot;&quot;Serve the calculator widget HTML.&quot;&quot;&quot;<br>    return {<br>        &quot;uri&quot;: &quot;ui://widget/calculator-result.html&quot;,<br>        &quot;mimeType&quot;: &quot;text/html+skybridge&quot;,<br>        &quot;text&quot;: create_calculator_widget(),<br>        &quot;_meta&quot;: {<br>            &quot;openai/widgetDescription&quot;: &quot;Displays the result of addition calculations in a beautiful gradient card format.&quot;,<br>            &quot;openai/widgetPrefersBorder&quot;: False<br>        }<br>    }</pre><h4>Step 5: Server Configuration and CORS</h4><p>Add CORS middleware and create the ASGI app:</p><pre># Create the FastAPI app from FastMCP<br>app = mcp.streamable_http_app()<br><br># Add CORS middleware for ChatGPT integration<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],  # Configure appropriately for production<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br><br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;🚀 Calculator MCP Server Starting…&quot;)<br>    print(&quot;📊 Tool: add(a, b) - Add two numbers&quot;)<br>    print(&quot;🎨 Widget: Interactive calculation display&quot;)<br>    print(&quot;🌐 Endpoints:&quot;)<br>    print(&quot; - GET /mcp (SSE streaming)&quot;)<br>    print(&quot; - POST /mcp/messages (MCP messages)&quot;)<br>    print(&quot; - GET /mcp/resources (Widget resources)&quot;)<br>    uvicorn.run(&quot;calculator_server:app&quot;, host=&quot;0.0.0.0&quot;, port=8000, reload=True)</pre><h4>Step 6: Testing Locally</h4><p>Create a simple test script `test_server.py`:</p><pre>import requests<br>import json<br><br>BASE_URL = &quot;http://localhost:8000&quot;<br><br>def test_mcp_method(method, params=None):<br>    &quot;&quot;&quot;Test MCP method calls.&quot;&quot;&quot;<br>    response = requests.post(<br>        f&quot;{BASE_URL}/mcp/messages&quot;,<br>        json={<br>            &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>            &quot;id&quot;: 1,<br>            &quot;method&quot;: method,<br>            &quot;params&quot;: params or {}<br>        },<br>        headers={&quot;Content-Type&quot;: &quot;application/json&quot;}<br>    )<br>    return response.json()<br><br># Test the server<br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;🧪 Testing Calculator MCP Server…&quot;)<br><br>    # Test initialization<br>    init_result = test_mcp_method(&quot;initialize&quot;, {<br>        &quot;protocolVersion&quot;: &quot;2024–11–05&quot;,<br>        &quot;capabilities&quot;: {},<br>        &quot;clientInfo&quot;: {&quot;name&quot;: &quot;test-client&quot;, &quot;version&quot;: &quot;1.0.0&quot;}<br>    })<br>    print(&quot;✅ Initialize:&quot;, init_result.get(&quot;result&quot;, {}).get(&quot;serverInfo&quot;, {}).get(&quot;name&quot;))<br><br>    # Test tools list<br>    tools_result = test_mcp_method(&quot;tools/list&quot;)<br>    tools = tools_result.get(&quot;result&quot;, {}).get(&quot;tools&quot;, [])<br>    print(f&quot;✅ Tools: {[tool[&#39;name&#39;] for tool in tools]}&quot;)<br><br>    # Test tool call<br>    add_result = test_mcp_method(&quot;tools/call&quot;, {<br>        &quot;name&quot;: &quot;add&quot;,<br>        &quot;arguments&quot;: {&quot;a&quot;: 15, &quot;b&quot;: 27}<br>    })<br>    result_data = add_result.get(&quot;result&quot;, {}).get(&quot;content&quot;, [{}])[0]<br>    print(f&quot;✅ Add Result: {result_data.get(&#39;text&#39;, &#39;No result&#39;)}&quot;)<br><br>    # Test resources<br>    resources_result = test_mcp_method(&quot;resources/list&quot;)<br>    resources = resources_result.get(&quot;result&quot;, {}).get(&quot;resources&quot;, [])<br>    print(f&quot;✅ Resources: {[r[&#39;uri&#39;] for r in resources]}&quot;)</pre><p>Run the tests:</p><pre># Start the server<br>uv run python calculator_server.py<br># In another terminal, test it<br>uv run python test_server.py</pre><h4>Step 7: Deploying to ChatGPT</h4><p>Local Development with Ngrok</p><p>Install ngrok and expose your server:</p><p><em># Install ngrok</em></p><pre>brew install ngrok # or download from ngrok.com</pre><p><em># Start your server</em></p><pre>uv run python calculator_server.py</pre><p><em># In another terminal, expose it</em></p><pre>ngrok http 8000</pre><p>Copy the ngrok URL (e.g., `https://abc123.ngrok-free.app`) and configure ChatGPT:</p><h4>Step 8: ChatGPT Integration</h4><p>1. Open ChatGPT and go to Settings → Integrations</p><p>2. Create a new connector with these settings:</p><p>- Name: Calculator MCP Server</p><p>- Connector URL: Your ngrok URL + `/mcp` (e.g., `https://abc123.ngrok-free.app/mcp`)</p><p>- Description: Interactive calculator with beautiful widgets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGyfYBSWzMMxKbxV2bdxaQ.png" /><figcaption>Our new app in ChatGPT</figcaption></figure><p>3. Test the integration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0CLrOGaav2lB2WQW5NRo9A.jpeg" /><figcaption>Invoke the new integration and the add tool we created</figcaption></figure><ul><li>Ask: “Can you add 3 and 7?”</li><li>ChatGPT should call your `add` tool and display the widget</li><li>You should see a beautiful gradient card showing “3 + 7 = 10”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q51HdMsOo7Hq2IqEQYOy2Q.png" /><figcaption>Tool result rendered in rich UI inside ChatGPT</figcaption></figure><h4>Best Practices</h4><p><strong>1. Widget Design</strong></p><p>- Keep widgets focused — One widget per tool</p><p>- Use responsive design — Works on mobile and desktop</p><p>- Implement loading states — Show progress during calculations</p><p>- Add error boundaries — Graceful degradation on failures</p><p><strong>2. Data Structure</strong></p><p>- Use consistent schemas — Standardize your `structuredContent`</p><p>- Validate inputs — Use Pydantic for type safety</p><p>- Handle edge cases — Empty data, invalid inputs, network errors</p><p><strong>3. Performance</strong></p><p>- Minimize widget size — Optimize CSS and JavaScript</p><p>- Cache resources — Use appropriate HTTP headers</p><p>- Async operations — Don’t block the main thread</p><p><strong>4. Security</strong></p><p>- Validate all inputs — Never trust user data</p><p>- Use HTTPS — Always in production</p><p>- Implement rate limiting — Prevent abuse</p><p>- Sanitize outputs — Prevent XSS attacks</p><h4>Common Issues</h4><p><strong><em>Widget not rendering:</em></strong></p><p>- Check that `openai/outputTemplate` matches resource URI</p><p>- Verify `mimeType` is `text/html+skybridge`</p><p>- Ensure widget HTML is valid</p><p><strong><em>Data not injecting:</em></strong></p><p>- Check `structuredContent` structure matches widget expectations</p><p>- Verify widget JavaScript is looking in the right place</p><p>- Use browser dev tools to inspect `window.openai`</p><p><strong><em>CORS errors:</em></strong></p><p>- Ensure CORS middleware is configured</p><p>- Check that ChatGPT can access your server</p><p>- Verify ngrok tunnel is active</p><p><strong><em>Tool not appearing:</em></strong></p><p>- Check tool metadata includes required fields</p><p>- Verify tool name matches exactly</p><p>- Ensure server is responding to `/mcp/messages`</p><h4>Conclusion</h4><p>Building MCP servers with Python opens up incredible possibilities for creating rich, interactive ChatGPT experiences. By combining FastMCP’s simplicity with custom HTML widgets, you can build applications that feel native to ChatGPT while providing powerful functionality.</p><p>The key is understanding the three pillars:</p><p>1. <strong><em>Tools</em></strong> that ChatGPT can call</p><p>2. <strong><em>Resources</em></strong> that define your UI templates</p><p>3. <strong><em>Structured Content</em></strong> that makes widgets dynamic</p><p>Start with simple tools and gradually add complexity. The MCP ecosystem is rapidly evolving, and your Python skills translate perfectly to this new paradigm of conversational AI applications.</p><h4>Resources</h4><p>Official OpenAI Apps SDK Documentation: <a href="https://developers.openai.com/apps-sdk/build/mcp-server">https://developers.openai.com/apps-sdk/build/mcp-server</a></p><p>Model Context Protocol Specification: <a href="https://modelcontextprotocol.io/">https://modelcontextprotocol.io/</a></p><p>FastMCP Python SDK: <a href="https://github.com/modelcontextprotocol/python-sdk">https://github.com/modelcontextprotocol/python-sdk</a></p><p>Example Repository: <a href="https://github.com/your-username/chatgpt-mcp-calculator">https://github.com/your-username/chatgpt-mcp-calculator</a></p><p><em>Ready to build the next generation of ChatGPT applications? Start with this calculator example and let your imagination run wild. The future of conversational AI is interactive, beautiful, and built with Python.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db19b1d3d70e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting AI to do your cognitive grunt-work: Staying up to date on Slack]]></title>
            <link>https://medium.com/@gurpartap.sandhu3/getting-ai-to-do-your-cognitive-grunt-work-unread-slack-6569a902eedc?source=rss-472ef08d0073------2</link>
            <guid isPermaLink="false">https://medium.com/p/6569a902eedc</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[slack]]></category>
            <dc:creator><![CDATA[GP Sandhu]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 00:02:20 GMT</pubDate>
            <atom:updated>2024-01-22T00:09:33.015Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*vbiBcZcD0Y5AQBtV2C-0ag.jpeg" /></figure><h4>Introduction</h4><p>Now that we have intelligence as an API call, I’ve been building my own <a href="https://medium.com/@gurpartap.sandhu3/build-you-own-ai-agent-from-scratch-in-30-mins-using-simple-python-1458f8099da0">personal AI agent</a> and trying to get it to do things I don’t really enjoy doing, like <a href="https://medium.com/@gurpartap.sandhu3/getting-ai-to-do-your-cognitive-grunt-work-unread-gmail-f26a82113c4c">reading email</a> and catching up with all unread Slack channels and DMs.</p><p>Slack is an amazing tool that I use for both work and personal stuff. The big issue is that there are so many channels and it is hard to keep up with all the stuff. What if we could get AI to read all that stuff and catch us up quickly. That is exactly what I got my personal AI agent to do.</p><h4>Step 1: Getting your Slack app to read messages from channels</h4><p>Slack offers a highly granular permission system for apps, which is crucial for protecting user data and ensuring apps only have access to the information they need. If you’re developing a Slack app that needs to read messages from channels, understanding the necessary permissions — or scopes — is essential.</p><p><strong>Public Channels</strong></p><p>For public channels, two main scopes are used:</p><ul><li>channels:history: This scope is pivotal for your Slack app&#39;s functionality. It grants the ability to fetch the message history from public channels. What does this mean for your app? It can access the content of messages, including past messages, subject to Slack API&#39;s limitations. This access is necessary for apps that analyze message content, search for specific keywords, or monitor channels for certain triggers.</li><li>channels:read: While the channels:history scope lets your app delve into message content, channels:read serves a different purpose. It allows your app to gather basic information about public channels within the workspace. This includes the channel&#39;s name, its defined purpose, the creation date, and other metadata. Note, however, that this scope does not extend to accessing the messages themselves.</li></ul><p><strong>Private Channels</strong></p><p>Private channels, or “groups” in the context of Slack’s scopes, require their own set of permissions:</p><ul><li>groups:history: Analogous to channels:history, the groups:history scope is what you&#39;ll need for private channels. It gives your app the same level of access to message history, but within the confines of Slack&#39;s private channels. This is where your app can read and interact with the message content that&#39;s not in the public eye.</li><li>groups:read: In a similar vein, groups:read is the private counterpart to channels:read. It empowers your app with the capability to understand the structure and metadata of private channels. This is useful for apps that need to list private channels, display information about them, or perform organizational functions without reading message content.</li></ul><p>Once you have these scopes, you’ll need to reinstall the app to your workspace for the permissions to take effect. Once you have done that, please add this app to the channels you want to read.</p><h4>Step 2: Getting your Slack app to read your DMs</h4><p>The next thing we need to do is give this app access to your DMs. The permissions again are fairly granular.</p><ul><li>im:history: This scope is the key to your app&#39;s ability to read the message history in one-on-one DMs. It grants access to the conversation&#39;s past messages, allowing your app to review conversations, search for information, or follow up on previous interactions.</li><li>im:read: While im:history focuses on message content, im:read allows your app to obtain basic information about the direct message channels it&#39;s a part of. This scope is helpful for apps that need to list or manage DMs without necessarily reading their content.</li><li>mpim:history: Extending the capabilities of im:history, this scope lets your app delve into the message history of multi-user DMs (group DMs). It&#39;s essential for apps that are designed to work in group settings, providing insights and interactions across multiple participants.</li><li>mpim:read: Similar to im:read but for multi-user DMs, this scope allows your app to gather basic details about group DMs. It&#39;s beneficial for organizational tools and apps that manage group communications.</li></ul><p>Once you have these permissions set, you’ll need to get a user token using the Oauth flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ysTvQ0ESf99PlvgOY3nag.png" /></figure><p>One interesting thing is that Slack API doesn’t actually share any flag on messages to tell if it read or unread. So you have to use time as a way to check messages. Once you have the token, you can use this code to read the messages</p><pre>@tool<br>def fetch_dms_last_x_hours(hours: int) -&gt; list:<br>    &quot;&quot;&quot;<br>    Fetches direct messages from the user&#39;s Slack account for the past specified number of hours.<br><br>    Args:<br>        hours (int): The number of hours in the past from which to retrieve direct messages.<br><br>    Returns:<br>        list: A list of dictionaries, each containing details of a direct message, including sender&#39;s user ID, <br>              timestamp, and text of the message. Returns None if an error occurs.<br>    &quot;&quot;&quot;<br>    try:<br>        slack_user_token = os.environ.get(&quot;SLACK_USER_TOKEN&quot;)<br>        client = WebClient(token=slack_user_token)<br>        hours_ago = time.time() - hours * 60 * 60<br>        dms_last_x_hours = []<br><br>        conversations = client.conversations_list(types=&#39;im&#39;)<br>        for conversation in conversations[&#39;channels&#39;]:<br>            conversation_id = conversation[&#39;id&#39;]<br>            history = client.conversations_history(channel=conversation_id, oldest=str(hours_ago))<br>            for message in history[&#39;messages&#39;]:<br>                dms_last_x_hours.append({<br>                    &quot;user&quot;: message.get(&#39;user&#39;, &#39;Unknown&#39;),<br>                    &quot;timestamp&quot;: message.get(&#39;ts&#39;, &#39;Unknown Timestamp&#39;),<br>                    &quot;text&quot;: message.get(&#39;text&#39;, &#39;No Text&#39;)<br>                })<br><br>        return dms_last_x_hours<br>    except SlackApiError as e:<br>        logging.error(f&quot;Error fetching DMs: {e.response[&#39;error&#39;]}&quot;)<br>        return None</pre><h4>Step 3: Connecting Slack tools to your AI Agent</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MdgtmuXAZ3aYgV_pHDjKGQ.png" /></figure><p><a href="https://www.langchain.com/">Langchain</a> is a great library for building AI apps. They already have a <a href="https://python.langchain.com/docs/integrations/toolkits/slack">Slack toolchain</a> that will help us read from channels where the app is added. We can combine that with the custom tool we wrote in the previous section to fetch DMs. Here is what the code looks like:</p><pre>slack_tools = SlackToolkit().get_tools()<br>custom_tools = [fetch_dms_last_x_hours]<br><br>tools = custom_tools + slack_tools<br>llm_with_tools = llm.bind(functions=[format_tool_to_openai_function(t) for t in tools])<br><br># Define the chat prompt<br>prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;You are a helpful AI assistant named TARS. You have a geeky, clever, sarcastic, and edgy sense of humor. You were created by GP to help me be more efficient.&quot;),<br>    MessagesPlaceholder(variable_name=&quot;chat_history&quot;),<br>    (&quot;user&quot;, &quot;{input}&quot;),<br>    MessagesPlaceholder(variable_name=&quot;agent_scratchpad&quot;),<br>])<br><br># Define the agent<br>agent = (<br>    {<br>        &quot;input&quot;: lambda x: x[&quot;input&quot;],<br>        &quot;agent_scratchpad&quot;: lambda x: format_to_openai_function_messages(x[&quot;intermediate_steps&quot;]),<br>        &quot;chat_history&quot;: lambda x: x[&quot;chat_history&quot;],<br>    }<br>    | prompt<br>    | llm_with_tools<br>    | OpenAIFunctionsAgentOutputParser()<br>)<br>agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)</pre><h4>Step 4: Run the tools by sending a DM to the app</h4><p>Now our app should be able to assist us in handing messages on channels and DMs. Just ask your AI agent and it should be able to read all that and catch you up quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LicgyV_L7YaujK087OpU9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WP9M6wbYHxwGB6Gvhn95PA.png" /></figure><h4>Conclusion</h4><p>Voilà! You’ve successfully harnessed AI to sift through your Slack overload. No more drowning in a sea of messages and channels. Your personal AI agent has got your back, filtering the noise and bringing you the essentials. Now, you’re free to focus on the bigger picture, with a little more peace of mind and a lot less clutter. Welcome to a smarter, streamlined Slack experience!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6569a902eedc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>