<?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 Benjamin Goodman on Medium]]></title>
        <description><![CDATA[Stories by Benjamin Goodman on Medium]]></description>
        <link>https://medium.com/@benjamin_goodman?source=rss-2f01806d4793------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gdvt8rUMklf14nbtBTiX7w.jpeg</url>
            <title>Stories by Benjamin Goodman on Medium</title>
            <link>https://medium.com/@benjamin_goodman?source=rss-2f01806d4793------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:27:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benjamin_goodman/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[Video Ingest and Streaming on AWS: A Serverless Pipeline from Upload to HLS]]></title>
            <link>https://aws.plainenglish.io/video-ingest-and-streaming-on-aws-a-serverless-pipeline-from-upload-to-hls-daea1fe842fc?source=rss-2f01806d4793------2</link>
            <guid isPermaLink="false">https://medium.com/p/daea1fe842fc</guid>
            <category><![CDATA[web-video-streaming]]></category>
            <category><![CDATA[aws-transcribe]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-media-converter]]></category>
            <dc:creator><![CDATA[Benjamin Goodman]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 19:50:33 GMT</pubDate>
            <atom:updated>2026-07-13T06:40:51.065Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build an event-driven pipeline that turns a raw video upload into an adaptive HLS stream — with subtitles and thumbnails included.</h4><h3><strong>What Does It Mean to Stream Video over HTTP?</strong></h3><p>Serving a video file is not the same as streaming it. If you drop an MP4 into an S3 bucket and link to it, a browser will download and play it — but it will download the entire file, or at least a large contiguous chunk of it, before playback is reliable. For a 500 MB file over a slow connection, that means a long wait and a poor experience. More importantly, the server has no idea what the viewer’s actual bandwidth is, so it can’t adjust quality accordingly.</p><p>HTTP streaming solves this by breaking video into small, independently downloadable segments — typically two to six seconds each — and describing them in a plain-text manifest file. The player downloads the manifest first, then fetches segments one at a time just before playback. Because each segment is a separate HTTP request, the player can switch to a higher or lower quality rendition between segments, adapting to changing network conditions in real time. This is adaptive bitrate streaming (ABR).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uWEVA3E9T_m4-tvsROEEQ.png" /></figure><p>The two dominant ABR formats are <strong>HLS</strong> (HTTP Live Streaming, developed by Apple) and <strong>MPEG-DASH</strong>. HLS has broader native browser and device support and is what this pipeline produces. An HLS stream consists of:</p><ul><li>A <strong>master manifest</strong> (.m3u8) that lists available renditions — each a combination of resolution and bitrate.</li><li>A <strong>rendition playlist</strong> (also .m3u8) for each quality level, listing the segment files in order.</li><li><strong>Segment files </strong>(.ts or .fmp4) containing a few seconds of audio and video, encoded for that rendition.</li></ul><p>Because these are all static files served over plain HTTPS, the entire delivery infrastructure is a CDN and an object store. There is no media server, no persistent connection, no special protocol. The “streaming” is just a sequence of HTTP GET requests.</p><p>The practical consequence: you can host an HLS stream on S3 and CloudFront with no compute in the playback path. The work happens <em>before</em> delivery, in the transcoding pipeline that converts a raw upload into the set of segmented, manifest-described renditions a player can consume.</p><p>This article covers the full journey from a raw video file landing in S3 to a browser playing it back as a smooth adaptive stream. We’ll walk through a fully serverless pipeline built around AWS MediaConvert, Transcribe, SQS, and EventBridge, using Terraform for infrastructure and Node.js Lambdas for the glue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UnFnsL8UPBD99iGvBNMsw.png" /></figure><h3><strong>Two Buckets, Two Concerns</strong></h3><p>The first structural decision is to keep uploads and streaming assets in separate S3 buckets with different access policies and lifecycle rules.</p><p>The <strong>uploads bucket</strong> is fully private. No public access, no CloudFront. It exists solely to receive raw video files and feed the transcoding pipeline. Once a video is processed, the original file has served its purpose.</p><p>The <strong>streaming bucket</strong> is also private — but it’s accessible via CloudFront using Origin Access Control (OAC). It holds the HLS segments, manifest files, subtitle tracks, and transcripts that MediaConvert and Transcribe produce. Nothing is served directly from S3; all playback traffic goes through CloudFront. This allows fine-grained control over caching policies and response headers for streaming assets, without affecting the upload flow.</p><h3><strong>Getting the File into S3: Presigned Uploads</strong></h3><p>Before the ingest pipeline can do anything, the raw video file needs to get into S3. The standard approach for large files is a <strong>presigned PUT URL</strong> — a time-limited, pre-authorized URL that lets a client upload directly to S3 without routing the file through a Lambda.</p><figure><img alt="A sequence diagram of the upload flow: the client calls POST /api/uploads through CloudFront, the API Lambda validates input, writes an UPLOADING record to DynamoDB, creates a presigned S3 PUT URL, returns the upload contract, and S3 publishes an ObjectCreated event to the ingest queue after the file upload completes." src="https://cdn-images-1.medium.com/max/1024/1*bezDKnHrxaa0ru1ZE1i2pQ.png" /></figure><p>The flow is:</p><ol><li>The client sends a lightweight API request with the video metadata: filename, content type, title, language code.</li><li>The API validates the request (allowed file types, well-formed language code), creates a video record in DynamoDB with status UPLOADING, and generates a presigned URL for the target S3 key.</li><li>The API returns the presigned URL, the video ID, and the expected headers to the client.</li><li>The client PUTs the file directly to S3 using that URL, with a matching Content-Typeheader.</li></ol><pre>// API generates the presigned URL<br>const originalKey = `uploads/${videoId}/original/${filename}`<br><br>const uploadUrl = await getSignedUrl(<br>  s3Client,<br>  new PutObjectCommand({<br>    Bucket: uploadBucketName,<br>    Key: originalKey,<br>    ContentType: contentType,<br>  }),<br>  { expiresIn: 900 }, // 15 minutes<br>)</pre><p>The key path uploads/{videoId}/original/{filename} is deliberate. You could also store videoIdas S3 user-defined metadata on the uploaded object, but ObjectCreatedevents do not include that metadata. That would force the ingest Lambda to make an extra HeadObjectcall to fetch x-amx-meta-video-id, and the client upload would also need to include the matching signed metadata header. Putting the ID in the object key keeps the event self-contained and avoids that extra S3 round trip.</p><p>A few other details worth noting:</p><ul><li><strong>Write the DynamoDB record before generating the URL. </strong>If the URL is issued but the record never gets written, the upload event will arrive with no corresponding record to process. Writing the record first means the pipeline can always look it up.</li><li><strong>The URL expires.</strong> 15 minutes is enough for most video files on reasonable connections. If an upload doesn’t complete in time, the presigned URL simply stops working — the client would need to request a new one.</li><li><strong>The uploads bucket has CORS configured for PUT.</strong> The browser needs permission to send the file cross-origin directly to S3. The ETagheader is exposed so the client can verify the upload completed successfully.</li></ul><p>Once the PUT completes, S3 fires an ObjectCreatedevent. That’s where the ingest pipeline begins.</p><h3><strong>The Ingest Pipeline: From S3 Event to Transcoding Job</strong></h3><p>When a file lands in the uploads bucket, you want transcoding to start automatically. The cleanest way to wire this is through S3 event notifications to SQS, with a Lambda consuming the queue.</p><figure><img alt="A high-level AWS media-processing diagram showing original files flowing through SQS and a Lambda that invokes MediaConvert, HLS assets saved to the streaming bucket, EventBridge triggering a second Lambda to start Transcribe, subtitles written back to storage, and metadata status updates recorded throughout the pipeline." src="https://cdn-images-1.medium.com/max/1024/1*qPy8TxZKWXw5ET-shPkDdA.png" /><figcaption><em>High-level processing flow: the upload enters through SQS and Lambda orchestration, MediaConvert produces the HLS assets, and EventBridge plus Transcribe complete the subtitle phase while the metadata table tracks progress.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rRy4AdZKkyOu_WiBE3GHdA.png" /></figure><h3><strong>S3 → SQS → Lambda</strong></h3><p>S3 sends an ObjectCreatedevent to an SQS queue. The queue has a dead-letter queue for messages that fail processing five times, and its visibility timeout is set to twice the Lambda timeout — this ensures a message stays invisible while the Lambda is working and only becomes available for retry if the Lambda crashes before completing.</p><pre>resource &quot;aws_sqs_queue&quot; &quot;ingest&quot; {<br>  name                       = &quot;video-stream-ingest&quot;<br>  visibility_timeout_seconds = 60<br><br>  redrive_policy = jsonencode({<br>    deadLetterTargetArn = aws_sqs_queue.ingest_dlq.arn<br>    maxReceiveCount     = 5<br>  })<br>}</pre><p>The Lambda event source mapping uses ReportBatchItemFailures, which lets the Lambda report individual message failures rather than treating the whole batch as a success or failure. This is essential for resilient batch processing — a transient error on one video shouldn’t block the others.</p><pre>resource &quot;aws_lambda_event_source_mapping&quot; &quot;callback_from_ingest&quot; {<br>  event_source_arn        = aws_sqs_queue.ingest.arn<br>  function_name           = aws_lambda_function.callback.arn<br>  batch_size              = 5<br>  function_response_types = [&quot;ReportBatchItemFailures&quot;]<br><br>  scaling_config {<br>    maximum_concurrency = 2<br>  }<br>}</pre><p>A maximum_concurrencycap on the event source mapping limits how many concurrent Lambda instances process the queue. This controls downstream pressure on MediaConvert and prevents accidental runaway scaling if a large number of uploads arrive simultaneously.</p><h3><strong>The Callback Lambda: Submitting the MediaConvert Job</strong></h3><p>The callback Lambda parses the S3 event from the SQS record, extracts the video ID from the object key (uploads/{videoId}/original/{filename}) and looks up the corresponding record in DynamoDB.</p><p>A few guard clauses prevent duplicate processing:</p><ul><li>If the video record has already been deleted, the message is silently skipped.</li><li>If a MediaConvert job ID is already present on the record, the message is a duplicate and is skipped.</li></ul><p>If all checks pass, the Lambda creates a MediaConvert job targeting the uploaded file and updates the DynamoDB record with processingStatus: PROCESSING_TRANSCODE.</p><h3><strong>MediaConvert Job Configuration</strong></h3><p>The job has two output groups: one HLS group producing two adaptive renditions, and one file group producing thumbnail still frames.</p><pre>{<br>  OutputGroups: [<br>    {<br>      Name: &#39;HLS&#39;,<br>      OutputGroupSettings: {<br>        Type: &#39;HLS_GROUP_SETTINGS&#39;,<br>        HlsGroupSettings: {<br>          Destination: `s3://${streamBucketName}/videos/${videoId}/hls/master`,<br>          SegmentLength: 6,<br>        },<br>      },<br>      Outputs: [<br>        {<br>          NameModifier: &#39;_720p&#39;,<br>          VideoDescription: {<br>            Width: 1280,<br>            Height: 720,<br>            CodecSettings: {<br>              Codec: &#39;H_264&#39;,<br>              H264Settings: {<br>                MaxBitrate: 3000000,<br>                RateControlMode: &#39;QVBR&#39;,<br>                GopSize: 2,<br>                GopSizeUnits: &#39;SECONDS&#39;,<br>                SceneChangeDetect: &#39;TRANSITION_DETECTION&#39;<br>              }<br>            }<br>          }<br>        },<br>        {<br>          NameModifier: &#39;_480p&#39;, VideoDescription: {<br>            Width: 854, Height: 480,<br>            CodecSettings: {<br>              Codec: &#39;H_264&#39;,<br>              H264Settings: {<br>                MaxBitrate: 1400000,<br>                RateControlMode: &#39;QVBR&#39;,<br>                GopSize: 2,<br>                GopSizeUnits: &#39;SECONDS&#39;,<br>                SceneChangeDetect: &#39;TRANSITION_DETECTION&#39;<br>              }<br>            }<br>          }<br>        }<br>      ]<br>    },<br>    {<br>      Name: &#39;Thumbnails&#39;,<br>      OutputGroupSettings: {<br>        Type: &#39;FILE_GROUP_SETTINGS&#39;,<br>        FileGroupSettings: {<br>          Destination: `s3://${streamBucketName}/videos/${videoId}/thumbnails/`,<br>        },<br>      },<br>      Outputs: [{<br>        NameModifier: &#39;_thumbnail&#39;,<br>        ContainerSettings: { Container: &#39;RAW&#39; },<br>        VideoDescription: {<br>          Width: 480,<br>          Height: 270,<br>          CodecSettings: {<br>            Codec: &#39;FRAME_CAPTURE&#39;,<br>            FrameCaptureSettings: {<br>              FramerateNumerator: 1,<br>              FramerateDenominator: 2,<br>              MaxCaptures: 3,<br>              Quality: 80,<br>            }<br>          }<br>        }<br>      }]<br>    }<br>  ]<br>}</pre><p>A few settings worth calling out:</p><ul><li><strong>QVBR rate control</strong>: Quality-defined variable bitrate. MediaConvert targets a quality level rather than a fixed bitrate, producing better quality at a lower average bitrate compared to CBR. Simpler scenes use fewer bits; complex scenes get more.</li><li><strong>Multiple </strong><strong>Outputsin one HLS group</strong>: MediaConvert builds the master manifest from all outputs under the same Destination. Both the 720p and 480p variants share hls/masteras their destination, so MediaConvert writes a single master playlist that advertises both. The player loads master.m3u8 and switches between renditions based on bandwidth.</li><li><strong>GopSize: 2 seconds</strong>: GOP stands for Group of Pictures — the span of frames between two keyframes. Only keyframes are fully self-contained; the frames between them are encoded as differences from their neighbours, so a player can only start decoding from a keyframe. Two-second GOPs mean a keyframe every two seconds, which allows HLS players to seek and start playback quickly. It also aligns with the six-second segment length (three GOPs per segment), ensuring every segment boundary falls on a keyframe — a requirement for seamless rendition switching.</li><li><strong>SceneChangeDetect: TRANSITION_DETECTION</strong>: Forces a keyframe on scene cuts, preventing visual artifacts at cuts and enabling cleaner segment boundaries.</li><li><strong>FRAME_CAPTURE output group</strong>: Captures JPEG still frames at 480×270 — one frame every two seconds, up to three captures. The output group uses FILE_GROUP_SETTINGS(not HLS), writing raw JPEG files directly to the thumbnails prefix.</li></ul><h3><strong>The HLS Master Manifest</strong></h3><p>With two renditions, the master manifest MediaConvert produces looks like this:</p><pre>#EXTM3U<br>#EXT-X-VERSION:3<br><br>#EXT-X-STREAM-INF:BANDWIDTH=3000000,RESOLUTION=1280x720,CODECS=&quot;avc1.64001f,mp4a.40.2&quot;<br>master_720p.m3u8<br><br>#EXT-X-STREAM-INF:BANDWIDTH=1400000,RESOLUTION=854x480,CODECS=&quot;avc1.64001f,mp4a.40.2&quot;<br>master_480p.m3u8</pre><p>Each STREAM-INF entry advertises a bandwidth ceiling and resolution. When a player starts, it picks the rendition that fits its current estimated bandwidth, then re-evaluates every few segments. A viewer on a strong connection gets 720p; one on mobile or a congested network steps down to 480p automatically — without rebuffering, and without the player needing any knowledge of your encoding settings.</p><h3><strong>The Pipeline Lambda: Chaining Transcoding to Subtitle Generation</strong></h3><p>When MediaConvert finishes, it emits a state change event to EventBridge. The pipeline Lambda handles two event types: MediaConvert state changes and Transcribe state changes. This two-phase design keeps subtitle generation decoupled from transcoding — they’re separate async jobs, but the pipeline coordinates them into a single video record lifecycle.</p><p><strong>Phase 1: MediaConvert Complete → Start Transcription</strong></p><p>When a COMPLETEevent arrives for a MediaConvert job, the pipeline Lambda:</p><ol><li>Lists the videos/{videoId}/thumbnails/prefix in S3 and picks the representative frame — specifically the third capture if available, falling back to the second, then the first. MediaConvert names frames numerically (test_thumbnail.0000001.jpg, .0000002.jpg, .0000003.jpg), so picking the middle or later frame avoids a common pitfall where the first few seconds are a black title card or a fade-in.</li><li>Updates the video record: processingStatus: PROCESSING_SUBTITLES, assetInfo.thumbnailKey, MediaConvert completion time.</li><li>Submits an AWS Transcribe job against the <strong>original upload</strong> (not the HLS output — Transcribe prefers the original uncompressed audio for accuracy).</li><li>Saves the Transcribe job ID to the video record.</li></ol><pre>await client.send(new StartTranscriptionJobCommand({<br>  TranscriptionJobName: `${video.videoId}__${video.languageCode}`,<br>  LanguageCode: video.languageCode,<br>  MediaFormat: detectMediaFormat(video.filename),<br>  Media: {<br>    MediaFileUri: `s3://${video.uploadBucket}/${video.originalKey}`,<br>  },<br>  OutputBucketName: config.streamBucketName,<br>  OutputKey: `videos/${videoId}/transcribe/`,<br>  Subtitles: {<br>    Formats: [&#39;vtt&#39;, &#39;srt&#39;],<br>    OutputStartIndex: 1,<br>  },<br>}))</pre><p>The Transcribe job name encodes both the video ID and the language code ({videoId}__{languageCode}). This lets the Transcribe completion handler extract the video ID without a separate database lookup.</p><p>Subtitle output goes directly to the streaming bucket alongside the HLS assets — both WebVTT (for browser &lt;track&gt;elements) and SRT (for offline use) are produced.</p><p><strong>Phase 2: Transcribe Complete → Mark READY</strong></p><p>When a Transcribe COMPLETEDevent arrives, the pipeline Lambda:</p><ol><li>Retrieves the full transcription job details to get the subtitle file URIs.</li><li>Converts the S3 URIs to relative object keys.</li><li>Updates the video record with processingStatus: READY and the assetInfo keys for the VTT, SRT, and transcript files.</li></ol><p>At this point, the video is ready to serve. The DynamoDB record now holds the S3 keys for the HLS master manifest and subtitles, and the API can return playback URLs.</p><h3><strong>State Tracking with DynamoDB</strong></h3><p>By now, you’ve seen four different parts of the system — the API, the callback Lambda, MediaConvert, and the pipeline Lambda — all reach into the same place: a single DynamoDB item keyed on videoId. That item is the thread that ties the whole asynchronous pipeline together. The API creates it before upload, the callback Lambda advances it when transcoding starts, and the pipeline Lambda finalizes it as subtitles and thumbnails arrive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcIemo7Fo4AaRT7vzyBE9g.png" /></figure><p>Its processingStatusfield moves through a linear progression:</p><ul><li>UPLOADING — Upload URL issued, file not yet in S3.</li><li>UPLOADED — File confirmed received, transcode not yet submitted.</li><li>PROCESSING_TRANSCODE — MediaConvert job running.</li><li>PROCESSING_SUBTITLES — Transcoding complete, Transcribe job running.</li><li>READY — All assets available, video is playable.</li><li>FAILED — A job failed. jobInfocontains the error detail.</li></ul><pre>const videoSchema = item({<br>  videoId: string().key(),<br>  title: string(),<br>  description: string(),<br>  filename: string(),<br>  contentType: string().enum(&#39;video/mp4&#39;),<br>  languageCode: string(),<br>  processingStatus: string().enum(...PROCESSING_STATUSES),<br>  durationSeconds: number().optional(),<br>  uploadBucket: string(),<br>  originalKey: string(),<br>  assetInfo: map({<br>    hlsMasterKey: string().optional(),<br>    subtitleVttKey: string().optional(),<br>    subtitleSrtKey: string().optional(),<br>    transcriptKey: string().optional(),<br>    thumbnailKey: string().optional(),<br>  }).optional(),<br>  jobInfo: map({<br>    mediaconvert: map({<br>      jobId: string().optional(),<br>      status: string().optional(),<br>      submittedAt: string().optional(),<br>      completedAt: string().optional(),<br>      errorMessage: string().optional(),<br>    }).optional(),<br>    transcribe: map({<br>      jobId: string().optional(),<br>      status: string().optional(),<br>      languageCode: string().optional(),<br>      submittedAt: string().optional(),<br>      completedAt: string().optional(),<br>      errorMessage: string().optional(),<br>    }).optional(),<br>  }).optional(),<br>  createdAt: string(),<br>  updatedAt: string(),<br>})</pre><p>Each field on the item serves a specific role in the pipeline:</p><ul><li>videoId— the partition key and the stable identifier used across S3 keys, job metadata, and API routes.</li><li>title, description — user-supplied metadata returned by the API and shown in any frontend listing or detail view.</li><li>filename, contentType — the original upload name and validated MIME type, used when submitting downstream processing jobs and for auditability.</li><li>languageCode — the requested transcription language, passed directly into the Transcribe job.</li><li>processingStatus — the current lifecycle state, which tells the API and operators whether the video is waiting, processing, ready, or failed.</li><li>durationSeconds — optional runtime metadata that can be filled in later once media analysis is available.</li><li>uploadBucket, originalKey — the exact S3 location of the raw uploaded file, which the pipeline uses as the source of truth for MediaConvert and Transcribe.</li><li>assetInfo — object keys for derived outputs such as the HLS master manifest, subtitles, transcript JSON, and thumbnail image.</li><li>jobInfo — the MediaConvert and Transcribe job identifiers, statuses, timestamps, and error messages needed for recovery, cancellation, and debugging.</li><li>createdAt, updatedAt — timestamps for record creation and the latest state transition.</li></ul><p>The jobInfo field stores MediaConvert and Transcribe job IDs and statuses. This is useful for debugging and for the API’s video deletion flow — before deleting a video, the API checks for active jobs and cancels them to avoid orphaned processing work and unexpected charges.</p><h3><strong>What the API Exposes</strong></h3><p>The API Lambda handles a small set of routes:</p><ul><li>POST /api/uploads— creates a presigned PUT URL and registers the video record at UPLOADINGstatus.</li><li>GET /api/videos — lists videos with thumbnail and HLS URLs (summary view).</li><li>GET /api/videos/{videoId} — returns full video details, including playback URLs and job info.</li><li>DELETE /api/videos/{videoId} — cancels active jobs, deletes S3 assets, and removes the DynamoDB record.</li></ul><p>Playback URLs are assembled from a configurable base URL. A fully processed video record looks like this:</p><pre>{<br>  &quot;videoId&quot;: &quot;40bd1f10-9de5-429b-8419-4a5d76c9a00e&quot;,<br>  &quot;title&quot;: &quot;Test Video&quot;,<br>  &quot;processingStatus&quot;: &quot;READY&quot;,<br>  &quot;languageCode&quot;: &quot;en-US&quot;,<br>  &quot;playback&quot;: {<br>    &quot;hlsUrl&quot;: &quot;/videos/40bd1f10-9de5-429b-8419-4a5d76c9a00e/hls/master.m3u8&quot;,<br>    &quot;subtitles&quot;: [<br>      {<br>        &quot;languageCode&quot;: &quot;en-US&quot;,<br>        &quot;label&quot;: &quot;English&quot;,<br>        &quot;url&quot;: &quot;/videos/40bd1f10-9de5-429b-8419-4a5d76c9a00e/transcribe/40bd1f10-9de5-429b-8419-4a5d76c9a00e__en-US.vtt&quot;<br>      }<br>    ]<br>  },<br>  &quot;assetInfo&quot;: {<br>    &quot;hlsMasterKey&quot;: &quot;videos/40bd1f10-9de5-429b-8419-4a5d76c9a00e/hls/master.m3u8&quot;,<br>    &quot;thumbnailKey&quot;: &quot;videos/40bd1f10-9de5-429b-8419-4a5d76c9a00e/thumbnails/test_thumbnail.0000002.jpg&quot;,<br>    &quot;subtitleVttKey&quot;: &quot;videos/40bd1f10-9de5-429b-8419-4a5d76c9a00e/transcribe/40bd1f10-9de5-429b-8419-4a5d76c9a00e__en-US.vtt&quot;,<br>    &quot;subtitleSrtKey&quot;: &quot;videos/40bd1f10-9de5-429b-8419-4a5d76c9a00e/transcribe/40bd1f10-9de5-429b-8419-4a5d76c9a00e__en-US.srt&quot;,<br>    &quot;transcriptKey&quot;: &quot;videos/40bd1f10-9de5-429b-8419-4a5d76c9a00e/transcribe/40bd1f10-9de5-429b-8419-4a5d76c9a00e__en-US.json&quot;<br>  }<br>}</pre><p>The playback object is what a frontend needs to start a player — HLS URL and subtitle tracks. The raw assetInfo keys are the underlying S3 object paths, useful for debugging or building additional tooling on top.</p><h3>Streaming HLS in the Browser</h3><figure><img alt="A sequence diagram showing a browser requesting the HLS master manifest, rendition playlist, video segments, and optional VTT subtitles from CloudFront, with CloudFront fetching each file from the private S3 streaming bucket on cache miss." src="https://cdn-images-1.medium.com/max/1024/1*ZxNtbj1-D1uvZExF_7v-_A.png" /></figure><p>By the time a video reaches aREADY state, playback is straightforward: load the master manifest at videos/{videoId}/hls/master.m3u8and, if transcription succeeded, the VTT subtitle file alongside it. If the frontend already knows videoIdand the playback base URL, it can request those CloudFront paths directly without doing an API lookup first. The player then fetches the master playlist, selects a rendition, and switches qualities as conditions change.</p><p>Native HLS playback is supported in Safari. For Chrome and Firefox, a JavaScript library like <a href="https://github.com/video-dev/hls.js">hls.js</a> is needed to feed the HLS stream to an HTML5 &lt;video&gt; element via Media Source Extensions (MSE).</p><pre>&lt;video id=&quot;player&quot; controls&gt;&lt;/video&gt;<br>&lt;track kind=&quot;subtitles&quot; src=&quot;/videos/{videoId}/transcribe/{videoId}__en-US.vtt&quot;<br>       srclang=&quot;en&quot; label=&quot;English&quot; default&gt;<br><br>&lt;script&gt;<br>  const video = document.getElementById(&#39;player&#39;);<br>  const src = &#39;/videos/{videoId}/hls/master.m3u8&#39;;<br><br>  if (video.canPlayType(&#39;application/vnd.apple.mpegurl&#39;)) {<br>    // Safari native HLS<br>    video.src = src;<br>  } else if (Hls.isSupported()) {<br>    const hls = new Hls();<br>    hls.loadSource(src);<br>    hls.attachMedia(video);<br>  }<br>&lt;/script&gt;</pre><p>The subtitle VTT file is served alongside the HLS assets from the streaming bucket, so the &lt;track&gt; element URL is just another CloudFront path.</p><figure><img alt="A screenshot of the browser demo player playing an AWS architecture walkthrough video with subtitles enabled and standard playback controls visible." src="https://cdn-images-1.medium.com/max/1024/1*S9yM6wF06DW-1aCc_bYYOg.png" /></figure><h3>Conclusion</h3><p>The key insight in this architecture is that video processing is inherently asynchronous. A file upload does not produce a playable stream immediately; it kicks off a chain of events that prepares one. SQS decouples the trigger from the work, EventBridge chains the async phases together, DynamoDB tracks state across them, and CloudFront plus S3 handle delivery without any compute in the hot path.</p><p>The result is a fully serverless pipeline that turns a raw upload into an adaptive HLS stream with thumbnails and subtitles, while staying simple to operate and inexpensive when idle.</p><p>The complete project is available in <a href="https://gitlab.com/ben_goodman/scratchpad/aws-video-streaming">GitLab</a>.</p><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daea1fe842fc" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/video-ingest-and-streaming-on-aws-a-serverless-pipeline-from-upload-to-hls-daea1fe842fc">Video Ingest and Streaming on AWS: A Serverless Pipeline from Upload to HLS</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uploading Documents to S3 Vector Buckets]]></title>
            <link>https://aws.plainenglish.io/uploading-documents-to-s3-vector-buckets-f418594feca3?source=rss-2f01806d4793------2</link>
            <guid isPermaLink="false">https://medium.com/p/f418594feca3</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[amazon-s3-vectors]]></category>
            <dc:creator><![CDATA[Benjamin Goodman]]></dc:creator>
            <pubDate>Sat, 09 Aug 2025 16:26:16 GMT</pubDate>
            <atom:updated>2025-08-10T13:59:08.782Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to upload, embed, and retrieve documents using AWS Textract, Bedrock, and S3 Vector Buckets.</h4><p>Amazon S3 Vector Buckets are a new feature of AWS providing a scalable and cost-effective solution for storing and retrieving vector data. Key benefits include low-latency queries, simplified API integration, and minimal infrastructure compared to services like OpenSearch.</p><p>Vector data — numerical representations of text, also known as embeddings — enable powerful semantic search by comparing the meaning of text rather than exact keywords.</p><p>In this article, we’ll build a basic serverless file manager that takes uploaded documents, converts them to vector data, and stores them in an S3 Vector Bucket. Later, we’ll perform semantic searches by converting a user’s query to a vector and retrieving the most relevant documents based on vector similarity.</p><h3>Getting Started With S3 Vectors</h3><p>Before we build anything, there’s some essential setup first:</p><ul><li>Enable AI models for text embedding.</li><li>Create a new vector bucket and index.</li><li>Create a Lambda layer for the S3 vectors SDK.</li></ul><p>Amazon Bedrock is the AWS service for managing AI models. We will need an AI model to make the conversion from text to vector. I didn’t realize this until way too late in the project, but all models are disabled by default. So begin by navigating to the Bedrock console and enabling a text embedding model. I’m using Amazon’s own amazon.titan-embed-text-v2:0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5_PNDQmb9naCwtOj2H_3gA.png" /><figcaption>You need to manually enable access for each model you plan to use.</figcaption></figure><p>The next step is to create a vector bucket. I’ve used the web console since there’s no Terraform support at the moment.</p><figure><img alt="Creating an S3 Vector Bucket using the AWS console." src="https://cdn-images-1.medium.com/max/1024/1*HVjahJ2mMP7LITZTqkTUbw.png" /><figcaption>Creating an S3 Vector Bucket using the AWS console.</figcaption></figure><p>After creating a bucket, we must make an index. This is where the vectors are stored, and so we need to set the vector’s dimension (or length). The text embedding model determines the dimension, and for AWS Titan, this is 1024.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNGWgONg6SYKb9J3od7S0w.png" /><figcaption>Creating an S3 vector index.</figcaption></figure><p>Next, under additional settings, we declare the vector’s metadata:</p><ul><li>id — used to retrieve metadata from a database.</li><li>chunk — the vector’s original text.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*401Uw5CXqJRfSWQFM_8gTA.png" /><figcaption>Assigning metadata to S3 vectors.</figcaption></figure><p>Once an index has been created, its settings can’t be modified — instead, you’ll need to delete the index and start over. Fortunately, it’s quick and easy via the CLI:</p><pre>aws s3vectors delete-index \<br>  --vector-bucket-name &#39;pdf-rag-embeddings-main&#39; \<br>  --index-name &#39;documents&#39;</pre><p>From here on, we’ll use the <a href="https://www.npmjs.com/package/@aws-sdk/client-s3vectors">SDK</a> to interact with the bucket. With AWS Lambda, the complete SDK is available in the runtime’s context, so it’s best practice to externalize all @aws-skd/* modules to keep bundle sizes to a minimum. However, this does not appear to be the case (yet) with @aws-sdk/client-s3Vectors and so externalizing it will cause runtime errors. The solution: export it as a custom layer.</p><pre>.aws/terraform/layers<br>└── s3vectors-layer<br>    └── nodejs<br>        ├── node_modules<br>        ├── package-lock.json<br>        └── package.json</pre><p>We create an npm project that has the required code as its dependencies.</p><pre>{<br>  &quot;name&quot;: &quot;aws-sdk-client-s3vectors&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;@aws-sdk/client-s3vectors&quot;: &quot;^3.862.0&quot;<br>  }<br>}</pre><p>Then, using Terraform, we can automatically build, compress, and deploy the custom layer.</p><pre>resource &quot;null_resource&quot; &quot;install_node_modules&quot; {<br>  provisioner &quot;local-exec&quot; {<br>    working_dir = &quot;${path.module}/layers/s3vectors-layer/nodejs&quot;<br>    command     = &quot;npm install&quot;<br>  }<br>  triggers = {<br>    always_run = &quot;${timestamp()}&quot;<br>  }<br>}<br><br>data &quot;null_data_source&quot; &quot;wait_for_install_node_modules&quot; {<br>  inputs = {<br>    lambda_exporter_id = &quot;${null_resource.install_node_modules.id}&quot;<br>  }<br>}<br><br>data &quot;archive_file&quot; &quot;s3vectors_zip&quot; {<br>  depends_on = [ data.null_data_source.wait_for_install_node_modules ]<br>  type             = &quot;zip&quot;<br>  source_dir       = &quot;${path.module}/layers/s3vectors-layer&quot;<br>  output_file_mode = &quot;0666&quot;<br>  output_path      = &quot;${path.module}/layers/s3vectors-layer.zip&quot;<br>}<br><br><br>resource &quot;aws_lambda_layer_version&quot; &quot;s3vectors_layer&quot; {<br>  layer_name          = &quot;s3vectors-sdk&quot;<br>  filename            = data.archive_file.s3vectors_zip.output_path<br>  source_code_hash    = data.archive_file.s3vectors_zip.output_base64sha256<br>  compatible_runtimes = [&quot;nodejs20.x&quot;]<br>  description         = &quot;Lambda Layer for @aws-sdk/client-s3vectors&quot;<br>}</pre><h3>Uploading Documents</h3><p>Uploading a document to a vector bucket involves several steps, including extracting text and converting it into vector format. We’ll use AWS Textract to extract text from documents stored in S3, and AWS Bedrock to generate text embeddings using a managed AI model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hze4pqcZnW0dGv9D" /><figcaption>The document upload workflow.</figcaption></figure><p>We also need to consider:</p><ul><li>The vector conversion is irreversible, so we’ll also need to retain the source text.</li><li>How do we get the source document back to the user?</li><li>Textract jobs take time and should be handled asynchronously.</li><li>How to store document metadata? And what to store?</li></ul><p>When uploading files to S3 — whether to a vector bucket or an object one — we need to store metadata that includes the generated S3 keys. Additionally, we must track the Textract job ID so the callback Lambda function can retrieve the relevant metadata when the job completes.</p><p>To serve the original documents via CloudFront, the metadata should, at a minimum, include the S3 object key. For convenience, I also store the full source URL, which combines the CloudFront domain with the object key.</p><p>Each document is assigned a random ID as its primary key. This same ID is used in the vector metadata, allowing us to link vector search results back to their source documents.</p><pre>type FileMetadata = {<br>    id: string; // primary key<br>    s3ObjectKey: string;<br>    textExtractionJobId: string; // (GSI) used to retrive the Textract results<br>    sourceUrl: string; // used to retrieve the source document<br>    vectorKeys?: Set&lt;string&gt; | undefined; // used to delete documents <br>}</pre><p>With these points in mind, let&#39;s envisage our upload scenario:</p><ol><li>User sends a POST /upload request to the HTTP endpoint.</li><li>Lambda parses the file and saves the original in an S3 bucket.</li><li>A Textract job for the S3 document is dispatched, and the file’s metadata is updated.</li><li>The job completion triggers a callback lambda that embeds the extracted text.</li><li>The embedded text is uploaded to a vector index, and the file’s metadata is updated.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_ZERdAD14OkCeSYSVjjCQ.png" /><figcaption>Infrastructure to upload and embed a document.</figcaption></figure><p>The first step is to upload the source document to a classic S3 bucket, as it will serve as our source for Textract.</p><pre>import { PutObjectCommand, S3Client } from &#39;@aws-sdk/client-s3&#39;<br>import { type MultipartFile } from &#39;lambda-multipart-parser&#39;<br>import { ASSETS_BUCKET_NAME } from &#39;../constants&#39;<br><br>const s3 = new S3Client({})<br><br>export const uploadSourceToS3 = async (<br>  id: string,<br>  assetFile: MultipartFile<br>): Promise&lt;string&gt; =&gt; {<br><br>  const objectKey = `${id}/${assetFile.filename}`<br><br>  await s3.send(<br>    new PutObjectCommand({<br>      Bucket: ASSETS_BUCKET_NAME,<br>      Key: objectKey,<br>      Body: assetFile.content,<br>      ContentType: assetFile.contentType,<br>    })<br>  ).catch((err) =&gt; {<br>    console.log(`uploading item ${id} to S3 failed`)<br>    console.log(err)<br>    throw err<br>  })<br><br>  return objectKey<br>}</pre><p>Using the S3 object just created, a Textract job is dispatched with a notification set to invoke a callback Lambda via SNS to handle the results when the job is complete.</p><pre>import {<br>  TextractClient,<br>  StartDocumentTextDetectionCommand<br>} from &#39;@aws-sdk/client-textract&#39;<br>import { TEXTRACT_COMPLETE_TOPIC_ARN, TEXTRACT_ROLE_ARN } from &#39;../constants&#39;<br><br>const client = new TextractClient({ region: &#39;us-east-1&#39; })<br><br>export const dispatchTextExtraction = async (s3ObjectKey: string): Promise&lt;string&gt; =&gt; {<br>  const startCommand = new StartDocumentTextDetectionCommand({<br>    DocumentLocation: {<br>      S3Object: {<br>        Bucket: process.env.ASSETS_BUCKET_NAME,<br>        Name: s3ObjectKey<br>      }<br>    },<br>    NotificationChannel: {<br>      RoleArn: TEXTRACT_ROLE_ARN,<br>      SNSTopicArn: TEXTRACT_COMPLETE_TOPIC_ARN<br>    }<br>  })<br>  const resp = await client.send(startCommand)<br>  if (!resp.JobId) {<br>    throw new Error(&#39;Failed to start text detection job: JobId is undefined&#39;)<br>  }<br>  console.log(&#39;Started text detection job with ID&#39;, resp)<br>  return resp.JobId<br>}</pre><p>Once the job is dispatched, we add its jobId to the file’s metadata. We do this so the callback Lambda can query the file’s metadata.</p><pre>export const uploadFile = async (file: MultipartFile) =&gt; {<br>  const nanoid = customAlphabet(&#39;1234567890abcdefghijklmnopqrstuvwxyz&#39;, 14)<br>  const id = nanoid()<br><br>  const s3ObjectKey = await uploadSourceToS3(id, file)<br><br>  console.log(`File uploaded to S3: ${s3ObjectKey}`)<br><br>  const textExtractionJobId = await dispatchTextExtraction(s3ObjectKey)<br><br>  return updateFileMetadata({<br>    id,<br>    s3ObjectKey,<br>    textExtractionJobId,<br>    sourceUrl: `${ASSETS_CLOUDFRONT_URL}/${s3ObjectKey}`,<br>  })<br>}</pre><p>Next, we create the callback Lambda function — the one that will handle the SNS event created by our Textract job. It gets the Textract jobId from the SNS event, so we begin with a function that uses it to get the Textract job results.</p><pre>import {<br>  TextractClient,<br>  GetDocumentTextDetectionCommand,<br>} from &#39;@aws-sdk/client-textract&#39;<br><br><br>const client = new TextractClient({ region: &#39;us-east-1&#39; })<br><br>export const getTextResults = async (jobId: string): Promise&lt;string[]&gt; =&gt; {<br>  const getCommand = new GetDocumentTextDetectionCommand({ JobId: jobId })<br>  const resp = await client.send(getCommand)<br><br>  if (resp.JobStatus === &#39;SUCCEEDED&#39;) {<br>    const text = resp.Blocks<br>      ?.filter(block =&gt; block.BlockType === &#39;LINE&#39; &amp;&amp; block.Text)<br>      .map(block =&gt; block.Text)<br>      .filter((text): text is string =&gt; typeof text === &#39;string&#39;) || []<br><br>    return text<br>  } else if (resp.JobStatus === &#39;FAILED&#39;) {<br>    throw new Error(`Text extraction job failed: ${resp.StatusMessage}`)<br>  } else {<br>    throw new Error(`Text extraction job is still in progress: ${resp.JobStatus}`)<br>  }<br>}</pre><p>This gets us the document’s text content as an array of strings. Now, we must chunk and embed the text. I’ve explained the process in the article below, but the gist of it is:</p><ul><li>Partition the Textract results into chunks of text.</li><li>Use an LLM to convert the chunks into vectors representing the chunk’s semantic meaning.</li></ul><p><a href="https://medium.com/@benjamin_goodman/creating-an-ai-powered-cookbook-c3a4a258fbab">Creating An AI-Powered Cookbook</a></p><p>My chunking method is to just partition the text into arrays of 300 words each, with an overlap of 30 words. This should ensure enough context for semantic meaning while avoiding diluting relevance.</p><pre>import { BedrockRuntimeClient, InvokeModelCommand } from &#39;@aws-sdk/client-bedrock-runtime&#39;<br><br><br>const chunkText = (text: string[], maxSize: number, overlapWords: number): string[] =&gt; {<br>  const words: string[] = text.flatMap(t =&gt; t.split(/\s+/))<br>  const chunks: string[] = []<br><br>  let start = 0<br>  while (start &lt; words.length) {<br>    const end = Math.min(start + maxSize, words.length)<br>    const chunk = words.slice(start, end).join(&#39; &#39;)<br>    chunks.push(chunk)<br>    start += maxSize - overlapWords<br>  }<br><br>  return chunks<br>}</pre><p>Now we use a text embedding model to convert the chunks into vectors.</p><pre>const embedText = async (text: string): Promise&lt;number[]&gt; =&gt; {<br><br>  const client = new BedrockRuntimeClient({ region: &#39;us-east-1&#39; })<br><br>  const input = {<br>    modelId: &#39;amazon.titan-embed-text-v2:0&#39;,<br>    contentType: &#39;application/json&#39;,<br>    accept: &#39;application/json&#39;,<br>    body: JSON.stringify({<br>      inputText: text<br>    }),<br>  }<br><br>  const command = new InvokeModelCommand(input)<br>  const response = await client.send(command)<br><br>  const body = JSON.parse(new TextDecoder().decode(response.body))<br>  <br>  const embedding = body.embedding<br><br>  return embedding<br>}</pre><p>It’s also important to retain the original text during this process, so I’ve made a function that keeps all the data together as an object.</p><pre>export interface EmbeddedText {<br>  vector: number[]<br>  text: string<br>}<br><br>export const embedDocument = async (input: string[]): Promise&lt;EmbeddedText[]&gt; =&gt; {<br>  const chunks = chunkText(input, 300, 30)<br><br>  return await Promise.all(chunks.map(async chunk =&gt; {<br>    return {<br>      vector: await embedText(chunk),<br>      text: chunk<br>    }<br>  }))<br>}</pre><p>Next, we upload the embedded chunks to our S3 vector index. Each indexed vector consists of a unique key, its numerical value, and optional metadata. We include the metadata for the file’s id and the original chunk text — both are required during retrieval later. We also accumulate the vector keys, which we’ll need later to delete the document.</p><pre>import { S3VectorsClient, PutVectorsCommand } from &#39;@aws-sdk/client-s3vectors&#39;<br>import { VECTOR_BUCKET_INDEX_ARN } from &#39;../constants&#39;<br>import { EmbeddedText } from &#39;../util/embedDocument&#39;<br><br>const s3Vectors = new S3VectorsClient({})<br><br>export interface VectorMetadata {<br>  id: string<br>  chunk: string<br>}<br><br>export const uploadVector = async (<br>  id: string,<br>  embeddings: EmbeddedText[]<br>): Promise&lt;Set&lt;string&gt;&gt; =&gt; {<br>  const keys = new Set&lt;string&gt;()<br><br>  const promises = embeddings.map(async (embedding, index) =&gt; {<br>    const input = {<br>      indexArn: VECTOR_BUCKET_INDEX_ARN,<br>      vectors: [<br>        {<br>          key: `${id}-${index}`,<br>          data: {<br>            float32: embedding.vector,<br>          },<br>          metadata: {<br>            id,<br>            chunk: embedding.text,<br>          },<br>        },<br>      ],<br>    }<br><br>    keys.add(`${id}-${index}`)<br><br>    await s3Vectors.send(new PutVectorsCommand(input))<br>  })<br><br>  await Promise.all(promises)<br><br>  return keys<br>}</pre><p>We’re now ready to handle the Textract SNS event with the callback Lambda:</p><pre>import { SNSHandler } from &#39;aws-lambda&#39;<br>import { getTextResults } from &#39;./util/getTextResults&#39;<br>import { embedDocument } from &#39;./util/embedDocument&#39;<br>import { getMetadataByJobId, updateFileMetadata } from &#39;./repo/fileMetadata&#39;<br>import { uploadVector } from &#39;./repo/uploadVector&#39;<br><br><br>export const handler: SNSHandler = async (event) =&gt; {<br><br>  for (const record of event.Records) {<br>    const message = JSON.parse(record.Sns.Message)<br><br>    const { JobId, Status, JobTag } = message<br><br>    if (Status !== &#39;SUCCEEDED&#39;) {<br>      console.warn(&#39;Textract job failed:&#39;, message)<br>      return<br>    }<br><br>    const text = await getTextResults(JobId)<br><br>    const fileMetadata = await getMetadataByJobId(JobId)<br><br>    if (!fileMetadata) {<br>      console.error(&#39;No file metadata found for JobId:&#39;, JobId)<br>      return<br>    }<br><br>    const embeddings = await embedDocument(text)<br><br>    const vectorKeys = await uploadVector(fileMetadata.id, embeddings)<br><br>    const updateMetadata = await updateFileMetadata({<br>      ...fileMetadata,<br>      vectorKeys, // Store the vector keys in the file metadata<br>    })<br><br>  }<br>}</pre><p>Now we test the upload service. I’m using a free dataset of PDFs I found on <a href="https://www.kaggle.com/datasets/manisha717/dataset-of-pdf-files">Kaggle</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2Da9_ittEJrQruky2y7ug.png" /><figcaption>An extract of one of the PDFs I used for testing. I think its for a patent.</figcaption></figure><p>Once we upload the PDF, we get its metadata in return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPif1H6sG0UvojQJ9Qaa_A.png" /><figcaption>Uploading the test PDF.</figcaption></figure><h3>Retrieving Documents</h3><p>At this point, we have an S3 bucket holding the original documents, a separate bucket containing their vector embeddings, and a database that links everything together. The next step is to enable document search using natural language input. To do this, we embed the input query as a vector and use it to search the S3 vector index. The matching results then allow us to retrieve the associated documents using their metadata.</p><ol><li>User messages a query.</li><li>The query is embedded as a vector.</li><li>The S3 vector index is queried for similar vectors.</li><li>Vector results and file metadata are merged.</li><li>A message containing the document’s summary and source URL is streamed back to the user.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*iup_cEC6eMsZCL1DL88FMA.png" /><figcaption>Infrastructure for document retrieval.</figcaption></figure><p>Let’s begin by querying the S3 vector index. We’ve already got the code for embedding text, so we reuse it when we vectorize the user’s query. We then pass in the vector as our query and send the command.</p><pre>const input = {<br>    indexArn: VECTOR_BUCKET_INDEX_ARN!,<br>    queryVector: {<br>      float32: vector,<br>    },<br>    topK: opts.topK || 5,<br>    returnMetadata: true<br>  }<br><br>const resp = await s3Vectors.send(new QueryVectorsCommand(input))</pre><p>The results are an array of vectors that were similar to the query vector. What’s of particular use is the vector’s metadata, which we’ll want to extract.</p><pre>{<br>  &quot;$metadata&quot;: {<br>      &quot;httpStatusCode&quot;: 200,<br>      &quot;requestId&quot;: &quot;59b1921b-6937-4362-9509-b96b18970387&quot;,<br>      &quot;attempts&quot;: 1,<br>      &quot;totalRetryDelay&quot;: 0<br>  },<br>  &quot;vectors&quot;: [<br>      {<br>          &quot;key&quot;: &quot;cjgupupu4iaw76-0&quot;,<br>          &quot;metadata&quot;: {<br>              &quot;id&quot;: &quot;cjgupupu4iaw76&quot;,<br>              &quot;chunk&quot;: &quot;Sample Document for PDF Testing Introduction ...&quot;<br>          }<br>      }<br>  ]<br>}</pre><p>The input embedding, vector search, and results handling are wrapped inside a function that accepts the user’s query and returns the matching chunks and the document’s ID (which is used to retrieve metadata).</p><pre>import { QueryVectorsCommand, S3VectorsClient } from &#39;@aws-sdk/client-s3vectors&#39;<br>import { VECTOR_BUCKET_INDEX_ARN } from &#39;../constants&#39;<br>import { embedText } from &#39;../util/embedText&#39;<br><br>const s3Vectors = new S3VectorsClient({})<br><br>export interface VectorMetadata {<br>  id: string<br>  chunk: string<br>}<br><br>export const queryVector = async (query: string, opts: { topK?: number } = {}) =&gt; {<br>  const vector = await embedText(query)<br><br>  const input = {<br>    indexArn: VECTOR_BUCKET_INDEX_ARN!,<br>    queryVector: {<br>      float32: vector,<br>    },<br>    topK: opts.topK || 5,<br>    returnMetadata: true<br>  }<br><br>  const resp = await s3Vectors.send(new QueryVectorsCommand(input))<br><br>  if (!resp.vectors || resp.vectors.length === 0) {<br>    console.log(&#39;No vectors found for the query&#39;)<br>    return []<br>  }<br><br><br>  return resp.vectors.map(v =&gt; {<br>    const metadata = v.metadata as VectorMetadata | undefined<br>    if (!metadata) {<br>      throw new Error(&#39;Metadata is required in the vector response&#39;)<br>    }<br>    <br>    // Ensure metadata has the required fields<br>    if (!metadata.id || !metadata.chunk) {<br>      throw new Error(&#39;Vector metadata must contain id and chunk fields&#39;)<br>    }<br><br>    return {<br>      id: metadata.id,<br>      chunk: metadata.chunk,<br>      key: v.key<br>    }<br>  })<br>}</pre><p>The next step is entirely optional — creating a chatbot to make the queries for us and deliver the results.</p><p><a href="https://aws.plainenglish.io/streaming-llm-responses-from-aws-lambda-46ed5cb25bee">Streaming LLM Responses from AWS Lambda</a></p><p>I already have the code handy, and it&#39;s the coolest way to test our new S3 vector index. I wasn’t sure what to search for, so I used the header text from the test PDF I uploaded earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*s8_ZONk2tEdvnlkAgC-rXw.gif" /><figcaption>Retrieved document chunks are summarized and a source URL is provided.</figcaption></figure><h3>Deleting Documents</h3><p>The final step in covering the document lifecycle is deletion. This is simplest process of them all and involves:</p><ul><li>Deleting the file’s source S3 object</li><li>Deleting all vectors associated with the file</li><li>Deleting the file’s metadata.</li></ul><p>The process is triggered by a DELETE request with the document ID as a path parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ht8bMZiplRGfWOnj55rNFA.png" /></figure><p>We need the keys of the objects and vectors we want to delete. Both s3ObjectKey and the set vectorKeys are part of the document metadata, and so are simple to retrieve using the document’s ID. All that remains is deleting the document’s object and vectors.</p><pre>import { DeleteObjectCommand, S3Client } from &#39;@aws-sdk/client-s3&#39;<br>import { S3VectorsClient, DeleteVectorsCommand } from &#39;@aws-sdk/client-s3vectors&#39;<br>import { ASSETS_BUCKET_NAME, VECTOR_BUCKET_INDEX_ARN } from &#39;../constants&#39;<br><br>const s3 = new S3Client({})<br>const s3Vectors = new S3VectorsClient({})<br><br>export const deleteSourceFromS3 = async (s3ObjectKey: string) =&gt; {<br>  const resp = await s3<br>    .send(<br>      new DeleteObjectCommand({<br>        Bucket: ASSETS_BUCKET_NAME,<br>        Key: s3ObjectKey,<br>      })<br>    )<br>    .catch((err) =&gt; {<br>      console.error(&#39;Error deleting file from S3:&#39;, err)<br>      throw err<br>    })<br><br>  return resp<br>} <br><br><br>export const deleteVectorFromS3 = async (vectorKeys?: Set&lt;string&gt;) =&gt; {<br>  if (!vectorKeys || vectorKeys.size === 0) {<br>    console.log(&#39;No vector keys provided for deletion&#39;)<br>    return<br>  }<br>  <br>  const resp = await s3Vectors<br>    .send(<br>      new DeleteVectorsCommand({<br>        indexArn: VECTOR_BUCKET_INDEX_ARN!,<br>        keys: Array.from(vectorKeys),<br>      })<br>    )<br><br>  return resp<br>}</pre><p>Examining the metadata from each operation confirms the file was deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N0QJtFfFFnnMeJtBipXuVA.png" /></figure><h3>Conclusion</h3><p>This example serves as an effective showcase of how S3 Vector Buckets can be used.</p><p>The complete project is available in <a href="https://gitlab.com/ben_goodman/scratchpad/pdf-rag">GitLab</a>.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 200k supporters? <strong>We do not get paid by Medium</strong>!</p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a><strong> and </strong><a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f418594feca3" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/uploading-documents-to-s3-vector-buckets-f418594feca3">Uploading Documents to S3 Vector Buckets</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streaming LLM Responses from AWS Lambda]]></title>
            <link>https://aws.plainenglish.io/streaming-llm-responses-from-aws-lambda-46ed5cb25bee?source=rss-2f01806d4793------2</link>
            <guid isPermaLink="false">https://medium.com/p/46ed5cb25bee</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Benjamin Goodman]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 14:32:13 GMT</pubDate>
            <atom:updated>2025-08-07T00:09:28.273Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using a WebSocket connection to stream an AI chat session to a React client.</h4><p>In this article, we’ll explore how to stream responses from a large language model (LLM) in real time using AWS Lambda and WebSocket connections to push generated text to a React client incrementally — chunk by chunk— enabling a smooth, conversational chat experience. You’ll learn how to set up the bi-directional WebSocket API with Amazon API Gateway, manage connections in Lambda, create a simple chat agent, and build a responsive front-end that updates as the AI agent generates its reply.</p><p>For the basis of this project, we’ll use a chatbot I developed earlier. It queries a database of cooking recipes to generate its output. Reading the article below is optional, but it does go into detail on how the recipes database was created.</p><p><a href="https://medium.com/@benjamin_goodman/creating-an-ai-powered-cookbook-c3a4a258fbab">Creating An AI-Powered Cookbook</a></p><p>The initial effort was a success, but it was hampered by high latency — something I’ll improve upon later with improved session handling. But in the meantime, we can introduce streaming as a partial solution to latency.</p><p>While slightly more complex (or fun) to implement, sending the LLM’s response incrementally as it&#39;s generated will ultimately deliver a superior user experience; it&#39;s basically the ultimate loading bar in terms of functionality and design. In essence, it doesn’t speed things up, but does give the user something to watch while also confirming that the AI is working.</p><figure><img alt="An animated GIF of a website streaming text generated by an LLM." src="https://cdn-images-1.medium.com/max/699/1*zYp4xljaZqNyMDn0LIH4_Q.gif" /><figcaption>The output for a chat session with gastro-genie.com streaming in real time over a WebSocket connection.</figcaption></figure><h3>Achieving Real-Time Two-Way Communication</h3><p>Before we can consider how to stream an LLM, we need infrastructure that can support it. Let’s start by understanding what we want, and then we can build it.</p><p>The process isn’t too dissimilar to a conventional HTTP request, with the greatest difference being how we send data back to the client (the exact method is a problem for later, though).</p><ol><li>Client opens a WebSocket to API Gateway.</li><li>Messages from the client trigger a Lambda function, which retrieves the user’s chat session from a DynamoDB table and instantiates the chat agent.</li><li>Lambda runs the chat agent with the user’s input and chat session history.</li><li>Lambda posts messages back to the client (via the gateway) as the LLM generates text.</li><li>Finally, an ‘end of message’ response is sent to the client, and the chat session table is updated.</li></ol><figure><img alt="Sequence diagram showing how a React client streams LLM responses via a WebSocket connection to AWS API Gateway. The Lambda function retrieves chat history, forwards the message to an AI agent, streams response chunks back through the gateway, and signals completion with an end-of-message event." src="https://cdn-images-1.medium.com/max/1024/1*qPmLvduPNkZuGiWvPbxYwQ.png" /><figcaption>The sequnce of events during a typical user exchange will serve as our blueprint.</figcaption></figure><p>I’ve chosen to use a WebSocket instead of HTTP streaming because it’s a simpler and more practical solution for this use case. While it’s possible to implement proper HTTP streaming using a Lambda Function URL to bypass API Gateway’s limitations, the WebSocket approach offers more flexibility for messaging and less setup required, in my opinion.</p><p>Our next requirement is session storage, which will be implemented using a DynamoDB table. Keeping a chat session is crucial for maintaining continuity in conversations between the user and the agent. The session serves as the agent’s memory, allowing it to reference past messages. This data will include the user’s chat history and relevant metadata — specific details can be determined later.</p><p>Lastly, the LLM and data retrieval services are outsourced to OpenAI and Pinecone, respectively, so we needn’t worry about that right now, either.</p><figure><img alt="Architectual diagram of AWS cloud infrastructure. It illustrates a lambda function and API gateway serving a client. The lambda function connects to a dynamo table for session management and external AI &amp; data services." src="https://cdn-images-1.medium.com/max/1024/1*PcjTR2aIOm6xfBV46e6Elw.png" /><figcaption>Just a regular API setup.</figcaption></figure><p>Using Terraform to provision the infrastructure is a fairly unremarkable process; however, there are two exceptions to the ‘standard’ one-way WebSocket setup I’d like to highlight:</p><p>Firstly, the API gateway configuration must include a <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/apigatewayv2_route_response">route response</a> to enable two-way communication.</p><pre># define an API gateway for a websocket connection<br>resource &quot;aws_apigatewayv2_api&quot; &quot;default&quot; {<br>    name          = &quot;${var.project_name}-api-gateway-${terraform.workspace}&quot;<br>    protocol_type = &quot;WEBSOCKET&quot;<br>    route_selection_expression = &quot;$request.body.action&quot;<br>}<br><br>resource &quot;aws_apigatewayv2_stage&quot; &quot;default&quot; {<br>    api_id = aws_apigatewayv2_api.default.id<br>    name        = &quot;${var.project_name}-${terraform.workspace}&quot;<br>    auto_deploy = true<br>}<br><br># integrates the gateway with the chat lambda<br>resource &quot;aws_apigatewayv2_integration&quot; &quot;default&quot; {<br>    api_id = aws_apigatewayv2_api.default.id<br>    integration_uri    = module.chat_lambda_function.invoke_arn<br>    integration_type   = &quot;AWS_PROXY&quot;<br>}<br><br><br>resource &quot;aws_apigatewayv2_route&quot; &quot;default&quot; {<br>    api_id = aws_apigatewayv2_api.default.id<br>    target    = &quot;integrations/${aws_apigatewayv2_integration.default.id}&quot;<br>    route_key = &quot;$default&quot;<br>}<br><br># route responses are needed for two-way communication<br># https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/apigatewayv2_route_response#enabling-two-way-communication<br>resource &quot;aws_apigatewayv2_route_response&quot; &quot;default&quot; {<br>    api_id = aws_apigatewayv2_api.default.id<br>    route_id = aws_apigatewayv2_route.default.id<br>    route_response_key = &quot;$default&quot;<br>}</pre><p>Secondly, the IAM policy for the Lambda function must grant permissions for it to invoke the API gateway to post messages to the client.</p><pre>resource &quot;aws_iam_role&quot; &quot;lambda_role&quot; {<br>  name = &quot;${var.project_name}-exec-role-${terraform.workspace}&quot;<br><br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [{<br>        Effect = &quot;Allow&quot;<br>        Principal = {<br>            Service = &quot;lambda.amazonaws.com&quot;<br>        }<br>        Action = &quot;sts:AssumeRole&quot;<br>      }]<br>  })<br>}<br><br>resource &quot;aws_iam_policy&quot; &quot;dynamo_db_access_policy&quot; {<br>  name = &quot;dynamo-policy-${var.project_name}-${terraform.workspace}&quot;<br><br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [{<br>      Effect = &quot;Allow&quot;<br>      Action = [<br>        # Permmissions needed for session management<br>        &quot;dynamodb:Scan&quot;,<br>        &quot;dynamodb:GetRecords&quot;,<br>        &quot;dynamodb:GetItem&quot;,<br>        &quot;dynamodb:PutItem&quot;,<br>        &quot;dynamodb:UpdateItem&quot;,<br>        &quot;dynamodb:DeleteItem&quot;,<br>        &quot;dynamodb:Query&quot;,<br>        # Additional permissions for API Gateway to message clients<br>        &quot;execute-api:ManageConnections&quot;,<br>        &quot;execute-api:Invoke&quot;<br>      ]<br>      Resource = [<br>        aws_dynamodb_table.chat_sessions.arn,<br>        &quot;${aws_dynamodb_table.chat_sessions.arn}/*&quot;,<br>         # Additional API gateway resources required<br>        &quot;arn:aws:execute-api:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:${aws_apigatewayv2_api.default.id}/*/POST/@connections/*&quot;,<br>        &quot;arn:aws:execute-api:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:${aws_apigatewayv2_api.default.id}/*/POST/*/@connections/*&quot;<br>      ]<br>    }]<br>  })<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;lambda_role_attachment&quot; {<br>  role       = aws_iam_role.lambda_role.name<br>  policy_arn = aws_iam_policy.dynamo_db_access_policy.arn<br>}</pre><p>Now that we have an API gateway capable of two-way messaging, let&#39;s handle the rest.</p><p>The dynamo table needs to store a simple JSON object, which can be retrieved using a UUID, and with no special indexes required. We’re also going to take advantage of Dynamo’s TTL feature; this will delete any expired chat sessions automatically, cleaning the table for us. In other words, it&#39;s going to be simple.</p><pre>resource &quot;aws_dynamodb_table&quot; &quot;chat_sessions&quot; {<br>  name           = &quot;${var.project_name}-chat-sessions-${terraform.workspace}&quot;<br>  billing_mode   = &quot;PAY_PER_REQUEST&quot;<br>  hash_key       = &quot;sessionId&quot;<br><br>  attribute {<br>    name = &quot;sessionId&quot;<br>    type = &quot;S&quot;<br>  }<br><br>  ttl {<br>    attribute_name = &quot;expiresAt&quot;<br>    enabled        = true<br>  }<br>}</pre><p>There’s nothing special about the Lambda function except for a longer-than-usual timeout (30 ~ 60s should be sufficient). We inject the API keys for the external services as environment variables at this stage.</p><pre>module &quot;chat_handler_payload&quot; {<br>    source  = &quot;gitlab.com/ben_goodman/lambda-function/aws//modules/code_builder&quot;<br>    version = &quot;4.0.0&quot;<br><br>    working_dir   = &quot;${path.module}/../../chat_lambda&quot;<br>    command       = &quot;npm install &amp;&amp; npm run build&quot;<br>    archive_source_file = &quot;${path.module}/../../chat_lambda/dist/index.js&quot;<br>}<br><br>module &quot;chat_lambda_function&quot; {<br>    # https://gitlab.com/ben_goodman/utility/terraform-modules/lambda-function/-/tree/main?ref_type=heads<br>    source  = &quot;gitlab.com/ben_goodman/lambda-function/aws&quot;<br>    version = &quot;4.0.0&quot;<br><br>    lambda_payload   = module.chat_handler_payload.archive_file<br>    function_name    = &quot;${var.project_name}-chat-${terraform.workspace}&quot;<br>    function_handler = &quot;index.handler&quot;<br>    publish          = true<br>    memory_size      = 2048<br>    role             = aws_iam_role.lambda_role<br>    runtime          = &quot;nodejs20.x&quot;<br>    timeout          = 60<br><br>    environment_variables = {<br>        PINECONE_INDEX_NAME = var.pinecone_index_name<br>        PINECONE_API_KEY    = jsondecode(data.aws_secretsmanager_secret_version.ai_cookbook_secret_version.secret_string)[&quot;PINECONE_API_KEY&quot;]<br>        OPENAI_API_KEY      = jsondecode(data.aws_secretsmanager_secret_version.ai_cookbook_secret_version.secret_string)[&quot;OPENAI_API_KEY&quot;]<br>        SESSION_TABLE_NAME  = aws_dynamodb_table.chat_sessions.name<br>    }<br>}<br><br>resource &quot;aws_lambda_permission&quot; &quot;allow_default_gateway&quot; {<br>    statement_id  = &quot;api-gateway-exec-${var.project_name}-${terraform.workspace}&quot;<br>    action        = &quot;lambda:InvokeFunction&quot;<br>    function_name = module.chat_lambda_function.name<br>    principal     = &quot;apigateway.amazonaws.com&quot;<br>    source_arn    = &quot;${aws_apigatewayv2_api.default.execution_arn}/*/*&quot;<br>}</pre><p>And that&#39;s it. If you want a custom domain name, then optionally set up a Route53 record with API gateway domain mapping.</p><pre>resource &quot;aws_apigatewayv2_domain_name&quot; &quot;ws&quot; {<br>  domain_name = var.domain_name<br>  domain_name_configuration {<br>    certificate_arn = var.certificate_arn<br>    endpoint_type   = &quot;REGIONAL&quot;<br>    security_policy = &quot;TLS_1_2&quot;<br>  }<br>}<br><br>resource &quot;aws_apigatewayv2_api_mapping&quot; &quot;ws&quot; {<br>  api_id      = aws_apigatewayv2_api.default.id<br>  domain_name = aws_apigatewayv2_domain_name.ws.id<br>  stage       = aws_apigatewayv2_stage.default.name<br>}<br><br>resource &quot;aws_route53_record&quot; &quot;ws_alias&quot; {<br>  zone_id = var.route53_zone_id<br>  name    = var.domain_name<br>  type    = &quot;A&quot;<br>  alias {<br>    name                   = aws_apigatewayv2_domain_name.ws.domain_name_configuration[0].target_domain_name<br>    zone_id                = aws_apigatewayv2_domain_name.ws.domain_name_configuration[0].hosted_zone_id<br>    evaluate_target_health = false<br>  }<br>}</pre><p>Depending on whether you&#39;re using a custom domain or not, your output for the websocket URL will be different:</p><pre># either use the API gateway&#39;s URL<br>output &quot;ws_url&quot; {<br>    value = &quot;${aws_apigatewayv2_api.default.api_endpoint}/${aws_apigatewayv2_stage.default.name}&quot;<br>}<br><br># or use a custom one<br>output &quot;ws_url&quot; {<br>    value = aws_route53_record.ws_alias.fqdn<br>}</pre><p>You’re now ready to run terraform and apply the infrastructure.</p><h3>Session Management</h3><p>Before we dive into building the chatbot, let&#39;s define our session management strategy, beginning by sketching out what our chat session will look like.</p><p>The sessionId is the partition key we’ll use to look up a session, and was declared earlier in Terraform as a string. Similarly, expiresAt will be our time-to-live (TTL) attribute. The actual chat data will be stored in an array — not the most efficient means, but it’s simple and sufficient for a small project.</p><p>Our chat session should also resemble the types used by the OpenAI SDK: <a href="https://openai.github.io/openai-agents-js/openai/agents-core/type-aliases/agentinputitem/#_top">AgentInputItem</a> and <a href="https://openai.github.io/openai-agents-js/openai/agents-core/type-aliases/agentoutputitem/#_top">AgentOutputItem</a>. I’ve linked the online API docs for these types just to highlight that the real knowledge is within the source code itself. It&#39;s worth digging into the type structure so we can be better informed on how we should structure our chat events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFLkP0VIhs8RvoC6hEJBCQ.png" /><figcaption>Using an IDE to easily browse the exported types.</figcaption></figure><p>After some light digging, the gist of our chat event will be fields for role, type, and content. I added a timestamp because I thought it would be useful later (it wasn’t).</p><pre>type SessionItem = {<br>    sessionId: string;<br>    expiresAt: number;<br>    chatHistory: {<br>        role: &quot;system&quot; | &quot;user&quot;;<br>        type: &quot;message&quot;;<br>        content: string;<br>        timestamp: number;<br>    }[];<br>}</pre><p>I’m using <a href="https://www.dynamodbtoolbox.com/">DynamoDB Toolbox</a> because it’s typesafe and easier to use IMO than the Dynamo SDK. I establish a schema for the chat session, then an Entity, which will be called on later when making queries.</p><pre>import { list, map, item, string, number, Entity, ValidValue } from &#39;dynamodb-toolbox&#39;<br>import SessionsTable from &#39;./SessionsTable&#39;<br><br>const historyObject = map({<br>  role: string().enum(&#39;system&#39;, &#39;user&#39;).required(),<br>  type: string().enum(&#39;message&#39;).required(),<br>  content: string().required(),<br>  timestamp: number().required(),<br>})<br><br>const schema = item({<br>  sessionId: string().key(),<br>  expiresAt: number().required(),<br>  chatHistory: list(historyObject).required(),<br>})<br><br>export type HistoryEvent = ValidValue&lt;typeof historyObject&gt;<br><br>export type SessionItem = ValidValue&lt;typeof schema&gt;<br><br>export default new Entity({<br>  name: &#39;ChatSession&#39;,<br>  schema,<br>  table: SessionsTable,<br>})</pre><p>Next, we need functions to create, update, retrieve, and delete sessions. When updating the chat session with new messages, it’s important to also update the expiresAt value, which will be used to determine if the session goes stale. It’s here that we reset the session’s TTL to 1 day from now.</p><pre>import { $append, DeleteItemCommand, GetItemCommand, PutItemCommand, UpdateItemCommand } from &#39;dynamodb-toolbox&#39;<br>import SessionEntity, { HistoryEvent, SessionItem } from &#39;../database/SessionEntity&#39;<br><br>/**<br> * Pushes a new message to the chat history.<br> * @param sessionId - The ID of the session to update.<br> * @param message - The message to add to the chat history.<br> */<br>export const pushChatHistory = async (<br>  sessionId: string,<br>  message: {<br>    role: &#39;system&#39; | &#39;user&#39;<br>    content: string<br>  }<br>): Promise&lt;void&gt; =&gt; {<br>  const historyEvent: HistoryEvent = {<br>    ...message,<br>    timestamp: Date.now(),<br>    type: &#39;message&#39;,<br>  }<br><br>  console.log(&#39;Pushing chat history:&#39;, sessionId, historyEvent)<br><br>  const resp = await SessionEntity<br>    .build(UpdateItemCommand)<br>    .item({<br>      sessionId,<br>      chatHistory: $append([ historyEvent ]),<br>      expiresAt: Math.floor(Date.now() / 1000) + 60 * 60 * 24, // Reset TTL to 1 day<br>    })<br>    .send()<br>    .catch((error) =&gt; {<br>      console.error(&#39;Error pushing chat history:&#39;, error)<br>      throw new Error(`Failed to push chat history: ${error.message}`)<br>    })<br><br>  if (!resp.$metadata.httpStatusCode || resp.$metadata.httpStatusCode !== 200) {<br>    throw new Error(`Failed to push chat history: ${resp.$metadata.httpStatusCode}`)<br>  }<br>}</pre><p>The other database operations are much simpler. Here, we retrieve a chat session, or create one if it doesn’t exist.</p><pre>/**<br> * Retrieves a chat session by its ID or creates one<br> * if the session is not found.<br> * @param sessionId - The ID of the session to retrieve.<br> * @returns The retrieved session item.<br> */<br>export const getChatSession = async (sessionId: string): Promise&lt;SessionItem&gt; =&gt; {<br>  const resp = await SessionEntity<br>    .build(GetItemCommand)<br>    .key({ sessionId })<br>    .send()<br><br>  if (!resp.Item) {<br>    return createSession(sessionId)<br>  }<br><br>  return resp.Item<br>}</pre><p>In my first attempt, I delegated session management to the chat agent via tools to retrieve and update the session as required. While this approach technically works, I found it to be unreliable at times, and the added latency from the tool calls started to add up. This time round, I’ll reconstruct the conversation into a chat thread and pass it off to the agent’s runner later.</p><pre>import { AgentInputItem, AgentOutputItem } from &#39;@openai/agents&#39;<br><br>// get the chat history array<br>const { chatHistory = [] } = await getChatSession(sessionId)<br><br>// update the chat history with the user&#39;s message<br>await pushChatHistory(<br>  sessionId,<br>  {<br>   role: &#39;user&#39;,<br>   content: message,<br> }<br>)<br><br>// combine the history with the user&#39;s message <br>const thread: (AgentInputItem|AgentOutputItem)[] = [<br>  ...chatHistory,<br>  {<br>    role: &#39;user&#39;,<br>    type: &#39;message&#39;,<br>    content: message,<br>  }<br>]<br><br>// thread is then passed to the agent runner.</pre><h3>Creating a Chat Agent</h3><p>Now that we have an infrastructure sufficient to stream and store messages, it’s time to generate them using an agent. Agents are autonomous software entities that perform tasks. An AI agent uses an LLM to understand input, reason through possible actions, and interact with tools or external systems to complete its goals.</p><p>Our task is to parse natural language input and potentially use it to query recipes, depending on the input. Then, we must convert the JSON array of recipes into something human-readable that answers the input. Also, the ‘input’ is a chat thread. It’s a lot to take in, yet the LLM chews through it all.</p><p>I’ll begin with the system prompt, which will define the agent’s behavior, tone, and goals. The key points of it are:</p><ul><li>The agent must limit its responses to the recipes it has access to.</li><li>The agent should format its message using Markdown.</li></ul><pre># Gastro Genie Agent Prompt<br><br>## About<br><br>  You are the Gastro Genie which assists users in finding recipes from a database.<br>  You have access to over 70,000 recipes.<br>  Do not provide information outside of the recipes database or this prompt.<br>  You can only respond with information related to the recipes you retrieve.<br>  You can answer questions about cooking, ingredients, and meal planning.<br>  You can also provide cooking tips and suggestions based on the user&#39;s query.<br>  You were created by Benjamin Goodman (ben.website), a software engineer and AI enthusiast.<br>  Your source code is available on GitLab at https://gitlab.com/ben_goodman/apps/ai-cookbook/.<br><br>## Tools<br><br>  You can use tools to interact with the database and retrieve recipes based on user queries.<br>  You have a tool called &#39;getRecipes&#39; that allows you to search for recipes.<br>  You must use this tool to find recipes that match the user&#39;s query.<br><br>## Response<br><br>Respond to the user with a Markdown formatted response.<br>  Your response should include:<br>  - A summary of the recipes found<br>  - A list of recipe titles with links to their details<br>  - Any relevant information about the recipes<br>  <br>  If no recipes are found, inform the user that no results were found for their query.</pre><p>Now it’s time to define the agent itself. We want it to know the user’s chat session ID and, optionally, how many recipes to fetch per query (topK). These values will be provided when the agent is run and stored using a <a href="https://openai.github.io/openai-agents-js/guides/context/#local-context">local context</a>, which is passed to tool calls and used as needed.</p><pre>import OpenAI from &#39;openai&#39;<br>import { Agent, ModelSettings, setDefaultOpenAIClient } from &#39;@openai/agents&#39;<br>import { getRecipes } from &#39;./tools/getRecipes&#39;<br>import { deleteChatSession } from &#39;./tools/deleteChatSession&#39;<br><br>// The local context takes input at runtime and<br>// is passed to tool calls.<br>export type CookbookAgentContext = {<br>  // required when deleting chat session<br>  sessionId: string,<br>  // number of recipes to return from queries<br>  topK: number,<br>}<br><br>const instructions = `# Gastro Genie Agent Prompt...`<br><br>export default class CookbookAgent extends Agent&lt;CookbookAgentContext, &#39;text&#39;&gt; {<br>  constructor(modelSettings?: ModelSettings) {<br>    super({<br>      name: &#39;Cookbook Agent&#39;,<br>      instructions,<br>      tools: [<br>        getRecipes,<br>        deleteChatSession,<br>      ],<br>      modelSettings,<br>      outputType: &#39;text&#39;<br>    })<br><br>    const client = new OpenAI({<br>      apiKey: process.env.OPENAI_API_KEY!,<br>    })<br><br>    setDefaultOpenAIClient(client)<br>  }<br>}</pre><p>Next, we’ll provide the agent with tools to help it search for recipes and reset the chat session as needed. These tools expand the agent&#39;s capabilities by linking it to external systems, such as databases.</p><p>We’ll start with the recipe search tool by defining a function that queries the database. It takes a natural language query like “tuna sandwich,” converts it into a vector, and retrieves the top K closest matching recipes.</p><pre>import { Pinecone } from &#39;@pinecone-database/pinecone&#39;<br>// https://gitlab.com/ben_goodman/apps/ai-cookbook/-/blob/8746e6f98a75fb936bf19ec30ee7c299d4672126/chat_lambda/src/util/embedText.ts<br>import { embedText } from &#39;../util/embedText&#39;<br><br>/**<br> * Queries the Pinecone recipe database for matching recipes.<br> * @param query - The query string to search for recipes.<br> * @param opts - Optional parameters for the query.<br> * @returns An array of matching recipes.<br> */<br>export const queryRecipe = async (query: string, opts?: { topK?: number }) =&gt; {<br>  const pinecone = new Pinecone({<br>    apiKey: process.env.PINECONE_API_KEY!,<br>  })<br><br>  const embedding = await embedText(query)<br><br>  const index = pinecone.Index(process.env.PINECONE_INDEX_NAME!)<br><br>  const response = await index.query({<br>    vector: embedding,<br>    // the max number of recipies returned<br>    topK: opts?.topK ?? 5,<br>    includeValues: true,<br>    includeMetadata: true,<br>  })<br><br>  return response.matches.map((match) =&gt; ({<br>    id: match.id,<br>    score: match.score,<br>    metadata: match.metadata,<br>  }))<br>}</pre><p>The function returns an array of recipes that match the input query. The LLM will parse this object later and use the information within to generate its response.</p><pre>[<br>  {<br>    id: &#39;Tuna Egg Sandwich&#39;,<br>    score: 0.591650963,<br>    metadata: {<br>      slug: &#39;Tuna-Egg-Sandwich&#39;,<br>      text: &#39;&lt;Recipe&gt;\n&#39; +<br>        &#39;&lt;Title&gt;Tuna Egg Sandwich&lt;/Title&gt;\n&#39; +<br>        &#39;&lt;Ingredients&gt;1 (5 ounce) can tuna, drained, 3 hard-cooked eggs, peeled and chopped, 1 cup chopped celery, 1 tablespoon mayonnaise, salt and pepper to taste, 4 slices whole wheat bread&lt;/Ingredients&gt;\n&#39; +<br>        &#39;&lt;Directions&gt;In a medium bowl, stir together the tuna, eggs, celery and mayonnaise. Season with salt and pepper to taste. Place half of the mixture onto 1 slice of bread and the other half on another slice of bread. Top with remaining slices of bread. Serve.&lt;/Directions&gt;\n&#39; +<br>        &#39;&lt;Source&gt;allrecipes.com&lt;/Source&gt;\n&#39; +<br>        &#39;&lt;URL&gt;http://allrecipes.com/recipe/83569/tuna-egg-sandwich/&lt;/URL&gt;\n&#39; +<br>        &#39;&lt;/Recipe&gt;&#39;,<br>      title: &#39;Tuna Egg Sandwich&#39;<br>    }<br>  },<br>  ...<br>]</pre><p>Now we write the agent’s tool. We define input parameters for the query, and extract topK from the local context. Finally, we stringify the recipe&#39;s response before it’s passed to the LLM.</p><pre>import { RunContext, tool } from &#39;@openai/agents&#39;<br>import { z } from &#39;zod&#39;<br>import { CookbookAgentContext } from &#39;..&#39;<br>import { queryRecipe } from &#39;../../repo/queryRecipe&#39;<br><br>export const getRecipes = tool({<br>  name: &#39;getRecipes&#39;,<br>  description: &#39;Retrieve recipes based on a search query&#39;,<br>  parameters: z.object({<br>    query: z.string().describe(&#39;The search query for recipes&#39;)<br>  }),<br>  async execute({ query }, context?: RunContext&lt;CookbookAgentContext&gt;) {<br>    const topK = context?.context?.topK<br><br>    if (!query) {<br>      return &#39;Query is required to search for recipes.&#39;<br>    }<br><br>    if (!topK || typeof topK !== &#39;number&#39;) {<br>      return &#39;Invalid topK value. It should be a number.&#39;<br>    }<br><br>    const recipes = await queryRecipe(query, { topK })<br><br>    if (recipes.length === 0) {<br>      return &#39;No recipes found for your query.&#39;<br>    }<br><br>    return JSON.stringify(recipes)<br>  }<br>})</pre><p>Clearing the chat session can be helpful if the agent is making irrelevant references to past recipes. Also, allowing the user to ask the agent to “start over”, etc., makes for good UX.</p><pre>import { RunContext, tool } from &#39;@openai/agents&#39;<br>import { z } from &#39;zod&#39;<br>import { CookbookAgentContext } from &#39;..&#39;<br>// https://gitlab.com/ben_goodman/apps/ai-cookbook/-/blob/aaed9367450c6cdaf1787dc774e79f1eb3b5f2dc/chat_lambda/src/repo/session.ts<br>import { deleteSession } from &#39;../../repo/session&#39;<br><br>export const deleteChatSession = tool({<br>  name: &#39;deleteChatSession&#39;,<br>  description: &#39;Delete an existing chat session&#39;,<br>  parameters: z.object({}),<br>  async execute(_, runContext?: RunContext&lt;CookbookAgentContext&gt;): Promise&lt;string&gt; {<br>    const sessionId = runContext?.context.sessionId<br><br>    if (!sessionId) {<br>      return &#39;No session ID provided from the context. Cannot delete chat session.&#39;<br>    }<br><br>    await deleteSession(sessionId)<br><br>    return `Session ${sessionId} deleted successfully.`<br>  }<br>})</pre><p>We’re now ready for the next step: running the agent.</p><h3>Running the Agent</h3><p>For the agent to perform any action (such as answering a question), it must be passed into a <a href="https://openai.github.io/openai-agents-js/guides/running-agents/">runner</a> class or utility. The runner is responsible for managing the agent’s execution flow — feeding it inputs, handling tool calls, maintaining context, and streaming the output.</p><p>We’ll run the CookbookAgent we set up earlier using the user&#39;s message and their chat history as input. We&#39;ll also provide the agent&#39;s context and, if needed, tweak model settings like temperature. All of this should be wrapped in a helper function that we can call later when handling incoming WebSocket messages.</p><pre>import { AgentInputItem, AgentOutputItem, run } from &#39;@openai/agents&#39;<br>import { getChatSession, pushChatHistory } from &#39;../repo/session&#39;<br>import CookbookAgent from &#39;../agent&#39;<br><br>const DEFAULT_SETTINGS = {<br>  temperature: 0.7,<br>  topK: 5,<br>  topP: 0.9,<br>}<br><br>/**<br> * Invokes the CookbookAgent with the user&#39;s<br> * input and chat history for the session ID.<br> *<br> * @param message - The user message to send to the agent.<br> * @param sessionId - The session ID for the chat session.<br> * @param opts - Optional settings for the agent invocation.<br> * @param opts.topK - The number of recipes to query for.<br> * @param opts.temperature - The temperature setting for the agent.<br> * @param opts.topP - The top P setting for the agent.<br> */<br>export const invokeChatAgent = async (<br>  message: string,<br>  sessionId: string,<br>  opts: {<br>    temperature?: number<br>    topK?: number<br>    topP?: number<br>  }<br>) =&gt; {<br>  console.log(&#39;Invoking chat agent:&#39;, message, sessionId, opts)<br><br>  const { chatHistory = [] } = await getChatSession(sessionId)<br><br>  await pushChatHistory(<br>    sessionId,<br>    {<br>      role: &#39;user&#39;,<br>      content: message,<br>    }<br>  )<br><br>  const thread: (AgentInputItem|AgentOutputItem)[] = [<br>    ...chatHistory,<br>    {<br>      role: &#39;user&#39;,<br>      type: &#39;message&#39;,<br>      content: message,<br>    }<br>  ]<br><br>  const agent = new CookbookAgent({<br>    temperature: opts?.temperature ?? DEFAULT_SETTINGS.temperature,<br>    topP: opts?.topP ?? DEFAULT_SETTINGS.topP,<br>  })<br><br>  return run(<br>    agent,<br>    thread,<br>    {<br>      stream: true,<br>      context: {<br>        sessionId,<br>        topK: opts?.topK ?? DEFAULT_SETTINGS.topK<br>      },<br>    }<br>  )<br>}</pre><p>Since we set stream: true in the runner’s options, it will return a <a href="https://openai.github.io/openai-agents-js/openai/agents/classes/streamedrunresult/">StreamedRunResult</a> object. We’ll use that to generate a Node.js ReadableStream which we can iterate over and handle each event from the agent in turn. For example,</p><pre>const resp = invokeChatAgent(...)<br><br>const stream: ReadableStream&lt;RunStreamEvent&gt; = resp.toStream()<br>  <br>for await (const event of stream) {<br>   // handle run stream event...<br>}</pre><p>It&#39;s worth mentioning at this point that there is a <a href="https://openai.github.io/openai-agents-js/guides/streaming/#get-the-text-output">simpler method</a> that doesn’t involve handling events directly, but I think this approach is much more informative.</p><p>There are two run stream events we’re primarily interested in:</p><p>output_text_delta — contains the chunk of message that we want to stream back to the client.</p><pre>{<br>  data: {<br>    type: &#39;output_text_delta&#39;,<br>    delta: &#39;test &#39;, // &lt;-- this is the content we want to stream<br>    providerData: {<br>      type: &#39;response.output_text.delta&#39;,<br>      sequence_number: 101,<br>      item_id: &#39;msg_688fa5078...&#39;,<br>      output_index: 0,<br>      content_index: 0,<br>      logprobs: []<br>    }<br>  },<br>  type: &#39;raw_model_stream_event&#39;<br>}</pre><p>message_output_created — signifies the completion of the message. This is when we want to update the chat history and inform the UI that the message is complete.</p><pre>{<br>  name: &quot;message_output_created&quot;,<br>  item: {<br>    type: &quot;message_output_item&quot;,<br>    rawItem: {<br>      providerData: {},<br>      id: &quot;msg_688fa5078...&quot;,<br>      type: &quot;message&quot;,<br>      role: &quot;assistant&quot;,<br>      status: &quot;completed&quot;,<br>      content: [<br>        {<br>          type: &quot;output_text&quot;,<br>          text: &quot;It looks like you entered \&quot;test.\&quot; ...&quot;<br>        }<br>      ]<br>    },<br>    agent: {<br>      name: &quot;Cookbook Agent&quot;<br>    }<br>  },<br>  type: &quot;run_item_stream_event&quot;<br>}</pre><p>We can also take the opportunity to dive deeper into low-level model events. Here’s the event for a tool call:</p><pre>{<br>  providerData: {<br>    id: &#39;fc_688e4a8...&#39;,<br>    type: &#39;function_call&#39;<br>  },<br>  id: &#39;fc_688e4a8e....&#39;,<br>  type: &#39;function_call&#39;,<br>  callId: &#39;call_nfhg8DrdoUFB0M7F3TpCY7kS&#39;,<br>  name: &#39;getRecipes&#39;,<br>  status: &#39;completed&#39;,<br>  arguments: &#39;{&quot;query&quot;:&quot;beef stew with vegetables and red wine&quot;}&#39;<br>}</pre><p>And the event for a tool result:</p><pre>{<br>  type: &#39;function_call_result&#39;,<br>  name: &#39;getRecipes&#39;,<br>  callId: &#39;call_nfhg8DrdoUFB0M7F3TpCY7kS&#39;,<br>  status: &#39;completed&#39;,<br>  output: {<br>    type: &#39;text&#39;,<br>    text: &#39;[{recipe1}, {recipe2}, ...]&#39;<br>  }<br>}</pre><p>By capturing these events, we can provide a loading status back to the client. I didn’t find it as helpful for this case, but for more complex agents with more tools and a longer running time, it could easily be another UX requirement.</p><p>As before, we want to wrap this step into a function to use when we handle incoming and outgoing socket messages — the specifics of which we’ll cover in the next step. For now, we create a function that exposes the events of interest to their respective callback: onOutputTextDelta and onMessageOutputCreated.</p><p>If you want to handle tool calls or other such events, then now’s the time to include them too. For brevity, I’ve excluded all but the essentials for this project, but you can get the complete code <a href="https://gitlab.com/ben_goodman/apps/ai-cookbook/-/blob/147293f4fd12c7d78b859ed8e4e1adfff9687c61/chat_lambda/src/util/streamResponse.ts">here</a>.</p><pre>import { StreamedRunResult } from &#39;@openai/agents&#39;<br>import CookbookAgent, { CookbookAgentContext } from &#39;../agent&#39;<br><br><br>/**<br> * Streams the response from the CookbookAgent.<br> * This function handles the streamed output from the agent and processes it<br> * through the provided handlers.<br> * @param response - The streamed run result from the agent.<br> * This should be a StreamedRunResult&lt;CookbookAgentContext, CookbookAgent&gt;<br> * @param handlers - The handlers to process the streamed output.<br> */<br>export const streamResponse = async (<br>  response: StreamedRunResult&lt;CookbookAgentContext, CookbookAgent | any&gt;,<br>  handlers: {<br>    onOutputTextDelta: (delta: string) =&gt; Promise&lt;void&gt;,<br>    onMessageOutputCreated: (finalOutput: string) =&gt; Promise&lt;void&gt;,<br>  }<br>): Promise&lt;void&gt; =&gt; {<br>  <br>  const stream = response.toStream()<br>  <br>  for await (const event of stream) {<br><br>    // stream the output text deltas<br>    // these events are emitted as the model generates it&#39;s output<br>    if (event.type === &#39;raw_model_stream_event&#39;) {<br>      const data = event.data<br>      if (data.type === &#39;output_text_delta&#39;) {<br>        const delta = data.delta<br>        if (delta) {<br>          await handlers.onOutputTextDelta(delta)<br>          continue<br>        }<br>      }<br>    }<br><br>    // handle the event when a message output is created<br>    // this is when the model has finished generating it&#39;s output<br>    if (event.type === &#39;run_item_stream_event&#39;) {<br>      if (event.name === &#39;message_output_created&#39;) {<br>        const message = event.item.toJSON().rawItem<br>        if (!message) {<br>          throw new Error(&#39;No message content found in event:&#39; + JSON.stringify(event))<br>        }<br>        if (message.type === &#39;message&#39; &amp;&amp; message.role === &#39;assistant&#39;) {<br>          const firstContent = message.content[0]<br>          if (firstContent.type === &#39;output_text&#39; &amp;&amp; &#39;text&#39; in firstContent) {<br>            if (!response.finalOutput) {<br>              throw new Error(&#39;No final output found in response&#39;)<br>            }<br>            await handlers.onMessageOutputCreated(response.finalOutput as string)<br>            break<br>          }<br>        }<br>        continue<br>      }<br>    }<br>  } <br>}</pre><p>We now have a streamable agent, so we’re ready to address the final task: integrate the streamable agent with our WebSocket.</p><h3>Handling API Gateway Events</h3><p>Here, we accept incoming client messages as API gateway events and then pass messages back to the client as we receive the agent’s stream events. But first, we solve the final problem in two-way streaming: how to actually send messages back to the client.</p><p>Sending a message from our WebSocket connection requires invoking the API gateway using its SDK so we write a helper function to abstract the <a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/apigatewaymanagementapi/command/PostToConnectionCommand/">postToConnection</a> call, simplifying how we send data to connected clients. It’s important to note that your code will be slightly different depending on whether you used a custom domain or not back in the infrastructure setup stage.</p><p>If you are using the default URL provided by the API gateway, then include the gateway stage with the endpoint:</p><pre>const apigwManagementApi = new ApiGatewayManagementApi({<br>  endpoint: `https://${event.requestContext.domainName}/${event.requestContext.stage}`,<br>})</pre><p>Else, for custom domains, simply provide the domain name:</p><pre>const apigwManagementApi = new ApiGatewayManagementApi({<br>  endpoint: `https://${event.requestContext.domainName}`,<br>})</pre><p>Now, we define the MessageResponse that will be received by the client and make it our argument for the post message function.</p><pre>import { ApiGatewayManagementApi } from &#39;@aws-sdk/client-apigatewaymanagementapi&#39;<br>import { APIGatewayProxyEvent } from &#39;aws-lambda&#39;<br><br>export interface MessageResponse {<br>  status: &#39;inProgress&#39; | &#39;complete&#39;<br>  content: string<br>  role: &#39;user&#39; | &#39;system&#39;<br>}<br><br>/**<br> * Posts a message to the connected client.<br> * @param event - The API Gateway event containing the connection ID.<br> * @returns A function that sends a message to the client.<br> */<br>export const postToClient = (event: APIGatewayProxyEvent) =&gt; {<br>  const connectionId = event.requestContext.connectionId<br>  const apigwManagementApi = new ApiGatewayManagementApi({<br>    // If using a custom domain, do NOT include the stage in the endpoint.<br>    // endpoint: `https://${event.requestContext.domainName}/${event.requestContext.stage}`,<br>    endpoint: `https://${event.requestContext.domainName}`,<br>  })<br><br>  return async (message: MessageResponse) =&gt; {   <br>    await apigwManagementApi.postToConnection({<br>      ConnectionId: connectionId,<br>      Data: Buffer.from(JSON.stringify(message)),<br>    })<br>  }<br>}</pre><p>What about messages <em>from</em> the client? At a minimum, they should include some query and the session ID. Optionally, they can include model parameters.</p><figure><img alt="A dialog box containing sliders for AI model settings: temperature, topK and topP." src="https://cdn-images-1.medium.com/max/1024/1*fTO9pBEdQCujLUd5yg3S_A.png" /><figcaption>I love adding options.</figcaption></figure><p>As code, the incoming user message would have the following structure:</p><pre>interface UserMessage {<br>  input: string<br>  sessionId: string<br>  temperature?: number<br>  topK?: number<br>  topP?: number<br>}</pre><p>Since user messages will arrive as strings, we need to parse them into objects like the one above. As we’re already using <a href="https://zod.dev/?v=1.0.24">zod</a> to create tool schemas, let&#39;s also use it to parse our input safely.</p><pre>// this is the format for messages sent by the client<br>const MessageSchema = z.object({<br>  input: z.string().min(1, &#39;Input is required&#39;),<br>  sessionId: z.string().min(1, &#39;Session ID is missing&#39;),<br>  temperature: z.number().optional(),<br>  topK: z.number().optional(),<br>  topP: z.number().optional(),<br>})</pre><p>All that&#39;s left is to invoke the chat agent with the parsed input and stream the result.</p><pre>import { APIGatewayProxyEvent, APIGatewayProxyResult } from &#39;aws-lambda&#39;<br>import z from &#39;zod&#39;<br>import { postToClient } from &#39;../util/postToClient&#39;<br>import { invokeChatAgent } from &#39;../services/invokeChatAgent&#39;<br>import { pushChatHistory } from &#39;../repo/session&#39;<br>import { streamResponse } from &#39;../util/streamResponse&#39;<br><br><br>export const handleMessage = async (event: APIGatewayProxyEvent) =&gt; {<br>  const postMessage = postToClient(event)<br><br>  // the body contains the client&#39;s message<br>  const { body } = event<br><br>  if (!body) {<br>    return {<br>      statusCode: 400,<br>      body: &#39;Body is missing&#39;<br>    }<br>  }<br><br>  // pasre and validate the message<br>  const parsedBody = MessageSchema.safeParse(JSON.parse(body))<br><br>  if (!parsedBody.success) {<br>    return {<br>      statusCode: 400,<br>      body: JSON.stringify(parsedBody.error),<br>    }<br>  }<br><br>  const { input, sessionId, ...opts } = parsedBody.data<br><br>  // run the chat agent with the user&#39;s input and sesison data<br>  const resp = await invokeChatAgent(input, sessionId, opts)<br><br>  // handle the agent&#39;s streaming events<br>  await streamResponse(<br>    resp,<br>    {<br>      // callback for streaming in progress chunks<br>      onOutputTextDelta: async (delta: string) =&gt; {<br>        await postMessage({<br>          role: &#39;system&#39;,<br>          status: &#39;inProgress&#39;,<br>          content: delta,<br>        })<br>      },<br>      // callback for handling message completion<br>      onMessageOutputCreated: async (finalOutput: string) =&gt; {<br>        await postMessage({<br>          role: &#39;system&#39;,<br>          status: &#39;complete&#39;,<br>          content: finalOutput,<br>        })<br>        await pushChatHistory(<br>          sessionId,<br>          {<br>            role: &#39;system&#39;,<br>            content: finalOutput,<br>          }<br>        )<br>      },<br>    })<br><br>  return {<br>    statusCode: 200,<br>    body: &#39;&#39;<br>  }<br>}</pre><p>And that completes the server! Deploy and test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVUL0_tMxoDsLMZxGOc6rA.png" /><figcaption>The socket streams message chunks when in progress, then finalizes by sending the the complete message with an updated status.</figcaption></figure><h3>Client React Hook</h3><p>Now it&#39;s time to showcase your amazing AI streaming service by creating a GUI that displays the chat and accepts user input.</p><p>Let&#39;s consider how the UI will work:</p><ol><li>User sends a message.</li><li>App receives incoming message chunks. Adds them to a temporary buffer.</li><li>App displays the buffer’s content as it updates.</li><li>When the end of the message is received, the completed message is added to the client’s copy of the chat history.</li><li>The app displays the updated chat history with the latest message.</li></ol><figure><img alt="A sequnce diagram illustarting the react app’s behaviour." src="https://cdn-images-1.medium.com/max/1024/1*R4BMIXFfpttPCrxyCvmTRg.png" /></figure><p>We’ll start by writing a custom hook that will send a message to the server and manage its responses in a way that lets us easily render them in the UI. That means storing the message history in an array so it can be mapped by whatever React component we make to render the chat thread. We’ll also need to consider rendering the message chunks as they’re delivered, so we’ll need a temporary buffer. Lastly, a loading flag to disable the UI’s input while messages are streaming in.</p><pre>export interface MessageHistoryItem {<br>  content: string<br>  role: &#39;user&#39; | &#39;system&#39;<br>}<br><br>export const useRecipes = (sessionId: string) =&gt; {<br><br>  const [messageHistory, setMessageHistory] = useState&lt;MessageHistoryItem[]&gt;([])<br>  const [buffer, setBuffer] = useState(&#39;&#39;)<br>  const [isLoading, setIsLoading] = useState(false)<br>  <br>  ...<br><br>  return {<br>    messageHistory,<br>    buffer,<br>    isLoading<br>  }<br>}</pre><p>We should also consider how to initialize the message history from the browser’s local storage. I’ve opted to use a side effect that runs when the component is mounted.</p><pre>useEffect(() =&gt; {<br>    const storedHistory = JSON.parse(window.localStorage.getItem(LS_KEY_CHAT_HISTORY) ?? &#39;[]&#39;)<br>    if (storedHistory) {<br>      setMessageHistory(storedHistory)<br>    }<br>  }, [])</pre><p>The actual work of interfacing with a WebSocket will be handled by the npm module <a href="https://www.npmjs.com/package/react-use-websocket">react-use-websocket</a> . It&#39;s very simple to use:</p><pre>const { sendMessage, lastMessage, readyState } = useWebSocket(SOCKET_URL)</pre><ul><li>sendMessage — function to send a message to the WebSocket server.</li><li>lastMessage — the state of the last message.</li><li>readyState — the state of the WebSocket connection.</li></ul><p>For handling incoming messages, we need to implement a side effect for the lastMessage state to update the buffer and message history. Recall that the message is a stringified JSON object, so first we parse it, then add its content to the buffer. If the message is complete, we update the message history and update the loading state.</p><pre>useEffect(() =&gt; {<br>  if (lastMessage &amp;&amp; lastMessage.data) {<br>   // recall from earlier:   <br>   // interface MessageResponse {<br>   //   status: &#39;inProgress&#39; | &#39;complete&#39;<br>   //   content: string<br>   //   role: &#39;user&#39; | &#39;system&#39;<br>   // }<br>    const parsedMessage = JSON.parse(lastMessage.data) as MessageResponse<br>    <br>    if (parsedMessage.role === &#39;system&#39; &amp;&amp; parsedMessage.status === &#39;complete&#39;) {<br>      window.localStorage.setItem(LS_KEY_CHAT_HISTORY, JSON.stringify([...messageHistory, { content: parsedMessage.content, role: &#39;system&#39; }]))<br>      setBuffer(&#39;&#39;)<br>      setMessageHistory(prev =&gt; [...prev, { content: parsedMessage.content, role: &#39;system&#39; }])<br>      setIsLoading(false)<br>      return<br>    }<br><br>    setBuffer(prev =&gt; prev + parsedMessage.content)<br>  }<br>}, [lastMessage])</pre><p>The last element of our hook is the function to send user queries as WebSocket messages.</p><pre>export interface ChatOptions {<br>  temperature?: number<br>  topK?: number<br>  topP?: number<br>}<br><br>const send = (message: string, opts: ChatOptions = {}) =&gt; {<br>    if (readyState === WebSocket.OPEN &amp;&amp; !isLoading) {<br>      setIsLoading(true)<br>      setBuffer(&#39;&#39;)<br>      setMessageHistory(prev =&gt; [...prev, { content: message, role: &#39;user&#39; }])<br>      window.localStorage.setItem(LS_KEY_CHAT_HISTORY, JSON.stringify([...messageHistory, { content: message, role: &#39;user&#39; }]))<br>      sendMessage(JSON.stringify({<br>        input: message,<br>        sessionId,<br>        ...opts<br>      }))<br>    }<br>  }</pre><p>We’re now ready to assemble the final hook.</p><pre>import { useEffect, useState } from &#39;react&#39;<br>import useWebSocket from &#39;react-use-websocket&#39;<br>import { LS_KEY_CHAT_HISTORY, SOCKET_URL } from &#39;../constants&#39;<br>import { ChatOptions } from &#39;./useChatOptions&#39;<br><br>// the messages recieved by the server<br>export interface MessageResponse {<br>  status: &#39;inProgress&#39; | &#39;complete&#39;<br>  content: string<br>  role: &#39;user&#39; | &#39;system&#39;<br>}<br><br>// used for application state<br>export interface MessageHistoryItem {<br>  content: string<br>  role: &#39;user&#39; | &#39;system&#39;<br>}<br><br>export const useRecipes = (sessionId: string) =&gt; {<br>  const { sendMessage, lastMessage, readyState } = useWebSocket(SOCKET_URL)<br>  const [messageHistory, setMessageHistory] = useState&lt;MessageHistoryItem[]&gt;([])<br>  const [buffer, setBuffer] = useState&lt;string&gt;(&#39;&#39;)<br>  const [isLoading, setIsLoading] = useState(false)<br><br>  useEffect(() =&gt; {<br>    const storedHistory = JSON.parse(window.localStorage.getItem(LS_KEY_CHAT_HISTORY) ?? &#39;[]&#39;)<br>    if (storedHistory) {<br>      setMessageHistory(storedHistory)<br>    }<br>  }, [])<br><br>  useEffect(() =&gt; {<br>    if (lastMessage &amp;&amp; lastMessage.data) {<br>      const parsedMessage = JSON.parse(lastMessage.data) as MessageResponse<br>      <br>      if (parsedMessage.role === &#39;system&#39; &amp;&amp; parsedMessage.status === &#39;complete&#39;) {<br>        window.localStorage.setItem(LS_KEY_CHAT_HISTORY, JSON.stringify([...messageHistory, { content: parsedMessage.content, role: &#39;system&#39; }]))<br>        setBuffer(&#39;&#39;)<br>        setMessageHistory(prev =&gt; [...prev, { content: parsedMessage.content, role: &#39;system&#39; }])<br>        setIsLoading(false)<br>        return<br>      }<br><br>      setBuffer(prev =&gt; prev + parsedMessage.content)<br>    }<br>  }, [lastMessage])<br><br>  const send = (message: string, opts: ChatOptions = {}) =&gt; {<br>    if (readyState === WebSocket.OPEN &amp;&amp; !isLoading) {<br>      setIsLoading(true)<br>      setBuffer(&#39;&#39;)<br>      setMessageHistory(prev =&gt; [...prev, { content: message, role: &#39;user&#39; }])<br>      window.localStorage.setItem(LS_KEY_CHAT_HISTORY, JSON.stringify([...messageHistory, { content: message, role: &#39;user&#39; }]))<br>      sendMessage(JSON.stringify({<br>        input: message,<br>        sessionId,<br>        ...opts<br>      }))<br>    }<br>  }<br><br>  return {<br>    send,<br>    readyState,<br>    messageHistory,<br>    isLoading,<br>    buffer,<br>  }<br>}</pre><h3>Rendering Chat Messages</h3><p>We’ll need to create a message component to display both user and system messages (forming the chat history), as well as the buffer’s content while receiving message chunks. We’ll also need to handle markdown rendering — for which we’ll use the<a href="https://www.npmjs.com/package/markdown-to-jsx">markdown-to-jsx</a> npm module. I like to customize my Markdown rendering, and I’ve found this module to offer the easiest solution.</p><p>What we’ll end up with is a stack of MessageItem components, forming the combined chat history and incoming message buffer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*uEwZpO-3j8QrafwxZGoduQ.png" /><figcaption>The buffer component is only visible while messages are being loaded. The chat history is always displayed.</figcaption></figure><p>The message component is a styled list element, with variable text alignment: right for the user, left for the AI.</p><pre>const MessageItem = styled.li&lt;{ role: &#39;user&#39; | &#39;system&#39; }&gt;`<br>  margin: 8px;<br>  padding: 8px;<br>  border-radius: 4px;<br>  text-align: ${({ role }) =&gt; (role === &#39;user&#39; ? &#39;right&#39; : &#39;left&#39;)};<br>`</pre><p>We create the chat history by mapping our MessageItem element over the messageHistory state exposed by the useRecipes hook.</p><pre>messageHistory.map((item, index) =&gt; (<br>  &lt;Card key={index}&gt;<br>    &lt;MessageItem role={item.role}&gt;<br>      &lt;RenderMarkdown content={item.content} /&gt;<br>    &lt;/MessageItem&gt;<br>  &lt;/Card&gt;<br>))</pre><p>Then, we display the buffer on the condition that an incoming message is loading and the buffer has content.</p><pre>isLoading &amp;&amp; outputBuffer &amp;&amp; (<br>  &lt;Card&gt;<br>    &lt;MessageItem role=&quot;system&quot;&gt;<br>      &lt;RenderMarkdown content={outputBuffer} /&gt;<br>    &lt;/MessageItem&gt;<br>  &lt;/Card&gt;<br>)</pre><p>Piecing it all together, we get the MessageHistory component.</p><pre>import React, { forwardRef } from &#39;react&#39;<br>import styled from &#39;styled-components&#39;<br>import { MessageHistoryItem } from &#39;../hooks/useRecipes&#39;<br>import { Card } from &#39;./Card&#39;<br>import { RenderMarkdown } from &#39;./RenderMarkdown&#39;<br><br>const StyleWrapper = styled.div`<br>  width: 100%;<br>  max-height: 80vh;<br>  overflow-y: auto;<br>`<br><br>const MessageList = styled.ul`<br>  list-style: none;<br>  padding: 0;<br>`<br><br>// changes the text alignment depending on role<br>const MessageItem = styled.li&lt;{ role: &#39;user&#39; | &#39;system&#39; }&gt;`<br>  margin: 8px;<br>  padding: 8px;<br>  border-radius: 4px;<br>  text-align: ${({ role }) =&gt; (role === &#39;user&#39; ? &#39;right&#39; : &#39;left&#39;)};<br>`<br><br>export interface MessageHistoryProps {<br>  // need a ref to scroll to the bottom of the chat history<br>  // when new messages are added<br>  ref: React.Ref&lt;HTMLDivElement&gt;<br>  // the message history to render<br>  // this includes the user&#39;s latest message.<br>  history: MessageHistoryItem[]<br>  // the output buffer for the current system message<br>  // this is used to render the message as it is being streamed<br>  outputBuffer?: string<br>  // whether the system message is still loading<br>  // used to disable the UI<br>  isLoading?: boolean<br>}<br><br>export const MessageHistory = forwardRef((props: MessageHistoryProps, ref: React.Ref&lt;HTMLDivElement&gt;) =&gt; {<br>  const { history, outputBuffer, isLoading } = props<br>  return (<br>    &lt;StyleWrapper ref={ref}&gt;<br>      &lt;MessageList&gt;<br>        {/* always render the message history */}<br>        {history.map((item, index) =&gt; (<br>          &lt;Card key={index}&gt;<br>            &lt;MessageItem role={item.role}&gt;<br>              &lt;RenderMarkdown content={item.content} /&gt;<br>            &lt;/MessageItem&gt;<br>          &lt;/Card&gt;<br>        ))}<br>        {/* render incoming message buffer when it is active */}<br>        {isLoading &amp;&amp; outputBuffer &amp;&amp; (<br>          &lt;Card&gt;<br>            &lt;MessageItem role=&quot;system&quot;&gt;<br>              &lt;RenderMarkdown content={outputBuffer} /&gt;<br>            &lt;/MessageItem&gt;<br>          &lt;/Card&gt;<br>        )}<br>      &lt;/MessageList&gt;<br>    &lt;/StyleWrapper&gt;<br>  )<br>})</pre><p>I won’t cover the development of an <a href="https://gitlab.com/ben_goodman/apps/ai-cookbook/-/blob/147293f4fd12c7d78b859ed8e4e1adfff9687c61/ui/src/components/UserInput.tsx">input component</a> since there aren’t any special considerations required. Any text input element will do. With that done, we integrate our UI components with the hook we developed earlier.</p><pre>const App = () =&gt; {<br>  const { sessionId, reset } = useSessionId()<br>  const ref = React.useRef&lt;HTMLDivElement&gt;(null)<br>  const {<br>    send,<br>    readyState,<br>    messageHistory,<br>    buffer,<br>    isLoading<br>  } = useRecipes(sessionId)<br><br>  useEffect(() =&gt; {<br>    // if messages are updated, scroll to the bottom of the chat history<br>    if (ref.current) {<br>      ref.current.scrollTop = ref.current.scrollHeight<br>    }<br>  }, [buffer, messageHistory])<br><br>  const handleSubmit = async (query: string, opts?: ChatOptions) =&gt; {<br>    if (!query.trim()) return<br>    send(query, opts)<br>  }<br><br>  return (<br>    &lt;StyleWrapper&gt;<br><br>      &lt;Header onNewSession={reset}/&gt;<br><br>      {messageHistory.length === 0 &amp;&amp; (<br>        &lt;WelcomeMessage onCardClick={handleSubmit} /&gt;<br>      )}<br><br>      {messageHistory.length &gt; 0 &amp;&amp; (<br>        &lt;MessageHistory<br>          ref={ref}<br>          history={messageHistory}<br>          outputBuffer={buffer}<br>          isLoading={isLoading}<br>        /&gt;<br>      )}<br><br>      &lt;UserInput<br>        onSubmit={handleSubmit}<br>        isLoading={isLoading}<br>        readyState={readyState}<br>      /&gt;<br><br>    &lt;/StyleWrapper&gt;<br>  )<br>}</pre><p>That concludes the UI development. The complete code for this stage can be found in <a href="https://gitlab.com/ben_goodman/apps/ai-cookbook/-/tree/147293f4fd12c7d78b859ed8e4e1adfff9687c61/ui">GitLab</a>.</p><h3>Conclusion</h3><p>The final product can be viewed at <a href="https://gastro-genie.com/">gastro-genie.com</a>.</p><p>The complete source code for the project is available in <a href="https://gitlab.com/ben_goodman/apps/ai-cookbook/-/tree/main?ref_type=heads">GitLab</a>.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 200k supporters? <strong>We do not get paid by Medium</strong>!</p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a><strong> and </strong><a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46ed5cb25bee" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/streaming-llm-responses-from-aws-lambda-46ed5cb25bee">Streaming LLM Responses from AWS Lambda</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating An AI-Powered Cookbook]]></title>
            <link>https://medium.com/@benjamin_goodman/creating-an-ai-powered-cookbook-c3a4a258fbab?source=rss-2f01806d4793------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3a4a258fbab</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Benjamin Goodman]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 22:24:35 GMT</pubDate>
            <atom:updated>2025-07-15T22:24:35.064Z</atom:updated>
            <content:encoded><![CDATA[<h4>Utilizing agentic AI to query a database of over 70,000 recipes.</h4><h4>Introduction</h4><p>A Retrieval-Augmented Generation (RAG) system is an AI architecture that combines two key components: a retriever and a generator. The retriever searches a large knowledge base (such as documents or recipes) to find the most relevant information for a user’s query. The generator (usually a language model) then uses this retrieved information to craft a more accurate and context-aware response.</p><p>In the context of an AI agent, RAG enables the agent to answer questions or provide assistance using up-to-date, domain-specific knowledge, rather than relying solely on what the model was trained on. This makes the agent more reliable, factual, and useful, especially for tasks like recipe search.</p><h4>Creating A Knowledge Base</h4><p>A knowledge base is a collection of information that is organized to facilitate easy searching, retrieval, and use by people or, in this case, a computer program.</p><p>What about an AI, though? What is the best way to organize data so that a language model can query it? The answer lies in vectors. We will use an LLM to capture the semantic meaning of each recipe, which will be expressed as a numerical vector; a process called ‘embedding’.</p><p>The process is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFzDZd5zPxPXIw4JpNCQWw.png" /></figure><ol><li><strong>Chunk the data:</strong><br>Break the documents into small, meaningful pieces. We need to convert our JSON recipe into text that is both readable and understandable.</li><li><strong>Embed each chunk:</strong><br>Use an embedding model to convert each chunk into a high-dimensional vector that captures its semantic meaning.</li><li><strong>Store in a vector database:</strong><br>Save the vectors (along with metadata) in a vector database. This enables fast similarity search to find the most relevant chunks for a given query.</li></ol><p>For my database, I opted for <a href="https://www.pinecone.io/">Pinecone</a>, which has a very generous free plan. The embedding model I will use is OpenAI’s text-embedding-3-large model. If using the same model, be sure to set the Pinecone index’s vector dimension to 3072 to accommodate the output.</p><p>With a workflow defined, it&#39;s time to write code.</p><p>The source of the recipes is the GitHub repo <a href="https://github.com/dpapathanasiou/recipes">dpapathanasiou/recipes</a>. I cloned the repo and moved all the JSON recipes into a single directory, which will make iterating over each of them slightly easier.</p><p>An example JSON recipe is below.</p><pre>{<br>    &quot;directions&quot;: [<br>        &quot;Preheat a waffle iron according to manufacturer&#39;s instructions.&quot;,<br>        &quot;Beat egg whites in a glass or metal bowl until soft peaks form. Lift your beater or whisk straight up: the egg whites will form soft mounds rather than a sharp peak.&quot;,<br>        &quot;Beat egg yolks, buttermilk, pumpkin, and butter together with a whisk in a large bowl until smooth; add flour, brown sugar, baking powder, cinnamon, baking soda, ginger, salt, and cloves. Stir the mixture with the whisk just until you have a smooth batter.&quot;,<br>        &quot;Fold the egg whites into the batter just until combined.&quot;,<br>        &quot;Prepare cooking surfaces of your waffle iron with cooking spray. Ladle about 2/3 cup batter into the prepared iron and cook until browned, 4 to 5 minutes.&quot;<br>    ],<br>    &quot;ingredients&quot;: [<br>        &quot;4 large eggs, separated&quot;,<br>        &quot;1 pint buttermilk, shaken vigorously&quot;,<br>        &quot;1 cup canned solid-pack pumpkin&quot;,<br>        &quot;6 tablespoons unsalted butter, melted&quot;,<br>        &quot;2 1/2 cups all-purpose flour&quot;,<br>        &quot;1/3 cup packed light brown sugar&quot;,<br>        &quot;2 1/4 teaspoons baking powder&quot;,<br>        &quot;2 teaspoons ground cinnamon&quot;,<br>        &quot;1 teaspoon baking soda&quot;,<br>        &quot;1 teaspoon ground ginger&quot;,<br>        &quot;1/2 teaspoon salt&quot;,<br>        &quot;1/4 teaspoon ground cloves&quot;,<br>        &quot;cooking spray&quot;<br>    ],<br>    &quot;language&quot;: &quot;en-US&quot;,<br>    &quot;source&quot;: &quot;allrecipes.com&quot;,<br>    &quot;tags&quot;: [],<br>    &quot;title&quot;: &quot;Perfect Pumpkin Spice Waffles&quot;,<br>    &quot;url&quot;: &quot;http://allrecipes.com/recipe/239490/perfect-pumpkin-spice-waffles/&quot;<br>}</pre><p>The script below will take a filepath for a JSON recipe, then:</p><ol><li>Chunk the JSON into text.</li><li>Embed the chunk into a vector.</li><li>Upsert the vector to our database.</li></ol><pre><br>import fs from &#39;fs/promises&#39;<br>import { Document } from &quot;langchain/document&quot;<br>import { OpenAIEmbeddings } from &quot;@langchain/openai&quot;<br>import { Pinecone } from &#39;@pinecone-database/pinecone&#39;<br>import slugify from &#39;slugify&#39;<br><br>type Recipe = {<br>  directions: string[]<br>  ingredients: string[]<br>  language: string<br>  source: string<br>  tags: string[]<br>  title: string<br>  url: string<br>}<br><br>const removeNonASCII = (str: string): string =&gt; str.replace(/[^\x00-\x7F]/g, &#39;&#39;)<br><br>const chunkJSON = (recipe: Recipe): string =&gt; {<br>return `<br>&lt;Recipe&gt;<br>&lt;Title&gt;${recipe.title}&lt;/Title&gt;<br>&lt;Ingredients&gt;${recipe.ingredients.join(&#39;, &#39;)}&lt;/Ingredients&gt;<br>&lt;Directions&gt;${recipe.directions.join(&#39; &#39;)}&lt;/Directions&gt;<br>&lt;Source&gt;${recipe.source}&lt;/Source&gt;<br>&lt;URL&gt;${recipe.url}&lt;/URL&gt;<br>&lt;/Recipe&gt;<br>`.trim()<br>}<br><br>const embedRecipe = async (recipe: Recipe)  =&gt; {<br>  const text = chunkJSON(recipe)<br><br>  const doc = new Document({<br>    pageContent: text,<br>    metadata: {<br>      title: recipe.title,<br>      slug: slugify(recipe.title),<br>      text<br>    }<br>  })<br>  <br>  const embeddings = new OpenAIEmbeddings({<br>    apiKey: process.env.OPENAI_API_KEY!,<br>    model: &quot;text-embedding-3-large&quot;,<br>  })<br>  <br>  const [vector] = await embeddings.embedDocuments([doc.pageContent])<br><br>  return {<br>    ...doc,<br>    embedding: vector,<br>  }<br><br>}<br><br>const upsertToPinecone = async (recipe: Recipe) =&gt; {<br>  const pinecone = new Pinecone({<br>    apiKey: process.env.PINECONE_API_KEY!,<br>  })<br>  const index = pinecone.Index(&#39;cookbook-rag&#39;)<br><br>  const { embedding, ...doc } = await embedRecipe(recipe)<br><br>  await index.upsert([<br>    {<br>      id: removeNonASCII(doc.metadata.title),<br>      values: embedding,<br>      metadata: doc.metadata<br>    }<br>  ]).catch(error =&gt; {<br>    console.error(`Error upserting recipe &quot;${doc.metadata.title}&quot;:`, error)<br>    return Promise.resolve()<br>  })<br>}<br><br>export const uploadRecipe = async (sourcePath: string) =&gt; {<br>  const data = await fs.readFile(sourcePath, &#39;utf-8&#39;)<br>  const recipe: Recipe = JSON.parse(data)<br>  await upsertToPinecone(recipe)<br>  console.log(`Recipe &quot;${recipe.title}&quot; added to Pinecone index.`)<br>}</pre><h4>Querying The Knowledge Base</h4><p>Retreiving recipes from the database is a process similar to uploading them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MhDv049j3RMUYCShJBjGIA.png" /></figure><ol><li>An embedding model converts natural language queries into vectors.</li><li>The vector is used to query the vector database, returning the top five most relevant recipes.</li></ol><p>Following this approach, we create a function to perform the query. We’ll use this function anytime we need to get recipes from the database.</p><pre>import { OpenAI } from &#39;openai&#39;<br>import { Pinecone } from &#39;@pinecone-database/pinecone&#39;<br><br><br>const embedText = async (text: string): Promise&lt;number[]&gt; =&gt; {<br>  const openai = new OpenAI({<br>    apiKey: process.env.OPENAI_API_KEY!,<br>  })<br><br>  const input = text.trim().replace(/\s+/g, &#39; &#39;)<br><br>  const response = await openai.embeddings.create({<br>    model: &#39;text-embedding-3-large&#39;,<br>    input,<br>  })<br><br>  return response.data[0].embedding<br>}<br><br>export const queryRecipe = async (query: string, opts?: { topK?: number }) =&gt; {<br>  const pinecone = new Pinecone({<br>    apiKey: process.env.PINECONE_API_KEY!,<br>  })<br><br>  const embedding = await embedText(query)<br><br>  const index = pinecone.Index(&#39;cookbook-rag&#39;)<br><br>  const response = await index.query({<br>    vector: embedding,<br>    topK: opts?.topK ?? 5,<br>    includeValues: true,<br>    includeMetadata: true,<br>  })<br><br>  return response.matches.map((match) =&gt; ({<br>    id: match.id,<br>    score: match.score,<br>    metadata: match.metadata,<br>  }))<br>}</pre><h4>Developing A Chat Agent</h4><p>The chat agent acts as an interface between the client and the recipes database. To bridge the gap between the two systems, a <em>tool</em> must be defined. Tools enable agents to perform actions beyond their built-in capabilities or retrieve external data for their model’s context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCI_QwsOrBotBVgLci9O8g.png" /></figure><p>The recipe query tool allows the agent to invoke the previously defined queryRecipe function. The tool returns a list of relevant recipes, which is then incorporated into the agent’s context. This context enables the agent to generate more informed and accurate responses, which are derived from the knowledge base created earlier.</p><pre>import { queryRecipe } from &#39;../../util/queryRecipe&#39;<br>import { tool } from &#39;@openai/agents&#39;<br>import { z } from &#39;zod&#39;<br><br>export const getRecipes = tool({<br>  name: &#39;getRecipes&#39;,<br>  description: &#39;Retrieve recipes based on a search query&#39;,<br>  parameters: z.object({<br>    query: z.string().describe(&#39;The search query for recipes&#39;)<br>  }),<br>  async execute({ query }) {<br>    const opts = { topK: 5 }<br>    const recipes = await queryRecipe(query, opts)<br><br>    if (recipes.length === 0) {<br>      return { message: &#39;No recipes found for the given query.&#39; }<br>    }<br><br>    return {<br>      message: `Found ${recipes.length} recipes.`,<br>      recipes,<br>    }<br>  }<br>})</pre><p>Next, we declare the agent’s instructions — a prompt that informs the model of its role, capabilities, and how it should respond.</p><pre>&lt;About&gt;<br>  You are an AI agent which assists users in finding recipes from a database.<br>  You have access to over 70,000 recipes.<br>&lt;/About&gt;<br>  <br>&lt;Tools&gt;<br>  You can use tools to interact with the database and retrieve recipes based on user queries.<br>  You have a tool called &#39;getRecipes&#39; that allows you to search for recipes.<br>  You must use this tool to find recipes that match the user&#39;s query.<br>&lt;/Tools&gt;<br><br>&lt;ResponseInstructions&gt;<br>  Your response should be a JSON object with:<br>    - A `message` field for your final response.<br>  Use the following format for your message field: &#39;&lt;%= messageFormat %&gt;&#39;.<br>&lt;/ResponseInstructions&gt;</pre><p>Finally, we create a <em>CookbookAgent</em> class.</p><pre>import ejs from &#39;ejs&#39;<br>import OpenAI from &#39;openai&#39;<br>import { Agent, ModelSettings, RunContext, setDefaultOpenAIClient } from &#39;@openai/agents&#39;<br>import { getRecipes } from &#39;./tools/getRecipes&#39;<br>import prompt from &#39;./prompt.txt&#39;<br><br>export type CookbookAgentContext = {<br>  messageFormat: &#39;text&#39; | &#39;markdown&#39;,<br>}<br><br>const instructions = (runContext: RunContext&lt;CookbookAgentContext&gt;) =&gt; {<br>  const { messageFormat } = runContext.context<br>  return ejs.render(prompt, { messageFormat })<br>}<br><br>export default class CookbookAgent extends Agent&lt;CookbookAgentContext&gt; {<br>  constructor(modelSettings?: ModelSettings) {<br>    super({<br>      name: &#39;CookbookAgent&#39;,<br>      instructions,<br>      tools: [<br>        getRecipes,<br>      ],<br>      modelSettings<br>    })<br><br>    const client = new OpenAI({<br>      apiKey: process.env.OPENAI_API_KEY!,<br>    })<br><br>    setDefaultOpenAIClient(client)<br>  }<br>}</pre><p>We could run the agent as-is, and it will fetch recipes as intended. However, we haven&#39;t taken any steps to give the agent a memory; by giving it an awareness of the chat history, we can unlock powerful abilities like understanding user intent, multi-turn reasoning, and continuity.</p><h4>Adding Chat History Context</h4><p>Chat history provides context for the conversation between the agent and the user. Without such context, the following conversation would be impossible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ORSP40OlyJdXAxpyIqz8g.png" /><figcaption>An example of the continutity gained from maintaining a chat history.</figcaption></figure><p>Enabling chat history requires creating a database to store the data and a set of tools for the agent to interact with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E7z4WHAWFPFRE3mvtgMkRA.png" /></figure><p>The chat history is part of the user’s session context, which is an item consisting of:</p><ul><li>sessionId — a UUID specific to a user.</li><li>expiresAt — an expiry date for the session.</li><li>chatHistory — an array of agent or user messages.</li></ul><p>Using DynamoDB Toolbox, an entity is defined that will represent the user’s session.</p><pre>import { list, map, item, string, number, Entity, ValidValue } from &#39;dynamodb-toolbox&#39;<br><br>const dynamoDBClient = new DynamoDBClient()<br><br>const TABLE_NAME = process.env.SESSION_TABLE_NAME!<br><br>const SessionsTable = new Table({<br>  name: TABLE_NAME,<br>  partitionKey: {<br>    name: &#39;sessionId&#39;,<br>    type: &#39;string&#39;<br>  },<br>  documentClient: DynamoDBDocumentClient.from(dynamoDBClient),<br>})<br><br>const historyObject = map({<br>  role: string().required(),<br>  content: string().required(),<br>  timestamp: number().required(),<br>})<br><br>const schema = item({<br>  sessionId: string().key(),<br>  expiresAt: number().required(),<br>  chatHistory: list(historyObject).required(),<br>})<br><br>export type SessionItem = ValidValue&lt;typeof schema&gt;<br><br>export default new Entity({<br>  name: &#39;ChatSession&#39;,<br>  schema,<br>  table: SessionsTable,<br>})</pre><p>We can incorporate <a href="https://gitlab.com/ben_goodman/apps/ai-cookbook/-/blob/3a9087b504148def82dbdf7e33068225debe8e13/chat/src/repo/session.ts">utility functions</a> to create/retrieve/delete chat sessions from the database into our agent as tools.</p><p>We start with a tool to create a chat session.</p><pre>import { tool } from &#39;@openai/agents&#39;<br>import { z } from &#39;zod&#39;<br>import { createSession } from &#39;../../repo/session&#39;<br><br>export const createChatSession = tool({<br>  name: &#39;createChatSession&#39;,<br>  description: &#39;Create a new chat session&#39;,<br>  parameters: z.object({<br>    sessionId: z.string().describe(&#39;The ID of the session to start chat history for&#39;)<br>  }),<br>  async execute({ sessionId }) {<br>    <br>    if (!sessionId) {<br>      return { message: &#39;No session ID provided. Cannot create chat session.&#39; }<br>    }<br><br>    const session = await createSession(sessionId)<br><br>    if (!session) {<br>      return { message: &#39;Failed to create session.&#39; }<br>    }<br><br>    return sessionId<br>  }<br>})</pre><p>Then, a tool to retrieve a session’s chat history.</p><pre>import { tool } from &#39;@openai/agents&#39;<br>import { z } from &#39;zod&#39;<br>import { getSession } from &#39;../../repo/session&#39;<br><br>export const getChatHistory = tool({<br>  name: &#39;getChatHistory&#39;,<br>  description: &#39;Retrieve the chat history for a given session ID&#39;,<br>  parameters: z.object({<br>    sessionId: z.string().describe(&#39;The ID of the session to retrieve chat history for&#39;)<br>  }),<br>  async execute({ sessionId }) {<br>    if (!sessionId) {<br>      return { message: &#39;No session ID provided. Cannot retrieve chat history.&#39; }<br>    }<br><br>    const session = await getSession(sessionId)<br><br>    if (!session) {<br>      return { message: `No chat history found for session ID ${sessionId}.` }<br>    }<br><br>    return {<br>      message: `Retrieved chat history for session ID ${sessionId}.`,<br>      chatHistory: session.chatHistory,<br>    }<br>  }<br>})</pre><p>Lastly, a tool to delete a session.</p><pre>import { tool } from &#39;@openai/agents&#39;<br>import { z } from &#39;zod&#39;<br>import { deleteSession } from &#39;../../repo/session&#39;<br><br>export const deleteChatSession = tool({<br>  name: &#39;deleteChatSession&#39;,<br>  description: &#39;Delete an existing chat session&#39;,<br>  parameters: z.object({<br>    sessionId: z.string().describe(&#39;The ID of the session to delete&#39;)<br>  }),<br>  async execute({ sessionId }) {<br>    <br>    if (!sessionId) {<br>      return { message: &#39;No session ID provided. Cannot delete chat session.&#39; }<br>    }<br><br>    await deleteSession(sessionId)<br><br>    return { message: `Session ${sessionId} deleted successfully.` }<br>  }<br>})</pre><p>Next, we update the agent’s instructions to include a section on session management:</p><pre>&lt;SessionInstructions&gt;<br>  The user&#39;s sessionId is: &#39;&lt;%= sessionId %&gt;&#39;.<br><br>  If the session ID is defined:<br>    The session stores the chat history for this interaction.<br>    You must begin each session by retrieving the chat history.<br>    Use this sessionId with the `getChatHistory` tool to retrieve the chat history.<br>    If there is no chat history for the sessionId, use the `createChatSession` tool to create a new session.<br>    Update the chat history using the `updateChatHistory` tool after each interaction.<br>    When to update chat history:<br>      - After receiving a user query.<br>      - After providing a response to the user.<br>    If you cannot update the chat history, respond with an error message.<br>    <br>  Else, if the session ID is null:<br>    This is an ephemeral session which does not use chat history.<br>    You can still interact with the user, but the chat history will not be stored.<br>&lt;/SessionInstructions&gt;<br><br>&lt;ResponseInstructions&gt;<br>  Your response should be a JSON object with:<br>    - A `message` field for your final response.<br>    - A `sessionId` field for the current session.<br>  Use the following format for your message field: &#39;&lt;%= messageFormat %&gt;&#39;.<br>&lt;/ResponseInstructions&gt;</pre><p>Our agent’s code now becomes:</p><pre>import ejs from &#39;ejs&#39;<br>import OpenAI from &#39;openai&#39;<br>import { Agent, ModelSettings, RunContext, setDefaultOpenAIClient } from &#39;@openai/agents&#39;<br>import { getRecipes } from &#39;./tools/getRecipes&#39;<br>import { getChatHistory } from &#39;./tools/getChatHistory&#39;<br>import { createChatSession } from &#39;./tools/createChatSession&#39;<br>import { updateChatHistory } from &#39;./tools/updateChatHistory&#39;<br>import { deleteChatSession } from &#39;./tools/deleteChatSession&#39;<br>import { SessionItem } from &#39;../database/SessionEntity&#39;<br>import prompt from &#39;./prompt.txt&#39;<br><br><br>export type CookbookAgentContext = {<br>  sessionId: string | null,<br>  messageFormat: &#39;text&#39; | &#39;markdown&#39;,<br>  chatHistory: SessionItem[&#39;chatHistory&#39;] | null,<br>}<br><br>const instructions = (runContext: RunContext&lt;CookbookAgentContext&gt;) =&gt; {<br>  const { sessionId, messageFormat } = runContext.context<br>  return ejs.render(prompt, { sessionId, messageFormat })<br>}<br><br>export default class CookbookAgent extends Agent&lt;CookbookAgentContext&gt; {<br>  constructor(modelSettings?: ModelSettings) {<br>    super({<br>      name: &#39;CookbookAgent&#39;,<br>      instructions,<br>      tools: [<br>        getChatHistory,<br>        createChatSession,<br>        updateChatHistory,<br>        deleteChatSession,<br>        getRecipes,<br>      ],<br>      modelSettings: {<br>        ...modelSettings,<br>        parallelToolCalls: true,<br>      }<br>    })<br><br>    // Set the default OpenAI client for this agent<br>    const client = new OpenAI({<br>      apiKey: process.env.OPENAI_API_KEY!,<br>    })<br><br>    setDefaultOpenAIClient(client)<br>  }<br>}</pre><h4>Deploying to AWS</h4><p>In this step, we make our chat agent/RAG system accessible over the internet as a serverless API.</p><p>The API gateway will have two endpoints:</p><ul><li>POST /chat — Passes a user query to the agent.</li><li>POST /mcp — MCP server.</li></ul><figure><img alt="A diagram illustrating the architecture of the serverless cooking chat agent. The core of the system is two lambda functions which handle requests for chat and MCP services." src="https://cdn-images-1.medium.com/max/1024/1*s8xHtRr2Lrf5GovpgFrT5Q.png" /></figure><p>Interfacing our agent with the API requires a handler function for POST /chat requests.</p><pre>import type { APIGatewayProxyEvent, APIGatewayProxyResult,  } from &#39;aws-lambda&#39;<br>import { run } from &#39;@openai/agents&#39;<br>import CookbookAgent, { CookbookAgentContext } from &#39;../agent&#39;<br><br>export const chatHandler = async (event: APIGatewayProxyEvent): Promise&lt;APIGatewayProxyResult&gt; =&gt; {<br>  const body = event.body ? (typeof event.body === &#39;string&#39; ? JSON.parse(event.body) : event.body) : {}<br><br>  const query = (body as any).query<br>  const sessionId = (body as any).sessionId<br>  const messageFormat = (body as any).messageFormat || &#39;text&#39;<br>  const temperature = (body as any).temperature || 0.7<br><br>  const agent = new CookbookAgent({<br>    temperature,<br>  })<br><br>  const context: CookbookAgentContext = {<br>    sessionId: sessionId ?? null,<br>    messageFormat,<br>    chatHistory: null<br>  }<br><br>  console.log(&#39;Running agent with query:&#39;, query, &#39;and context:&#39;, context)<br><br>  const response = await run(agent, query, { context })<br><br>  if (!response || !response.finalOutput) {<br>    return {<br>      statusCode: 500,<br>      body: &#39;Failed to process the request.&#39;<br>    }<br>  }<br><br>  return {<br>    statusCode: 200,<br>    body: response.finalOutput,<br>  }<br>}</pre><p>We can perform a quick test.</p><pre>curl -X POST \<br>  https://xxxxxxx.execute-api.us-east-1.amazonaws.com/ai-cookbook/chat \<br>  -d &#39;{&quot;query&quot;: &quot;suggest a recipe using chocolate&quot;}&#39; \<br>| jq<br><br>{<br>  &quot;message&quot;: &quot;Here&#39;s a delicious recipe you can try using chocolate:\n\n**Chocolate Delight**\n\n**Ingredients:**\n- 2 (8 or 9 inch) baked round chocolate cake layers, cooled\n- 1 cup coffee-flavored liqueur\n- 2 (5.9 ounce) packages instant chocolate pudding mix\n- 4 cups milk, or as needed\n- 6 (1.4 ounce) bars chocolate covered toffee bars, chopped\n- 2 (12 ounce) containers frozen whipped topping, thawed\n- 1 (1 ounce) square semisweet chocolate\n\n**Directions:**\n1. Cut chocolate cake into large squares and place on a baking sheet or large baking dish. Pour coffee-flavored liqueur over cake and set aside.\n2. Prepare chocolate pudding with milk according to package directions.\n3. In large trifle bowl or other glass bowl, crumble half of liqueur-moistened cake. Top cake with half of chocolate pudding, half of crumbled candy bars, and one container of whipped topping.\n4. Repeat with remaining cake, pudding, candy bars, and whipped topping.\n5. Shave chocolate with a vegetable peeler for garnish; sprinkle over top of dessert. Keep refrigerated until serving.\n\nYou can find the full recipe here: http://allrecipes.com/recipe/19008/chocolate-delight/\n\nLet me know if you want more chocolate recipes or something specific!&quot;,<br>  &quot;sessionId&quot;: &quot;&quot;,<br>  &quot;uiCallback&quot;: null<br>}</pre><h4>Adding An MCP Endpoint</h4><p>This is an optional step, as the client won&#39;t use it, but it still presents a valuable learning opportunity.</p><p>The article on <a href="https://builder.aws.com/content/2vzj07Wyk6Lw281Tvs1Lw7kJJNW/building-scalable-mcp-servers-on-aws-lambda-a-practical-guide">builder.aws.com</a> is a good description of how to do this on a Lambda function. However, I modified the code to use @venida/serverless-express for simplicity.</p><p>The MCP server exposes a tool called getRecipes which implements the queryRecipe function from much earlier. The rest is pretty much boilerplate.</p><pre>import { McpServer } from &#39;@modelcontextprotocol/sdk/server/mcp.js&#39;<br>import { StreamableHTTPServerTransport } from &#39;@modelcontextprotocol/sdk/server/streamableHttp.js&#39;<br>import express from &#39;express&#39;<br>import serverlessExpress from &#39;@vendia/serverless-express&#39;<br>import { z } from &#39;zod&#39;<br><br>import { queryRecipe } from &#39;../../chat/src/util/queryRecipe&#39;<br><br>// Create MCP server<br>const server = new McpServer({<br>  name: &#39;Recipes MCP Server&#39;,<br>  version: &#39;1.0.0&#39;<br>})<br><br>// Create Express application<br>const app = express()<br>app.use(express.json())<br><br>// Add a tool - implementing a simple recipe retrieval<br>server.registerTool(<br>  &#39;getRecipes&#39;,<br>  z.object({<br>    query: z.string().describe(&#39;The search query for recipes&#39;)<br>  }),<br>  async ({ query }) =&gt; {<br>    const recipes = await queryRecipe(query)<br>    return {<br>      content: [{ type: &#39;text&#39;, text: `Result: ${recipes}` }]<br>    }<br>  }<br>)<br><br>// Configure Streamable HTTP transport (sessionless)<br>const transport = new StreamableHTTPServerTransport({<br>  sessionIdGenerator: undefined, // Disable session management<br>})<br><br>// Set up routes<br>app.post(&#39;/mcp&#39;, async (req, res) =&gt; {<br>  try {<br>    await transport.handleRequest(req, res, req.body)<br>  } catch (error) {<br>    console.error(&#39;Error handling MCP request:&#39;, error)<br>    if (!res.headersSent) {<br>      res.status(500).json({<br>        jsonrpc: &#39;2.0&#39;,<br>        error: {<br>          code: -32603,<br>          message: &#39;Internal server error&#39;,<br>        },<br>        id: null,<br>      })<br>    }<br>  }<br>})<br><br>// Start the server<br>const PORT = 8080<br><br>server.connect(transport).then(() =&gt; {<br>  app.listen(PORT, () =&gt; {<br>    console.log(`MCP Server listening on port ${PORT}`)<br>  })<br>}).catch(error =&gt; {<br>  console.error(&#39;Failed to set up the server:&#39;, error)<br>  process.exit(1)<br>})<br><br>export const handler = serverlessExpress({ app })</pre><p>We can now test the MCP server. I’ve used the OpenAI prompts playground.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d8SUZf7g97uiIv0Cn-m3Ug.png" /></figure><h4>Developing a UI Client</h4><p>Now we aim to develop a straightforward React application that sends and displays messages to and from the chat API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lbana2Vri49zEzeR0GmURw.png" /></figure><p>The UI should include the necessary features to facilitate a conversation between the user and the agent. It should also respond to requests made by the agent. For example, if the user wishes to start a new session (i.e., clear its context), the agent can include a ‘UI callback’ in its response to clear the UI&#39;s context as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*Dgi79c9a5b6iCfXpqabD4Q.gif" /><figcaption>An example of the chat agent controlling the UI.</figcaption></figure><p>We’ll need to update the agent’s instructions to include directions for including a UI callback in its output. However, that&#39;s the only change required to the backend!</p><pre>&lt;UICallback&gt;<br>  The user interface callback is used to control the UI once the response is generated.<br><br>  You can use the `uiCallback` field in your response to provide instructions for the UI.<br>  The `uiCallback` should be either `null` or a JSON object with the following structure:<br>  {<br>    &quot;functionName&quot;: string,<br>    &quot;args&quot;: any[],<br>  }<br><br>  The following UI functions are available:<br>    - `resetSession`: This function resets the current session.<br>      It should be used when the user wants to start a new session or clear the current chat history.<br>&lt;/UICallback&gt;<br><br>&lt;ResponseInstructions&gt;<br>  Your response should be a JSON object with:<br>    - A `message` field for your final response.<br>    - A `sessionId` field for the current session.<br>    - A `uiCallback` field for any UI interactions (null otherwise).<br>  Use the following format for your message field: &#39;&lt;%= messageFormat %&gt;&#39;.<br>&lt;/ResponseInstructions&gt;</pre><p>The UI callback is executed by a React hook that exposes a function for chat, an isLoading bool and the messages array. It&#39;s also responsible for maintaining a copy of the application’s state in local storage, allowing displayed messages to persist across page reloads.</p><pre>import { useState, useEffect } from &#39;react&#39;<br>import { v4 as uuidv4 } from &#39;uuid&#39;<br><br>const API_URL = process.env.API_URL<br><br>const LS_KEY_SESSION = &#39;cookbook-session-id&#39;<br>const LS_KEY_MESSAGES = &#39;cookbook-messages&#39;<br><br>export type UICallback = {<br>  functionName: &#39;resetSession&#39;,<br>  args: unknown[],<br>}<br><br>export type ChatResponse = {<br>  message: string,<br>  sessionId: string | null,<br>  uiCallback: UICallback | null<br>}<br><br>export type UseRecipesProps = {<br>  onResetSession?: () =&gt; void,<br>}<br><br>export const useRecipes = (props?: UseRecipesProps) =&gt; {<br>  const [isLoading, setIsLoading] = useState(false)<br>  const [messages, setMessages] = useState&lt;{ text: string; role: &#39;user&#39; | &#39;assistant&#39; }[]&gt;([])<br><br>  // on page load, get any messages stored locally<br>  useEffect(() =&gt; {<br>    const storedMessages = window.localStorage.getItem(LS_KEY_MESSAGES)<br>    if (storedMessages) {<br>      setMessages(JSON.parse(storedMessages))<br>    }<br>  }, [])<br><br> // save `messages` to local store<br>  useEffect(() =&gt; {<br>    if (messages.length === 0) return<br>    window.localStorage.setItem(LS_KEY_MESSAGES, JSON.stringify(messages))<br>  }, [messages])<br><br><br>  const executeUICallback = (callback: UICallback) =&gt; {<br>    switch (callback.functionName) {<br>    case &#39;resetSession&#39;:<br>      localStorage.removeItem(LS_KEY_SESSION)<br>      localStorage.removeItem(LS_KEY_MESSAGES)<br>      setMessages([])<br>      props?.onResetSession?.()<br>      break<br>    default:<br>      console.warn(`No handler for UI callback: ${callback.functionName}`)<br>    }<br>  }<br><br>  const getSessionId = (): string | null =&gt; {<br>    if (typeof window === &#39;undefined&#39;) return null<br>    const sessionId = localStorage.getItem(LS_KEY_SESSION)<br>    if (sessionId) {<br>      return sessionId<br>    }<br>    const newSessionId = uuidv4()<br>    localStorage.setItem(LS_KEY_SESSION, newSessionId)<br>    return newSessionId<br>  }<br>  <br>  // post a request to the chat API<br>  const chat = async (query: string) =&gt; {<br>    setIsLoading(true)<br><br>    const sessionId = getSessionId()<br><br>    setMessages((prev) =&gt; [<br>      ...prev,<br>      { text: query, role: &#39;user&#39; }<br>    ])<br><br>    const body = JSON.stringify({<br>      query,<br>      sessionId,<br>      messageFormat: &#39;markdown&#39;<br>    })<br><br>    const resp = await fetch(`${API_URL}/chat`, {<br>      method: &#39;POST&#39;,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      },<br>      body,<br>    })<br>    if (!resp.ok) {<br>      const errorText = await resp.text()<br>      setIsLoading(false)<br>      throw new Error(`Failed to query recipes: ${errorText}`)<br>    }<br>    const data: ChatResponse = await resp.json()<br><br>    if (data.uiCallback) {<br>      executeUICallback(data.uiCallback)<br>    }<br><br>    setMessages((prev) =&gt; [<br>      ...prev,<br>      { text: data.message, role: &#39;assistant&#39; }<br>    ])<br><br>    setIsLoading(false)<br>    return data<br>  }<br><br>  return {<br>    chat,<br>    isLoading,<br>    messages<br>  }<br>}</pre><p>The rest is a very standard <a href="https://gitlab.com/ben_goodman/apps/ai-cookbook/-/tree/3a9087b504148def82dbdf7e33068225debe8e13/demo/src">React application</a>.</p><h4>Conclusion</h4><p>This project demonstrates how modern AI techniques — like Retrieval-Augmented Generation and vector databases — can transform the way we access and interact with knowledge. Moreover, its cheap and easy to implement.</p><p>Source code: <a href="https://gitlab.com/ben_goodman/apps/ai-cookbook">https://gitlab.com/ben_goodman/apps/ai-cookbook</a></p><p>Demo: <a href="https://ai-cookbook-6a4854.gitlab.io/">https://ai-cookbook-6a4854.gitlab.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3a4a258fbab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Six More Satisfying Agent-Based Models]]></title>
            <link>https://blog.devgenius.io/six-more-satisfying-agent-based-models-7c9749373376?source=rss-2f01806d4793------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c9749373376</guid>
            <category><![CDATA[agent-based-modeling]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[complexity]]></category>
            <dc:creator><![CDATA[Benjamin Goodman]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 16:41:36 GMT</pubDate>
            <atom:updated>2025-02-17T15:54:21.667Z</atom:updated>
            <content:encoded><![CDATA[<h4>Another ABM roundup featuring traffic congestion, multi-agent path finding and population dynamics.</h4><p>Agent-based modeling (ABM) is a computational approach used to simulate the actions and interactions of autonomous agents within a system. These agents, which can represent individuals, groups, or entities, follow simple rules and respond to their environment.</p><p>ABM is also a good excuse to learn somehting new as the models often verge into interdicplinary grounds such as biology and social behaviors.</p><p>All the models featured in this article were developed using <a href="https://www.npmjs.com/package/agentscape">agentscape</a> — an ABM library which I created.</p><h3>1. Traffic Congestion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*QiWd1GMp-Jk6HKcm06-thw.gif" /><figcaption>Agents traveling at less than 10% of their desired velocity will turn red.</figcaption></figure><ul><li><a href="https://gitlab.com/ben_goodman/apps/agent-based-modelling/traffic-congestion">Source Code</a></li><li><a href="https://apps.ben.website/traffic-congestion/index.html">App</a></li></ul><p>The model consists of a single-lane road with a number of agents that drive along it. Each agent has a desired velocity at which they would like to drive. They will accelerate or decelerate to reach this velocity based on the properties of the car in front of them. This acceleration strategy is based on the Intelligent Driver Model (See the book <a href="https://traffic-flow-dynamics.org/res/SampleChapter11.pdf">Traffic Flow Dynamics</a> section 11.3 for a description of the IDM).</p><p>The result is a simulation which exibits <a href="https://en.wikipedia.org/wiki/Traffic_wave">traffic waves</a> propogating against the flow of traffic.</p><p>The agent class acts by using the IDM to compute its ideal acceleration for the agent based on the properties of the leading agent, such as its distance and speed. The agent’s next position is then derived from its acceleration and current speed using Runge-Kutta integration.</p><pre>import { Entities } from &#39;agentscape&#39;<br>import { CellGrid } from &#39;agentscape/structures&#39;<br><br>export interface DriverConstructor extends Entities.AgentConstructor {<br>    initialVelocity: number<br>    desiredVelocity: number<br>    initialAcceleration: number<br>    maxAcceleration: number<br>    maxDeceleration: number<br>    miniumDistance: number<br>    safeTimeHeadway: number<br>    variancePercentage: number<br>}<br><br>export default class Driver extends Entities.Agent {<br>    public currentVelocity: number<br>    public currentAcceleration: number<br>    public desiredVelocity: number<br>    public maxAcceleration: number<br>    public miniumDistance: number<br>    public safeTimeHeadway: number<br>    public maxDeceleration: number<br>    public leadingAgent?: this = undefined<br><br>    constructor(opts: DriverConstructor) {<br>        super(opts)<br>        this.metabolism = 0<br>        this.currentVelocity = opts.initialVelocity<br>        this.maxAcceleration = this.rng.normalFloat(opts.maxAcceleration, opts.variancePercentage * opts.maxAcceleration)<br>        this.maxDeceleration = this.rng.normalFloat(opts.maxDeceleration, opts.variancePercentage * opts.maxDeceleration)<br>        this.miniumDistance = this.rng.normalFloat(opts.miniumDistance, opts.variancePercentage * opts.miniumDistance)<br>        this.safeTimeHeadway = this.rng.normalFloat(opts.safeTimeHeadway, opts.variancePercentage * opts.safeTimeHeadway)<br>        this.desiredVelocity = this.rng.normalFloat(opts.desiredVelocity, opts.variancePercentage * opts.desiredVelocity)<br>    }<br><br>    public act(grid: CellGrid&lt;Entities.Cell&gt;): void {<br><br>        // use rk4 to compute the new position from the acceleration function and current velocity<br>        const a1 = this.computeAcceleration(grid, this.currentVelocity)<br>        const k1_v = a1<br>        const k1_x = this.currentVelocity<br><br>        const a2 = this.computeAcceleration(grid, this.currentVelocity + 0.5 * k1_v * this.dt)<br>        const k2_v = a2<br>        const k2_x = this.currentVelocity + 0.5 * k1_v * this.dt<br><br>        const a3 = this.computeAcceleration(grid, this.currentVelocity + 0.5 * k2_v * this.dt)<br>        const k3_v = a3<br>        const k3_x = this.currentVelocity + 0.5 * k2_v * this.dt<br><br>        const a4 = this.computeAcceleration(grid, this.currentVelocity + k3_v * this.dt)<br>        const k4_v = a4<br>        const k4_x = this.currentVelocity + k3_v * this.dt<br><br>        this.currentVelocity = Math.max( 0, this.currentVelocity + (this.dt / 6) * (k1_v + 2 * k2_v + 2 * k3_v + k4_v) )<br><br>        const newPosition = [<br>            this.position.x + (this.dt / 6) * (k1_x + 2 * k2_x + 2 * k3_x + k4_x),<br>            this.position.y<br>        ] as [number, number]<br><br>        this.moveTo(grid, newPosition)<br>    }<br><br>    private computeAcceleration(grid: CellGrid&lt;Entities.Cell&gt;, velocity: number): number {<br>        if (!this.leadingAgent) {<br>            throw new Error(&#39;No leading agent&#39;)<br>        }<br><br>        const randomNoise = () =&gt; 0.2 * (this.rng.uniformFloat(0, 1) * 2 - 1)<br><br>        const a = this.maxAcceleration<br>        const b = this.maxDeceleration<br>        const T = this.safeTimeHeadway<br>        const s_0 = this.miniumDistance<br>        const v_0 = this.desiredVelocity<br>        const v_leader = this.leadingAgent.currentVelocity<br><br>        const distanceToLead = this.distanceTo(grid, this.leadingAgent)<br><br>        const desiredDistance = s_0 + Math.max(0, velocity * T + ( velocity * (velocity - v_leader) ) / (2 * Math.sqrt(a * b)))<br><br>        const a_1 = Math.pow(velocity / v_0, 4)<br>        const a_2 = Math.pow(desiredDistance / distanceToLead, 2)<br><br>        const acceleration = a * (1 - a_1 - a_2)<br><br>        return acceleration + randomNoise()<br>    }<br><br>}</pre><p>Here, we instantiate a set of agents and then assign each one its leader. Then, a grid with periodic boundary conditions and, finally, code to render the agent (points on a straight line) as points on a circle.</p><pre>initAgents() {<br>        // create an array of drivers<br>        const driverArray = Array.from({ length: this.agentCount }, (_, i) =&gt; {<br>            // initial positions spaced evenly along a linear path<br>            // will map positions to a circle later during render phase<br>            const x = (this.gridWidth / this.agentCount) * i<br><br>            return new Driver({<br>                initialPosition: [x, 15],<br>                randomSeed: i,<br>                desiredVelocity: this.desiredVelocity,<br>                maxAcceleration: this.maxAcceleration,<br>                maxDeceleration: this.maxDeceleration,<br>                miniumDistance: this.minimumDistance,<br>                safeTimeHeadway: this.safeTimeHeadway,<br>                initialVelocity: 1,<br>                initialAcceleration: 0.1,<br>                variancePercentage: this.variancePercentage / 100<br>            })<br>        })<br><br>        // the ith driver follows the &#39;ith + 1 % driverCount&#39; driver<br>        driverArray.forEach((driver, i) =&gt; {<br>            driver.leadingAgent = driverArray[(i + 1) % this.agentCount]<br>        })<br><br>        const drivers = AgentSet.fromArray(driverArray)<br><br>        return { drivers }<br>   }<br><br>    initGrid() {<br>        // drivers who reach the end of the road<br>        // will wrap around to the start<br>        return CellGrid.default(this.gridWidth, { boundaryCondition: &#39;periodic&#39; })<br>    }<br><br>    override render(renderer: Render2D) {<br>        renderer.clear()<br><br>        // map each agents x,y position to an r, theta point on a circle<br>        // then convert back to cartesian<br>        this.agents.drivers.forEach( driver =&gt; {<br>            // normalize position<br>            const t = driver.position.x / this.gridWidth<br>            // map to an angle<br>            const theta = 2 * Math.PI * t<br>            // the radius of the circle shall scale with the line length<br>            const R = Math.floor(this.gridWidth / 2.5)<br>            // the view is a square for origin is length / 2<br>            const O = Math.floor(this.gridWidth / 2)<br>            const x_circle = O + R * Math.cos(theta)<br>            const y_circle = O + R * Math.sin(theta)<br><br>            renderer.drawCircle(x_circle, y_circle, {<br>                radius: 1,<br>                fill: Color.fromName((driver.currentVelocity / driver.desiredVelocity) &lt; 0.1 ? &#39;red&#39; : &#39;black&#39;)<br>            })<br>        })<br>    }</pre><p>Maybe not the most satisfying subject to deal with in person, but certainly a pleasing result to watch.</p><h3>2. A Perfect Maze</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*upmULTZdkgInLy7OYJWDig.gif" /><figcaption>Agents uses recursive backtarcking to generate and navigate a perfect maze.</figcaption></figure><ul><li><a href="https://gitlab.com/ben_goodman/apps/agent-based-modelling/maze">Source Code</a></li><li><a href="https://apps.ben.website/maze">App</a></li></ul><p>A perfect maze is one without any inaccessible areas, loops, or disconnected walls and has only one path between two points. One of the simplest methods to generate such a maze is the recursive backtracking algorithm.</p><p>Like with all models before, the space the maze occupies will be made of cells. Each cell has a wall property that tracks the sides of the cell that are open or closed to their neighboring cell.</p><pre>import { Entities } from &#39;agentscape&#39;<br><br>export default class Cell extends Entities.Cell {<br>    public walls = {<br>        top: true,<br>        right: true,<br>        bottom: true,<br>        left: true<br>    }<br>}</pre><p>As the agent traverses the cell grid, it will eliminate the walls between specific cells.</p><p>Let&#39;s break down the maze generation algorithm:</p><ol><li>First, the agent initializes an array of visited cells and an array of previous locations.</li><li>The agent looks at its immediate, unvisited neighboring cells. If there are no unvisited cells, the agent backtracks to its previous location and tries again. If there is no last location, the maze is complete.</li><li>If at least one unvisited neighbor exists, the agent randomly picks one and removes the wall between it and the agent’s current cell.</li><li>The agent moves to the new cell, adds it to the list of visited cells, and repeats from 2.</li></ol><p>We implement this as the agent’s main behavior:</p><pre>import { Entities } from &#39;agentscape&#39;<br>import { CellGrid } from &#39;agentscape/structures&#39;;<br>import Cell from &#39;./Cell&#39;;<br><br>export default class Builder extends Entities.Agent {<br><br>    public visitedCells: Cell[] = []<br>    public lastMove: [number, number][] = []<br><br>    act(grid: CellGrid&lt;Cell&gt;) {<br><br>        const unvisitedNeighbors = this<br>            .getNeighborCells(grid)<br>            .filter(cell =&gt; !this.visitedCells.includes(cell))<br><br>        if (unvisitedNeighbors.length &gt; 0) {<br>            // Choose a random unvisited neighbor.<br>            const neighbor = this.rng.pickRandom(unvisitedNeighbors)<br><br>            // remove the wall between the current cell and the neighbor.<br>            this.removeWallBetweenCells(this.getCell(grid), neighbor)<br><br>            // Move to the neighbor cell and mark it as visited.<br>            this.moveTo(grid, neighbor.location)<br>            this.visitedCells.push(neighbor)<br>            this.lastMove.push(neighbor.location)<br>        } else {<br>            // If there are no unvisited neighbors, backtrack to the previous cell.<br>            const lastMove = this.lastMove.pop()<br>            if (lastMove) {<br>                this.moveTo(grid, lastMove)<br>            } else {<br>                // If there are no previous moves, the maze is complete.<br>                this.die()<br>            }<br>        }<br>    }<br><br>    private removeWallBetweenCells(cell1: Cell, cell2: Cell) {<br>        const x1 = cell1.location[0]<br>        const y1 = cell1.location[1]<br><br>        const x2 = cell2.location[0]<br>        const y2 = cell2.location[1]<br><br>        if (x1 === x2) {<br>            if (y1 &gt; y2) {<br>                cell1.walls.top = false<br>                cell2.walls.bottom = false<br>            } else {<br>                cell1.walls.bottom = false<br>                cell2.walls.top = false<br>            }<br>        } else if (y1 === y2) {<br>            if (x1 &gt; x2) {<br>                cell1.walls.left = false<br>                cell2.walls.right = false<br>            } else {<br>                cell1.walls.right = false<br>                cell2.walls.left = false<br>            }<br>        }<br>    }<br>}</pre><p>As a bonus exercise, we can use a similar approach to navigate the maze. Once again, after initializing a list for tracking visited cells and previous locations, the agent:</p><ol><li>Starts by checking if it has reached the destination. If so, it dies.</li><li>Else, it looks for unvisited neighboring cells that are linked to the one it currently stands in. It chooses one at random.</li><li>If there aren’t any, the agent backtracks once and starts over from step 1.</li><li>The agent moves to the new cell, updates the lists, and repeats from step 1.</li></ol><pre>import { Entities } from &#39;agentscape&#39;<br>import { CellGrid } from &#39;agentscape/structures&#39;;<br>import Cell from &#39;./Cell&#39;;<br>import { Color } from &#39;agentscape/numbers&#39;;<br>import Maze from &#39;./Model&#39;;<br><br>export interface NavigatorConstructor extends Entities.AgentConstructor {<br>    targetCell: Cell<br>}<br><br>export default class Navigator extends Entities.Agent {<br><br>    public override color = Color.fromName(&#39;red&#39;)<br><br>    public visitedCells: Cell[] = []<br><br>    public lastMove: [number, number][] = []<br>    public targetCell: Cell<br><br>    constructor(opts: NavigatorConstructor) {<br>        super(opts)<br>        this.targetCell = opts.targetCell<br>    }<br><br>    act(grid: CellGrid&lt;Cell&gt;) {<br>        <br>        const currentCell = this.getCell(grid)<br><br>        if (currentCell === this.targetCell) {<br>            this.die()<br>            return<br>        }<br><br>        // which neighbors are linked?<br>        const linkedNeighbors = this<br>            .getNeighborCells(grid)<br>            .filter(cell =&gt; this.areCellsLinked(currentCell, cell))<br><br>        // which linked neighbors have not been visited?<br>        const unvisitedNeighbors = linkedNeighbors<br>            .filter(cell =&gt; !this.visitedCells.includes(cell))<br><br>        if (unvisitedNeighbors.length &gt; 0) {<br>            // If an unvisited neighbor exists,<br>            // choose one at random<br>            // move to the neighbor cell.<br>            const neighbor = this.rng.pickRandom(unvisitedNeighbors)<br><br>            this.moveTo(grid, neighbor.location)<br>            this.visitedCells.push(neighbor)<br>            this.lastMove.push(neighbor.location)<br><br>            this.getCell(grid).color = Color.fromName(&#39;green&#39;)<br><br>        } else {<br>            // If there are no unvisited neighbors, backtrack to the previous cell.<br>            const lastMove = this.lastMove.pop()<br>            if (lastMove) {<br>                this.moveTo(grid, lastMove)<br>                this.getCell(grid).color = Color.fromName(&#39;white&#39;)<br>            } else {<br>                console.info(&#39;Navigator failed to find target cell&#39;)<br>                this.die()<br>            }<br>        }<br>    }<br><br>    private areCellsLinked(cell1: Cell, cell2: Cell) {<br>        const x1 = cell1.location[0]<br>        const y1 = cell1.location[1]<br>        const x2 = cell2.location[0]<br>        const y2 = cell2.location[1]<br><br>        if (x1 === x2) {<br>            if (y1 &gt; y2) {<br>                return !cell1.walls.top &amp;&amp; !cell2.walls.bottom<br>            } else {<br>                return !cell1.walls.bottom &amp;&amp; !cell2.walls.top<br>            }<br>        } else if (y1 === y2) {<br>            if (x1 &gt; x2) {<br>                return !cell1.walls.left &amp;&amp; !cell2.walls.right<br>            } else {<br>                return !cell1.walls.right &amp;&amp; !cell2.walls.left<br>            }<br>        }<br><br>        return false<br>    }<br>}</pre><p>A key principle of agent-based modeling is simplicity. This is another example demonstrating how simple instructions can give rise to complex behavior. However, the algorithm is limited in that it only supports a single agent. Perhaps performace can be increased by adding multiple agents to solve the problem in parallel?</p><h3>3. A* Path Finding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*d9AejcMbPne7iqFEXMJmzw.gif" /><figcaption>An agent replicates itself whenever it reaches a fork in the path and dies if it runs out of moves. The surviving agent reports its path on arrival to the target cell.</figcaption></figure><ul><li><a href="https://gitlab.com/ben_goodman/apps/agent-based-modelling/a-star">Source Code</a></li><li><a href="https://apps.ben.website/a-star/index.html">App</a></li></ul><p>A* (A-Star) is an algorithm for finding the shortest distances on a weighted graph, but it can be adapted to work on a grid of connected cells traversed by exploratory agents.</p><p>The cell class is simple and only requires properties for being an obstacle or a destination. If the cell is neither, then it is deemed traversable by the agent.</p><pre>import { Entities } from &#39;agentscape&#39;<br>import { Dynamic } from &#39;agentscape/entities/Cell&#39;<br>import { Color } from &#39;agentscape/numbers&#39;<br><br>export default class Cell extends Entities.Cell {<br><br>    public isObstacle = false<br>    public isDestination = false<br><br>    @Dynamic(self =&gt; {<br>        if (self.isDestination) {<br>            return Color.fromName(&#39;red&#39;)<br>        } else {<br>            return Color.fromName(self.isObstacle ? &#39;black&#39; : &#39;white&#39;)<br>        }<br>    })    <br>    public override color: Color<br>}</pre><p>The agent class, instantiated with a destination cell value and some initial position, implements A*:</p><p><strong>Step 1.</strong> The agent considers the unvisited, traversable neighboring cells and assigns each a value: <em>f = g + h</em></p><p>Where:</p><ul><li><em>f</em> : The cost of getting to the neighbor cell based on the current path.</li><li><em>g: </em>The estimated cost of getting to the destination from the neighbor cell (euclidean displacement).</li></ul><p>In each case, the ‘cost’ is simply the distance, as all traversable cells have equal weight.</p><p><strong>Step 2.</strong> If the agent has no unvisited neighbors, then it does one of the following:</p><ul><li><strong>Single Agent: </strong>It will backtrack to the last cell it visited and start over from Step 1.</li><li><strong>Multi-Agent:</strong> The agent will die and remove itself from the simulation.</li></ul><p><strong>Step 3.</strong> If the agent has one or more unvisited neighbors, the agent moves to the cell with the lowest <em>f </em>value and adds it to the set of visited cells. If a multi-agent system is used, and there is more than one unvisited neighbor, the agent will reproduce.</p><p>This is repeated until an agent reaches the destination cell.</p><p>For the multi-agent case, the trick is to make the visited cells set static. This means that all agents have access to the same set of visited cells.</p><pre>export default class Agent extends Entities.Agent {<br><br>    public override color: Color = Color.fromName(&#39;red&#39;)<br><br>    // used to stop the process when an agent finds the destination <br>    public static isDestinationReached = false<br>  <br>    // the set of cells that have been visited by an agent<br>    public static visited = new Set&lt;Cell&gt;()<br><br>    // used to ID which agent found the path<br>    public didFindDestination = false<br><br>    // the path taken by this agent and its ancestors.<br>    public path: Cell[] = []<br><br>...</pre><p>Then, the agent acts out the algorithm by exploring its neighboring cells and assigning <em>f</em> values.</p><pre>act(grid: CellGrid&lt;Cell&gt;, agentSet: { _default: AgentSet&lt;Agent&gt; } ) {<br>        // another agent has already reached the destination<br>        // this agent is no longer required <br>        if (Agent.isDestinationReached &amp;&amp; this.getCell(grid) !== this.destinationCell) {<br>            this.die()<br>            return<br>        }<br><br>        // if the agent has reached the destination<br>        // it will stop moving and report its success<br>        if (this.getCell(grid) === this.destinationCell) {<br>            Agent.isDestinationReached = true<br>            this.didFindDestination = true<br>            return<br>        }<br>            <br>        // otherwise, the agent must pick the next cell to move to<br>        const traversableNeighbors = this<br>            .getNeighborCells(grid, { includeDiagonals: this.allowDiagonals })<br>            .filter(cell =&gt; !cell.isObstacle)<br><br>        // assume there is at least one neighbor<br>        // if not, the agent is boxed in by obstacles<br>        if (traversableNeighbors.length === 0) {<br>            console.warn(&#39;Agent is stuck&#39;)<br>            this.die()<br>            return<br>        }<br><br>        // if the destination is a neighbor, move to it<br>        if (traversableNeighbors.includes(this.destinationCell)) {<br>            this.path.push(this.destinationCell)<br>            this.moveTo(grid, this.destinationCell.location)<br>            return<br>        }<br><br>        // consider unvisited neighbors<br>        const unvisitedNeighbors = traversableNeighbors.filter(cell =&gt; !Agent.visited.has(cell))<br><br>        // if there are no unvisited neighbors, backtrack or die,<br>        // depending on the model configuration.<br>        // multi-agent models do not require backtracking.<br>        if (unvisitedNeighbors.length === 0) {          <br>            if (this.allowMultiAgent) {<br>                this.die()<br>                return<br>            } else {<br>                // there is only one agent, so it must backtrack<br>                // to the last cell and start over.<br>                this.path.pop()<br>                const lastCell = this.path[this.path.length - 1]<br>                this.moveTo(grid, lastCell.location)<br>                return<br>            }<br>        }<br><br>        // if the agent reaches a fork in the road, it can reproduce<br>        // to explore multiple paths in parallel.<br>        if (this.allowMultiAgent &amp;&amp; unvisitedNeighbors.length &gt; 1) {<br>            const child = this.reproduce&lt;Agent&gt;()<br>            if (child) {<br>                // the child agent will continue the parent&#39;s path<br>                child.path = [...this.path]<br>                agentSet._default.add(child)<br>            }<br>        }<br><br>        // of the unvisited neighbors, choose the one with the lowest f value<br>        // where f = g + h<br>        const f = (neighborCell: Cell) =&gt; {<br>            const pathLength = this.path.reduce((acc, cell, i, array) =&gt; {<br>                return i === 0 ? acc : acc + cell.distanceTo(grid, array[i - 1])<br>            }, 0)<br>            // g = cost to get to cell based on current path<br>            const g = pathLength + this.distanceTo(grid, neighborCell)<br>            // h = estimated cost to get to destination<br>            const h = neighborCell.distanceTo(grid, this.destinationCell)<br>            return g + h<br>        }<br><br>        const nextCell = _Array.minimizeBy(unvisitedNeighbors, f)<br><br>        this.path.push(nextCell)<br>        Agent.visited.add(nextCell)<br>        this.moveTo(grid, nextCell.location)<br>    }</pre><p>What I found most satisfying about this project was how simple it was, extending into a multi-agent system and seeing the immense performance boost gained from it. It turns out there&#39;s a phrase for it: <a href="https://en.wikipedia.org/wiki/Embarrassingly_parallel">Embarrassingly Parallel</a>.</p><h3>4. Desire Paths</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Ck_K3dV-Sh_MRv3ZEbl7FQ.gif" /></figure><ul><li><a href="https://gitlab.com/ben_goodman/apps/agent-based-modelling/paths">Source Code</a></li><li><a href="https://apps.ben.website/paths/index.html">App</a></li></ul><p>Inspired by the <a href="https://ccl.northwestern.edu/netlogo/models/Paths">NetLogo</a> model, a <a href="https://en.wikipedia.org/wiki/Desire_path">desire path</a> is an unplanned trail caused by ground erosion due to foot traffic. In this model, the user clicks on the field to place destinations for agents to navigate to. As they walk along the field, they contribute small amounts of erosion, which build up to a threshold, at which point the cell becomes a path (brown). Agents prefer to walk on paths versus grass, and so the trail re-enforces itself over time.</p><pre>import { Entities } from &#39;agentscape&#39;<br>import _Array from &#39;agentscape/numbers/Array&#39;<br>import { Color } from &#39;agentscape/numbers&#39;<br>import { DynamicTrait } from &#39;agentscape/entities/Agent&#39;<br>import { CellGrid } from &#39;agentscape/structures&#39;<br>import PathEvolution from &#39;./Model&#39;<br>import Cell from &#39;./Cell&#39;<br><br>export default class Agent extends Entities.Agent {<br><br>    public override color = Color.fromName(&#39;white&#39;)<br>    <br>    public override dt = 1<br><br>    // thre agent&#39;s randomly picked final destination<br>    public destination: Entities.Cell = undefined<br>    <br>    // intermediate destinations<br>    public destinations: Cell[] = []<br><br>    // this enables the value to be adjusted at runtime<br>    // via the UI.<br>    @DynamicTrait( _ =&gt; PathEvolution.agentSightRange )<br>    public override sightRange: number<br><br>    act(grid: CellGrid&lt;Cell&gt;) {<br>        // agents pick a destination at random if they don&#39;t have one.<br>        // Then, they look to find closer, intermediate destinations.<br>        if (this.destinations.length === 0) {<br>            const allDestinations = [...PathEvolution.destinationCells]<br><br>            const finalDestination = this.rng.pickRandom(allDestinations) || grid.random(this.rng)<br>            <br>            // are there destinations that are closer to the agent than the initial destination?<br>            const closerDestinations = allDestinations<br>                .filter(cell =&gt; cell !== finalDestination)<br>                .filter(cell =&gt; cell.distanceTo(grid, this) &lt; finalDestination.distanceTo(grid, this))<br>                .sort((a, b) =&gt; a.distanceTo(grid, this) - b.distanceTo(grid, this))<br><br>            // if there are closer destinations, add them to the list<br>            if (closerDestinations.length &gt; 0) {<br>                this.destinations = [...closerDestinations, finalDestination]<br>            } else {<br>                this.destinations = [finalDestination]<br>            }<br><br>            this.destination = this.destinations.pop()<br>        }<br><br>        const distanceToDestination = this.distanceTo(grid, this.destination)<br><br>        // if we&#39;ve reached the destination, unset it<br>        if (distanceToDestination &lt; 0.5) {<br>            this.destination = this.destinations.pop()<br>            return<br>        }<br><br>        const allNeighbors = this.getCellsWithinRange(grid)<br><br>        // are any of the neighbor cells paths?<br>        // and if so, do any of them bring the agent closer to the destination?<br>        const pathNeighbors = allNeighbors<br>            .filter(cell =&gt; cell.isPath)<br>            .filter(cell =&gt; cell.distanceTo(grid, this.destination) &lt; distanceToDestination)<br><br>        // if there are path cells, only consider those<br>        const neighbors = pathNeighbors.length &gt; 0 ? pathNeighbors : allNeighbors<br>        <br>        // choose the cell closest to the destination<br>        const closest = _Array.minimizeBy(neighbors, (cell) =&gt; cell.distanceTo(grid, this.destination))<br><br>        this.faceCell(grid, closest)<br>        // move to the closest cell<br>        this.move(grid)<br><br>        const currentCell = this.getCell(grid)<br>        currentCell.erode()<br>    }<br>}<br><br></pre><p>The model’s cell class has a method for regrowing grass with each time step. The probability that grass regrows is derived from a function of the cell’s current height, such that shorter grass is less likely to regrow than longer grass. Regrowing at a fixed rate also works — I just did it the other way for fun.</p><pre>import { Entities } from &#39;agentscape&#39;<br>import { Dynamic } from &#39;agentscape/entities/Cell&#39;<br>import { Color, RandomGenerator } from &#39;agentscape/numbers&#39;<br>import PathEvolution from &#39;./Model&#39;<br><br>export interface CellConstructor extends Entities.CellConstructor {<br>    grassGrowthRate: number<br>    grassErosionRate: number<br>}<br><br>export default class Cell extends Entities.Cell {<br><br>    @Dynamic( self =&gt; {<br>        if ( self.isDestination ) {<br>            return Color.fromName(&#39;red&#39;)<br>        } else if (self.isPath) {<br>            return Color.fromName(&#39;brown&#39;)<br>        } else {<br>            return Color.fromRGB(0, self.grassHeight * 255, 0)<br>        }<br>    })<br>    public override color: Color<br><br>    @Dynamic(self =&gt; {<br>        // as an experiment, the probability for the grass to regrow is determined by<br>        // the current height of the grass such that taller(shorter) grass is more(less) likely to regrow.  <br>        return Math.max(0.1, 1 / (1 + Math.exp(-5 * (self.grassHeight - PathEvolution.pathThreshold))))<br>    })<br>    public growthProbability: number<br><br>    @Dynamic( self =&gt; self.grassHeight &lt; PathEvolution.pathThreshold)<br>    public isPath: boolean<br><br>    public isDestination: boolean<br><br>    public grassHeight: number<br><br>    public grassGrowthRate: number<br><br>    public grassErosionRate: number<br><br>    constructor(opts: CellConstructor) {<br>        super(opts)<br>        this.grassHeight = 1<br>        this.isDestination = false<br>        this.grassGrowthRate = opts.grassGrowthRate<br>        this.grassErosionRate = opts.grassErosionRate<br>    }<br><br>    erode() {<br>        this.grassHeight = Math.max(0, this.grassHeight - this.grassErosionRate)<br>    }<br><br>    regrow(rng: RandomGenerator): void {<br>        if (this.grassHeight &lt; 1) {<br>            if (rng.uniformFloat(0, 1) &lt; this.growthProbability) {<br>                this.grassHeight = Math.min(1, this.grassHeight + this.grassGrowthRate)<br>            }<br>        }<br>    }<br><br>}</pre><p>If you find a real-life satisfaction in desire paths then you’ll get minutes of enjoyment from this model.</p><h3>Predators &amp; Prey: Evolution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*ajbzL6IrpbNzJq2r-vkH1g.gif" /><figcaption>Wolves chase sheep for food, applying a form of natrual selection based on stride length.</figcaption></figure><ul><li><a href="https://gitlab.com/ben_goodman/apps/agent-based-modelling/predators-and-prey-evolution">Source Code</a></li><li><a href="https://apps.ben.website/predators-and-prey-evolution">App</a></li></ul><p>Sheep graze on grass and flee from wolves. Wolves chase down and eat sheep. At each simulation step, both agent types move a distance according to their stride length. This is an extension of a <a href="https://apps.ben.website/predators-and-prey/index.html">simpler model</a> where agents could eat and reproduce but only move a fixed distance at each time step.</p><p>This model changes that by allowing the agent’s stride length to mutate by small amounts over generations such that predation on sheep by wolves will apply selective pressure on sheep populations to evolve greater stride lengths.</p><p>The sheep starts with an initial stride length set by the user (default: 0.1 cell length). The sheep acts by:</p><ol><li>Checking if it can reproduce. If so, it reproduces with the neighboring sheep with the greatest stride length. This selection should give the sheep an evolutionary edge over the wolves.</li><li>The sheep then considers any wolves it can see. It flees the wolves by pointing itself away from the center of mass of the nearby wolfpack and moving forward a stride length.</li><li>If there are no wolves in sight, the sheep will wander randomly.</li><li>With each step, the sheep eats the grass cell it is standing on.</li></ol><pre>import Agent, { GeneticTrait, Hungry, type AgentConstructor } from &#39;agentscape/entities/Agent&#39;<br>import { AgentSet, CellGrid } from &#39;agentscape/structures&#39;<br>import { Color, Vector2, Array as _Array } from &#39;agentscape/numbers&#39;<br><br>import Wolf from &#39;./Wolf&#39;<br>import Grass from &#39;./Grass&#39;<br><br>interface SheepConstructor extends AgentConstructor {<br>    initialStrideLength: number<br>}<br><br>// the Hungry decorator means the agent<br>// looses energy with each step.<br>@Hungry<br>export default class Sheep extends Agent {<br>    override color = Color.fromName(&#39;white&#39;)<br><br>    // the distance the sheep can move in one step<br>    // a stride length of 1 means the sheep can one cell in one step.<br>    // A mutated value of this trait will be passed down to child agents.<br>    @GeneticTrait({ min: 0, max: 1 })<br>        strideLength: number<br><br>    constructor(opts: SheepConstructor) {<br>        super(opts)<br>        this.strideLength = opts.initialStrideLength<br>    }<br><br>    public act(<br>        field: CellGrid&lt;Grass&gt;,<br>        agentSets: {sheep: AgentSet&lt;Sheep&gt;, wolf: AgentSet&lt;Wolf&gt;}<br>    ): void {<br>        if (!this.isAlive) {<br>            return<br>        }<br><br>        // sheep will reproduce if it has enough energy<br>        if (this.energy &gt;= this.reproductionThreshold) {<br>            const others = agentSets.sheep.getWithinRange(field, this.position.components, 1)<br>            if (others.size &gt;= 1) {<br>                // sheep selects the other sheep with the longest stride length<br>                const other = _Array.maximizeBy([...others], (s) =&gt; s.strideLength)<br>                const child = this.reproduce({ other })<br>                if (child) {<br>                    agentSets.sheep.add(child)<br>                }<br>            }<br>        }<br><br>        const neighborWolves = this.getAgentsWithinRange(field, agentSets.wolf)<br>        <br>        // sheep moves away from wolves it can see<br>        if (neighborWolves.size &gt; 0) {<br>            // get the center of mass of the neighboring wolves<br>            const packCentroid = new Vector2(neighborWolves.getCentroid())<br><br>            // get the vector pointing away from the centroid<br>            const fleeTo = this.position.subtract(packCentroid).normal<br><br>            // get the cell to flee to<br>            const fleeToCell = field.getCellNearest(this.position.add(fleeTo).components)<br><br>            this.faceCell(field, fleeToCell)<br>            this.move(field, this.strideLength)<br>            this.eat(this.getCell(field))<br><br>            return<br>        }<br><br>        // sheep wanders around<br>        this.wander(field, {strideLength: this.strideLength})<br>        this.eat(this.getCell(field))<br>    }<br>}</pre><p>The wolf agent also has a mutating stride length, and wolf populations will evolve greater stride lengths in response to faster sheep. Wolves chase sheep by simply pointing towards one and moving forward a stride length. The wolf then eats any sheep it occupies the same cell as.</p><pre>import Agent, { GeneticTrait, Hungry, type AgentConstructor } from &#39;agentscape/entities/Agent&#39;<br>import { AgentSet, CellGrid } from &#39;agentscape/structures&#39;<br>import { Color } from &#39;agentscape/numbers&#39;<br><br>import Sheep from &#39;./Sheep&#39;<br>import Grass from &#39;./Grass&#39;<br><br>interface WolfConstructor extends AgentConstructor {<br>    initialStrideLength: number<br>}<br><br>@Hungry<br>export default class Wolf extends Agent {<br><br>    override color = Color.fromName(&#39;yellow&#39;)<br><br>    // the sheep the wolf is currently chasing<br>    private targetPrey?: Sheep = undefined<br><br>    // the distance the wolf can move in one step<br>    @GeneticTrait({ min: 0, max: 3 })<br>        strideLength: number<br><br>    constructor(opts: WolfConstructor) {<br>        super(opts)<br>        this.strideLength = opts.initialStrideLength<br>    }<br><br>    act(<br>        field: CellGrid&lt;Grass&gt;,<br>        agentSets: {sheep: AgentSet&lt;Sheep&gt;, wolf: AgentSet&lt;Wolf&gt;}<br>    ): void {<br><br>        if (!this.isAlive) {<br>            return<br>        }<br><br>        // wolf will reproduce if it has enough energy<br>        if (this.energy &gt;= this.reproductionThreshold) {<br>            const child = this.reproduce&lt;Wolf&gt;()<br>            if (child) {<br>                agentSets.wolf.add(child)<br>            }<br>        }<br><br>        // wolf chases a target sheep<br>        if (this.targetPrey) {<br>            if (!this.targetPrey.isAlive) {<br>                this.targetPrey = undefined<br>                return<br>            }<br><br>            this.faceAgent(field, this.targetPrey)<br>            this.move(field, this.strideLength)<br>            <br>            if (this.targetPrey.getCell(field) === this.getCell(field)) {<br>                this.eat(this.targetPrey)<br>                this.targetPrey = undefined<br>            }<br><br>            return<br>        }<br><br><br>        // wolf will pick a random sheep it can see and <br>        // set it as a target.<br>        if (!this.targetPrey) {<br>            this.targetPrey = this<br>                .getAgentsWithinRange(field, agentSets.sheep)<br>                .minimizeBy(s =&gt; this.distanceTo(field, s))<br>            if (this.targetPrey) {<br>                this.act(field, agentSets)<br>            } else {<br>                this.wander(field, {strideLength: this.strideLength})<br>            }<br>            return<br>        }<br><br>    }<br>}</pre><p>At first, sheep are slow and vulnerable but the population eventually rebounds as faster sheep begin to emerge. Its very satisfying to watch.</p><h3>Rock, Paper, Scissors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*MsLklpMGWWutfEdRc92xOQ.gif" /><figcaption>A never ending game of rock (red), paper (blue) and scissors (green).</figcaption></figure><ul><li><a href="https://gitlab.com/ben_goodman/apps/agent-based-modelling/rock-paper-scissors">Source Code</a></li><li><a href="https://apps.ben.website/rock-paper-scissors/index.html">App</a></li></ul><p>Another model adapted from <a href="https://ccl.northwestern.edu/netlogo/models/RockPaperScissors">NetLogo</a>, this one is a (sometimes) unending game of <em>rock, paper, scissors, (lizard, Spock)</em>.</p><p>This model is similar to the predator and prey model from earlier in that it examines changing populations of competing agents. In this case, however, there is a single agent type with a strategy (rock, paper, etc.).</p><p>At each time step, the agent does a combination of the following actions:</p><ol><li>Reproduce — The agent creates a new agent using the same strategy in a random empty neighboring cell.</li><li>Move — The agent swaps positions with a random neighbor.</li><li>Play — The agent plays against a neighboring agent. The loser dies and is removed from the grid.</li></ol><p>A Poisson distribution defines the rate at which these actions occur. The actions are then shuffled and played out while the agent is still alive.</p><pre>import Cell from &#39;agentscape/entities/Cell&#39;<br>import Agent, { AgentStyle, DynamicTrait, Trait, type AgentConstructor } from &#39;agentscape/entities/Agent&#39;<br>import { Color } from &#39;agentscape/numbers&#39;<br>import { AgentSet, CellGrid } from &#39;agentscape/structures&#39;<br><br>export enum Strategy {<br>    Rock = &#39;rock&#39;,<br>    Paper = &#39;paper&#39;,<br>    Scissors = &#39;scissors&#39;,<br>    Lizard = &#39;lizard&#39;,<br>    Spock = &#39;spock&#39;<br>}<br><br>export interface PlayerConstructor extends AgentConstructor {<br>    strategy: Strategy<br>    playRate: number<br>    moveRate: number<br>    reproduceRate: number<br>}<br><br>export default class Player extends Agent {<br><br>    public override style = AgentStyle.SQUARE<br>    public override strokeColor = undefined<br><br>    @Trait()<br>    public strategy: Strategy<br><br>    @Trait()<br>    public playRate: number<br><br>    @Trait()<br>    public moveRate: number<br><br>    @Trait()<br>    public reproduceRate: number<br><br>    @DynamicTrait( self =&gt; {<br>        switch (self.strategy) {<br>            case &#39;rock&#39;:<br>                return Color.fromName(&#39;red&#39;)<br>            case &#39;paper&#39;:<br>                return Color.fromName(&#39;blue&#39;)<br>            case &#39;scissors&#39;:<br>                return Color.fromName(&#39;green&#39;)<br>            case &#39;lizard&#39;:<br>                return Color.fromName(&#39;orange&#39;)<br>            case &#39;spock&#39;:<br>                return Color.fromName(&#39;purple&#39;)<br>        }})<br>        color: Color<br><br>    constructor(opts: PlayerConstructor) {<br>        super(opts)<br>        this.strategy = opts.strategy<br>        this.playRate = opts.playRate<br>        this.moveRate = opts.moveRate<br>        this.reproduceRate = opts.reproduceRate<br>    }<br><br>    act(<br>        grid: CellGrid&lt;Cell&gt;,<br>        agentSets: { players: AgentSet&lt;Player&gt; }<br>    ) {<br>        const players = agentSets.players as unknown as AgentSet&lt;Player&gt;<br><br>        const repetitions = Math.floor(grid.width / 3 )<br>        <br>        const playEvents = Array.from({ length: this.rng.poissonInt(repetitions * this.playRate) }, () =&gt; 0)<br>        <br>        const moveEvents = Array.from({ length: this.rng.poissonInt(repetitions * this.moveRate) }, () =&gt; 1)<br>        <br>        const reproduceEvents = Array.from({ length: this.rng.poissonInt(repetitions * this.reproduceRate) }, () =&gt; <br><br>        const events = this.rng.shuffle([<br>            ...playEvents,<br>            ...moveEvents,<br>            ...reproduceEvents<br>        ])<br><br>        // execute the events while still alive<br>        for (const event of events) {<br>            if (!this.isAlive) {<br>                return<br>            }<br>            switch (event) {<br>                case 0:<br>                    this.playEvent(grid)<br>                    break<br>                case 1:<br>                    this.moveEvent(grid)<br>                    break<br>                case 2:<br>                    this.reproduceEvent(grid, players)<br>                    break<br>            }<br>        }<br>    }<br>    <br>    reproduceEvent(grid: CellGrid&lt;Cell&gt;, agentSet: AgentSet&lt;Player&gt;): void {<br>        const emptyNeighbors = this.getNeighborCells(grid).filter( cell =&gt; cell.tenantAgents.size === 0 )<br>        if (emptyNeighbors.length &gt; 0) {<br>            const childPosition = this.rng.pickRandom(emptyNeighbors).location<br>            const child = this.reproduce&lt;this&gt;({<br>                childPosition<br>            })<br>            agentSet.add(child, grid)<br>        }<br>    }<br><br>    // swaps positions with a random neighbor<br>    moveEvent(grid: CellGrid&lt;Cell&gt;): void {<br>        const randomNeighbor = this.getNeighbors(grid).random(this.rng)<br>        if (randomNeighbor) {<br>            this.swap(grid, randomNeighbor)<br>        }<br>    }<br>    <br>    // pick a random neighboring agent to play with<br>    playEvent(grid: CellGrid&lt;Cell&gt;): void {<br>        const randomNeighbor = this.getNeighbors(grid).random(this.rng)<br>        if (!randomNeighbor) {<br>            return<br>        }<br><br>        switch (this.strategy) {<br>            // rock beats scissors &amp; lizard and looses to paper &amp; spock<br>            case Strategy.Rock:<br>                if (randomNeighbor.strategy === Strategy.Scissors || randomNeighbor.strategy === Strategy.Lizard) {<br>                    randomNeighbor.die()<br>                } else if (randomNeighbor.strategy === Strategy.Paper || randomNeighbor.strategy === Strategy.Spock) {<br>                    this.die()<br>                } else {<br>                    return<br>                }<br>                break<br>            // scissors beats paper &amp; lizard and looses to rock &amp; spock<br>            case Strategy.Scissors:<br>                if (randomNeighbor.strategy === Strategy.Paper || randomNeighbor.strategy === Strategy.Lizard) {<br>                    randomNeighbor.die()<br>                } else if (randomNeighbor.strategy === Strategy.Rock || randomNeighbor.strategy === Strategy.Spock) {<br>                    this.die()<br>                } else {<br>                    return<br>                }<br>                break<br>            // paper beats rock &amp; spock and looses to scissors &amp; lizard<br>            case Strategy.Paper:<br>                if (randomNeighbor.strategy === Strategy.Rock || randomNeighbor.strategy === Strategy.Spock) {<br>                    randomNeighbor.die()<br>                } else if (randomNeighbor.strategy === Strategy.Scissors || randomNeighbor.strategy === Strategy.Lizard) {<br>                    this.die()<br>                } else {<br>                    return<br>                }<br>                break<br>            // lizard beats spock &amp; paper and looses to rock &amp; scissors<br>            case Strategy.Lizard:<br>                if (randomNeighbor.strategy === Strategy.Spock || randomNeighbor.strategy === Strategy.Paper) {<br>                    randomNeighbor.die()<br>                } else if (randomNeighbor.strategy === Strategy.Rock || randomNeighbor.strategy === Strategy.Scissors) {<br>                    this.die()<br>                } else {<br>                    return<br>                }<br>                break<br>            // spock beats scissors &amp; rock and looses to paper &amp; lizard<br>            case Strategy.Spock:<br>                if (randomNeighbor.strategy === Strategy.Scissors || randomNeighbor.strategy === Strategy.Rock) {<br>                    randomNeighbor.die()<br>                } else if (randomNeighbor.strategy === Strategy.Paper || randomNeighbor.strategy === Strategy.Lizard) {<br>                    this.die()<br>                } else {<br>                    return<br>                }<br>                break<br>        }<br>    }<br>}</pre><p>This model is interesting since it extends the typical population dynamic into 3 or 5 competing species using a different approach of having multiple agent events per step. The population results are still comparable with a typical predator/prey system (i.e. <a href="https://en.wikipedia.org/wiki/Lotka%E2%80%93Volterra_equations">Lotka–Volterra predator–prey model</a>) though.</p><h3>Conclusion</h3><p>That concludes this compliation of ABMs. For more ABMs, see my <a href="https://gitlab.com/ben_goodman/apps/agent-based-modelling">GitLab repository</a> or <a href="https://apps.ben.website/">website</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c9749373376" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/six-more-satisfying-agent-based-models-7c9749373376">Six More Satisfying Agent-Based Models</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Listing AWS S3 Buckets with Lambda and OpenGraph]]></title>
            <link>https://awstip.com/listing-aws-s3-buckets-with-lambda-and-opengraph-c6b339bee44c?source=rss-2f01806d4793------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6b339bee44c</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Benjamin Goodman]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 19:12:43 GMT</pubDate>
            <atom:updated>2024-12-24T18:08:50.206Z</atom:updated>
            <content:encoded><![CDATA[<h4>Automatically generating a human-readable sitemap for an S3 bucket using a Lambda function.</h4><p>An S3 bucket combined with a CloudFront distribution can be used to serve static content in a cheap and easy manner. In this case, the static content is web applications synced to S3 from a CI/CD pipeline. Each application is its own directory at the bucket’s root, which is served by CloudFront from <a href="https://apps.ben.website/">https://apps.ben.website</a> such that an application’s URL becomes https://apps.ben.website/&lt;APP_NAME&gt; - e.g., apps.ben.website/app_1.</p><pre> .<br> ├── app_1<br> │   ├── index.html<br> │   ├── ...<br> │   └── abc123.js<br> ├── app_2 <br> │   ├── index.html<br> │   ├── ...<br> │   └── abc123.js<br> ...</pre><p>With CloudFront, there is a default root object option that applies to requests for the root URL and serves a specified object, meaning you can configure CloudFront to resolve foo.com as foo.com/bar.baz. However, this behavior doesn&#39;t extend to &#39;sub-directories&#39; of the origin - or in other words, you can&#39;t do the equivalent of &quot;if navigating to foo.com/*/ then actually return foo.com/*/index.html”. Fortunately, we can apply this behavior ourselves with a CloudFront function triggered by a viewer request event.</p><pre>function handler(event) {<br>    var request = event.request<br><br>    // case of navigating elsewhere in the site<br>    var splitUri = request.uri.split(&#39;/&#39;)<br>    if (splitUri[splitUri.length - 1].indexOf(&#39;.&#39;) &lt; 0) {<br>        request.uri += &#39;/index.html&#39;<br>    }<br><br>    return request<br>}</pre><p>I like this setup because I can create new hosted applications without provisioning new infrastructure. However, without some form of a sitemap, its unclear how to navigate to the apps in the S3 bucket unless you know the exact name of the S3 object it is filed under.</p><p>The solution is to use a lambda function that generates the sitemap as an HTML file and syncs it to the S3 bucket with the key index.html. An S3 object event triggers the lambda function, so uploading any changes to the shared app bucket from the app&#39;s CI/CD pipeline will result in an updated index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*lxmJePGuXxUW6kdFjdd0qQ.png" /></figure><h3>Triggering the Lambda Function</h3><p>We start by defining the permissions the Lambda function will need to list, get, and put objects to the S3 bucket origin.</p><pre>resource &quot;aws_iam_role&quot; &quot;lambda_role&quot; {<br>  name = &quot;lambda-role-multi-app-hosting&quot;<br><br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [{<br>      Effect = &quot;Allow&quot;<br>      Principal = {<br>          Service: [<br>              &quot;lambda.amazonaws.com&quot;,<br>          ]<br>      }<br>      Action = &quot;sts:AssumeRole&quot;<br>    }]<br>  })<br>}<br><br>resource &quot;aws_iam_policy&quot; &quot;assets_bucket_access_policy&quot; {<br>  name = &quot;s3-access-policy-multi-app-hosting&quot;<br><br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>      {<br>        Effect = &quot;Allow&quot;<br>        Action = [<br>            &quot;s3:ListBucket&quot;,<br>            &quot;s3:GetObject&quot;,<br>            &quot;s3:PutObject&quot;,<br>        ]<br>        Resource = [<br>          &quot;arn:aws:s3:::multi-app-hosting-default-dev.bgoodman&quot;,<br>          &quot;arn:aws:s3:::multi-app-hosting-default-dev.bgoodman/*&quot;<br>        ]<br>      }<br>    ]<br>  })<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;assets_bucket_access_policy_attachment&quot; {<br>  role       = aws_iam_role.lambda_role.name<br>  policy_arn = aws_iam_policy.assets_bucket_access_policy.arn<br>}</pre><p>The Lambda function itself is unremarkable — a NodeJS setup with an environment variable for the S3 bucket name. The function’s trigger is a aws_s3_bucket_notification which observes changes to any *.js file. It is crucial to include this filter since it prevents recursive invocations whenever the sitemap HTML file is uploaded to the bucket.</p><pre># builds lambda source code and generates a zip archive<br>module &quot;sitemap_generator_payload&quot; {<br>    source  = &quot;gitlab.com/ben_goodman/lambda-function/aws//modules/code_builder&quot;<br>    version = &quot;4.0.0&quot;<br><br>    working_dir     = &quot;${path.module}/sitemap_generator&quot;<br>    command   = &quot;npm  ci &amp;&amp; npm run build&quot;<br>    archive_source_file = &quot;${path.module}/sitemap_generator/dist/index.js&quot;<br>}<br><br><br># provisions a lambda function with an env. var for the bucket name<br>module &quot;sitemap_generator_lambda_function&quot; {<br>    source  = &quot;gitlab.com/ben_goodman/lambda-function/aws&quot;<br>    version = &quot;4.0.0&quot;<br><br>    function_name    = &quot;${var.project_name}-sitemap-generator-${terraform.workspace}&quot;<br>    lambda_payload   = module.sitemap_generator_payload.archive_file<br>    function_handler = &quot;index.handler&quot;<br>    memory_size      = 512<br>    role             = aws_iam_role.lambda_role<br>    runtime          = &quot;nodejs18.x&quot;<br><br>    environment_variables = {<br>        BUCKET_NAME = &quot;multi-app-hosting-default-dev.bgoodman&quot;<br>    }<br>}<br><br><br># Allows s3 events to invoke the function<br>resource &quot;aws_lambda_permission&quot; &quot;allow_bucket&quot; {<br>  statement_id  = &quot;AllowExecutionFromS3Bucket&quot;<br>  action        = &quot;lambda:InvokeFunction&quot;<br>  function_name = module.sitemap_generator_lambda_function.arn<br>  principal     = &quot;s3.amazonaws.com&quot;<br>  source_arn    = &quot;arn:aws:s3:::multi-app-hosting-default-dev.bgoodman&quot;<br>}<br><br># Triggers the lambda function when a `*.js` file is created or deleted<br>resource &quot;aws_s3_bucket_notification&quot; &quot;bucket_notification&quot; {<br>  bucket = &quot;multi-app-hosting-default-dev.bgoodman&quot;<br><br>  lambda_function {<br>    lambda_function_arn = module.sitemap_generator_lambda_function.arn<br>    events              = [&quot;s3:ObjectCreated:*&quot;, &quot;s3:ObjectRemoved:*&quot;]<br>    filter_suffix       = &quot;.js&quot;<br>  }<br><br>  depends_on = [aws_lambda_permission.allow_bucket]<br>}</pre><h3>Generating a Sitemap</h3><p>This is the bucket we want to map. The goal is to write a function to get an array of object keys representing each application. We’ll do this by listing the bucket’s objects and filtering them for index.html files - each being the entry point of an application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwoPeeKD_E_SgKvcnoVNAw.png" /></figure><p>We start by listing all objects in the bucket.</p><pre>const getObjects = async (): Promise&lt;string[]&gt; =&gt; {<br>    const s3 = new S3()<br>    const objects = await s3.listObjectsV2({ Bucket: BUCKET_NAME }).promise()<br>    const objectKeys = objects.Contents?.map((object) =&gt; {<br>        return object.Key<br>    })<br><br>    return objectKeys<br>}</pre><p>The array of object keys is filtered only to return those ending in /index.html. This excludes the site map since its key does not start with a slash.</p><pre>const objectKeys = await getObjects()<br><br>// get keys ending in /index.html<br>const indexObjects = objectKeys.filter((key) =&gt; key.endsWith(&#39;/index.html&#39;))</pre><p>The array is then used to generate anchor tags, allowing the user to navigate to each app.</p><pre>const links = indexObjects.map((object) =&gt; {<br>    const dirName = object.split(&#39;/&#39;)[0]<br>    return `&lt;a class=&quot;default-link&quot; href=&quot;${object}&quot;&gt;&lt;h2&gt;${dirName}&lt;/h2&gt;&lt;/a&gt;`<br>})</pre><p>This results in a simple list of links which can be joined with br tags and wrapped in a div.</p><pre>&lt;div id=&quot;root&quot;&gt;<br>    &lt;a class=&quot;default-link&quot; href=&quot;ants/index.html&quot;&gt;<br>        &lt;h2&gt;ants&lt;/h2&gt;<br>    &lt;/a&gt;<br><br>    &lt;br&gt;<br><br>    &lt;a class=&quot;default-link&quot; href=&quot;boids-rs/index.html&quot;&gt;<br>        &lt;h2&gt;boids-rs&lt;/h2&gt;<br>    &lt;/a&gt;<br><br>    &lt;br&gt;<br><br>    &lt;a class=&quot;default-link&quot; href=&quot;boids/index.html&quot;&gt;<br>        &lt;h2&gt;boids&lt;/h2&gt;<br>    &lt;/a&gt;<br><br>    &lt;br&gt;<br><br>    &lt;a class=&quot;default-link&quot; href=&quot;brownian-motion/index.html&quot;&gt;<br>        &lt;h2&gt;brownian-motion&lt;/h2&gt;<br>    &lt;/a&gt;<br><br>    ...<br>&lt;/div&gt;</pre><p>This forms the basis for the index.html document that will be written to the root of the S3 bucket whenever the Lambda function runs.</p><pre>export const handler = async (event: S3Event ) =&gt; {<br>    const objectKeys = await getObjects()<br><br>    // get keys ending in /index.html<br>    const indexObjects = objectKeys.filter((key) =&gt; key.endsWith(&#39;/index.html&#39;))<br><br><br>    // generates a complete html document with application links as anchor tags.<br>    const indexHtml = generateIndexPage(indexObjects)<br><br>    // put the objects into an s3 object /index.html<br>    await s3.send(new PutObjectCommand({<br>        Bucket: BUCKET_NAME,<br>        Key: &#39;index.html&#39;,<br>        Body: indexHtml,<br>        ContentType: &#39;text/html&#39;,<br>        CacheControl: &#39;max-age=0&#39;<br>    }))<br>}</pre><p>At this stage, we now have a functioning sitemap which is automatically generated whenever a javascript file change is observed in the bucket. However, without any additional data, the list is not very descriptive — but we can improve on this by adding OpenGraph metadata to each hosted app and then using that to render something more presentable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OrqZegGTNwbhvckbO13AkQ.png" /></figure><h3>Enabling OpenGraph</h3><p>OpenGraph is the protocol responsible for creating the website previews that appear in rich text media when referencing a URL. The presented data is defined in the site’s html document using meta tags. Each application in the S3 bucket has an index.html similar to the one below, which contains the app&#39;s name, description, URL, and link to a preview image. The client will retrieve this information when the page loads, and is used to replace the standard hyperlinks that the Lamba function generated.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;meta property=&quot;og:title&quot; content=&quot;Predators and Prey&quot;&gt;<br>    &lt;meta property=&quot;og:description&quot; content=&quot;Simulated populations of sheep and wolves.&quot;&gt;<br>    &lt;meta property=&quot;og:url&quot; content=&quot;https://apps.ben.website/predators-and-prey&quot;&gt;<br>    &lt;meta property=&quot;og:image&quot; content=&quot;https://apps.ben.website/predators-and-prey/index.png&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;./index.css&quot;&gt;<br>    &lt;title&gt;Predators &amp; Prey&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    &lt;script type=&quot;module&quot; src=&quot;./src/index.ts&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>The OpenGraph logic is a small block of Javascript embedded in the generated sitemap HTML file. It’s essential not to include additional Javascript files since that will invoke the Lambda function (recursively, in this case). The script uses the npm package <a href="https://www.npmjs.com/package/fetch-opengraph">fetch-opengraph</a>, which retrieves OpenGraph metadata from a given URL as a JSON object that will be used to create a more informative link, complete with a preview image and description.</p><pre>import { fetch as fetchOpengraph } from &#39;https://cdn.jsdelivr.net/npm/fetch-opengraph@1.0.36/+esm&#39;<br>// enumerate the Lambda-generated links<br>const links = document.querySelectorAll(&#39;.default-link&#39;)<br>// replace each one with a metadata-based preview <br>links.forEach((link) =&gt; {<br>    fetchOpengraph(link.href).then((data) =&gt; {<br>        const title = data.ogTitle ? data.ogTitle : data.title<br>        const description = data.ogDescription ? data.ogDescription : data.description<br>        const image = data.ogImage ? data.ogImage.url : data.image<br>        const url = data.ogUrl ? data.ogUrl : data.url<br>        const html = `<br>        &lt;a class=&quot;og-link&quot; href=\${url}&gt;<br>            &lt;h2&gt;\${title}&lt;/h2&gt;<br>            &lt;p&gt;\${description}&lt;/p&gt;<br>            &lt;img src=&quot;\${image}&quot; /&gt;<br>        &lt;/a&gt;<br>        `<br>        link.outerHTML = html<br>    })<br>})</pre><p>When the page loads, the default links are replaced with the new OpenGraph previews.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gI2S_CvVTMQxExCV-Ic1A.png" /></figure><h3>Conclusion</h3><p>The system works remarkably well and is reliable to the point of forgetting it exists. The code for the multi-app hosting infrastructure is <a href="https://gitlab.com/ben_goodman/utility/multi-app-hosting">here</a>, and an example of an app using it is <a href="https://gitlab.com/ben_goodman/apps/agent-based-modelling/ants/-/blob/main/.gitlab-ci.yml">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6b339bee44c" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/listing-aws-s3-buckets-with-lambda-and-opengraph-c6b339bee44c">Listing AWS S3 Buckets with Lambda and OpenGraph</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Five Javascript Simulations to Satisfy Your Curiosity]]></title>
            <link>https://blog.devgenius.io/five-javascript-simulations-to-satisfy-your-curiosity-8216fe49ebe4?source=rss-2f01806d4793------2</link>
            <guid isPermaLink="false">https://medium.com/p/8216fe49ebe4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[complexity]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[agent-based-modeling]]></category>
            <dc:creator><![CDATA[Benjamin Goodman]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 03:01:47 GMT</pubDate>
            <atom:updated>2024-12-24T18:01:17.436Z</atom:updated>
            <content:encoded><![CDATA[<p>To get inspiration for my next project, I recently purchased a copy of <em>An Introduction to Agent-Based Modeling</em> by Uri Wilensky and William Rand. It&#39;s a great text that breaks down complex systems into simple and easy to implement models using NetLogo. As a software developer, however, part of the fun of this project was making my own tools — in this case, a library — to build the models with. So I wrote <a href="https://www.npmjs.com/package/agentscape">agentscape</a> which is very much inspired by NetLogo and was used to create the programs below.</p><h3>1. Ants</h3><ul><li><a href="https://apps.ben.website/ants">App</a></li><li><a href="https://gitlab.com/ben_goodman/apps/agent-based-modelling/ants">Source Code</a></li></ul><p>Potentially my favorite of the lot, this one is inspired by the ant foraging model from NetLogo and is described in the book.</p><p>This model explores how ants communicate the location of food via pheromones. Foraging ants (white) deposit a trail of nest pheromones (green), which are used by food-carrying ants (blue) to navigate back home at the center of the grid. The food ants leave a trail of food pheromones (red), which the foraging ants use. However, the pheromones will evaporate quickly over time, so trails only persist when ants work in tandem. This attracts more ants, reinforcing the trail, which should settle into the shortest path between the nest and food over time.</p><figure><img alt="A simulated ant colony where agents forage for food and returning it to the nest." src="https://cdn-images-1.medium.com/max/970/1*d9xKW9eTemdOvTn1fz3OmQ.gif" /></figure><p>The ants traverse a 2D grid made of cells. A cell can represent food, a nest, or simply an empty space. In the latter case, it will carry a pheromone value consisting of a 2D vector pointing in the direction of the ant’s travel. This direction is set when the ant on the cell deposits its pheromone via the depositPheromone method.</p><p>Why is the pheromone a vector? I want it to represent a trail with some means of direction. That, combined with the ants forward facing cone of smell, should keep the ants focused on moving forward and not spontaneously flipping back and forth because theres a stronger pheromone behind them. In an earlier attempt, the pheromone pointed to the location of the nest or the last food the ant visited, depending on the type. However, I didn’t think it was a very fair method and so I changed it to align with the ant’s direction of travel instead.</p><pre>class Cell extends Entities.Cell {<br>    public pheromoneDiffusionRange: number<br>    public pheromoneEvaporationRate: number<br>    public food: number<br>    public isNest: boolean<br>    public foodStore: number<br>    public pheromone: {<br>        food: Vector2<br>        nest: Vector2<br>    }<br><br>    constructor(opts: CellConstructor) {<br>        super(opts)<br>        this.pheromoneDiffusionRange = opts.pheromoneDiffusionRange<br>        this.pheromoneEvaporationRate = opts.pheromoneEvaporationRate<br>        this.food = 0<br>        this.foodStore = 0<br>        this.isNest = false<br>        this.pheromone = {<br>            food: new Vector2([0, 0]),<br>            nest: new Vector2([0, 0])<br>        }<br>    }<br><br><br>    depositPheromone(grid: CellGrid&lt;this&gt;, quantity: number, target: [number, number], type: &#39;food&#39; | &#39;nest&#39;) {<br>        // the pheromone points towards the target cell (the ant&#39;s last position)<br>        // get the vector from this cell to the target cell<br>        const targetVector = new Vector2([target[0] - this.location[0], target[1] - this.location[1]]).normal.scale(quantity)<br>        this.pheromone[type] = this.pheromone[type].add(targetVector)<br><br>        // add some simple diffusion<br>        const neighbors = this.getNeighbors(grid, true, this.pheromoneDiffusionRange)<br>        // really simple - thats all it needs<br>        neighbors.forEach((neighbor) =&gt; {<br>            const targetVector = new Vector2([target[0] - neighbor.location[0], target[1] - neighbor.location[1]]).normal.scale(quantity)<br>            neighbor.pheromone[type] = neighbor.pheromone[type].add(targetVector)<br>        })<br>    }<br>}</pre><p>Ants have two behaviors: forage for food and return to the nest.</p><pre>class Ant extends Entities.Agent {<br>    public pheromoneDepositRate: number<br>    public hasFood: boolean<br><br>    private dt: number = 0.5<br><br>    constructor(opts: AntConstructor) {<br>        super(opts)<br>        this.hasFood = false<br>        this.pheromoneDepositRate = opts.pheromoneDepositRate<br>    }<br><br>    public act(grid: CellGrid&lt;Cell&gt;): void {<br>        if (this.hasFood) {<br>            this.getCell(grid).depositPheromone(grid, this.pheromoneDepositRate, this.previousPosition.components, &#39;food&#39;)<br>            this.returnToNest(grid)<br>        } else {<br>            this.getCell(grid).depositPheromone(grid, this.pheromoneDepositRate, this.previousPosition.components, &#39;nest&#39;)<br>            this.forage(grid)<br>        }<br>    }<br><br>...<br>}</pre><p>Ants forage by ‘sniffing’ the cells in their ‘cone of vision/smell’ which extends out in front of each ant. It then uses the following strategy to navigate:</p><ol><li>The ant faces any food it can detect in its cone of vision-smell.</li><li>If no food is found, it faces the direction of the strongest food pheromone it can detect.</li><li>If no food scent is detected, it will face in the direction of a random cell that it can see.</li></ol><p>The ant then moves a step in the new direction and checks if it has found food. If so, it takes some food, it eats to replenish its energy and turns around 180 degrees. I’ve experimented with immortal ants which never get hungry, but that often results in large clusters of lost ants forming over time.</p><p>In an earlier attempt, the ant would align itself with the direction of the pheromone vector. This worked very well at the beginning but as the trails begain to intensify, ants would quickly get stuck in clusters. When an issue like this arrises, its often a good time to ask yourself if things are getting too complicated. So, in the name of simplicity, I had each ant face the <em>cell</em> with the strongest pheromone instead of the pheromone’s direction. Much simpler, and unexpectedly effective.</p><pre>forage(grid: CellGrid&lt;Cell&gt;): void {<br>    const visibleCells = this.getCellsWithinCone(grid, 120)<br><br>    // handle case with no visible cells<br>    if (visibleCells.length == 0) {<br>        this.rotation = this.rng.uniformFloat(0, Math.PI * 2)<br>        return<br>    }<br><br>    const foodCell = visibleCells.find(cell =&gt; cell.food &gt; 0)<br><br>    // the ant faces ant food cells it can see<br>    if (foodCell) {<br>        this.faceCell(foodCell)<br>    } else {<br>        // otherwise, it faces the direction of the pheromone gradient<br>        const maxCell = Numbers.Array.maximizeBy(visibleCells, cell =&gt; cell.pheromone.food.magnitude)<br><br>        // if is no scent, move randomly<br>        if (!maxCell.pheromone.food.magnitude == 0 ) {<br>            this.faceCell(this.rng.pickRandom(visibleCells))<br>        } else {<br>            this.faceCell(maxCell)<br>        }<br>    }<br><br>    this.move(this.dt, grid)<br><br>    const newCell = this.getCell(grid)<br><br>    // does the new cell contain food?<br>    if (newCell.food &gt; 0) {<br>        this.hasFood = true<br>        this.eat()<br>        this.lastFoodLocation = newCell.location<br>        newCell.food = Math.max(0, newCell.food - 1)<br>        this.rotation += Math.PI<br>        return<br>    }<br>}</pre><p>In the next step of the simulation, the ant will return to the nest. It does this in the same manner as when following food pheromones, where it moves towards the strongest nest pheromone vector until it finds a nest cell. Once it finds the nest, the ant adds its food to the nest, turns around, and goes back out to forage.</p><pre>private returnToNest(grid: CellGrid&lt;Cell&gt;): void {<br>    const visibleCells = this.getCellsWithinCone(grid, 120)<br><br>    // handle case with no visible cells<br>    if (visibleCells.length == 0) {<br>        this.rotation = this.rng.uniformFloat(0, Math.PI * 2)<br>        return<br>    }<br><br>    const nestCell = visibleCells.find(cell =&gt; cell.isNest)<br><br>    if (nestCell) {<br>        this.faceCell(nestCell)<br>    } else {<br>        const maxCell = Numbers.Array.maximizeBy(visibleCells, cell =&gt; cell.pheromone.nest.magnitude)<br><br>        // if is no scent, move randomly<br>        if (maxCell.pheromone.nest.magnitude == 0) {<br>            this.faceCell(this.rng.pickRandom(visibleCells))<br>        } else {<br>            this.faceCell(maxCell)<br>        }<br>    }<br><br>    this.move(this.dt, grid)<br><br>    const newCell = this.getCell(grid)<br><br>    // is the ant back at the nest?<br>    if (newCell.isNest) {<br>        this.hasFood = false<br>        newCell.foodStore += 1<br>        this.eat()<br>        this.rotation += Math.PI<br>        return<br>    }<br>}</pre><p>It’s fascinating to observe the ants as they seem to self-organize beyond what their basic programming would imply. The model’s simplicity is often key, and it’s very satisfying to see the odd behaviors that emerge from it, like the figure of eight formations they sometimes make.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*J4XuRtl9_C1dmjt4MPSr4Q.gif" /><figcaption>Ants sometimes get stuck in loops, but this one is likely a bug.</figcaption></figure><p>Getting the simulation just right is a tricky balancing act between pheromone deposition and evaporation. Enough pheromone needs to be applied by each ant to leave an appreciable trace, but not so much that the trail becomes saturated and loses its definition. A high evaporation rate is good for keeping the trail up to date as food locations change, but if it is too high, the trail will break, and ants will become lost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*K37QGZxchSOLAkfXhj7q0A.gif" /><figcaption>If the trail gets too thin, foraging ants will start following carrier ants, who follow the trail left by foraging ants. (lower left corner) This causes them to fall into a loop and eventually die.</figcaption></figure><p>At first, I dismissed the death loops as a simulation artefact (like the figure of eight loops) and not actual ant behaviour. But a quick search later, it turns out its real and its called an <a href="https://en.wikipedia.org/wiki/Ant_mill">Ant mill</a>. Wow!</p><h3>2. Predators &amp; Prey</h3><ul><li><a href="https://apps.ben.website/predators-and-prey">App</a></li><li><a href="https://gitlab.com/ben_goodman/apps/agent-based-modelling/predators-and-prey">Source Code</a></li></ul><p>Sheep consume grass, and wolves prey on sheep. As wolves reproduce, the sheep population decreases, allowing the grass to regrow. Subsequently, the wolf population begins to decline. This cycle paves the way for an increase in the sheep population, and under appropriate conditions, the cycle repeats.</p><p>This dynamic is also described by the <a href="https://en.wikipedia.org/wiki/Lotka%E2%80%93Volterra_equations">Lotka–Volterra equations</a> which despite being based on continuous differential equations as opposed to a discrete series of states based on rules and positions on a grid, we can still expect the results of each to be comparable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*_JsYqnJ8pKUh2jZtNpX74g.gif" /></figure><p>The model has three components: sheep, wolves, and grass.</p><p>The life of a sheep is straightforward — they scan the four cardinal directions for a neighboring patch of grass to consume. Consuming grass reduces the environmental resources but boosts the sheep’s energy, enabling reproduction. The creatures in this simulation reproduce asexually since models don’t have to mirror reality exactly — one could even consider each individual agent as representing a couple of sheep, for instance.</p><pre>export default class Sheep extends Agent {<br>    constructor(opts: AgentConstructor) {<br>        super(opts)<br>    }<br><br>    public act(world: Field, flock: AgentSet&lt;Sheep&gt;): void {<br>      if (!this.isAlive) {<br>            return<br>        }<br><br>        const neighborCells = this.getNeighborCells(world, false)<br>        const neighborsWithGrass = neighborCells.filter(cell =&gt; cell.hasGrass)<br><br>        // sheep will move to a random neighbor with grass<br>        if (neighborsWithGrass.length &gt; 0) {<br>            const randomNeighbor = this.rng.pickRandom(neighborsWithGrass)<br>            this.moveTo(randomNeighbor.location, world)<br>            randomNeighbor.hasGrass = false<br>            this.eat()<br>        } else {<br>            // if no grass, move to a random neighbor<br>            const randomNeighbor = this.rng.pickRandom(neighborCells)<br>            this.moveTo(randomNeighbor.location, world)<br>        }<br><br>        // sheep will reproduce if it has enough energy<br>        if (this.energy &gt;= this.reproductionThreshold) {<br>            flock.add(this.reproduce())<br>        }<br>    }<br>}</pre><p>The second species of agent is the wolf. Like the sheep, the wolf examines its neighboring region for a food cell to move to. Unlike sheep, wolves can look and move diagonally and with greater range. When a wolf moves into a cell with a sheep, the wolf gains energy, and the sheep dies.</p><pre>class Wolf extends Agent {<br>    constructor(opts: AgentConstructor) {<br>        super(opts)<br>    }<br><br>    public act(<br>        world: Field,<br>        herd: AgentSet&lt;Sheep&gt;,<br>        pack: AgentSet&lt;Wolf&gt;<br>    ): void {<br><br>        if (!this.isAlive) {<br>            return<br>        }<br><br>        const neighbors = this.getNeighborCells(world, false)<br>        const neighboringSheep = herd.getWithinRange(this.position.components, this.sightRange)<br><br>        // wolf will move to a random neighbor with sheep<br>        if (neighboringSheep.size &gt; 0) {<br>            const randomNeighbor = neighboringSheep.random(this.rng)<br>            this.moveTo(randomNeighbor.position.components, world)<br>            this.eat()<br>            randomNeighbor.isAlive = false<br>        } else {<br>            // if no sheep, move to a random neighbor<br>            const randomNeighbor = this.rng.pickRandom(neighbors)<br>            this.moveTo(randomNeighbor.location, world)<br>        }<br><br>        // wolf will reproduce if it has enough energy<br>        if (this.energy &gt;= this.reproductionThreshold) {<br>            pack.add(this.reproduce())<br>        }<br>    }<br>}</pre><p>The world is a 2D array of Grass with a chance to regrow with each step of the simulation.</p><pre>export default class Grass extends Cell {<br>    public hasGrass: boolean = false<br>    public grassRegrowProbability: number<br><br>    constructor(opts: GrassConstructor) {<br>        super(opts)<br>        this.grassRegrowProbability = opts.grassRegrowProbability<br>    }<br><br>    public regrow(rng: RandomGenerator): void {<br>        if (rng.uniformFloat(0, 1) &lt; this.grassRegrowProbability) {<br>            this.hasGrass = true<br>        }<br>    }<br>}</pre><p>Running the simulation at its default parameters yields a population that settles into an oscillating pattern. However, the system is very sensitive, and modifying the initial conditions — even slightly — can significantly change the outcome.</p><p>In this example, the grass regrow rate was changed from 0.02 to 0.01, and both species seem to have reached a steady equilibrium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*UikDC0ScTRrzBIuOtCt6Iw.png" /></figure><p>By increasing the grass regrow probability and energy sheep gain from grass, making conditions more favorable for the prey, it is possible to create conditions where wolves hunt the sheep to extinction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*BaVC1ikeSmnAQp6WwWMmsQ.gif" /></figure><h3>3. Schelling’s Model of Segregation</h3><ul><li><a href="https://apps.ben.website/segregation/index.html">App</a></li><li><a href="https://gitlab.com/ben_goodman/apps/agent-based-modelling/segregation">Source Code</a></li></ul><p>Schelling’s model of segregation is a theoretical framework proposed by economist Thomas Schelling to explain how individual preferences can lead to segregated patterns in society, even when individuals do not explicitly seek segregation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*_QxgoKPy6gEoPu9fr5MxAg.gif" /></figure><p>The model goes as follows:</p><ol><li>An agent is happy if a certain percentage (targetSimilarity) of its neighbors are the same type.</li><li>Happy agents stay in place.</li><li>Else, unhappy agents turn a random amount and move forward a random amount. They do this until they find an unoccupied cell.</li></ol><pre>export enum AgentType {<br>    RED = &#39;red&#39;,<br>    BLUE = &#39;blue&#39;,<br>    YELLOW = &#39;yellow&#39;,<br>}<br><br>export interface AgentConstructor extends Entities.AgentConstructor {<br>    targetSimilarity: number<br>    movementRange: number<br>}<br><br>export default class Agent extends Entities.Agent {<br>    isHappy: boolean<br>    type: AgentType<br>    // the percentage of similar neighbors needed for happines<br>    targetSimilarity: number<br>    // how far an agent can move in a single step<br>    movementRange: number<br><br>    constructor(opts: AgentConstructor) {<br>        super(opts)<br>        // pick a random type to be<br>        this.type = this.rng.pickRandom([AgentType.RED, AgentType.BLUE, AgentType.YELLOW])<br>        this.isHappy = null<br>        this.targetSimilarity = opts.targetSimilarity<br>        this.movementRange = opts.movementRange<br>    }<br><br>    act&lt;T extends Agent, U extends Entities.Cell&gt;(world: CellGrid&lt;U&gt;, agents: AgentSet&lt;T&gt;) {<br>        // get the neighbors of the agent<br>        const allNeighbors = this.getNeighbors(world, agents)<br>        // get the neighbors of the same type<br>        const similarNeighbors = allNeighbors.filter((neighbor) =&gt; neighbor.type === this.type)<br>        // determine if happy<br>        this.isHappy = similarNeighbors.size &gt;= ( this.targetSimilarity * allNeighbors.size / 100 )<br><br>        // if not happy, move to a random unoccupied cell<br>        if (this.isHappy) {<br>            return<br>        } else {<br>            this.moveToUnoccupiedCell(world, agents)<br>        }<br>    }<br><br>    private moveToUnoccupiedCell&lt;T extends Agent, U extends Entities.Cell&gt;(world: CellGrid&lt;U&gt;, agents: AgentSet&lt;T&gt;) {<br>        // the agent turns a random amount and moves forward a random amount (1, movementRange)<br>        this.rotation = this.rng.pickRandom([0, Math.PI / 2, Math.PI, 3 * Math.PI / 2])<br>        this.move(this.rng.uniformInt(1, this.movementRange), world)<br>        // check if there is an agent in the new cell<br>        const newCell = this.getCell(world)<br><br>        const isNewCellOccupied = newCell.tenantAgents.size &gt; 0 &amp;&amp; [...newCell.tenantAgents].some((agent) =&gt; agent !== this)<br>        if (isNewCellOccupied) {<br>            return this.moveToUnoccupiedCell(world, agents)<br>        } else {<br>            this.moveTo(newCell.location, world)<br>        }<br>    }<br>}</pre><p>The simulation ends when everyone is happy, so depending on the density of agents and the value of targetSimilarity, the program can run forever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*kowZSjHBRNkblATy7MGeEQ.gif" /></figure><h3>4. Brownian Motion</h3><ul><li><a href="https://apps.ben.website/brownian-motion/index.html">App</a></li><li><a href="https://gitlab.com/ben_goodman/apps/agent-based-modelling/brownian-motion">Source Code</a></li></ul><p>Brownian motion describes the random motion particles take when suspended in a liquid or gas, like dust floating in air. Here, we simulate the Brownian motion of a large particle (like dust) randomly impacted by surrounding smaller particles representing gas molecules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ue_Uys668ckQNHrscx0ZQA.gif" /></figure><p>In <em>agentscape</em>, particles are just agents that have been extended with mass and velocity properties and a collision resolution method that finds any intersecting particles and computes a new velocity for each. I primarily did this example to verify it works, and I was surprised to get such convincing results so easily.</p><pre>interface ParticleConstructor extends Entities.ParticleConstructor {<br>    particleType: &#39;small&#39; | &#39;big&#39;<br>}<br><br>class Particle extends Entities.Particle {<br>    particleType: &#39;small&#39; | &#39;big&#39;<br><br>    constructor(opts: ParticleConstructor) {<br>        super(opts)<br>        this.particleType = opts.particleType<br>        this.mass = opts.particleType === &#39;big&#39; ? 10 : 0.1<br>        this.radius = opts.particleType === &#39;big&#39; ? 10 : 0.1<br>    }<br><br>    act(grid: CellGrid&lt;Cell&gt;, particles: AgentSet&lt;Particle&gt;) {<br>        // update velocity based on any collisions<br>        this.resolveCollisions(grid, particles)<br><br>        const newPosition = this.position.add(this.velocity).components<br>        this.moveTo(newPosition, grid, { checkBounds: false })<br><br>        // if big, record position<br>        if (this.particleType === &#39;big&#39;) {<br>            const cell = this.getCell(grid)<br>            cell.visited = true<br>        }<br>    }<br>}</pre><p>The system is initialized by generating <em>N</em> small particles at random locations with random velocities and a stationary big particle at the center of the grid. The x,y components of the random velocities are multiplied at random by -1 — this ensures an even distribution of positive and negative velocities which corresponds to an even distribution of initial directions.</p><pre>const particles = AgentSet.fromFactory(this.particleCount, () =&gt; {<br>    const initialPosition = this.rng.uniformFloatArray(0, this.gridSize - 1, 2) as [number, number]<br>    // generates normally distributed velocity vectors with<br>    //  components ranging from -0.5 to 0.5<br>    const initialVelocity = this.rng.normalFloatArray(0.5, 0.2, 2)<br>      .map(v =&gt; this.rng.uniformInt(-1, 1) * v) as [number, number]<br>    return new Particle({<br>        particleType: &#39;small&#39;,<br>        initialPosition,<br>        initialVelocity<br>    })<br>})<br><br>// add a big particle<br>const bigParticle = new Particle({<br>    particleType: &#39;big&#39;,<br>    initialPosition: [this.gridSize / 2, this.gridSize / 2],<br>    initialVelocity: [0, 0]<br>})<br><br>particles.add(bigParticle)</pre><h3>5. Diffusion-Limited Aggregation</h3><ul><li><a href="https://apps.ben.website/diffusion-limited-aggregation/index.html">App</a></li><li><a href="https://gitlab.com/ben_goodman/apps/agent-based-modelling/diffusion-limited-aggregation">Source Code</a></li></ul><p>Like the previous model, this one uses the random motion of particles but introduces a new concept of the seed particle. Whenever a free particle collides with the seed, it stops moving and becomes a seed itself. This process repeats until there are no free particles left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*_sm3pRXA2M_TQkPTRGUQpA.gif" /></figure><pre>class Particle extends Entities.Particle {<br>    public seed = false<br><br>    constructor(opts: Entities.ParticleConstructor) {<br>        super(opts)<br>    }<br><br>    act(grid: CellGrid&lt;Cell&gt;, particles: AgentSet&lt;Particle&gt;) {<br>        if (this.seed) {<br>            return<br>        }<br><br>        this.resolveCollisions(grid, particles)<br><br>        const newPosition = this.position.add(this.velocity).components<br>        this.moveTo(newPosition, grid, { checkBounds: false })<br><br>        // if within an agent radius of a seed, stop<br>        particles.forEach((particle) =&gt; {<br>            if (particle.seed &amp;&amp; this.position.euclideanDistance(particle.position) &lt;= particle.radius + this.radius) {<br>                this.seed = true<br>            }<br>        })<br>    }<br>}</pre><p>Initialization is done by generating <em>N </em>small particles with random velocities and positions, and a seed particle in the center.</p><pre>const particles = AgentSet.fromFactory(this.particleCount, () =&gt; {<br>    const initialPosition = this.rng.uniformFloatArray(0, this.gridSize - 1, 2) as [number, number]<br>    const initialVelocity = this.rng.normalFloatArray(0.5, 0.2, 2).map(v =&gt; this.rng.uniformInt(-1, 1) * v) as [number, number]<br>    return new Particle({<br>        initialPosition,<br>        initialVelocity,<br>        radius: this.particleRadius,<br>        mass: 0.1<br>    })<br>})<br><br>// add a seed particle<br>const seedParticle = new Particle({<br>    initialPosition: [this.gridSize / 2, this.gridSize / 2],<br>    initialVelocity: [0, 0],<br>    mass: 100<br>})<br><br>seedParticle.seed = true<br><br>particles.add(seedParticle)</pre><h3>Conclusion</h3><p>Agent-based modeling is a fascinating endeavor which can reveal unforseen and complex behaviors within seemingly mundane systems. Discovering such emergence within a simulation can be highly rewarding and lead to all kinds of research tangents — I certainly have a new appreciation for ants.</p><p>And rememebr that developing models for complex systems needn’t been complicated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8216fe49ebe4" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/five-javascript-simulations-to-satisfy-your-curiosity-8216fe49ebe4">Five Javascript Simulations to Satisfy Your Curiosity</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create A Node.js AWS Lambda API, From Scratch.]]></title>
            <link>https://awstip.com/create-a-node-js-aws-lambda-api-from-scratch-294232ce1bdd?source=rss-2f01806d4793------2</link>
            <guid isPermaLink="false">https://medium.com/p/294232ce1bdd</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Benjamin Goodman]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 15:57:38 GMT</pubDate>
            <atom:updated>2024-09-13T16:01:27.717Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a Lambda HTTP API using the Terraform AWS provider and Typescript.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NEMNC7pxesWh6PdpFpRAFQ.png" /></figure><h3>Introduction</h3><p>Lambda functions are a means of executing code without using servers. More specifically, they allow you to execute code in the context of ‘events’ that are triggered by other AWS services. For the case of building an API, the trigger is an API Gateway with the event containing information regarding an HTTP request.</p><p>For this example, the API will be a simple ‘hello, world’ project with only one route (/api/health), which returns a 200 response. This project can be used to learn a new skill or cloned and used as a template for something larger.</p><p>A tree of the project layout is provided for context.</p><pre>.<br>├── .aws<br>│   └── terraform<br>│       ├── api_gteway.tf<br>│       ├── backend.tf<br>│       ├── lambda_exec_role.tf<br>│       ├── lambda_payload.tf<br>│       ├── log_group.tf<br>│       ├── main.tf<br>│       ├── outputs.tf<br>│       ├── provider.tf<br>│       ├── terraform.tfvars<br>│       ├── variables.tf<br>│       └── versions.tf<br>├── dist<br>│   ├── index.js<br>│   └── index.js.zip<br>├── Makefile<br>├── README.md<br>├── package-lock.json<br>├── package.json<br>└── src<br>    └── index.ts</pre><h3>Declare a Lambda Function</h3><p>Declaring a Lambda function will require:</p><ul><li>A suitable name</li><li>An IAM role</li><li>A runtime spec and payload</li></ul><p>We begin by using the <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function">Terraform Lambda resource</a> to create our function.</p><pre># .aws/terraform/main.tf<br><br>resource &quot;aws_lambda_function&quot; &quot;default&quot; {<br>    publish          = true<br>    function_name    = &quot;api-handler-${var.project_name}-${terraform.workspace}&quot;<br>    runtime          = &quot;nodejs20.x&quot;<br>    handler          = &quot;index.handler&quot;<br>    filename         = data.archive_file.handler_function_payload.output_path<br>    source_code_hash = data.archive_file.handler_function_payload.output_base64sha256<br>    package_type     = &quot;Zip&quot;<br>    role             = resource.aws_iam_role.lambda_iam_role.arn<br>}</pre><p>A comprehensive list of runtime values is available at <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html">Lambda runtimes - AWS Lambda</a></p><p>The handler argument refers to the handler code&#39;s entry-point (index.js) and exported function, which, in this example, will be called handler. For more information, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html">Define Lambda function handler in Node.js</a>.</p><p>The next sections will explain the creation of an IAM role and how to process the function’s source code into an appropriate payload.</p><h3>Declare an IAM Role</h3><p>Identity &amp; Access Management is a crucial AWS topic since it’s the service that defines who (user) or what (service) can perform certain actions on certain resources.</p><p>For a lambda function, we must define a policy which grants permission to the &quot;lambda.amazonaws.com&quot; service when the function executes.</p><pre># .aws/terraform/lambda_exec_role.tf<br><br>data &quot;aws_iam_policy_document&quot; &quot;execution_role&quot; {<br>    statement {<br>        effect = &quot;Allow&quot;<br>        principals {<br>            type        = &quot;Service&quot;<br>            identifiers = [<br>                &quot;lambda.amazonaws.com&quot;,<br>            ]<br>        }<br>        actions = [&quot;sts:AssumeRole&quot;]<br>    }<br>}</pre><p>The policy is then attached to an IAM role, which will be passed on to the Lambda function.</p><pre>resource &quot;aws_iam_role&quot; &quot;lambda_iam_role&quot; {<br>    name               = &quot;${var.project_name}.${var.resource_namespace}.${terraform.workspace}.iam_role&quot;<br>    assume_role_policy = data.aws_iam_policy_document.execution_role.json<br>}</pre><h3>Create a Log Stream</h3><p>Logs will allow you to debug your Lambda function handler since every console.* call in your code will create a log entry. You <em>will</em> need this, especially if you are starting out.</p><pre># .aws/terraform/log_group.tf<br><br>locals {<br>    log_group_name = &quot;${var.project_name}.${var.resource_namespace}.${terraform.workspace}&quot;<br>}<br><br>resource &quot;aws_cloudwatch_log_group&quot; &quot;function_log_group&quot; {<br>    name              = &quot;/aws/lambda/${local.log_group_name}&quot;<br>    retention_in_days = 7<br>    lifecycle {<br>        prevent_destroy = false<br>    }<br>}</pre><p>We must define an IAM policy that permits the Lambda function to interact with the CloudWatch service.</p><pre>data &quot;aws_iam_policy_document&quot; &quot;lambda_logging&quot; {<br>  statement {<br>    effect = &quot;Allow&quot;<br>    actions = [<br>        &quot;logs:CreateLogGroup&quot;,<br>        &quot;logs:CreateLogStream&quot;,<br>        &quot;logs:PutLogEvents&quot;,<br>    ]<br>    resources = [&quot;arn:aws:logs:*:*:*&quot;]<br>  }<br>}<br><br>resource &quot;aws_iam_policy&quot; &quot;lambda_logging&quot; {<br>    name        = &quot;lambda_logging_${local.log_group_name}&quot;<br>    path        = &quot;/&quot;<br>    description = &quot;IAM policy for logging from a lambda&quot;<br>    policy      = data.aws_iam_policy_document.lambda_logging.json<br>}</pre><p>Next, we attach the logging policy to the Lambda function’s IAM role.</p><pre>resource &quot;aws_iam_role_policy_attachment&quot; &quot;lambda_logs&quot; {<br>    role       = aws_iam_role.lambda_iam_role.name<br>    policy_arn = aws_iam_policy.lambda_logging.arn<br>}</pre><h3>Process the Lambda Payload</h3><p>We’ll take the simple approach for this example and deploy the source code as a zip archive. We’ll use Terraform to create an archive file and run any required build scripts. Alternatively, the code can be built and archived by a separate process prior to running Terraform, but this offers the most satisfying experience in terms of automation.</p><p>Since the source code is Typescript, it must first be transpiled into an ES module, which a Makefile handles. This allows for a great deal of flexibility for larger projects.</p><pre># .aws/terraform/lambda_payload.tf<br><br>locals {<br>    # the source code is in the project root.<br>    payload_working_dir = &quot;${path.module}/../../&quot;<br>}<br><br>resource &quot;null_resource&quot; &quot;build_handler_function&quot; {<br>    provisioner &quot;local-exec&quot; {<br>        working_dir = local.payload_working_dir<br>        # build code<br>        command     = &quot;make payload&quot;<br>    }<br>    triggers = {<br>        always_run = &quot;${timestamp()}&quot;<br>    }<br>}<br><br>data &quot;null_data_source&quot; &quot;wait_for_build_handler_function&quot; {<br>  inputs = {<br>    lambda_exporter_id = &quot;${null_resource.build_handler_function.id}&quot;<br>    source_file = &quot;${local.payload_working_dir}/dist/index.js&quot;<br>  }<br>}<br><br><br># create a zip archive of the build artefacts<br>data &quot;archive_file&quot; &quot;handler_function_payload&quot; {<br>    depends_on = [ data.null_data_source.wait_for_build_handler_function ]<br>    type             = &quot;zip&quot;<br>    source_file      = data.null_data_source.wait_for_build_handler_function.outputs.source_file<br>    output_file_mode = &quot;0666&quot;<br>    output_path      = &quot;${local.payload_working_dir}/dist/index.js.zip&quot;<br>}</pre><h3>Develop the Lambda Event Handler</h3><p>Lambdas are functions that operate on events. In this case, the event is a JSON object originating from an API gateway. Thus, we can expect the event to bear the features of an HTTP request.</p><p>The types package used is <a href="https://www.npmjs.com/package/@types/aws-lambda">@types/aws-lambda — npm</a>.</p><p>The code below uses the event’s resource and httpMethod properties to identify which API route is being called by the client and be handled accordingly.</p><pre>// ./src/index.ts<br><br>import type { APIGatewayProxyEvent, APIGatewayProxyResult } from &#39;aws-lambda&#39;<br><br>export const handler = async (event: APIGatewayProxyEvent): Promise&lt;APIGatewayProxyResult&gt; =&gt; {<br>    const  { resource, httpMethod } = event<br><br>    const resourceId = `${httpMethod} ${resource}`<br><br>    switch (resourceId) {<br>    case &#39;GET /api/health&#39;:<br>        return {<br>            statusCode: 200,<br>            headers: {<br>                &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            },<br>            body: JSON.stringify({ message: &#39;OK&#39; }),<br>        }<br>    default:<br>        return {<br>            statusCode: 500,<br>            headers: {<br>                &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            },<br>            body: JSON.stringify({ message: &#39;Not Found&#39; }),<br>        }<br>    }<br>}</pre><p>The AWS docs (<a href="https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html#async-typescript"> Define Lambda function handler in TypeScript</a>) specify that the function handler is an ES module, so <a href="https://esbuild.github.io/">esbuild</a> will be used to transpile the source into a suitable output. The build process is scripted in a Makefile.</p><pre># ./Makefile<br><br>clean:<br>    rm -rf dist || true<br>    rm -rf node_modules || true<br><br>node_modules:<br>    npm ci<br><br>payload: clean node_modules<br>    npx esbuild ./src/index.ts \<br>        --bundle \<br>        --outfile=dist/index.js \<br>        --bundle \<br>        --minify \<br>        --platform=node \<br>        --target=es2020</pre><h3>Define an API Gateway</h3><p>An API Gateway will receive HTTP requests for the Lambda function. We can do the same thing using a <a href="https://docs.aws.amazon.com/lambda/latest/dg/urls-configuration.html">function URL</a>, but a gateway will enable us to define allowed routes as resources, which is relevant to the Lambda function handler code from earlier.</p><p>We start by defining a simple API gateway with a single deployment stage.</p><pre># .aws/terraform/lambda_payload.tf<br><br>resource &quot;aws_apigatewayv2_api&quot; &quot;default&quot; {<br>    name          = &quot;${var.project_name}-api-gateway-${terraform.workspace}&quot;<br>    protocol_type = &quot;HTTP&quot;<br>}<br><br>resource &quot;aws_apigatewayv2_stage&quot; &quot;default&quot; {<br>    api_id = aws_apigatewayv2_api.default.id<br>    name        = &quot;$default&quot;<br>    auto_deploy = true<br>}</pre><p>Then we ‘attach’ the Lambda function to the gateway as an ‘integration’. Integrations are destinations for routes.</p><pre>resource &quot;aws_apigatewayv2_integration&quot; &quot;default&quot; {<br>    api_id = aws_apigatewayv2_api.default.id<br>    integration_uri    = resource.aws_lambda_function.default.invoke_arn<br>    integration_type   = &quot;AWS_PROXY&quot;<br>    integration_method = &quot;POST&quot;<br>}</pre><p>This example project has only one route: GET /api/health.</p><pre>resource &quot;aws_apigatewayv2_route&quot; &quot;health_check&quot; {<br>    api_id = aws_apigatewayv2_api.default.id<br>    target    = &quot;integrations/${aws_apigatewayv2_integration.default.id}&quot;<br>    route_key = &quot;GET /api/health&quot;<br>}</pre><p>With the API gateway configuration complete, the final step is to assign it permissions to invoke the Lambda function.</p><pre># .aws/terraform/main.tf<br><br>resource &quot;aws_lambda_permission&quot; &quot;allow_default_gateway&quot; {<br>    statement_id  = &quot;gateway-exec-${var.project_name}-${terraform.workspace}&quot;<br>    action        = &quot;lambda:InvokeFunction&quot;<br>    function_name = resource.aws_lambda_function.default.function_name<br>    principal     = &quot;apigateway.amazonaws.com&quot;<br>    source_arn    = &quot;${aws_apigatewayv2_api.default.execution_arn}/*/*&quot;<br>}</pre><h3>Provision Resources</h3><p>Before we can run the Terraform CLI, we need to finish the project’s configuration. We start by declaring a version for the AWS provider:</p><pre># .aws/terraform/versions.tf<br><br>terraform {<br>    required_version = &quot;~&gt; 1.5.0&quot;<br><br>    required_providers {<br>        aws = {<br>            source  = &quot;hashicorp/aws&quot;<br>            version = &quot;~&gt; 5.46.0&quot;<br>        }<br>    }<br>}</pre><p>Then, we declare the variables referenced by the project.</p><pre># .aws/terraform/variables.tf<br><br>variable &quot;project_name&quot; {<br>    type = string<br>}<br><br>variable &quot;resource_namespace&quot; {<br>    type = string<br>}</pre><p>For automation purposes, we can optionally declare values for these variables.</p><pre># .aws/terraform/terraform.tfvars<br><br>project_name       = &quot;example-lambda&quot;<br>resource_namespace = &quot;bgoodman&quot;</pre><p>Lastly, we declare an output for the API gateway’s URL. We’ll use this to test the deployment.</p><pre># .aws/terraform/outputs.tf<br><br>output &quot;gateway_base_url&quot; {<br>    value = aws_apigatewayv2_stage.default.invoke_url<br>}</pre><p>It’s now time to run the Terraform CLI in the usual fashion.</p><pre>terraform init<br>terraform plan -out tfplan<br>terraform apply tfplan</pre><p>Once complete, you should see an overview of what was deployed and, most importantly, the output value for the API gateway’s URL.</p><pre>...<br><br><br>Apply complete! Resources: 11 added, 0 changed, 0 destroyed.<br><br>Outputs:<br><br>gateway_base_url = &quot;https://krs5jx3mif.execute-api.us-east-1.amazonaws.com/&quot;</pre><h3>Validation</h3><p>To validate the deployment, we curl the API&#39;s one and only route.</p><pre>$ curl https://krs5jx3mif.execute-api.us-east-1.amazonaws.com/api/health<br><br><br># {&quot;message&quot;:&quot;OK&quot;}</pre><h3>Conclusion</h3><p>The complete project is hosted at <a href="https://gitlab.com/ben_goodman/scratchpad/lambda-from-scratch">projects / Scratchpad / Lambda From Scratch · GitLab</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=294232ce1bdd" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/create-a-node-js-aws-lambda-api-from-scratch-294232ce1bdd">Create A Node.js AWS Lambda API, From Scratch.</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Publishing to NPM With GitLab CI]]></title>
            <link>https://medium.com/@benjamin_goodman/publishing-to-npm-with-gitlab-ci-cc446dbcf5cc?source=rss-2f01806d4793------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc446dbcf5cc</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Benjamin Goodman]]></dc:creator>
            <pubDate>Sun, 28 Jul 2024 16:07:39 GMT</pubDate>
            <atom:updated>2024-07-28T16:07:39.771Z</atom:updated>
            <content:encoded><![CDATA[<h4>Developing a CI/CD pipeline to automatically publish pre-release versions to GitLab’s package registry and release versions to NPM.</h4><p>This article describes the process for publishing an existing project to the GitLab registry and the public npm registry.</p><h3>Pipeline Preamble</h3><p>Here, I set the project’s git strategy. I’m using a trunk-based approach with main being the only long-lived branch. All other branches are for features that are attached to MRs. The pipeline will run on the following events:</p><ul><li>Commits to MRs (publish a beta release)</li><li>Merge to main (publish a release candidate)</li><li>Tag creation (publish a production release)</li></ul><p>I also imported GitLab’s SAST template, because why not?</p><pre>variables:<br>  RELEASE_TAG_PATTERN: &#39;/v\d+\.\d+\.\d+(?:-\d+)*/&#39;<br>  REGISTRY_NAMESPACE: &#39;@bgoodman&#39;<br><br>workflow:<br>  rules:<br>    # builds a beta release for merge requests.<br>    - if: $CI_MERGE_REQUEST_IID<br>    - if: $CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;<br>    - if: $CI_OPEN_MERGE_REQUESTS<br>      when: never<br>    # builds a release candidate on commit to main.<br>    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH<br>    # builds a production release for a matching tag.<br>    - if: $CI_COMMIT_TAG =~ $RELEASE_TAG_PATTERN<br><br>include:<br>  - template: Jobs/SAST.gitlab-ci.yml</pre><p>A package must be built before it can be published. I’ve defined a simple Build job that installs the project’s dependencies and caches them for future use. The actual build process is handled by calling npm run build which is specific for each project and is beyond the scope of this article. The only requirement here is that the project’s build artifacts are exported to the directory dist/ as that is where the cache expects them to be.</p><pre># will be referenced by &#39;publish&#39; jobs later.<br>.nodejs_artifact_cache: &amp;nodejs_artifact_cache<br>  cache:<br>    - key:<br>        files:<br>          - package-lock.json<br>          - package.json<br>      paths:<br>        - node_modules/<br>        - dist/<br>        - .npm/<br><br>Build:<br>  &lt;&lt;: *nodejs_artifact_cache<br>  script:<br>    - npm ci --cache .npm --prefer-offline<br>    - npm run build<br><br># Shift left and run on MRs instead.<br>semgrep-sast:<br>  rules:<br>    - if: $CI_MERGE_REQUEST_IID<br>      when: always<br>    - when: never</pre><p>Additionally, I’ve overridden the rules for GitLab’s semgrep-sast template so it runs on MR pipelines instead of on integration to main.</p><p>At this stage, we have a pipeline that can build a project using npm and perform a basic security scan. We’re now ready to define publishing jobs.</p><h3>Publish A Beta Version</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*Zi4gcZDKlANr-KWmHK-wfg.png" /><figcaption>An example of an MR pipeline.</figcaption></figure><p>A beta version is published whenever an MR is created, or a commit is pushed to one. Betas will be published to the GitLab project registry, which has been configured to keep beta versions for 90 days only. Using GitLab as a registry is a good choice for sandbox projects or where only contributors would need access to the release.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuN7Eq9BS3-TpJM-bjI9Vw.png" /><figcaption>Any beta release older than 90 days is automatically deleted.</figcaption></figure><p>Publishing a beta version of an npm module is done using npm publish --tag $BETA_RELEASE_TAG — but that&#39;s only half of what&#39;s needed. To prevent beta releases from conflicting in the registry, an updated beta version for the project needs to be explicitly set in package.json.</p><pre>{<br>  &quot;name&quot;: &quot;@bgoodman/react-console-component&quot;,<br>  &quot;version&quot;: &quot;1.0.2-beta-1234abcd&quot;,<br>...<br>}</pre><p>This update can be done quickly using jq.</p><pre>mv package.json package.json.bak<br>jq --arg _TAG &quot;-$BETA_RELEASE_TAG&quot; &#39;.version += $_TAG&#39; package.json.bak &gt; package.json</pre><p>The complete job for publishing a beta release is below.</p><pre>Publish Beta:<br>  variables:<br>    BETA_RELEASE_TAG: &quot;beta-$CI_COMMIT_SHORT_SHA&quot;<br>  rules:<br>    - if:  $CI_MERGE_REQUEST_IID<br>      when: always<br>  cache:<br>    - !reference [.nodejs_artifact_cache, cache]<br>  needs:<br>    - Build<br>    - semgrep-sast<br>  script:<br>  # Apply a temporary beta tag to the package.json version.<br>    - mv package.json package.json.bak<br>    - jq --arg _TAG &quot;-$BETA_RELEASE_TAG&quot; &#39;.version += $_TAG&#39; package.json.bak &gt; package.json<br>  # npm publish requires a pristine repo - all changes must be committed first.<br>    - |<br>      git \<br>        -c user.name=&quot;$GITLAB_USER_NAME&quot; \<br>        -c user.email=&quot;$GITLAB_USER_EMAIL&quot; \<br>        commit \<br>        -a \<br>        -m &quot;Apply temporary tag \&quot;$BETA_RELEASE_TAG\&quot;.&quot; \<br>        --no-verify \<br>        --allow-empty<br>    # publish to the gitlab registry<br>    - echo &quot;${REGISTRY_NAMESPACE}:registry=https://${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/&quot; &gt; .npmrc<br>    - echo &quot;//${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/:_authToken=${CI_JOB_TOKEN}&quot; &gt;&gt; .npmrc<br>    - npm publish --verbose --tag $BETA_RELEASE_TAG<br>    # reset the temporary tag.<br>    - git reset HEAD^ --hard &gt;/dev/null 2&gt;&amp;1 || true</pre><p>Now, you can have many beta releases per MR without conflict.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cdrPvL9mnUN5-2gnjvvuYw.png" /></figure><h3>Publish a Release Candidate</h3><p>A release candidate is published when a commit is made to the main branch (i.e., when an MR is merged). Like the beta version, RC’s are published to the GitLab registry too. Unlike beta versions, they are published without tags.</p><pre>Publish Main:<br>  rules:<br>    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH<br>      when: always<br>  cache:<br>    - !reference [.nodejs_artifact_cache, cache]<br>  needs:<br>    - Build<br>  script:<br>    - echo &quot;${REGISTRY_NAMESPACE}:registry=https://${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/&quot; &gt; .npmrc<br>    - echo &quot;//${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/:_authToken=${CI_JOB_TOKEN}&quot; &gt;&gt; .npmrc<br>    - npm publish --verbose</pre><h3>Publish a Release</h3><p>This is the final stage which publishes to the npm registry. It’s triggered on the creation of a git tag matching a semver with the pattern /v\d+\.\d+\.\d+(?:-\d)*/. I’ve set tags matching v* as protected so that only maintainers can create one and thus publish the project to NPM.</p><p>Special care should be taken with the variable NPM_PUBLISH_TOKEN since it is a very privileged secret. Either set it as a CI variable in GitLab or use a 3rd party secret manager (AWS, etc.)</p><pre>Publish Release:<br>  rules:<br>    - if: $CI_COMMIT_TAG =~ $RELEASE_TAG_PATTERN<br>      when: always<br>  cache:<br>    - !reference [.nodejs_artifact_cache, cache]<br>  needs:<br>    - Build<br>  script:<br>  # authenticate npm registry access and publish<br>    - echo &#39;//registry.npmjs.org/:_authToken=&#39;&quot;${NPM_PUBLISH_TOKEN}&quot; &gt; .npmrc<br>    - npm publish --verbose</pre><h3>Conclusion</h3><p>If all you want to do is publish to npm, then there you have it — it’s quite a simple process. However, it doesn&#39;t take much additional work to implement a complete CI/CD pipeline that can scale for multiple developers while staying inside GitLab’s free tier.</p><p>The complete code for this pipeline is available <a href="https://gitlab.com/ben_goodman/ui-components/react-console-component/-/blob/12f92ba89ca02e4fb75a02f90e0ffc2c773eb507/.gitlab-ci.yml">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc446dbcf5cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building A Serverless Bash REPL]]></title>
            <link>https://medium.com/@benjamin_goodman/building-a-serverless-bash-repl-05ccc37f6709?source=rss-2f01806d4793------2</link>
            <guid isPermaLink="false">https://medium.com/p/05ccc37f6709</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[bash]]></category>
            <dc:creator><![CDATA[Benjamin Goodman]]></dc:creator>
            <pubDate>Sun, 21 Jul 2024 21:23:11 GMT</pubDate>
            <atom:updated>2024-07-21T21:23:11.237Z</atom:updated>
            <content:encoded><![CDATA[<p>A Read-Eval-Print-Loop (REPL) is an interactive program that takes a user input, evaluates it, and returns the output. Such environments are helpful for experimentation and prototyping, and REPLs for many languages are available as online applications, even if the language is not web-native. This article describes creating a Bash REPL as a web application using an AWS Lambda Function as the basis for an HTTP API to evaluate Bash code and return the output as a response to the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*m6W7qSMihyFYI_u5bWVT2w.png" /></figure><h3>Create a Custom Bash Server</h3><p>My plan for building an API to evaluate Bash code is to create a Bash web server using a custom Lambda runtime. The AWS docs describe this process in <a href="https://docs.aws.amazon.com/en_us/lambda/latest/dg/runtimes-walkthrough.html">Tutorial: Building a custom runtime — AWS Lambda (amazon.com)</a>.</p><p>Because Lambda events are JSON objects, parsing them in bash will be a chore unless using some tool like <a href="https://jqlang.github.io/jq/manual/">jq</a>. Thus, I’ve included the jq AMD64 binary with my Lambda function handler code.</p><pre>./lambda_handler<br>├── bin<br>│   └── jq<br>├── bootstrap<br>└── function.sh</pre><p>The bootstrap script is executed first and sets up the runtime environment. I’ve modified the runtime PATH variable to include /var/task/bin which is the directory housing the jq binary.</p><pre>#!/bin/sh<br><br># bootstrap.sh <br><br># Initialization - load function handler<br># equal to &#39;source /var/task/function.sh&#39;<br>source $LAMBDA_TASK_ROOT/&quot;$(echo $_HANDLER | cut -d. -f1).sh&quot;<br><br># Add `jq` to PATH<br>export PATH=&quot;/var/task/bin:$PATH&quot;<br><br># Processing<br>while true<br>do<br>    HEADERS=&quot;$(mktemp)&quot;<br>    # Get an event. The HTTP request will block until one is received<br>    EVENT_DATA=$(curl -sS -LD &quot;$HEADERS&quot; &quot;http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next&quot;)<br><br>    # Extract request ID by scraping response headers received above<br>    REQUEST_ID=$(grep -Fi Lambda-Runtime-Aws-Request-Id &quot;$HEADERS&quot; | tr -d &#39;[:space:]&#39; | cut -d: -f2)<br><br>    # Run the handler function from the script<br>    RESPONSE=$($(echo &quot;$_HANDLER&quot; | cut -d. -f2) &quot;$EVENT_DATA&quot;)<br><br>    # Send the response<br>    curl &quot;http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/$REQUEST_ID/response&quot;  -d &quot;$RESPONSE&quot;<br>done</pre><p>My Bash server will have two routes:</p><ul><li>A health check — GET /api/health</li><li>Code evaluation — GET /api/exec/{_src}</li></ul><p>This is where using an API Gateway becomes helpful since it enables me to define these routes explicitly. When the gateway sends an API request to the Lambda function, its event will contain the request method and route information conveniently together as the property .requestContext.resourceId. Because we installed jqearlier, getting the request’s resource ID is trivial. And because our server runs on Bash, we can evaluate incoming source code easily using eval.</p><pre># Handles the incoming APIGatewayProxy event and echoes a response.<br>function handler () {<br>    EVENT_DATA=$1<br><br>    # i.e.,<br>    # {<br>    #  &quot;version&quot;: &quot;1.0&quot;,<br>    #  &quot;resource&quot;: &quot;/api/exec/{_src}&quot;,<br>    #  &quot;path&quot;: &quot;/api/exec/test&quot;,<br>    #  &quot;httpMethod&quot;: &quot;GET&quot;,<br>    #  &quot;headers&quot;: { ...<br>    #  ...<br>    echo &quot;EVENT_DATA: $EVENT_DATA&quot; <br><br>    resource_id=$(echo &quot;$EVENT_DATA&quot; | jq -r &#39;.requestContext.resourceId&#39;)<br><br>    # Serves a health check response (Ok).<br>    # GET /api/health<br>    if [ &quot;$resource_id&quot; == &quot;GET /api/health&quot; ]; then<br>        echo &#39;{&quot;statusCode&quot;: 200, &quot;body&quot;: &quot;Ok.&quot;}&#39;<br>        return<br>    fi<br><br>    # Executes {_src} as a bash script and returns the output.<br>    # GET /api/exec/{_src}<br>    if [ &quot;$resource_id&quot; == &quot;GET /api/exec/{_src}&quot; ]; then<br>        # decode incoming source code from base64.<br>        _src=$(echo &quot;$EVENT_DATA&quot; | jq -r &#39;.pathParameters._src&#39;)<br>        _src=$(echo $_src | base64 -d)<br><br>        # evaluate source code and capture the result.<br>        if ! result=$(eval &quot;$_src&quot; 2&gt;&amp;1); then<br>            # sanitize the error message.<br>            result=&quot;Error: $(echo $result | grep -oP &#39;line\s+\d+:\s+\K.+&#39;)&quot;<br>        fi<br><br>        # using jq to build a response object.<br>        RESPONSE=$(<br>            jq -n \<br>                --arg status_code 200 \<br>                --arg result &quot;$result&quot; \<br>            &#39;{<br>                &quot;statusCode&quot;: $status_code,<br>                &quot;body&quot;: $result<br>            }&#39;<br>        )<br><br>        echo &quot;$RESPONSE&quot;<br>        return<br>    fi<br><br>    # fallthrough<br>    echo &#39;{&quot;statusCode&quot;: 501, &quot;body&quot;: &quot;Not implemented.&quot;}&#39;<br>}</pre><h3>Provision Cloud Resources</h3><p>I’ve used Terraform to provision the project’s cloud infrastructure. It&#39;s a standard setup that zips the lambda_handler directory from the previous stage and implements the OS-only provided.al2023 runtime.</p><pre>data &quot;archive_file&quot; &quot;handler_function_payload&quot; {<br>    type             = &quot;zip&quot;<br>    source_dir      = &quot;${path.module}/lambda_handler&quot;<br>    output_file_mode = &quot;0666&quot;<br>    output_path      = &quot;${path.module}/dist/lambda_handler.zip&quot;<br>}<br><br>module &quot;lambda_function&quot; {<br>    source  = &quot;gitlab.com/ben_goodman/lambda-function/aws&quot;<br>    version = &quot;3.0.0&quot;<br><br>    org              = &quot;${var.resource_namespace}-${terraform.workspace}&quot;<br>    project_name     = &quot;bash-repl&quot;<br>    lambda_payload   = data.archive_file.handler_function_payload<br>    function_name    = &quot;bash-exec&quot;<br>    function_handler = &quot;function.handler&quot;<br>    publish          = true<br>    memory_size      = 512<br>    runtime          = &quot;provided.al2023&quot;<br>}<br><br>resource &quot;aws_lambda_permission&quot; &quot;allow_default_gateway&quot; {<br>    statement_id  = &quot;bash-repl-gateway-exec&quot;<br>    action        = &quot;lambda:InvokeFunction&quot;<br>    function_name = module.lambda_function.name<br>    principal     = &quot;apigateway.amazonaws.com&quot;<br>    source_arn    = &quot;${aws_apigatewayv2_api.default.execution_arn}/*/*&quot;<br>}</pre><p>Likewise, the API Gateway config is standard, too. The route definitions are included here.</p><pre>resource &quot;aws_apigatewayv2_api&quot; &quot;default&quot; {<br>    name          = &quot;bash-repl-api-gateway-${terraform.workspace}&quot;<br>    protocol_type = &quot;HTTP&quot;<br>}<br><br>resource &quot;aws_cloudwatch_log_group&quot; &quot;default&quot; {<br>    name = &quot;/aws/bash-repl_gateway_${terraform.workspace}/${aws_apigatewayv2_api.default.name}&quot;<br>    retention_in_days = 30<br>}<br><br>resource &quot;aws_apigatewayv2_stage&quot; &quot;default&quot; {<br>    api_id = aws_apigatewayv2_api.default.id<br>    name        = &quot;$default&quot;<br>    auto_deploy = true<br><br>    access_log_settings {<br>        destination_arn = aws_cloudwatch_log_group.default.arn<br><br>        format = jsonencode({<br>            requestId               = &quot;$context.requestId&quot;<br>            sourceIp                = &quot;$context.identity.sourceIp&quot;<br>            requestTime             = &quot;$context.requestTime&quot;<br>            protocol                = &quot;$context.protocol&quot;<br>            httpMethod              = &quot;$context.httpMethod&quot;<br>            resourcePath            = &quot;$context.resourcePath&quot;<br>            routeKey                = &quot;$context.routeKey&quot;<br>            status                  = &quot;$context.status&quot;<br>            responseLength          = &quot;$context.responseLength&quot;<br>            integrationErrorMessage = &quot;$context.integrationErrorMessage&quot;<br>        })<br>    }<br>}<br><br>resource &quot;aws_apigatewayv2_integration&quot; &quot;default&quot; {<br>    api_id = aws_apigatewayv2_api.default.id<br>    integration_uri    = module.lambda_function.invoke_arn<br>    integration_type   = &quot;AWS_PROXY&quot;<br>    integration_method = &quot;POST&quot;<br>}<br><br>resource &quot;aws_apigatewayv2_route&quot; &quot;health_check&quot; {<br>    api_id = aws_apigatewayv2_api.default.id<br>    target    = &quot;integrations/${aws_apigatewayv2_integration.default.id}&quot;<br>    route_key = &quot;GET /api/health&quot;<br>}<br><br>resource &quot;aws_apigatewayv2_route&quot; &quot;exec_bash&quot; {<br>    api_id = aws_apigatewayv2_api.default.id<br>    target    = &quot;integrations/${aws_apigatewayv2_integration.default.id}&quot;<br>    route_key = &quot;GET /api/exec/{_src}&quot;<br>}</pre><p>The complete code for this section is available at <a href="https://gitlab.com/ben_goodman/apps/bash-repl/-/tree/main/.aws/terraform?ref_type=heads">.aws/terraform · main · projects / Apps / Bash REPL · GitLab</a>.</p><p>At this stage, the API is now ready to test.</p><pre>src=&quot;$(echo &#39;echo &quot;hello, world&quot;&#39; | base64)&quot;<br><br>curl -X GET \<br>  https://ezb24gwwx1.execute-api.us-east-1.amazonaws.com/api/exec/$src<br><br># hello, world</pre><p>This is only half of the project, though. The next step is to create a simple GUI for entering input and displaying the results.</p><h3>Create A Simple UI</h3><p>React is used to create the user interface. First, I’ll define a custom hook that calls the API with the user’s input code.</p><pre>export const useEval = () =&gt; {<br>    return {<br>        evalCode: async (code: string): Promise&lt;string&gt; =&gt; {<br>            // encode the input to base64<br>            const encoded = btoa(code)<br>            const resp = await fetch(`./api/exec/${encoded}`)<br>            return await resp.text()<br>        }<br>    }<br>}</pre><p>Then, I’ll create a text input for the user’s code, and wrap the output for the API response in a pre tag. Lastly, a button is added with a on-click handler which calls the custom useEval hook with the user’s code.</p><pre>import React from &#39;react&#39;<br>import styled from &#39;styled-components&#39;<br>import { Button } from &#39;@contentful/f36-button&#39;<br>import { Allotment } from &#39;allotment&#39;<br>import &#39;allotment/dist/style.css&#39;<br>import Editor from &#39;react-simple-code-editor&#39;<br>import { highlight, languages } from &#39;prismjs/components/prism-core&#39;<br>import &#39;prismjs/components/prism-bash&#39;<br>import &#39;prismjs/themes/prism.css&#39;<br>import { useEval } from &#39;./services/useEval&#39;<br><br><br>const StyledSplitContainer = styled(Allotment)`<br>    height: 90vh;<br>    width: 95%;<br>`<br><br>const StyledEditor = styled(Editor)`<br>    height: 100%;<br>    border: 1px solid #d1d5da;<br>`<br><br><br>export const App = () =&gt; {<br>    const { evalCode } = useEval()<br>    const [input, setInput] = React.useState&lt;string&gt;(&#39;&#39;)<br>    const [output, setOutput] = React.useState&lt;string&gt;(&#39;&#39;)<br>    const [isLoading, setLoading] = React.useState&lt;boolean&gt;(false)<br><br>    return (<br>        &lt;&gt;<br>            &lt;Button<br>                variant=&#39;primary&#39;<br>                isDisabled={isLoading}<br>                onClick={<br>                    async () =&gt; {<br>                        setLoading(true)<br>                        const result = await evalCode(input)<br>                        setOutput(result)<br>                        setLoading(false)<br>                    }<br>                }<br>            &gt;<br>                {isLoading &amp;&amp; &#39;Loading&#39; || &#39;Run&#39;}<br>            &lt;/Button&gt;<br><br>            &lt;StyledSplitContainer vertical={true}&gt;<br>                &lt;StyledEditor<br>                    value={input}<br>                    onValueChange={code =&gt; setInput(code)}<br>                    highlight={code =&gt; highlight(code, languages.bash, &#39;bash&#39;)}<br>                    padding={10}<br>                /&gt;<br><br>                &lt;pre&gt;<br>                    {output}<br>                &lt;/pre&gt;<br>            &lt;/StyledSplitContainer&gt;<br>        &lt;/&gt;<br>    )<br>}</pre><p>The result is a very minimalistic interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*xi2SQlPs9OgZGydA0pBVkQ.png" /></figure><p>And it gives very interesting results. I was able to run commands like pwdand echo $PATH - very helpful when trying to install jq (the initial version used RegEx to parse JSON events).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*k-DcQvGgnbChFF118-TFww.png" /></figure><h3>Conclusion</h3><p>Is this safe? Is this something I want to host freely? No, not really, and by the time you read this, the URLs encountered for this project will no longer work. But hey, you can always clone the project and deploy your own Bash REPL using the AWS free tier.</p><p>The project’s source is availiable at <a href="https://gitlab.com/ben_goodman/apps/bash-repl">projects / Apps / Bash REPL · GitLab</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05ccc37f6709" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>