<?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 Nadeesha Nawagaththegama on Medium]]></title>
        <description><![CDATA[Stories by Nadeesha Nawagaththegama on Medium]]></description>
        <link>https://medium.com/@nadeeshadileen?source=rss-42d9989815a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*q8aGEqq2bXGXnc6Pm-pdhQ.jpeg</url>
            <title>Stories by Nadeesha Nawagaththegama on Medium</title>
            <link>https://medium.com/@nadeeshadileen?source=rss-42d9989815a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:25:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nadeeshadileen/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[Letting the model check fares and flights]]></title>
            <link>https://medium.com/@nadeeshadileen/letting-the-model-check-fares-and-flights-ad1ce1881e71?source=rss-42d9989815a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad1ce1881e71</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-bedrock]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Nadeesha Nawagaththegama]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 02:20:54 GMT</pubDate>
            <atom:updated>2026-12-02T02:20:54.454Z</atom:updated>
            <content:encoded><![CDATA[<p>By the end of this post you will have a script where the model asks for a fare estimate and a flight status, your code looks them up, and the model writes the answer from real numbers. The full run makes two Bedrock calls and costs about a hundredth of a cent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXqcplABpc1h62lsFI0mPw.png" /></figure><h3>What you’ll build</h3><p>Palmway Transfers is a fictional airport transfer company at Bandaranaike International Airport (CMB) in Sri Lanka, created for this series. In <a href="https://medium.com/@nadeeshadileen/teaching-the-assistant-to-remember-a-booking-211c3198938b?sharedUserId=nadeeshadileen">Part 2</a> the assistant could follow a booking, but we had to tell it never to mention a price, because it had no price list. Customers ask two questions all the time: “How much is it?” and “Do you know my flight is late?” Now the assistant can answer both.</p><p>Here is the end of a real run:</p><pre>Customer: My flight FA245 lands today. How much is a van from the airport to Galle, and is my flight on time?</pre><pre>Assistant: Your flight FA245 is currently delayed and estimated to land at 13:55 local time. The estimated fare for a van from the airport to Galle is LKR 30,000. Please note that this is an estimate and the final price is confirmed at booking.</pre><p>The model did not guess the delay or the fare. Both came from functions in our code.</p><p>Code for this part: <a href="https://github.com/nadeeshaDileen/airport-ride-ai/blob/main/src/03-tool-use.ts">src/03-tool-use.ts</a>, with the tools in <a href="https://github.com/nadeeshaDileen/airport-ride-ai/blob/main/src/shared/converse-tools.ts">src/shared/converse-tools.ts</a> and <a href="https://github.com/nadeeshaDileen/airport-ride-ai/blob/main/src/shared/taxi-tools.ts">src/shared/taxi-tools.ts</a>.</p><h3>The idea in plain words</h3><p>A model can only work with text it is given. It cannot open your fares database or check a flight. Ask anyway and it may produce a number that looks right and is wrong.</p><p><strong>Tool use</strong> (also called function calling) fixes this. You describe a few functions to the model: their name, what they do, and what inputs they take. When the model needs one, it does not run it. It cannot. It stops and replies with a toolUse block that says, in effect, &quot;please run estimate_fare with these inputs&quot;. The stopReason of that reply is tool_use.</p><p>Your code then runs the function, and sends the result back as a toolResult block. The model reads the result and either asks for another tool or writes the final answer. So the flow is:</p><ol><li>Send the question and the tool descriptions.</li><li>If stopReason is tool_use, run every tool the model asked for and send the results back.</li><li>Repeat until stopReason is something else, usually end_turn.</li><li>Stop after a fixed number of rounds, in case the model keeps asking.</li></ol><p>The tools in this repo return mock data from small in-memory tables, so the demo runs anywhere. In a real app, estimate_fare would call Palmway&#39;s pricing service and get_flight_status would call a flight data API. The loop around them stays the same.</p><h3>The code, piece by piece</h3><h3>1. Describe a tool</h3><pre>{<br>  toolSpec: {<br>    name: &#39;estimate_fare&#39;,<br>    description:<br>      &#39;Estimate the fare in LKR for an airport transfer from Bandaranaike International Airport (CMB). &#39; +<br>      &#39;Needs a vehicle type and either a destination name or a distance in km.&#39;,<br>    inputSchema: {<br>      json: {<br>        type: &#39;object&#39;,<br>        properties: {<br>          vehicleType: { type: &#39;string&#39;, enum: [...VEHICLE_TYPES], description: &#39;mini, sedan or van&#39; },<br>          destination: { type: &#39;string&#39;, description: &#39;Destination town, e.g. &quot;Kandy&quot; or &quot;Galle&quot;&#39; },<br>          distanceKm: { type: &#39;number&#39;, description: &#39;Road distance in km, if the destination is not known&#39; },<br>          pickupHour: { type: &#39;integer&#39;, description: &#39;Pickup hour in local time, 0-23 (night surcharge applies 22-5)&#39; },<br>        },<br>        required: [&#39;vehicleType&#39;],<br>      },<br>    },<br>  },<br>},</pre><p>A tool is a toolSpec with three parts:</p><ul><li><strong>name</strong> is how the model refers to the tool in its request.</li><li><strong>description</strong> is how the model decides <em>when</em> to use it. It is the only thing the model knows about the tool, so write it for a reader who has never seen your code. &quot;Estimate the fare in LKR for an airport transfer from CMB&quot; tells the model this is the tool for &quot;How much is a van to Galle?&quot;.</li><li><strong>inputSchema</strong> is a JSON Schema for the inputs. The enum limits vehicleType to three values, and each property has its own description. The model fills these in from the conversation.</li></ul><p>A vague description like “pricing tool” leads to the model calling it for the wrong questions, or not calling it at all. The second tool, get_flight_status, is shorter: one required flightNumber string.</p><h3>2. The functions behind the tools</h3><pre>export function runTaxiTool(name: string, input: unknown): Record&lt;string, unknown&gt; {<br>  switch (name) {<br>    case &#39;estimate_fare&#39;:<br>      return estimateFare(input as FareInput);<br>    case &#39;get_flight_status&#39;:<br>      return getFlightStatus(input as { flightNumber: string });<br>    default:<br>      return { error: `Unknown tool: ${name}` };<br>  }<br>}</pre><p>This maps the tool name from the model’s request to a real function. An unknown name returns an error object, so the model gets a message it can read.</p><p>estimateFare adds a base fare and a price per kilometre, plus 10% between 22:00 and 05:59. A Van is 3,000 LKR plus 180 LKR per km, and Galle is 150 km in the demo table, so the fare is 30,000 LKR. getFlightStatus reads a table of three made-up &quot;FA&quot; flights.</p><h3>3. System prompt and tool config</h3><pre>const MAX_TOOL_TURNS = 5;</pre><pre>const SYSTEM = [<br>  {<br>    text:<br>      &#39;You are the assistant for Palmway Transfers, a fictional airport transfer company in Sri Lanka. &#39; +<br>      &#39;Use the tools for fares and flight status. Never guess a price or a flight time. &#39; +<br>      &#39;Keep the answer under 100 words.&#39;,<br>  },<br>];</pre><p>The system prompt no longer lists vehicles or prices. It tells the model to use the tools and never to guess. MAX_TOOL_TURNS limits how many calls the loop may make.</p><h3>4. The loop</h3><pre>const messages: Message[] = [{ role: &#39;user&#39;, content: [{ text: question }] }];</pre><pre>for (let turn = 1; turn &lt;= MAX_TOOL_TURNS; turn++) {<br>  const response = await client.send(<br>    new ConverseCommand({<br>      modelId: MODEL_ID,<br>      system: SYSTEM,<br>      messages,<br>      toolConfig: { tools: TAXI_TOOLS },<br>      inferenceConfig: { temperature: 0, maxTokens: 400 },<br>    })<br>  );</pre><pre>  const reply = response.output?.message;<br>  if (!reply) throw new Error(&#39;No message in response&#39;);<br>  messages.push(reply);</pre><p>The only new field in the request is toolConfig, which sends the tool descriptions with every call. Temperature is 0 because we want the model to pick tools the same way each time.</p><p>As in <a href="https://medium.com/@nadeeshadileen/teaching-the-assistant-to-remember-a-booking-211c3198938b?sharedUserId=nadeeshadileen">Part 2</a>, the assistant’s reply goes into the history as it is. That reply now contains toolUse blocks. The model has to see its own request again on the next call, or the tool result will not match anything.</p><h3>5. Stop when the model answers</h3><pre>if (response.stopReason !== &#39;tool_use&#39;) {<br>    const text = reply.content?.map((b) =&gt; b.text ?? &#39;&#39;).join(&#39;&#39;) ?? &#39;&#39;;<br>    console.log(`\nAssistant: ${stripThinking(text)}`);<br>    return;<br>  }</pre><p>If the model did not ask for a tool, it has answered, and we print the text. We join every text block instead of reading content[0], because a reply can hold more than one block.</p><p>stripThinking removes &lt;thinking&gt;...&lt;/thinking&gt; sections. Nova Lite sometimes writes its reasoning inside these tags before the answer. That is useful while you debug, but a customer should not see it.</p><h3>6. Run the tools and send the results back</h3><pre>const results: ContentBlock[] = [];<br>  for (const block of reply.content ?? []) {<br>    if (!block.toolUse) continue;<br>    const { name, input, toolUseId } = block.toolUse;<br>    const result = runTaxiTool(name ?? &#39;&#39;, input);<br>    results.push({ toolResult: { toolUseId, content: [{ json: result as never }] } });<br>  }</pre><pre>  messages.push({ role: &#39;user&#39;, content: results });<br>}</pre><pre>throw new Error(`Stopped after ${MAX_TOOL_TURNS} tool turns without a final answer.`);</pre><p>This is the core of tool use. (The console.log lines are left out here to keep it short.)</p><ul><li>We loop over <strong>every</strong> block in the reply. The model can ask for several tools at once, and in our run it asked for two.</li><li>Each toolUse has a toolUseId. The matching toolResult must carry the same ID. That is how the model knows which result belongs to which request.</li><li>The result goes in as json, so the model reads structured data instead of a sentence we wrote.</li><li>All results go back in <strong>one</strong> message with role: &#39;user&#39;. Tool results come from your side of the conversation, so they are sent as the user, which also keeps user and assistant taking turns as in <a href="https://medium.com/@nadeeshadileen/teaching-the-assistant-to-remember-a-booking-211c3198938b?sharedUserId=nadeeshadileen">Part 2</a>.</li></ul><p>If the loop runs MAX_TOOL_TURNS times without a final answer, the script stops with an error. Without this guard, a model that keeps asking for tools (for example, retrying a lookup that keeps failing) would keep making paid calls forever.</p><h3>Run it</h3><pre>AWS_PROFILE=&lt;your-aws-profile&gt; npm run 03</pre><p>You can ask your own question after --, for example npm run 03 -- &quot;Is FA318 on time?&quot;.</p><h3>Real output</h3><pre>Customer: My flight FA245 lands today. How much is a van from the airport to Galle, and is my flight on time?</pre><pre>[Call 1] stopReason: tool_use, tokens: 773<br>  Model wants: get_flight_status({&quot;flightNumber&quot;:&quot;FA 245&quot;})<br>  Tool returned: {&quot;flightNumber&quot;:&quot;FA245&quot;,&quot;from&quot;:&quot;Singapore&quot;,&quot;scheduled&quot;:&quot;13:15&quot;,&quot;status&quot;:&quot;Delayed&quot;,&quot;estimated&quot;:&quot;13:55&quot;,&quot;timezone&quot;:&quot;local airport time&quot;}<br>  Model wants: estimate_fare({&quot;destination&quot;:&quot;Galle&quot;,&quot;vehicleType&quot;:&quot;van&quot;})<br>  Tool returned: {&quot;vehicle&quot;:&quot;Van&quot;,&quot;maxPassengers&quot;:8,&quot;maxSuitcases&quot;:8,&quot;distanceKm&quot;:150,&quot;nightSurchargeApplied&quot;:false,&quot;estimatedFareLkr&quot;:30000,&quot;note&quot;:&quot;Estimate only. The final price is confirmed at booking.&quot;}<br>[Call 2] stopReason: end_turn, tokens: 998</pre><pre>Assistant: Your flight FA245 is currently delayed and estimated to land at 13:55 local time. The estimated fare for a van from the airport to Galle is LKR 30,000. Please note that this is an estimate and the final price is confirmed at booking.</pre><p>What to notice:</p><ul><li><strong>Two calls, not three.</strong> In call 1 the model asked for both tools in one reply, so stopReason was tool_use and the reply held two toolUse blocks. Our code ran both and sent both results in one message. Call 2 ended with end_turn and the answer.</li><li><strong>The model chose the inputs.</strong> The customer typed “FA245”, but the model sent &quot;FA 245&quot; with a space. That matches the example in our own schema description (e.g. &quot;FA 245&quot;). getFlightStatus removes spaces before the lookup, so it still worked. For the fare it picked van from the enum and Galle as the destination, and left out pickupHour.</li><li><strong>Every fact in the answer came from a tool.</strong> The delay, the 13:55 estimate, the 30,000 LKR fare and even “the final price is confirmed at booking” all appear in the tool results.</li><li><strong>The answer is not perfect.</strong> It does not say how late the flight is (40 minutes), or that the driver waits, because this system prompt no longer says so.</li></ul><h3>Tokens and cost</h3><p>This script prints only totalTokens for each call, not the split between input and output, so the cost below is an estimate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*oEDMoTfKcSg6am4XO6jf_g.png" /></figure><p>The tool descriptions are sent with every call, which is why a short question already uses 773 tokens. Call 2 resends everything from call 1, as in <a href="https://medium.com/@nadeeshadileen/teaching-the-assistant-to-remember-a-booking-211c3198938b?sharedUserId=nadeeshadileen">Part 2</a>, so most of the 1,771 tokens are input.</p><p>With Nova Lite at about $0.06 per million input tokens and $0.24 per million output tokens (approximate, from the <a href="https://aws.amazon.com/nova/pricing/">Amazon Nova pricing page</a> at the time of writing):</p><ul><li>If all 1,771 tokens were input, the run cost <strong>$0.000106</strong>.</li><li>The final answer is about 50 words. Even if the model wrote around 150 output tokens across both calls, the run cost about <strong>$0.00013</strong>.</li></ul><p>So the run cost roughly one hundredth of a cent. To see the exact split, print response.usage.inputTokens and response.usage.outputTokens as in <a href="https://medium.com/@nadeeshadileen/teaching-the-assistant-to-remember-a-booking-211c3198938b?sharedUserId=nadeeshadileen">Part 2</a>.</p><h3>Gotchas</h3><ul><li><strong>The model never runs your code.</strong> Bedrock only returns a request. If your loop does not run the tool and send a toolResult, nothing happens. If you send a toolResult without the assistant message that holds the matching toolUse, the call fails with a ValidationException.</li><li><strong>More than one </strong><strong>toolUse per reply.</strong> Our run had two in one reply. Code that reads only the first tool block would answer half the question. Loop over all blocks and send all results together in one user message.</li><li><strong>The model chooses the inputs.</strong> It turned “FA245” into “FA 245”. It could also send “Galle Fort” or “galle” or leave out a field. Normalise input in the tool (trim, upper or lower case) and return a clear error for unknown values. estimateFare returns the list of known destinations when it cannot find one, so the model can ask the customer.</li><li><strong>Validate tool input.</strong> The schema guides the model but your code should not trust it. runTaxiTool casts input to a type without checking it. If the model ever left out vehicleType, estimateFare would throw on vehicleType.toLowerCase() and the whole script would stop. In a real app, check required fields (for example with zod) and return an error object instead. The Converse API also lets you set status: &#39;error&#39; on a toolResult to tell the model a tool failed.</li><li><strong>&lt;thinking&gt; text.</strong> Nova Lite sometimes puts its reasoning in &lt;thinking&gt; tags. Strip it before you show text to a customer.</li><li><strong>Keep the turn limit.</strong> Five rounds is plenty for two tools. When the limit is hit, show the customer a fallback such as “Our team will reply shortly” instead of an error.</li></ul><h3>Next step</h3><p>The assistant can now check fares and flights, but it will try to help with anything a customer types. Palmway Transfers needs it to refuse some requests: skipping payment, making fake bookings, or abusing drivers. In Part 4 we add Amazon Bedrock Guardrails with denied topics and read the guardrailAction to see when a message was blocked. Part 4 builds on the knowledge base from Part 5.</p><p><em>Palmway Transfers is a fictional company created for this series. Code: </em><a href="https://github.com/nadeeshaDileen/airport-ride-ai"><em>airport-ride-ai on GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad1ce1881e71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching the assistant to remember a booking]]></title>
            <link>https://medium.com/@nadeeshadileen/teaching-the-assistant-to-remember-a-booking-211c3198938b?source=rss-42d9989815a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/211c3198938b</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[amazon-bedrock]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Nadeesha Nawagaththegama]]></dc:creator>
            <pubDate>Sat, 28 Nov 2026 01:08:57 GMT</pubDate>
            <atom:updated>2026-11-28T01:08:57.038Z</atom:updated>
            <content:encoded><![CDATA[<p>By the end of this post, you will have a script that takes an airport booking over four messages, keeps the whole conversation in a list, and prints how the token count grows with each message. The full run costs less than a hundredth of a cent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GV29uskJ7z2Okq7xc24Hw.png" /></figure><h3>What you’ll build</h3><p><a href="https://medium.com/@nadeeshadileen/your-first-amazon-bedrock-call-from-node-js-be0744ac89e5?sharedUserId=nadeeshadileen">In Part 1</a>, our assistant for Palmway Transfers answered one question and stopped. Palmway Transfers is a fictional airport transfer company at Bandaranaike International Airport (CMB) in Sri Lanka, created for this series.</p><p>Real customers do not send everything in one message. They give the flight first, then the number of people, and then ask about a child seat. By the last message, the assistant has to know all of it. Here is the final turn from a real run:</p><pre>--- Turn 4 ---<br>Customer: Great, please summarise the whole booking (flight, date, destination, people, luggage, extras) so I can check it.<br>Assistant: Your booking: flight FA101, 14 March, Kandy, 3 passengers, 2 suitcases, 1 child seat. The team will send the price and confirmation by email.<br>(input tokens: 338, output tokens: 42)</pre><p>The last customer message does not mention Kandy, the flight or the suitcases. The assistant gets them right because it sent the earlier messages too.</p><p>Code for this part: <a href="https://github.com/nadeeshaDileen/airport-ride-ai/blob/main/src/02-multi-turn.ts">src/02-multi-turn.ts</a></p><h3>The idea in plain words</h3><p>A model on Bedrock has no memory. Each call is separate. When the call ends, the model keeps nothing about you, your customer, or what was said. If you send “Can you add a child seat for him?” On its own, the model has no idea who “him” is.</p><p>So the memory has to live in your code. You keep a list of every message in the conversation, and on every call you send the whole list. The model reads it from the top, as if it were seeing the conversation for the first time, and writes the next reply.</p><p>That list is the messages array we met in <a href="https://medium.com/@nadeeshadileen/your-first-amazon-bedrock-call-from-node-js-be0744ac89e5?sharedUserId=nadeeshadileen">Part 1</a>. In Part 1 it held one message. Now it grows:</p><ol><li>Add the customer’s message to the list.</li><li>Send the system prompt and the whole list to Bedrock.</li><li>Add the assistant’s reply to the list.</li><li>Repeat for the next customer message.</li></ol><p>Step 3 is the one people forget. If you only keep the customer’s messages, the model never sees what it said before. It may ask the same question twice, or contradict an earlier answer.</p><p>This has a cost. Every call sends the full history again, so every call has more input tokens than the one before.</p><h3>The code, piece by piece</h3><h3>1. Client, model and system prompt</h3><pre>import { BedrockRuntimeClient, ConverseCommand, Message } from &#39;@aws-sdk/client-bedrock-runtime&#39;;</pre><pre>const client = new BedrockRuntimeClient({ region: &#39;us-east-1&#39; });</pre><pre>const MODEL_ID = &#39;us.amazon.nova-lite-v1:0&#39;;</pre><p>This is the same setup as Part 1: the Bedrock runtime client, credentials from AWS_PROFILE, and Amazon Nova Lite through a US cross-region inference profile. The new import is Message, the SDK type for one entry in the conversation.</p><pre>const SYSTEM = [<br>  {<br>    text:<br>      &#39;You are the booking assistant for Palmway Transfers, a fictional airport transfer company in Sri Lanka. &#39; +<br>      &#39;Collect the details for a transfer from Bandaranaike International Airport (CMB): flight number, &#39; +<br>      &#39;arrival date and time, destination, number of passengers, suitcases, and child seats. &#39; +<br>      &#39;Vehicles: Mini car (3 passengers, 2 suitcases), Sedan (3 passengers, 3 suitcases), Van (8 passengers, 8 suitcases). &#39; +<br>      &#39;Remember everything the customer already told you and do not ask for it again. &#39; +<br>      &#39;You have no price list and cannot confirm bookings: never mention a price or currency amount, &#39; +<br>      &#39;and say the team will send the price and confirmation by email. &#39; +<br>      &#39;Keep each reply under 80 words.&#39;,<br>  },<br>];</pre><p>The assistant now collects booking details. “Remember everything the customer already told you” only works because we send the history. “Never mention a price” stops the model from making up a fare, since it has no price list yet.</p><p>The system prompt is not part of the messages array. It goes in its own system field and is sent with every call.</p><h3>2. The customer’s messages</h3><pre>const userTurns = [<br>  &#39;Hi, I need a pickup from the airport to Kandy. I land on flight FA101 on 14 March at 8:40 in the morning.&#39;,<br>  &#39;It will be me and my wife, plus our 4-year-old son. We have two big suitcases.&#39;,<br>  &#39;Can you add a child seat for him? And which vehicle would you suggest?&#39;,<br>  &#39;Great, please summarise the whole booking (flight, date, destination, people, luggage, extras) so I can check it.&#39;,<br>];</pre><p>These stand in for a real customer typing. “Him” in turn 3 means the son from turn 2, and the turn 4 summary needs details from all earlier turns.</p><h3>3. The history and the loop</h3><pre>const history: Message[] = [];</pre><pre>for (const [i, userText] of userTurns.entries()) {<br>  console.log(`\n--- Turn ${i + 1} ---`);<br>  console.log(`Customer: ${userText}`);</pre><pre>  // 1. Add the customer&#39;s message to the history.<br>  history.push({ role: &#39;user&#39;, content: [{ text: userText }] });</pre><p>history is the assistant&#39;s memory. It starts empty and lives for as long as the script runs. Each customer message goes in with role: &#39;user&#39;, in the same shape as Part 1.</p><h3>4. Send the whole history</h3><pre>// 2. Send the whole history.<br>  const response = await client.send(<br>    new ConverseCommand({<br>      modelId: MODEL_ID,<br>      system: SYSTEM,<br>      messages: history,<br>      inferenceConfig: { temperature: 0.3, maxTokens: 250 },<br>    })<br>  );</pre><p>The only change from Part 1 is messages: history. On turn 1 the array has one message. On turn 4 it has seven: four from the customer and three replies.</p><p>The temperature is lower than in Part 1 (0.3 instead of 0.5). A booking assistant should be predictable. We want it to repeat details correctly, not phrase them in a creative way.</p><h3>5. Keep the reply</h3><pre>const reply = response.output?.message;<br>  if (!reply) throw new Error(&#39;No message in response&#39;);</pre><pre>  console.log(`Assistant: ${reply.content?.[0]?.text}`);<br>  console.log(`(input tokens: ${response.usage?.inputTokens}, output tokens: ${response.usage?.outputTokens})`);</pre><pre>  // 3. Add the reply to the history so the next turn can see it.<br>  history.push(reply);<br>}</pre><p>response.output.message is already a complete message with role: &#39;assistant&#39;. We push it into the history as it is, without copying out the text. That keeps every content block. In Part 3 a reply can hold a tool request as well as text, and the model needs to see that block again on the next call.</p><p>After each call we print the token usage, so we can watch it grow.</p><h3>Run it</h3><pre>AWS_PROFILE=&lt;your-aws-profile&gt; npm run 02</pre><h3>Real output</h3><pre>--- Turn 1 ---<br>Customer: Hi, I need a pickup from the airport to Kandy. I land on flight FA101 on 14 March at 8:40 in the morning.<br>Assistant: Thank you! We&#39;ll arrange a suitable vehicle for you. The team will send the price and confirmation by email.<br>(input tokens: 179, output tokens: 25)</pre><pre>--- Turn 2 ---<br>Customer: It will be me and my wife, plus our 4-year-old son. We have two big suitcases.<br>Assistant: Got it. We&#39;ll arrange a vehicle with enough space for your family and luggage. The team will send the price and confirmation by email.<br>(input tokens: 233, output tokens: 30)</pre><pre>--- Turn 3 ---<br>Customer: Can you add a child seat for him? And which vehicle would you suggest?<br>Assistant: We&#39;ll add a child seat and suggest a suitable vehicle. The team will send the price and confirmation by email.<br>(input tokens: 283, output tokens: 25)</pre><pre>--- Turn 4 ---<br>Customer: Great, please summarise the whole booking (flight, date, destination, people, luggage, extras) so I can check it.<br>Assistant: Your booking: flight FA101, 14 March, Kandy, 3 passengers, 2 suitcases, 1 child seat. The team will send the price and confirmation by email.<br>(input tokens: 338, output tokens: 42)</pre><pre>Note: input tokens grow every turn because the full history is sent again.</pre><p>What to notice:</p><ul><li><strong>The memory works.</strong> The turn 4 summary has the flight, date and destination from turn 1, the passengers and suitcases from turn 2, and the child seat from turn 3. “Him” in turn 3 was understood as the son.</li><li><strong>It never asked for the same thing twice.</strong> That is the system prompt instruction plus the history working together.</li><li><strong>Memory does not make the model do its job well.</strong> In turn 3 it said it would “suggest a suitable vehicle” but never named one. On paper the Mini car fits 3 passengers and 2 suitcases, so it could have named that, or the Sedan for more room. The summary also left out the 8:40 arrival time. A small model with a short prompt will miss things, which is why a summary step for the customer to check is worth having. Later parts give the assistant tools and documents so it relies less on guessing.</li><li><strong>Input tokens grow every turn:</strong> 179, 233, 283, 338. Each step adds about 50 to 55 tokens, which is the previous reply plus the new customer message.</li></ul><p>Run it again and the wording will change, so you may get a vehicle suggestion next time.</p><h3>Tokens and cost</h3><p>Input tokens for each turn, added up:</p><pre>Turn Inputtokens Outputtokens   Cost<br>1     179         25           $0.0000167<br>2     233         30           $0.0000212<br>3     283         25           $0.0000230<br>4     338         42           $0.0000304<br><br>         Tokens     Price per 1M tokens     Cost<br>Input     1,033       $0.06               $0.0000620<br>Output    122         $0.24               $0.0000293<br>Total     1,155                           $0.0000913</pre><p>These are approximate Nova Lite on-demand prices for us-east-1, from the <a href="https://aws.amazon.com/nova/pricing/">Amazon Nova pricing page</a> at the time of writing. Check the page for current prices.</p><p>The whole booking cost less than a hundredth of a cent. Look at the input column, though. We paid for 1,033 input tokens for a conversation that is under 400 tokens long, system prompt included. The system prompt and the first message were sent four times.</p><p>The total you pay grows faster than the conversation. A chat with 20 turns pays for turn 1 twenty times. With Nova Lite that is rarely a problem for a booking chat, but it matters for long conversations and more expensive models.</p><h3>Gotchas</h3><ul><li><strong>Roles must take turns.</strong> The <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference.html">Converse API</a> expects the conversation to start with a user message, and user and assistant to alternate after that. If a call fails and you add the next customer message anyway, you end up with two user messages in a row and the next call fails with a ValidationException. When a call fails, remove the customer message you just added, or retry the same call.</li><li><strong>Trimming long histories.</strong> Models have a limit on how much input they accept, and you pay for every token you resend. The common fixes are to keep only the last N messages, or to ask the model to summarise the older part of the conversation and send that summary instead. When you cut, cut at a user message so the array still starts with user. Keep anything the booking needs, such as the flight number, in a summary or in your own data, not only in old messages.</li><li><strong>The history is yours to store.</strong> This script keeps it in a variable, so it is gone when the script ends. A web or WhatsApp assistant needs one history per customer, stored in a database and loaded before each call.</li></ul><h3>Next step</h3><p>The assistant can now follow a booking, but it still guesses at anything it was not told. It did not name a vehicle, and it has to send every price question to the team. In Part 3 we give the model tools: a fare estimate and a flight status check. The model decides when to call them, our code runs them, and the model uses the results in its answer.</p><p><em>Palmway Transfers is a fictional company created for this series. Code: </em><a href="https://github.com/nadeeshaDileen/airport-ride-ai"><em>airport-ride-ai on GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=211c3198938b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your first Amazon Bedrock call from Node.js]]></title>
            <link>https://medium.com/@nadeeshadileen/your-first-amazon-bedrock-call-from-node-js-be0744ac89e5?source=rss-42d9989815a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/be0744ac89e5</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[amazon-bedrock]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Nadeesha Nawagaththegama]]></dc:creator>
            <pubDate>Sat, 21 Nov 2026 19:00:43 GMT</pubDate>
            <atom:updated>2026-11-28T01:46:45.340Z</atom:updated>
            <content:encoded><![CDATA[<p>By the end of this post you will have a TypeScript script that sends a customer’s question to a model on Amazon Bedrock and prints the answer, the number of tokens used, and enough information to work out what the call cost. It costs less than a hundredth of a cent to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p5i34oJxGkRvHc7xSnpM9Q.png" /></figure><h3>What you’ll build</h3><p>This series follows Palmway Transfers, a fictional company that drives travellers from Bandaranaike International Airport (CMB) in Sri Lanka to their hotels. Like any small transfer business, it gets the same questions every day. Which car do I need? Will the driver wait if my flight is late? Do you have child seats?</p><p>Over seven parts we will build an assistant that answers those questions. In this first part it answers one question:</p><pre>Customer: We are a family of four with three large suitcases, landing at 11pm. Which vehicle should we book, and what happens if our flight is late?<br>Assistant: Hi there! For a family of four with three large suitcases, I recommend booking our Van, which can accommodate up to 8 passengers and 8 suitcases. If your flight is delayed, our driver will track it and wait up to 60 minutes after the landing time at no extra cost. Safe travels!</pre><pre>Tokens: { inputTokens: 188, outputTokens: 66, totalTokens: 254 }<br>Stop reason: end_turn<br>Latency (ms): 952</pre><p>Code for this part: [src/01-converse.ts](/blob/main/src/01-converse.ts)</p><h3>The idea in plain words</h3><p>Amazon Bedrock gives you many models from different providers behind one AWS API. You do not run any servers. You send a request, Bedrock runs the model, and you pay for the tokens you used.</p><p>The <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference.html"><strong>Converse API</strong></a> is the request format to learn first. It is the same for every chat model on Bedrock, so you can switch from Amazon Nova to another model by changing one string. A Converse request has three main parts:</p><ol><li><strong>System prompt.</strong> Instructions the customer never sees. This is where we tell the model it works for Palmway Transfers and give it a few facts about the business.</li><li><strong>Messages.</strong> The conversation so far. In this part it is only one message: the customer’s question.</li><li><strong>Inference settings.</strong> How long the answer may be and how much variety to allow.</li></ol><p>The model does not know anything about Palmway Transfers. It can only use what we put in the system prompt. That is why the facts (vehicle sizes, waiting time) are in the prompt. In Part 5 we will move those facts into real documents, but for now a few lines of text are enough.</p><p>We use <strong>Amazon Nova Lite</strong>, a small, fast and cheap model. It is a good fit for short customer questions.</p><h3>Before you start</h3><p>You need:</p><ul><li>Node.js 20 or later</li><li>An AWS account, the AWS CLI v2, and a named profile that can call Bedrock in us-east-1</li><li>Access to Amazon Nova Lite in the Bedrock console (check the model access page if your first call fails)</li></ul><p>Clone the repo and install:</p><pre>git clone &lt;github-link&gt; airport-ride-ai<br>cd airport-ride-ai<br>npm install</pre><h3>The project setup</h3><p>The project is plain Node.js with TypeScript. The parts that matter:</p><pre>{<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;01&quot;: &quot;tsx src/01-converse.ts&quot;,<br>    &quot;build&quot;: &quot;tsc --noEmit&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;@aws-sdk/client-bedrock-runtime&quot;: &quot;3.1167.0&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;tsx&quot;: &quot;4.23.15&quot;,<br>    &quot;typescript&quot;: &quot;7.0.2&quot;<br>  }<br>}</pre><p>&quot;type&quot;: &quot;module&quot; makes the project use ES modules, so we can write import and use top-level await. Part 7 needs this too, because the Strands Agents SDK only ships as ES modules. tsx runs TypeScript files directly, so there is no build step while you learn. npm run build only type-checks.</p><p>Versions are pinned exactly. If a tutorial works today, it should still work when someone reads it next year.</p><h3>The code, piece by piece</h3><h3>1. Create the client</h3><pre>import { BedrockRuntimeClient, ConverseCommand } from &#39;@aws-sdk/client-bedrock-runtime&#39;;</pre><pre>const client = new BedrockRuntimeClient({ region: &#39;us-east-1&#39; });</pre><pre>const MODEL_ID = &#39;us.amazon.nova-lite-v1:0&#39;;</pre><p>BedrockRuntimeClient is the AWS SDK v3 client for calling models. We do not pass any credentials. The SDK reads them from the AWS_PROFILE environment variable when we run the script, so no keys end up in the code.</p><p>The model ID starts with us.. That makes it a cross-Region inference profile: Bedrock may run the request in any of several US Regions to balance load. You still send the request to us-east-1.</p><h3>2. Write the system prompt</h3><pre>const SYSTEM_PROMPT = `You are the customer assistant for Palmway Transfers, a fictional airport transfer company in Sri Lanka.<br>Facts you can use:<br>- We pick up from Bandaranaike International Airport (CMB) 24 hours a day.<br>- Vehicles: Mini car (up to 3 passengers, 2 suitcases), Sedan (up to 3 passengers, 3 suitcases), Van (up to 8 passengers, 8 suitcases).<br>- For airport pickups the driver tracks the flight and waits up to 60 minutes after the actual landing time at no extra cost.<br>- Child seats are free but must be requested when booking.<br>Answer in a friendly, short way (under 120 words). If you do not know something, say so.`;</pre><p>This is the assistant’s job description. Three things in it do real work:</p><ul><li>The <strong>facts</strong> are the only business knowledge the model has.</li><li><strong>“Under 120 words”</strong> keeps answers short. Short answers are cheaper and easier to read on a phone in an arrivals hall.</li><li><strong>“If you do not know something, say so”</strong> reduces the chance that the model makes up a policy. It does not remove that chance. We will deal with that properly in later parts.</li></ul><h3>3. Read the question</h3><pre>const question =<br>  process.argv[2] ??<br>  &#39;We are a family of four with three large suitcases, landing at 11pm. Which vehicle should we book, and what happens if our flight is late?&#39;;</pre><p>The script has a default question, but you can pass your own after --, for example npm run 01 -- &quot;Do you pick up at 3am?&quot;.</p><p>This question is a good test. The answer needs two facts from the prompt (vehicle sizes and waiting time), and the model has to work out that four people do not fit in a car with three seats.</p><h3>4. Send the request</h3><pre>const response = await client.send(<br>  new ConverseCommand({<br>    modelId: MODEL_ID,<br>    system: [{ text: SYSTEM_PROMPT }],<br>    messages: [{ role: &#39;user&#39;, content: [{ text: question }] }],<br>    inferenceConfig: { temperature: 0.5, maxTokens: 300 },<br>  })<br>);</pre><p>This is the whole Bedrock call.</p><ul><li>system is a list of content blocks. Here there is one text block.</li><li>messages is the conversation. Each message has a role (user or assistant) and a list of content blocks. A block can hold text, an image, a document, or (in Part 3) a tool request.</li><li>temperature controls variety. 0 gives the most predictable answer; 1 gives the most variety. 0.5 is a reasonable middle for a friendly reply.</li><li>maxTokens is a hard limit on the answer length. If the model hits it, the answer is cut off.</li></ul><h3>5. Read the response</h3><pre>console.log(&#39;Assistant:&#39;, response.output?.message?.content?.[0]?.text);<br>console.log(&#39;\nTokens:&#39;, response.usage);<br>console.log(&#39;Stop reason:&#39;, response.stopReason);<br>console.log(&#39;Latency (ms):&#39;, response.metrics?.latencyMs);</pre><p>The answer is in output.message, in the same shape as the messages we sent. That matters in Part 2, where we add this message to the history and send it back.</p><ul><li>usage gives input, output and total tokens. This is what you pay for.</li><li>stopReason tells you why the model stopped. end_turn means it finished normally. max_tokens means it ran out of room and the answer is incomplete.</li><li>metrics.latencyMs is how long Bedrock took to answer.</li></ul><h3>Run it</h3><pre>AWS_PROFILE=&lt;your-aws-profile&gt; npm run 01</pre><h3>Real output</h3><pre>Customer: We are a family of four with three large suitcases, landing at 11pm. Which vehicle should we book, and what happens if our flight is late?</pre><pre>Assistant: Hi there! For a family of four with three large suitcases, I recommend booking our Van, which can accommodate up to 8 passengers and 8 suitcases. If your flight is delayed, our driver will track it and wait up to 60 minutes after the landing time at no extra cost. Safe travels!</pre><pre>Tokens: { inputTokens: 188, outputTokens: 66, totalTokens: 254 }<br>Stop reason: end_turn<br>Latency (ms): 952</pre><p>The model picked the Van, which is correct: the Mini car and Sedan both take only 3 passengers. It also used the waiting-time fact. It did not mention that 11pm might cost extra, because the prompt says nothing about night prices. The model can only be as good as the facts we give it.</p><p>Run the script again and the wording will change a little. That is the temperature at work.</p><h3>Tokens and cost</h3><p>Nova Lite on-demand prices in us-east-1, from the <a href="https://aws.amazon.com/bedrock/pricing/">Amazon Bedrock pricing page</a> at the time of writing:</p><pre>           | Tokens | Price per 1M tokens | Cost           |<br>           |--------|---------------------|----------------|<br>Input      | 188    | $0.06               | $0.0000113     |<br>Output     | 66     | $0.24               | $0.0000158     |<br>**Total**  | 254    |                     | **$0.0000271** |</pre><p>That is about 37,000 questions for one US dollar. Notice that most of the input tokens are the system prompt, not the question. Every call pays for the system prompt again, so keep it short.</p><h3>Gotchas</h3><ul><li><strong>AccessDeniedException on the first call.</strong> Usually the model is not enabled for your account, or your profile&#39;s IAM policy does not allow bedrock:InvokeModel. Check the model access page in the Bedrock console for us-east-1.</li><li><strong>Expired credentials.</strong> If you sign in with IAM Identity Center, the session expires. Run aws sso login --profile &lt;your-aws-profile&gt; again.</li><li><strong>Do not rely on </strong><strong>default.</strong> Pass the profile explicitly on every run. It avoids calling the wrong account by accident.</li><li><strong>content[0] is not always text.</strong> For plain questions it is. Once tools are involved (Part 3), the first block can be a tool request, so later scripts look at every block.</li><li><strong>A cut-off answer.</strong> If stopReason is max_tokens, raise maxTokens or ask for a shorter answer in the system prompt.</li></ul><h3>Next step</h3><p>Our assistant answers one question and forgets it straight away. A real booking takes several messages: the flight, then the number of people, then a child seat. In <a href="https://medium.com/@nadeeshadileen/teaching-the-assistant-to-remember-a-booking-211c3198938b?sharedUserId=nadeeshadileen">Part 2 </a>we keep a conversation history so the assistant can follow along, and we see why the input token count grows with every message.</p><p><em>Palmway Transfers is a fictional company created for this series. Code: </em><a href="https://github.com/nadeeshaDileen/airport-ride-ai"><em>airport-ride-ai on GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be0744ac89e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>