<?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 Salam shaik on Medium]]></title>
        <description><![CDATA[Stories by Salam shaik on Medium]]></description>
        <link>https://medium.com/@shaiksalam9182?source=rss-6579539aa7a3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8j0FD-kgiC5HXl8gwl3ong.jpeg</url>
            <title>Stories by Salam shaik on Medium</title>
            <link>https://medium.com/@shaiksalam9182?source=rss-6579539aa7a3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:07:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shaiksalam9182/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[Text-to-Clip: Building a Serverless AI Engine that Edits Video from Descriptions]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@shaiksalam9182/text-to-clip-building-a-serverless-ai-engine-that-edits-video-from-descriptions-974444450c17?source=rss-6579539aa7a3------2"><img src="https://cdn-images-1.medium.com/max/2600/1*M7BX2oSoOyM1lgexzCjdIA.png" width="3168"></a></p><p class="medium-feed-snippet">Hi everyone,</p><p class="medium-feed-link"><a href="https://medium.com/@shaiksalam9182/text-to-clip-building-a-serverless-ai-engine-that-edits-video-from-descriptions-974444450c17?source=rss-6579539aa7a3------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@shaiksalam9182/text-to-clip-building-a-serverless-ai-engine-that-edits-video-from-descriptions-974444450c17?source=rss-6579539aa7a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/974444450c17</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-bedrock]]></category>
            <dc:creator><![CDATA[Salam shaik]]></dc:creator>
            <pubDate>Thu, 08 Jan 2026 20:51:23 GMT</pubDate>
            <atom:updated>2026-01-08T20:51:23.283Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How I Built a Video Memory Agent using AWS Bedrock and OpenSearch]]></title>
            <link>https://medium.com/@shaiksalam9182/how-i-built-a-video-memory-agent-using-aws-bedrock-and-opensearch-bfa2b94afb95?source=rss-6579539aa7a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfa2b94afb95</guid>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[aws-opensearch]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-ai-services]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Salam shaik]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 21:21:35 GMT</pubDate>
            <atom:updated>2025-12-22T21:21:35.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BjQPj84Ax7ZDq8wKVXojyw.png" /></figure><p>Hi everyone,</p><p>Searching on OTT platforms is often frustrating. While metadata-based search works for titles, it fails when you search for specific moments — like describing a scene or asking, ‘When does the hero cry?’ You simply can’t get that level of detail from metadata alone.</p><p>My solution was to build an agent that actually ‘watches’ the movie. By analyzing video frames and transcriptions to create a semantic memory, we can achieve far greater accuracy and unlock entirely new ways to interact with video content.</p><p><strong>AWS Services I used:</strong></p><ul><li>Bedrock for Titan, Nova Premiere models, and for Agent creation</li><li>Open search service for storing the video data</li><li>AWS Transcribe Service</li><li>Lambda</li><li>S3 for storing raw video and video frames.</li></ul><h3><strong>High-Level Data Flow:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7oCGmg86kEDMG3Bhp4qESQ.png" /></figure><p>Let me divide this article into different sections:</p><ul><li>Building the Ingestion layer</li><li>Building the Memory layer</li><li>Building the Reasoning layer</li><li>Building the Interface layer</li></ul><h3>Building the Ingestion layer:</h3><ul><li>For this experiment, I downloaded the movie <strong>The Night Of The Living Dead(1968), </strong>which is an open-source movie</li><li>Upload the movie to an S3 bucket</li><li>Visit the AWS Transcribe service and create a transcription job</li><li>Give a name for the job and keep the General model only</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*eZbhZ8swsDGpmlSOW8KrKw.png" /></figure><ul><li>Select the stored movie as input</li><li>Select .srt as output format</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XbYEkYVGsYL7qfCAM8djUQ.png" /></figure><ul><li>Click on next and keep the other options as they are, and create the job</li><li>Once the job is finished, you can see the output SRT file in the bucket you mentioned</li><li>Now that we have the movie file ready and the transcription ready.</li><li>Let’s analyze the video and store that information as JSON files in S3 for further processing</li></ul><pre>import argparse<br>import io<br>import json<br>import math<br>import os<br>from datetime import timedelta<br><br>import boto3<br>from botocore.exceptions import ClientError<br>from moviepy import VideoFileClip<br>from PIL import Image<br>import srt<br><br><br># -----------------------------<br># S3 helpers<br># -----------------------------<br>def parse_s3_uri(uri: str):<br>    &quot;&quot;&quot;<br>    Parse an s3://bucket/key URI into (bucket, key).<br>    &quot;&quot;&quot;<br>    if not uri.startswith(&quot;s3://&quot;):<br>        raise ValueError(f&quot;Invalid S3 URI: {uri}&quot;)<br>    without_scheme = uri[5:]<br>    parts = without_scheme.split(&quot;/&quot;, 1)<br>    if len(parts) != 2:<br>        raise ValueError(f&quot;Invalid S3 URI (missing key): {uri}&quot;)<br>    bucket, key = parts<br>    return bucket, key<br><br><br>def download_s3_object(s3_client, s3_uri: str, local_path: str):<br>    bucket, key = parse_s3_uri(s3_uri)<br>    os.makedirs(os.path.dirname(local_path), exist_ok=True)<br>    print(f&quot;Downloading {s3_uri} -&gt; {local_path}&quot;)<br>    s3_client.download_file(bucket, key, local_path)<br>    return local_path<br><br><br>def upload_json_to_s3(s3_client, s3_uri_prefix: str, filename: str, data: dict):<br>    &quot;&quot;&quot;<br>    Upload a JSON dict as a file under a given s3://bucket/prefix.<br>    &quot;&quot;&quot;<br>    bucket, prefix = parse_s3_uri(s3_uri_prefix)<br>    key = prefix.rstrip(&quot;/&quot;) + &quot;/&quot; + filename<br>    body = json.dumps(data, ensure_ascii=False).encode(&quot;utf-8&quot;)<br>    print(f&quot;Uploading scene doc -&gt; s3://{bucket}/{key}&quot;)<br>    s3_client.put_object(Bucket=bucket, Key=key, Body=body)<br><br><br># -----------------------------<br># SRT helpers<br># -----------------------------<br>def load_srt_subtitles(srt_path: str):<br>    &quot;&quot;&quot;<br>    Load SRT file and return a list of srt.Subtitle objects.<br>    &quot;&quot;&quot;<br>    with open(srt_path, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        content = f.read()<br>    subtitles = list(srt.parse(content))<br>    return subtitles<br><br><br>def get_text_for_range(subtitles, start_sec: float, end_sec: float) -&gt; str:<br>    &quot;&quot;&quot;<br>    Get concatenated subtitle text for [start_sec, end_sec) range.<br>    Includes any subtitle that overlaps this time range.<br>    &quot;&quot;&quot;<br>    texts = []<br>    for sub in subtitles:<br>        sub_start = sub.start.total_seconds()<br>        sub_end = sub.end.total_seconds()<br>        # Overlap check<br>        if sub_end &lt;= start_sec or sub_start &gt;= end_sec:<br>            continue<br>        # Clean line breaks<br>        texts.append(sub.content.replace(&quot;\n&quot;, &quot; &quot;))<br>    return &quot; &quot;.join(texts).strip()<br><br><br># -----------------------------<br># Video frame extraction helpers<br># -----------------------------<br>def extract_minute_frame_bytes(<br>    clip: VideoFileClip,<br>    minute_index: int,<br>    frames_per_minute: int = 5,<br>    image_format: str = &quot;jpeg&quot;,<br>):<br>    &quot;&quot;&quot;<br>    For a given minute index, extract `frames_per_minute` frames<br>    as raw image bytes (JPEG by default).<br>    Returns a list of bytes objects.<br>    &quot;&quot;&quot;<br>    duration_sec = clip.duration<br>    start = minute_index * 60.0<br>    if start &gt;= duration_sec:<br>        return []<br><br>    end = min(start + 60.0, duration_sec)<br>    window = end - start<br>    if window &lt;= 0:<br>        return []<br><br>    # Sample timestamps evenly inside the minute window.<br>    # Use (frames_per_minute + 1) so we don&#39;t hit exact edges.<br>    step = window / (frames_per_minute + 1)<br>    timestamps = [start + step * (i + 1) for i in range(frames_per_minute)]<br><br>    images_bytes = []<br>    for t in timestamps:<br>        # Clip to duration just in case of rounding<br>        t = min(t, duration_sec - 0.01)<br>        frame = clip.get_frame(t)  # numpy array (H, W, 3)<br><br>        # Convert numpy array to JPEG bytes using Pillow<br>        pil_img = Image.fromarray(frame)<br>        buf = io.BytesIO()<br>        pil_img.save(buf, format=image_format.upper())<br>        buf.seek(0)<br>        images_bytes.append(buf.read())<br><br>    return images_bytes<br><br><br>def format_timestamp(seconds: float) -&gt; str:<br>    &quot;&quot;&quot;<br>    Format seconds as HH:MM:SS (floor).<br>    &quot;&quot;&quot;<br>    return str(timedelta(seconds=int(seconds)))<br><br><br># -----------------------------<br># Bedrock (Nova Premier) helper<br># -----------------------------<br>def call_nova_premier(<br>    bedrock_client,<br>    model_id: str,<br>    scene_text: str,<br>    frame_bytes_list,<br>    minute_index: int,<br>):<br>    &quot;&quot;&quot;<br>    Call Amazon Nova Premier via the Bedrock Converse API with:<br>      - scene_text (subtitles for this minute)<br>      - up to N images (frames) as bytes<br><br>    Returns a structured dict with:<br>      scene_summary, characters, locations, emotions,<br>      relationships, topics, visual_tags, important_events<br>    &quot;&quot;&quot;<br><br>    system_prompt = (<br>        &quot;You are a precise video scene analyst. &quot;<br>        &quot;You receive up to 5 frames from a one-minute video segment &quot;<br>        &quot;plus the dialogue/subtitles text for the same time range.\n&quot;<br>        &quot;Your task is to return a STRICT JSON object with this exact schema:\n\n&quot;<br>        &quot;{\n&quot;<br>        &#39;  \&quot;scene_summary\&quot;: \&quot;...\&quot;,\n&#39;<br>        &quot;  \&quot;characters\&quot;: [\&quot;...\&quot;],\n&quot;<br>        &quot;  \&quot;locations\&quot;: [\&quot;...\&quot;],\n&quot;<br>        &quot;  \&quot;emotions\&quot;: [\&quot;...\&quot;],\n&quot;<br>        &quot;  \&quot;relationships\&quot;: [\&quot;...\&quot;],\n&quot;<br>        &quot;  \&quot;topics\&quot;: [\&quot;...\&quot;],\n&quot;<br>        &quot;  \&quot;visual_tags\&quot;: [\&quot;...\&quot;],\n&quot;<br>        &quot;  \&quot;important_events\&quot;: [\&quot;...\&quot;]\n&quot;<br>        &quot;}\n\n&quot;<br>        &quot;Rules:\n&quot;<br>        &quot;- Only output JSON, nothing else.\n&quot;<br>        &quot;- If a field is unknown, use an empty list [] or a short generic summary.\n&quot;<br>        &quot;- Keep lists reasonably short and focused.&quot;<br>    )<br><br>    user_text = (<br>        f&quot;This is minute {minute_index} of the video.\n\n&quot;<br>        f&quot;Subtitles for this minute:\n{scene_text or &#39;[No subtitles in this range]&#39;}\n\n&quot;<br>        &quot;Use the attached frames and text together to analyze this specific one-minute scene.\n&quot;<br>        &quot;Return ONLY the JSON object as specified.&quot;<br>    )<br><br>    # Build message content: first text, then each image as a separate block<br>    content_blocks = [{&quot;text&quot;: user_text}]<br><br>    for img_bytes in frame_bytes_list:<br>        content_blocks.append(<br>            {<br>                &quot;image&quot;: {<br>                    &quot;format&quot;: &quot;jpeg&quot;,<br>                    &quot;source&quot;: {<br>                        &quot;bytes&quot;: img_bytes<br>                    },<br>                }<br>            }<br>        )<br><br>    messages = [<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: content_blocks,<br>        }<br>    ]<br><br>    try:<br>        response = bedrock_client.converse(<br>            modelId=model_id,<br>            system=[{&quot;text&quot;: system_prompt}],<br>            messages=messages,<br>            inferenceConfig={<br>                &quot;maxTokens&quot;: 512,<br>                &quot;temperature&quot;: 0.2,<br>                &quot;topP&quot;: 0.9,<br>            },<br>        )<br><br>        output_message = response[&quot;output&quot;][&quot;message&quot;]<br>        raw_text = output_message[&quot;content&quot;][0][&quot;text&quot;]<br><br>        # Sometimes models may wrap JSON with text; try to extract JSON substring<br>        raw_text = raw_text.strip()<br>        try:<br>            # Try direct parse first<br>            scene_info = json.loads(raw_text)<br>        except json.JSONDecodeError:<br>            # Fallback: find first &#39;{&#39; and last &#39;}&#39; and parse that<br>            start = raw_text.find(&quot;{&quot;)<br>            end = raw_text.rfind(&quot;}&quot;)<br>            if start != -1 and end != -1 and end &gt; start:<br>                json_str = raw_text[start : end + 1]<br>                scene_info = json.loads(json_str)<br>            else:<br>                raise<br><br>        # Ensure all expected keys exist<br>        default_scene = {<br>            &quot;scene_summary&quot;: &quot;&quot;,<br>            &quot;characters&quot;: [],<br>            &quot;locations&quot;: [],<br>            &quot;emotions&quot;: [],<br>            &quot;relationships&quot;: [],<br>            &quot;topics&quot;: [],<br>            &quot;visual_tags&quot;: [],<br>            &quot;important_events&quot;: [],<br>        }<br>        default_scene.update(scene_info or {})<br>        return default_scene<br><br>    except Exception as e:<br>        print(f&quot;[ERROR] Bedrock call or JSON parsing failed for minute {minute_index}: {e}&quot;)<br>        return {<br>            &quot;scene_summary&quot;: &quot;&quot;,<br>            &quot;characters&quot;: [],<br>            &quot;locations&quot;: [],<br>            &quot;emotions&quot;: [],<br>            &quot;relationships&quot;: [],<br>            &quot;topics&quot;: [],<br>            &quot;visual_tags&quot;: [],<br>            &quot;important_events&quot;: [],<br>        }<br><br><br># -----------------------------<br># Main orchestration<br># -----------------------------<br>def analyze_video_from_s3(<br>    video_s3_uri: str,<br>    srt_s3_uri: str,<br>    region: str,<br>    model_id: str,<br>    frames_per_minute: int,<br>    output_s3_prefix: str,<br>    video_id: str,<br>    episode_title: str = &quot;&quot;,<br>    season: int | None = None,<br>    episode: int | None = None,<br>):<br>    &quot;&quot;&quot;<br>    1. Download video and SRT from S3.<br>    2. Parse duration and subtitles.<br>    3. For each minute:<br>       - sample frames<br>       - gather subtitle text<br>       - call Nova Premier for structured analysis<br>       - build scene_doc and upload to S3<br>    &quot;&quot;&quot;<br><br>    session = boto3.Session(region_name=region)<br>    s3_client = session.client(&quot;s3&quot;)<br>    bedrock_client = session.client(&quot;bedrock-runtime&quot;)<br><br>    # Local temp paths<br>    tmp_dir = &quot;./tmp_video_analysis&quot;<br>    os.makedirs(tmp_dir, exist_ok=True)<br>    video_path = os.path.join(tmp_dir, &quot;video_input.mp4&quot;)<br>    srt_path = os.path.join(tmp_dir, &quot;subtitles.srt&quot;)<br><br>    # Download from S3<br>    download_s3_object(s3_client, video_s3_uri, video_path)<br>    download_s3_object(s3_client, srt_s3_uri, srt_path)<br><br>    # Load subtitles<br>    subtitles = load_srt_subtitles(srt_path)<br><br>    # Load video and get duration<br>    clip = VideoFileClip(video_path)<br>    duration_sec = clip.duration<br>    num_minutes = math.ceil(duration_sec / 60.0)<br><br>    print(f&quot;Video duration: {duration_sec:.2f} seconds (~{num_minutes} minutes)\n&quot;)<br><br>    try:<br>        for minute_index in range(num_minutes):<br>            start_sec = minute_index * 60.0<br>            end_sec = min((minute_index + 1) * 60.0, duration_sec)<br><br>            print(f&quot;Processing minute {minute_index} [{start_sec:.1f}s - {end_sec:.1f}s]&quot;)<br><br>            # 1) Extract frames for this minute<br>            frames = extract_minute_frame_bytes(<br>                clip,<br>                minute_index,<br>                frames_per_minute=frames_per_minute,<br>                image_format=&quot;jpeg&quot;,<br>            )<br><br>            if not frames:<br>                print(f&quot;  No frames extracted for minute {minute_index}, skipping scene doc.&quot;)<br>                continue<br><br>            # 2) Extract subtitles text for this minute<br>            scene_text = get_text_for_range(subtitles, start_sec, end_sec)<br><br>            # 3) Call Nova Premier for structured scene info<br>            scene_info = call_nova_premier(<br>                bedrock_client=bedrock_client,<br>                model_id=model_id,<br>                scene_text=scene_text,<br>                frame_bytes_list=frames,<br>                minute_index=minute_index,<br>            )<br><br>            # 4) Build scene_doc<br>            scene_id = f&quot;{video_id}_m{minute_index:04d}&quot;<br>            scene_doc = {<br>                &quot;video_id&quot;: video_id,<br>                &quot;episode_title&quot;: episode_title,<br>                &quot;season&quot;: season,<br>                &quot;episode&quot;: episode,<br>                &quot;scene_id&quot;: scene_id,<br>                &quot;start_sec&quot;: start_sec,<br>                &quot;end_sec&quot;: end_sec,<br>                &quot;timestamp_label&quot;: f&quot;{format_timestamp(start_sec)} - {format_timestamp(end_sec)}&quot;,<br>                &quot;transcript&quot;: scene_text,<br>                &quot;nova_scene_summary&quot;: scene_info.get(&quot;scene_summary&quot;, &quot;&quot;),<br>                &quot;characters&quot;: scene_info.get(&quot;characters&quot;, []),<br>                &quot;locations&quot;: scene_info.get(&quot;locations&quot;, []),<br>                &quot;emotions&quot;: scene_info.get(&quot;emotions&quot;, []),<br>                &quot;relationships&quot;: scene_info.get(&quot;relationships&quot;, []),<br>                &quot;topics&quot;: scene_info.get(&quot;topics&quot;, []),<br>                &quot;visual_tags&quot;: scene_info.get(&quot;visual_tags&quot;, []),<br>                &quot;important_events&quot;: scene_info.get(&quot;important_events&quot;, []),<br>            }<br><br>            # 5) Upload scene_doc JSON to S3<br>            filename = f&quot;{scene_id}.json&quot;<br>            upload_json_to_s3(s3_client, output_s3_prefix, filename, scene_doc)<br><br>            print(f&quot;  Scene doc created: {scene_id}&quot;)<br><br>    finally:<br>        clip.close()<br><br><br>def main():<br>    parser = argparse.ArgumentParser(<br>        description=(<br>            &quot;Download a video from S3, sample frames per minute, &quot;<br>            &quot;combine with SRT text, analyze with Amazon Nova Premier, &quot;<br>            &quot;and upload per-minute scene docs to S3.&quot;<br>        )<br>    )<br>    parser.add_argument(<br>        &quot;--video-s3&quot;,<br>        required=True,<br>        help=&quot;S3 URI of the video file. Example: s3://my-bucket/path/video.mp4&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--srt-s3&quot;,<br>        required=True,<br>        help=&quot;S3 URI of the SRT subtitle file. Example: s3://my-bucket/path/video.srt&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--output-s3-prefix&quot;,<br>        required=True,<br>        help=(<br>            &quot;S3 URI prefix where scene docs will be stored. &quot;<br>            &quot;Example: s3://my-bucket/3netra/FRIENDS_S01E01&quot;<br>        ),<br>    )<br>    parser.add_argument(<br>        &quot;--video-id&quot;,<br>        required=True,<br>        help=&quot;Logical video ID (e.g., FRIENDS_S01E01). Used in scene_id and metadata.&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--episode-title&quot;,<br>        default=&quot;&quot;,<br>        help=&quot;Optional episode title for metadata.&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--season&quot;,<br>        type=int,<br>        default=None,<br>        help=&quot;Optional season number for metadata.&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--episode&quot;,<br>        type=int,<br>        default=None,<br>        help=&quot;Optional episode number for metadata.&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--region&quot;,<br>        default=&quot;us-east-1&quot;,<br>        help=&quot;AWS Region where Bedrock is available (default: us-east-1).&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--model-id&quot;,<br>        default=&quot;amazon.nova-premier-v1:0&quot;,<br>        help=&quot;Bedrock model ID for Nova Premier (default: amazon.nova-premier-v1:0).&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--frames-per-minute&quot;,<br>        type=int,<br>        default=5,<br>        help=&quot;How many frames to sample per minute window (default: 5).&quot;,<br>    )<br><br>    args = parser.parse_args()<br><br>    analyze_video_from_s3(<br>        video_s3_uri=args.video_s3,<br>        srt_s3_uri=args.srt_s3,<br>        region=args.region,<br>        model_id=args.model_id,<br>        frames_per_minute=args.frames_per_minute,<br>        output_s3_prefix=args.output_s3_prefix,<br>        video_id=args.video_id,<br>        episode_title=args.episode_title,<br>        season=args.season,<br>        episode=args.episode,<br>    )<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><ul><li>This script will help in downloading the video from the S3 and extracting frames for every minute, and combines those frames with the dialogues in the SRT file within that limit and sends them to the Nova Premiere model for analyzing</li><li>Those JSON files will be dumped to the S3 bucket.</li><li>This ends the ingestion module. Let’s work on the memory module</li></ul><h3><strong>Building the Memory layer:</strong></h3><ul><li>Visit the Open Search service from the AWS console</li><li>Create a domain with 1AZ, single standby, and with a t3.large instance for the dev/test environment</li><li>Once the domain is up and running, visit the Opensearch dashboard and create an index with this schema in dev tools from the side menu</li></ul><pre>PUT video_scenes<br>{<br>  &quot;settings&quot;: {<br>    &quot;index&quot;: {<br>      &quot;knn&quot;: true<br>    }<br>  },<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;video_id&quot;:        { &quot;type&quot;: &quot;keyword&quot; },<br>      &quot;scene_id&quot;:        { &quot;type&quot;: &quot;keyword&quot; },<br>      &quot;episode_title&quot;:   { &quot;type&quot;: &quot;text&quot; },<br>      &quot;season&quot;:          { &quot;type&quot;: &quot;integer&quot; },<br>      &quot;episode&quot;:         { &quot;type&quot;: &quot;integer&quot; },<br><br>      &quot;start_sec&quot;:       { &quot;type&quot;: &quot;integer&quot; },<br>      &quot;end_sec&quot;:         { &quot;type&quot;: &quot;integer&quot; },<br>      &quot;timestamp_label&quot;: { &quot;type&quot;: &quot;keyword&quot; },<br><br>      &quot;transcript&quot;:       { &quot;type&quot;: &quot;text&quot; },<br>      &quot;nova_scene_summary&quot;: { &quot;type&quot;: &quot;text&quot; },<br><br>      &quot;characters&quot;:      { &quot;type&quot;: &quot;keyword&quot; },<br>      &quot;locations&quot;:       { &quot;type&quot;: &quot;keyword&quot; },<br>      &quot;emotions&quot;:        { &quot;type&quot;: &quot;keyword&quot; },<br>      &quot;relationships&quot;:   { &quot;type&quot;: &quot;text&quot; },<br>      &quot;topics&quot;:          { &quot;type&quot;: &quot;keyword&quot; },<br>      &quot;visual_tags&quot;:     { &quot;type&quot;: &quot;keyword&quot; },<br>      &quot;important_events&quot;:{ &quot;type&quot;: &quot;text&quot; },<br><br>      &quot;embedding&quot;: {<br>        &quot;type&quot;: &quot;knn_vector&quot;,<br>        &quot;dimension&quot;: 1024,<br>        &quot;method&quot;: {<br>          &quot;name&quot;: &quot;hnsw&quot;,<br>          &quot;space_type&quot;: &quot;cosinesimil&quot;,<br>          &quot;engine&quot;: &quot;lucene&quot;<br>        }<br>      }<br>    }<br>  }<br>}</pre><ul><li>Use the script below to generate embeddings for the JSON files and dump them into this index</li></ul><pre>import argparse<br>import json<br>import os<br><br>import boto3<br>from botocore.exceptions import ClientError<br>from opensearchpy import OpenSearch, RequestsHttpConnection<br>from requests_aws4auth import AWS4Auth<br><br><br># -------------- S3 helpers --------------<br>def parse_s3_uri(uri: str):<br>    if not uri.startswith(&quot;s3://&quot;):<br>        raise ValueError(f&quot;Invalid S3 URI: {uri}&quot;)<br>    without = uri[5:]<br>    parts = without.split(&quot;/&quot;, 1)<br>    if len(parts) != 2:<br>        raise ValueError(f&quot;Invalid S3 URI (missing key/prefix): {uri}&quot;)<br>    return parts[0], parts[1]<br><br><br>def list_s3_json_objects(s3_client, s3_prefix_uri: str):<br>    &quot;&quot;&quot;<br>    List all JSON objects under the given s3://bucket/prefix<br>    (this is where your scene_docs are stored).<br>    &quot;&quot;&quot;<br>    bucket, prefix = parse_s3_uri(s3_prefix_uri)<br>    paginator = s3_client.get_paginator(&quot;list_objects_v2&quot;)<br><br>    for page in paginator.paginate(Bucket=bucket, Prefix=prefix.rstrip(&quot;/&quot;) + &quot;/&quot;):<br>        for obj in page.get(&quot;Contents&quot;, []):<br>            key = obj[&quot;Key&quot;]<br>            if key.lower().endswith(&quot;.json&quot;):<br>                yield bucket, key<br><br><br>def get_s3_json(s3_client, bucket: str, key: str) -&gt; dict:<br>    resp = s3_client.get_object(Bucket=bucket, Key=key)<br>    body = resp[&quot;Body&quot;].read().decode(&quot;utf-8&quot;)<br>    return json.loads(body)<br><br><br># -------------- Bedrock (Titan Embeddings) --------------<br>def get_titan_embedding(bedrock_client, model_id: str, text: str, dimensions: int = 1024):<br>    &quot;&quot;&quot;<br>    Call Titan Text Embeddings v2 (or G1) to get an embedding vector.<br>    Docs: inputText + optional dimensions. :contentReference[oaicite:1]{index=1}<br>    &quot;&quot;&quot;<br>    if not text:<br>        text = &quot; &quot;  # Titan requires non-empty string<br><br>    body = json.dumps(<br>        {<br>            &quot;inputText&quot;: text<br>        }<br>    )<br><br>    resp = bedrock_client.invoke_model(<br>        modelId=model_id,<br>        body=body,<br>        contentType=&quot;application/json&quot;,<br>        accept=&quot;application/json&quot;,<br>    )<br>    resp_body = json.loads(resp[&quot;body&quot;].read())<br>    # titan-embed-text-v2 response: {&quot;embedding&quot;: [...], &quot;inputTextTokenCount&quot;: ...}<br>    embedding = resp_body[&quot;embedding&quot;]<br>    return embedding<br><br><br>def build_embedding_text(scene_doc: dict) -&gt; str:<br>    &quot;&quot;&quot;<br>    Concatenate important fields into a single text for embeddings.<br>    &quot;&quot;&quot;<br>    parts = []<br><br>    summary = scene_doc.get(&quot;nova_scene_summary&quot;) or scene_doc.get(&quot;scene_summary&quot;) or &quot;&quot;<br>    transcript = scene_doc.get(&quot;transcript&quot;, &quot;&quot;)<br>    chars = &quot;, &quot;.join(scene_doc.get(&quot;characters&quot;, []))<br>    rels = &quot;; &quot;.join(scene_doc.get(&quot;relationships&quot;, []))<br>    topics = &quot;, &quot;.join(scene_doc.get(&quot;topics&quot;, []))<br>    emotions = &quot;, &quot;.join(scene_doc.get(&quot;emotions&quot;, []))<br>    visual_tags = &quot;, &quot;.join(scene_doc.get(&quot;visual_tags&quot;, []))<br><br>    if summary:<br>        parts.append(&quot;[Summary] &quot; + summary)<br>    if transcript:<br>        parts.append(&quot;[Transcript] &quot; + transcript)<br>    if chars:<br>        parts.append(&quot;[Characters] &quot; + chars)<br>    if rels:<br>        parts.append(&quot;[Relationships] &quot; + rels)<br>    if topics:<br>        parts.append(&quot;[Topics] &quot; + topics)<br>    if emotions:<br>        parts.append(&quot;[Emotions] &quot; + emotions)<br>    if visual_tags:<br>        parts.append(&quot;[Visual tags] &quot; + visual_tags)<br><br>    return &quot;\n&quot;.join(parts)<br><br><br># -------------- OpenSearch client --------------<br>def create_opensearch_client(<br>    region: str,<br>    endpoint: str,<br>    service: str = &quot;aoss&quot;,<br>    username: str | None = None,<br>    password: str | None = None,<br>):<br>    &quot;&quot;&quot;<br>    Create an OpenSearch client.<br><br>    Authentication modes:<br>      - If `username` and `password` are provided, use HTTP Basic auth.<br>      - Otherwise, fall back to SigV4 (AWS) auth for Serverless or classic domains.<br><br>    service:<br>      - &#39;aoss&#39; for OpenSearch Serverless<br>      - &#39;es&#39;   for classic OpenSearch domains<br>    &quot;&quot;&quot;<br>    host = endpoint.replace(&quot;https://&quot;, &quot;&quot;).replace(&quot;http://&quot;, &quot;&quot;)<br><br>    if username is not None and password is not None:<br>        # Use HTTP basic auth (username/password)<br>        http_auth = (username, password)<br>    else:<br>        # Fall back to AWS SigV4 auth<br>        session = boto3.Session(region_name=region)<br>        credentials = session.get_credentials()<br>        awsauth = AWS4Auth(<br>            credentials.access_key,<br>            credentials.secret_key,<br>            region,<br>            service,<br>            session_token=credentials.token,<br>        )<br>        http_auth = awsauth<br><br>    client = OpenSearch(<br>        hosts=[{&quot;host&quot;: host, &quot;port&quot;: 443}],<br>        http_auth=http_auth,<br>        use_ssl=True,<br>        verify_certs=True,<br>        connection_class=RequestsHttpConnection,<br>    )<br>    return client<br><br><br>def index_scene_doc(os_client, index_name: str, doc: dict):<br>    &quot;&quot;&quot;<br>    Index a single scene_doc into OpenSearch.<br>    &quot;&quot;&quot;<br>    scene_id = doc[&quot;scene_id&quot;]<br>    resp = os_client.index(index=index_name, id=scene_id, body=doc, refresh=False)<br>    return resp<br><br><br># -------------- Main indexing flow --------------<br>def index_scenes_to_opensearch(<br>    scene_s3_prefix: str,<br>    region: str,<br>    embed_model_id: str,<br>    os_endpoint: str,<br>    os_index: str,<br>    os_service: str = &quot;aoss&quot;,<br>    os_username: str | None = None,<br>    os_password: str | None = None,<br>    embedding_dim: int = 1024,<br>):<br>    session = boto3.Session(region_name=region)<br>    s3_client = session.client(&quot;s3&quot;)<br>    bedrock_client = session.client(&quot;bedrock-runtime&quot;)<br>    os_client = create_opensearch_client(<br>        region, os_endpoint, service=os_service, username=os_username, password=os_password<br>    )<br><br>    for bucket, key in list_s3_json_objects(s3_client, scene_s3_prefix):<br>        print(f&quot;Processing s3://{bucket}/{key}&quot;)<br>        scene_doc = get_s3_json(s3_client, bucket, key)<br><br>        # Build text and embedding<br>        embed_text = build_embedding_text(scene_doc)<br>        embedding = get_titan_embedding(<br>            bedrock_client, embed_model_id, embed_text, dimensions=embedding_dim<br>        )<br><br>        # Attach embedding field<br>        scene_doc[&quot;embedding&quot;] = embedding<br><br>        # Index into OpenSearch<br>        resp = index_scene_doc(os_client, os_index, scene_doc)<br>        result = resp.get(&quot;result&quot;, &quot;unknown&quot;)<br>        print(f&quot;  Indexed scene_id={scene_doc.get(&#39;scene_id&#39;)} result={result}&quot;)<br><br><br>def main():<br>    parser = argparse.ArgumentParser(<br>        description=(<br>            &quot;Index 3Netra scene docs from S3 into OpenSearch using Titan embeddings.&quot;<br>        )<br>    )<br>    parser.add_argument(<br>        &quot;--scene-s3-prefix&quot;,<br>        required=True,<br>        help=(<br>            &quot;S3 URI prefix where scene JSONs are stored. &quot;<br>            &quot;Example: s3://my-bucket/3netra/FRIENDS_S01E01&quot;<br>        ),<br>    )<br>    parser.add_argument(<br>        &quot;--region&quot;,<br>        default=&quot;us-east-1&quot;,<br>        help=&quot;AWS Region for Bedrock, S3, and OpenSearch (default: us-east-1).&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--embed-model-id&quot;,<br>        default=&quot;amazon.titan-embed-text-v2:0&quot;,<br>        help=&quot;Titan embeddings model ID (default: amazon.titan-embed-text-v2:0).&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--os-endpoint&quot;,<br>        required=True,<br>        help=(<br>            &quot;OpenSearch HTTPS endpoint (no index). &quot;<br>            &quot;Example: https://abc123.us-east-1.aoss.amazonaws.com&quot;<br>        ),<br>    )<br>    parser.add_argument(<br>        &quot;--os-index&quot;,<br>        default=&quot;video_scenes&quot;,<br>        help=&quot;OpenSearch index name (default: video_scenes).&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--os-service&quot;,<br>        default=&quot;aoss&quot;,<br>        help=&quot;SigV4 service name: &#39;aoss&#39; for Serverless, &#39;es&#39; for domains (default: aoss).&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--os-username&quot;,<br>        help=(<br>            &quot;OpenSearch basic auth username (optional). &quot;<br>            &quot;If not provided, the script will read `OS_USERNAME` or `OPENSEARCH_USERNAME` env vars.&quot;<br>        ),<br>    )<br>    parser.add_argument(<br>        &quot;--os-password&quot;,<br>        help=(<br>            &quot;OpenSearch basic auth password (optional). &quot;<br>            &quot;If not provided, the script will read `OS_PASSWORD` or `OPENSEARCH_PASSWORD` env vars.&quot;<br>        ),<br>    )<br>    parser.add_argument(<br>        &quot;--embedding-dim&quot;,<br>        type=int,<br>        default=1024,<br>        help=&quot;Embedding dimension (must match index mapping, default: 1024).&quot;,<br>    )<br><br>    args = parser.parse_args()<br><br>    # Accept username/password from CLI args or environment variables.<br>    os_username = (<br>        args.os_username<br>        or os.environ.get(&quot;OS_USERNAME&quot;)<br>        or os.environ.get(&quot;OPENSEARCH_USERNAME&quot;)<br>    )<br>    os_password = (<br>        args.os_password<br>        or os.environ.get(&quot;OS_PASSWORD&quot;)<br>        or os.environ.get(&quot;OPENSEARCH_PASSWORD&quot;)<br>    )<br><br>    index_scenes_to_opensearch(<br>        scene_s3_prefix=args.scene_s3_prefix,<br>        region=args.region,<br>        embed_model_id=args.embed_model_id,<br>        os_endpoint=args.os_endpoint,<br>        os_index=args.os_index,<br>        os_service=args.os_service,<br>        os_username=os_username,<br>        os_password=os_password,<br>        embedding_dim=args.embedding_dim,<br>    )<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><ul><li>You can see the data dumped through the Discover section or using the workbench from the side menu in the OpenSearch dashboard</li></ul><h3>Building the Reasoning Layer:</h3><ul><li>Create a lambda function with this code</li></ul><pre>import json<br>import boto3<br>import os<br>from opensearchpy import OpenSearch, RequestsHttpConnection<br><br># --- Configuration ---<br># Store these in Lambda Environment Variables for security<br>OPENSEARCH_HOST = &quot;&quot;<br>OPENSEARCH_USER = &quot;&quot;<br>OPENSEARCH_PASS = &quot;&quot;<br>REGION = os.environ.get(&#39;AWS_REGION&#39;, &#39;us-west-2&#39;)<br><br># --- Clients ---<br>bedrock_runtime = boto3.client(&#39;bedrock-runtime&#39;, region_name=REGION)<br><br>os_client = OpenSearch(<br>    hosts=[{&#39;host&#39;: OPENSEARCH_HOST, &#39;port&#39;: 443}],<br>    http_auth=(OPENSEARCH_USER, OPENSEARCH_PASS),<br>    use_ssl=True,<br>    verify_certs=True,<br>    connection_class=RequestsHttpConnection<br>)<br><br>def get_embedding(text):<br>    &quot;&quot;&quot;Generates vector embedding using Titan v2&quot;&quot;&quot;<br>    body = json.dumps({&quot;inputText&quot;: text})<br>    response = bedrock_runtime.invoke_model(<br>        modelId=&quot;amazon.titan-embed-text-v2:0&quot;,<br>        body=body,<br>        accept=&quot;application/json&quot;,<br>        contentType=&quot;application/json&quot;<br>    )<br>    response_body = json.loads(response[&#39;body&#39;].read())<br>    return response_body[&#39;embedding&#39;]<br><br>def search_opensearch(vector, video_id, k=5):<br>    &quot;&quot;&quot;Performs k-NN search on OpenSearch&quot;&quot;&quot;<br>    query = {<br>        &quot;size&quot;: k,<br>        &quot;_source&quot;: [&quot;timestamp_label&quot;, &quot;nova_scene_summary&quot;, &quot;characters&quot;, &quot;emotions&quot;],<br>        &quot;query&quot;: {<br>            &quot;knn&quot;: {<br>                &quot;embedding&quot;: {  # Ensure this field name matches your index mapping<br>                    &quot;vector&quot;: vector,<br>                    &quot;k&quot;: k<br>                }<br>            }<br>        }<br>    }<br>    # In production, use an alias or specific index logic<br>    index_name = &quot;video_scenes&quot;<br>    response = os_client.search(index=index_name, body=query)<br>    return [hit[&#39;_source&#39;] for hit in response[&#39;hits&#39;][&#39;hits&#39;]]<br><br>def parse_timestamp(ts_str):<br>    &quot;&quot;&quot;Helper to convert timestamp to seconds for sorting&quot;&quot;&quot;<br>    try:<br>        start = ts_str.split(&#39;-&#39;)[0].strip()<br>        parts = list(map(int, start.split(&#39;:&#39;)))<br>        if len(parts) == 3: return parts[0]*3600 + parts[1]*60 + parts[2]<br>        if len(parts) == 2: return parts[0]*60 + parts[1]<br>        return 0<br>    except:<br>        return 0<br><br>def lambda_handler(event, context):<br>    print(f&quot;Received Event: {event}&quot;)<br>    <br>    # 1. Initialize Response Info<br>    # We must echo back the same identifiers Bedrock sent us<br>    action_group = event.get(&#39;actionGroup&#39;, &#39;&#39;)<br>    api_path = event.get(&#39;apiPath&#39;)<br>    http_method = event.get(&#39;httpMethod&#39;)<br>    function_name = event.get(&#39;function&#39;) # Fallback for different agent types<br>    <br>    # 2. Extract Parameters<br>    # Bedrock sends parameters in a list: [{&#39;name&#39;: &#39;query&#39;, &#39;value&#39;: &#39;...&#39;}, ...]<br>    params = {}<br>    if &#39;parameters&#39; in event:<br>        for p in event[&#39;parameters&#39;]:<br>            params[p[&#39;name&#39;]] = p[&#39;value&#39;]<br>            <br>    # Also check &#39;requestBody&#39; if parameters aren&#39;t found (common in POST requests)<br>    if not params and &#39;requestBody&#39; in event:<br>        try:<br>            body_content = event[&#39;requestBody&#39;][&#39;content&#39;][&#39;application/json&#39;][&#39;properties&#39;]<br>            for prop in body_content:<br>                params[prop[&#39;name&#39;]] = prop[&#39;value&#39;]<br>        except:<br>            pass<br><br>    user_query = params.get(&#39;query&#39;, &#39;&#39;)<br>    video_id = params.get(&#39;video_id&#39;, &#39;default_video&#39;)<br><br>    # 3. Validation<br>    if not user_query:<br>        result_text = &quot;Error: No query provided in parameters.&quot;<br>    else:<br>        # 4. Perform Search (Your existing logic)<br>        try:<br>            print(f&quot;Embedding query: {user_query}&quot;)<br>            vector = get_embedding(user_query)<br>            <br>            print(f&quot;Searching OpenSearch for video: {video_id}&quot;)<br>            raw_hits = search_opensearch(vector, video_id)<br>            <br>            # Sort by timestamp<br>            sorted_hits = sorted(raw_hits, key=lambda x: parse_timestamp(x.get(&#39;timestamp_label&#39;, &#39;0:00&#39;)))<br>            <br>            # Format Context<br>            result_text = &quot;RELEVANT VIDEO SCENES (Chronological):\n&quot;<br>            if not sorted_hits:<br>                result_text += &quot;No relevant scenes found in memory.&quot;<br>            else:<br>                for hit in sorted_hits:<br>                    # Robust field access<br>                    time_lbl = hit.get(&#39;timestamp_label&#39;, &#39;Unknown Time&#39;)<br>                    summary = hit.get(&#39;nova_scene_summary&#39;, &#39;No summary&#39;)<br>                    emotions = hit.get(&#39;emotions&#39;, [])<br>                    if isinstance(emotions, list): emotions = &quot;, &quot;.join(emotions)<br>                    <br>                    result_text += f&quot;[Time: {time_lbl}] {summary} (Emotions: {emotions})\n&quot;<br>                    <br>        except Exception as e:<br>            print(f&quot;Processing Error: {str(e)}&quot;)<br>            result_text = f&quot;System Error during search: {str(e)}&quot;<br><br>    # 5. Construct Response (Dynamic based on Input Type)<br>    response_body = {<br>        &quot;application/json&quot;: {<br>            &quot;body&quot;: result_text<br>        }<br>    }<br><br>    response = {<br>        &quot;messageVersion&quot;: &quot;1.0&quot;,<br>        &quot;response&quot;: {<br>            &quot;actionGroup&quot;: action_group,<br>            &quot;responseBody&quot;: response_body<br>        }<br>    }<br><br>    # If it was an API Path call (OpenAPI), add these keys:<br>    if api_path:<br>        response[&#39;response&#39;][&#39;apiPath&#39;] = api_path<br>        response[&#39;response&#39;][&#39;httpMethod&#39;] = http_method<br>        response[&#39;response&#39;][&#39;httpStatusCode&#39;] = 200<br>    # If it was a Function call, add this key:<br>    elif function_name:<br>        response[&#39;response&#39;][&#39;function&#39;] = function_name<br><br>    print(f&quot;Returning Response: {response}&quot;)<br>    return response<br>    &quot;&quot;&quot;<br>    The Entry Point for the Bedrock Agent.<br>    Bedrock sends parameters inside &#39;parameters&#39; or &#39;requestBody&#39;.<br>    &quot;&quot;&quot;<br>    print(f&quot;Received Event: {event}&quot;)<br>    <br>    # 1. Parse Input from Bedrock Agent<br>    # Bedrock Agents structure events differently. We usually define an Action Group.<br>    # We will assume we extract &#39;query&#39; and &#39;video_id&#39; from the function parameters.<br>    <br>    agent_params = {}<br>    if &#39;parameters&#39; in event:<br>        # Standard Agent format<br>        for param in event[&#39;parameters&#39;]:<br>            agent_params[param[&#39;name&#39;]] = param[&#39;value&#39;]<br>    <br>    user_query = agent_params.get(&#39;query&#39;, &#39;&#39;)<br>    video_id = agent_params.get(&#39;video_id&#39;, &#39;default_video&#39;) # Fallback if needed<br><br>    if not user_query:<br>        return {<br>            &quot;messageVersion&quot;: &quot;1.0&quot;,<br>            &quot;response&quot;: {<br>                &quot;actionGroup&quot;: event.get(&#39;actionGroup&#39;, &#39;&#39;),<br>                &quot;function&quot;: event.get(&#39;function&#39;, &#39;&#39;),<br>                &quot;functionResponse&quot;: {<br>                    &quot;responseBody&quot;: {<br>                        &quot;TEXT&quot;: {&quot;body&quot;: &quot;Error: No query provided.&quot;}<br>                    }<br>                }<br>            }<br>        }<br><br>    # 2. Logic: Embed -&gt; Search -&gt; Sort<br>    try:<br>        vector = get_embedding(user_query)<br>        raw_hits = search_opensearch(vector, video_id)<br>        <br>        # Sort by timestamp (Layer 3 Logic)<br>        sorted_hits = sorted(raw_hits, key=lambda x: parse_timestamp(x.get(&#39;timestamp_label&#39;, &#39;0:00&#39;)))<br>        <br>        # 3. Format Output (The Context String)<br>        context_str = &quot;RELEVANT VIDEO SCENES:\n&quot;<br>        for hit in sorted_hits:<br>            context_str += f&quot;[Time: {hit.get(&#39;timestamp_label&#39;)}] {hit.get(&#39;nova_scene_summary&#39;)} (Emotions: {hit.get(&#39;emotions&#39;)})\n&quot;<br><br>        # 4. Return to Bedrock Agent<br>        # The response structure MUST match what Bedrock expects<br>        response_body = {<br>            &quot;TEXT&quot;: {<br>                &quot;body&quot;: context_str<br>            }<br>        }<br><br>        action_response = {<br>            &quot;actionGroup&quot;: event[&#39;actionGroup&#39;],<br>            &quot;function&quot;: event[&#39;function&#39;],<br>            &quot;functionResponse&quot;: {<br>                &quot;responseBody&quot;: response_body<br>            }<br>        }<br><br>        return {<br>            &quot;messageVersion&quot;: &quot;1.0&quot;,<br>            &quot;response&quot;: action_response<br>        }<br><br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br>        return {<br>            &quot;messageVersion&quot;: &quot;1.0&quot;,<br>            &quot;response&quot;: {<br>                &quot;actionGroup&quot;: event.get(&#39;actionGroup&#39;, &#39;&#39;),<br>                &quot;function&quot;: event.get(&#39;function&#39;, &#39;&#39;),<br>                &quot;functionResponse&quot;: {<br>                    &quot;responseBody&quot;: {<br>                        &quot;TEXT&quot;: {&quot;body&quot;: f&quot;System Error: {str(e)}&quot;}<br>                    }<br>                }<br>            }<br>        }</pre><ul><li>The code first acts as an adapter. It accepts the JSON event from the <strong>Bedrock Agent</strong> (which contains the user’s natural language query) and extracts the core question (e.g., <em>“Why is he crying?”</em>)</li><li>It converts the user’s text query into a <strong>vector embedding</strong> using the <strong>Titan Text v2</strong> model.</li><li>It sends this vector to <strong>OpenSearch</strong> to find the top $k$ most <em>semantically similar</em> scenes. This finds the “right content” regardless of where it is in the video.</li><li><strong>This is the most critical step for reasoning.</strong> The code takes the search results (which come back sorted by <em>relevance score</em>) and re-sorts them by <strong>timestamp</strong>.</li><li><em>Why:</em> This reconstructs the narrative timeline. It ensures the LLM reads the “Cause” (Minute 10) before the “Effect” (Minute 50), preventing it from hallucinating a backwards story.</li><li>Finally, the code strips away complex JSON syntax and formats the data into a clean, human-readable <strong>text block</strong>.</li><li>It labels every scene [Time: MM:SS] so the LLM can cite its sources in the final answer.</li></ul><p><strong>Agent Creation:</strong></p><ul><li>Visit the Agents section from the Bedrock side panel</li><li>Click on the Create Agent button</li><li>Give a name and description for the agent</li><li>Select the model you want to use and give proper instructions for the model based on our use case</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*PG5LQzkSQbEAS7wYcBxfDw.png" /></figure><ul><li>The instructions I gave for the model are</li></ul><pre>You are 3Netra, an expert Video Intelligence AI. <br>You have access to a tool called &quot;search_video_memory&quot; that retrieves scene details from the video.<br><br>YOUR RULES:<br>1. ALWAYS use the &quot;search_video_memory&quot; tool when the user asks about the video content.<br>2. The tool returns a list of scenes with timestamps.<br>3. Answer the user&#39;s question using ONLY that information.<br>4. If the tool returns no relevant info, say &quot;I cannot find that in the video memory.&quot;<br>5. CITE TIMESTAMPS in your answer like this: [05:00].</pre><ul><li>Save till this part and click on add action group.</li><li>Give a name for this, and select the Define with API Schemas, and select the lambda we previously created</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*smo5rWWC-xssJ3rJhuJbog.png" /></figure><ul><li>In the action group schema, select Define via in-line Schema Editor</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*Vas9IG0cG8HP_pW8YbBxKg.png" /></figure><ul><li>Paste this schema there</li></ul><pre>{<br>  &quot;openapi&quot;: &quot;3.0.0&quot;,<br>  &quot;info&quot;: {<br>    &quot;title&quot;: &quot;Video Memory Search API&quot;,<br>    &quot;version&quot;: &quot;1.0.0&quot;,<br>    &quot;description&quot;: &quot;API for searching semantic events and scenes within a video.&quot;<br>  },<br>  &quot;paths&quot;: {<br>    &quot;/search_video_memory&quot;: {<br>      &quot;post&quot;: {<br>        &quot;summary&quot;: &quot;Searches the video memory for relevant scenes based on a user query.&quot;,<br>        &quot;description&quot;: &quot;Use this function whenever the user asks a question about the content, plot, characters, or events in the video.&quot;,<br>        &quot;operationId&quot;: &quot;search_video_memory&quot;,<br>        &quot;parameters&quot;: [<br>          {<br>            &quot;name&quot;: &quot;query&quot;,<br>            &quot;in&quot;: &quot;query&quot;,<br>            &quot;description&quot;: &quot;The natural language question or topic the user is asking about (e.g., &#39;Why is he crying?&#39;).&quot;,<br>            &quot;required&quot;: true,<br>            &quot;schema&quot;: {<br>              &quot;type&quot;: &quot;string&quot;<br>            }<br>          },<br>          {<br>            &quot;name&quot;: &quot;video_id&quot;,<br>            &quot;in&quot;: &quot;query&quot;,<br>            &quot;description&quot;: &quot;The identifier of the video (e.g., &#39;movie_1&#39;). Default to &#39;current_video&#39; if not specified.&quot;,<br>            &quot;required&quot;: true,<br>            &quot;schema&quot;: {<br>              &quot;type&quot;: &quot;string&quot;<br>            }<br>          }<br>        ],<br>        &quot;responses&quot;: {<br>          &quot;200&quot;: {<br>            &quot;description&quot;: &quot;Successfully retrieved scene context&quot;,<br>            &quot;content&quot;: {<br>              &quot;application/json&quot;: {<br>                &quot;schema&quot;: {<br>                  &quot;type&quot;: &quot;object&quot;,<br>                  &quot;properties&quot;: {<br>                    &quot;body&quot;: {<br>                      &quot;type&quot;: &quot;string&quot;,<br>                      &quot;description&quot;: &quot;The text containing relevant scene summaries and timestamps.&quot;<br>                    }<br>                  }<br>                }<br>              }<br>            }<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><ul><li>Save and Exit. Then, prepare the model with these settings. On the right side, you can test your model with your inputs.</li><li>Make sure you have proper permission to access Lambda</li><li>If there are any errors, follow the trace to resolve the issue</li><li>Once you confirm the agent is working fine, create an alias to use it at the interface layer</li></ul><h3>Building the Interface layer:</h3><ul><li>For building the interface layer, we are gonna use the Streamlit library. Install it through PIP</li><li>Copy the Alias code and Agent code to use in this script</li></ul><pre>import streamlit as st<br>import boto3<br>import uuid<br>import json<br><br># --- CONFIGURATION ---<br># Replace these with your actual IDs from Step 1<br>AGENT_ID = &quot;&quot;      # e.g., &quot;X7W3J9...&quot;<br>AGENT_ALIAS_ID = &quot;&quot; # e.g., &quot;TSTALIAS...&quot;<br>SESSION_ID = str(uuid.uuid4())           # Unique ID for this chat session<br>REGION = &quot;us-west-2&quot;                     # Ensure this matches your Agent&#39;s region<br><br># --- CLIENT SETUP ---<br>client = boto3.client(&quot;bedrock-agent-runtime&quot;, region_name=REGION)<br><br>st.set_page_config(page_title=&quot;3Netra Video Agent&quot;, layout=&quot;wide&quot;)<br>st.title(&quot;👁️ 3Netra: Video Memory Agent&quot;)<br><br># --- SESSION STATE (Memory) ---<br>if &quot;messages&quot; not in st.session_state:<br>    st.session_state.messages = []<br><br># --- UI LOGIC ---<br># 1. Display Chat History<br>for message in st.session_state.messages:<br>    with st.chat_message(message[&quot;role&quot;]):<br>        st.markdown(message[&quot;content&quot;])<br><br># 2. Handle User Input<br>if prompt := st.chat_input(&quot;Ask about the video...&quot;):<br>    # Add user message to history<br>    st.session_state.messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt})<br>    with st.chat_message(&quot;user&quot;):<br>        st.markdown(prompt)<br><br>    # 3. Call Bedrock Agent<br>    with st.chat_message(&quot;assistant&quot;):<br>        message_placeholder = st.empty()<br>        full_response = &quot;&quot;<br>        <br>        try:<br>            # The invoke_agent API is streaming (it comes back in chunks)<br>            response = client.invoke_agent(<br>                agentId=AGENT_ID,<br>                agentAliasId=AGENT_ALIAS_ID,<br>                sessionId=SESSION_ID,<br>                inputText=prompt<br>            )<br>            <br>            # Parse the event stream<br>            event_stream = response.get(&quot;completion&quot;)<br>            for event in event_stream:<br>                if &#39;chunk&#39; in event:<br>                    chunk = event[&#39;chunk&#39;]<br>                    if &#39;bytes&#39; in chunk:<br>                        text_chunk = chunk[&#39;bytes&#39;].decode(&#39;utf-8&#39;)<br>                        full_response += text_chunk<br>                        message_placeholder.markdown(full_response + &quot;▌&quot;)<br>            <br>            message_placeholder.markdown(full_response)<br>            <br>            # Add assistant response to history<br>            st.session_state.messages.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: full_response})<br><br>        except Exception as e:<br>            st.error(f&quot;Error invoking agent: {e}&quot;)</pre><ul><li>Once the script is ready. Run the script using this command</li></ul><pre>streamlit run app.py</pre><ul><li>It will open the browser with the chat interface. These are the questions I asked. You can see the response from the model</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SHmJta3OzZQp3C_ZsB3gbg.png" /></figure><ul><li>The response is not bad. We can refine it more by making more changes in the ingestion layer to get more accurate results.</li></ul><p>That’s it. We built an agent that can respond based on the video memory. It has a lot of other applications also. Will explore more in the upcoming articles.</p><p>Thanks. Feel free to drop comments and suggestions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfa2b94afb95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Real-World Context-Aware Movie Chatbot Using Amazon Bedrock — Nova Pro]]></title>
            <link>https://medium.com/@shaiksalam9182/building-a-real-world-context-aware-movie-chatbot-using-amazon-bedrock-nova-pro-391d47ed1bac?source=rss-6579539aa7a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/391d47ed1bac</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Salam shaik]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 19:58:40 GMT</pubDate>
            <atom:updated>2025-06-25T19:58:40.489Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Real-World Context-Aware Movie Chatbot Using Amazon Bedrock — Nova Pro</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9vFn8FQ6D9OpLwYVwczOAA.png" /></figure><p>Hi everyone,</p><p>This article helps you build a chatbot that can <strong>suggest movies</strong> based on your prompt, provide you with the <strong>movie details</strong>, and <strong>maintain context</strong> throughout the chat session.</p><p>The AWS services I have used to build this solution are:</p><ul><li><strong>AWS Bedrock </strong>— Nova Pro model — Converse API</li><li><strong>Lambda</strong></li><li><strong>API Gateway</strong></li><li><strong>EC2</strong> for running an <strong>Elastic Search</strong> container</li><li><strong>S3 </strong>for static web hosting</li><li><strong>CloudFront </strong>for CDN</li><li><strong>Route 53</strong> for DNS</li><li><strong>CloudWatch </strong>for Logging</li><li><strong>DynamoDB </strong>for storing Sessions and Data</li></ul><h3>Infrastructure Overview of the Chatbot Platform</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zpNnaXynARPNzJR-_8fCLg.png" /></figure><p>Let’s start the implementation. I divided this infrastructure into 3 parts</p><ul><li><strong>Front-end deployment</strong></li><li><strong>API Layer</strong></li><li><strong>Backend Services</strong></li></ul><p><strong>Deploying Front-end services:</strong></p><ul><li>Created an S3 bucket with the domain name I have and enabled S3 static web hosting from the properties of the bucket</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C1U3uGqMlSIDMK1-CH8kGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cuYNfO-ygx-K80OSMyf70w.png" /></figure><ul><li>Bucket Policy for static web hosting</li></ul><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;PublicReadGetObject&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::chitrangi.cloudnirvana.in/*&quot;<br>        }<br>    ]<br>}</pre><ul><li>Requested an SSL certificate from the Certificate Manager for the domain <strong>chitrangi.cloudnirvana.in</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7LdQyR-ia_pLVjoYVlwXA.png" /></figure><ul><li>Created a distribution in the CloudFront with this certificate and an S3 bucket hosting</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2IYLOkUNZP_1-ObcR2Z7tg.png" /></figure><ul><li>Created a record for the subdomain in Route 53 and pointed it to CloudFront</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*QGQF87UjQnqK1ev0UrH7_A.png" /></figure><ul><li>Now everything is ready, let’s upload the index.html file to the S3 bucket. Here is the code for the HTML file</li></ul><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;title&gt;🎬 Chitrangi - Movie Chatbot&lt;/title&gt;<br>  &lt;style&gt;<br>    body {<br>      font-family: &#39;Segoe UI&#39;, sans-serif;<br>      background-color: #f2f2f2;<br>      margin: 0;<br>      padding: 0;<br>    }<br><br>    #chat-container {<br>      width: 90%;<br>      max-width: 800px;<br>      margin: 30px auto;<br>      background: #fff;<br>      border-radius: 8px;<br>      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);<br>      padding: 20px;<br>      position: relative;<br>    }<br><br>    h2 {<br>      margin: 0 0 5px 0;<br>    }<br><br>    #session-info {<br>      font-size: 13px;<br>      color: #666;<br>      margin-bottom: 10px;<br>    }<br><br>    #info-box {<br>      background-color: #e9f7ef;<br>      border-left: 5px solid #28a745;<br>      padding: 10px 15px;<br>      margin-bottom: 15px;<br>      border-radius: 5px;<br>      font-size: 14px;<br>    }<br><br>    #messages {<br>      height: 500px;<br>      overflow-y: scroll;<br>      padding: 10px;<br>      border: 1px solid #ddd;<br>      border-radius: 5px;<br>      background-color: #f9f9f9;<br>    }<br><br>    .message {<br>      margin: 10px 0;<br>      padding: 10px 15px;<br>      border-radius: 18px;<br>      max-width: 75%;<br>      display: inline-block;<br>      word-wrap: break-word;<br>      animation: fadeIn 0.3s ease;<br>    }<br><br>    .user {<br>      background-color: #007bff;<br>      color: white;<br>      margin-left: auto;<br>      text-align: right;<br>    }<br><br>    .bot {<br>      background-color: #e0ffe0;<br>      color: #333;<br>      text-align: left;<br>      margin-right: auto;<br>    }<br><br>    .typing-indicator-bubble {<br>      background-color: #e0ffe0;<br>      color: #333;<br>      padding: 10px 15px;<br>      border-radius: 18px;<br>      max-width: 150px;<br>      margin: 10px 0;<br>      display: flex;<br>      gap: 4px;<br>      justify-content: center;<br>      align-items: center;<br>    }<br><br>    .dot {<br>      width: 8px;<br>      height: 8px;<br>      background-color: #888;<br>      border-radius: 50%;<br>      animation: bounce 1.4s infinite;<br>    }<br><br>    .dot:nth-child(2) {<br>      animation-delay: 0.2s;<br>    }<br><br>    .dot:nth-child(3) {<br>      animation-delay: 0.4s;<br>    }<br><br>    @keyframes bounce {<br>      0%, 80%, 100% { transform: scale(0); }<br>      40% { transform: scale(1); }<br>    }<br><br>    #input-container {<br>      margin-top: 15px;<br>      display: flex;<br>      gap: 10px;<br>    }<br><br>    #input {<br>      flex: 1;<br>      padding: 10px;<br>      font-size: 16px;<br>      border-radius: 5px;<br>      border: 1px solid #ccc;<br>    }<br><br>    #send {<br>      padding: 10px 20px;<br>      font-size: 16px;<br>      background: #007bff;<br>      color: white;<br>      border: none;<br>      border-radius: 5px;<br>      cursor: pointer;<br>    }<br><br>    #send:hover {<br>      background: #0056b3;<br>    }<br><br>    #reset {<br>      position: absolute;<br>      top: 20px;<br>      right: 20px;<br>      background: #dc3545;<br>      color: white;<br>      border: none;<br>      padding: 8px 16px;<br>      border-radius: 5px;<br>      cursor: pointer;<br>    }<br><br>    #reset:hover {<br>      background: #a71d2a;<br>    }<br><br>    @keyframes fadeIn {<br>      from { opacity: 0; transform: translateY(10px); }<br>      to { opacity: 1; transform: translateY(0); }<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>&lt;div id=&quot;chat-container&quot;&gt;<br>  &lt;h2&gt;🎬 Chitrangi - Movie Chatbot&lt;/h2&gt;<br>  &lt;div id=&quot;session-info&quot;&gt;Session ID: &lt;code id=&quot;session-id&quot;&gt;&lt;/code&gt;&lt;/div&gt;<br><br>  &lt;div id=&quot;info-box&quot;&gt;<br>    &lt;strong&gt;What Chitrangi can do:&lt;/strong&gt;<br>    &lt;ul style=&quot;margin: 5px 0 0 15px;&quot;&gt;<br>      &lt;li&gt;🎥 Suggest movies by genre or mood&lt;/li&gt;<br>      &lt;li&gt;📖 Provide movie details like synopsis and cast&lt;/li&gt;<br>      &lt;li&gt;🚫 Will not answer non-movie questions&lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br><br>  &lt;button id=&quot;reset&quot; onclick=&quot;resetSession()&quot;&gt;Start New Chat&lt;/button&gt;<br><br>  &lt;div id=&quot;messages&quot;&gt;&lt;/div&gt;<br><br>  &lt;div id=&quot;input-container&quot;&gt;<br>    &lt;input type=&quot;text&quot; id=&quot;input&quot; placeholder=&quot;Ask for a movie, like &#39;Suggest a thriller&#39;...&quot;&gt;<br>    &lt;button id=&quot;send&quot;&gt;Send&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;script&gt;<br>  const apiUrl = &quot;&quot;; // Replace with your API endpoint<br><br>  let sessionId = localStorage.getItem(&quot;chitrangi_session_id&quot;);<br>  if (!sessionId) {<br>    sessionId = crypto.randomUUID();<br>    localStorage.setItem(&quot;chitrangi_session_id&quot;, sessionId);<br>  }<br>  document.getElementById(&quot;session-id&quot;).textContent = sessionId;<br><br>  function resetSession() {<br>    localStorage.removeItem(&quot;chitrangi_session_id&quot;);<br>    sessionId = crypto.randomUUID();<br>    localStorage.setItem(&quot;chitrangi_session_id&quot;, sessionId);<br>    document.getElementById(&quot;session-id&quot;).textContent = sessionId;<br>    document.getElementById(&quot;messages&quot;).innerHTML = &quot;&quot;;<br>  }<br><br>  const messagesDiv = document.getElementById(&#39;messages&#39;);<br>  const inputField = document.getElementById(&#39;input&#39;);<br>  const sendButton = document.getElementById(&#39;send&#39;);<br><br>  function appendMessage(text, sender) {<br>    const div = document.createElement(&#39;div&#39;);<br>    div.classList.add(&#39;message&#39;, sender);<br>    div.textContent = text;<br>    const wrapper = document.createElement(&#39;div&#39;);<br>    wrapper.style.display = &#39;flex&#39;;<br>    wrapper.style.justifyContent = sender === &#39;user&#39; ? &#39;flex-end&#39; : &#39;flex-start&#39;;<br>    wrapper.appendChild(div);<br>    messagesDiv.appendChild(wrapper);<br>    messagesDiv.scrollTop = messagesDiv.scrollHeight;<br>  }<br><br>  function showTypingBubble() {<br>    const typingBubble = document.createElement(&#39;div&#39;);<br>    typingBubble.classList.add(&#39;typing-indicator-bubble&#39;);<br>    typingBubble.id = &#39;typing-bubble&#39;;<br>    typingBubble.innerHTML = `&lt;div class=&quot;dot&quot;&gt;&lt;/div&gt;&lt;div class=&quot;dot&quot;&gt;&lt;/div&gt;&lt;div class=&quot;dot&quot;&gt;&lt;/div&gt;`;<br>    const wrapper = document.createElement(&#39;div&#39;);<br>    wrapper.style.display = &#39;flex&#39;;<br>    wrapper.style.justifyContent = &#39;flex-start&#39;;<br>    wrapper.appendChild(typingBubble);<br>    messagesDiv.appendChild(wrapper);<br>    messagesDiv.scrollTop = messagesDiv.scrollHeight;<br>  }<br><br>  function removeTypingBubble() {<br>    const typingBubble = document.getElementById(&#39;typing-bubble&#39;);<br>    if (typingBubble &amp;&amp; typingBubble.parentElement) typingBubble.parentElement.remove();<br>  }<br><br>  async function typeMessage(text, sender) {<br>    const wrapper = document.createElement(&#39;div&#39;);<br>    wrapper.style.display = &#39;flex&#39;;<br>    wrapper.style.justifyContent = sender === &#39;user&#39; ? &#39;flex-end&#39; : &#39;flex-start&#39;;<br>    const div = document.createElement(&#39;div&#39;);<br>    div.classList.add(&#39;message&#39;, sender);<br>    div.style.whiteSpace = &#39;pre-wrap&#39;;<br>    div.innerHTML = text.replace(/(?&lt;=\n|^)\d+\.\s(.*)/g, (_, title) =&gt; `• &lt;strong&gt;${title}&lt;/strong&gt;`);<br>    wrapper.appendChild(div);<br>    messagesDiv.appendChild(wrapper);<br>    messagesDiv.scrollTop = messagesDiv.scrollHeight;<br>  }<br><br>  async function sendMessage() {<br>    const userInput = inputField.value.trim();<br>    if (!userInput) return;<br><br>    appendMessage(userInput, &#39;user&#39;);<br>    inputField.value = &#39;&#39;;<br>    showTypingBubble();<br><br>    try {<br>      const response = await fetch(apiUrl, {<br>        method: &#39;POST&#39;,<br>        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>        body: JSON.stringify({ message: userInput, session_id: sessionId })<br>      });<br><br>      const data = await response.json();<br>      removeTypingBubble();<br>      await typeMessage(data.response, &#39;bot&#39;);<br>    } catch (err) {<br>      removeTypingBubble();<br>      appendMessage(&#39;Error fetching response. Check your server.&#39;, &#39;bot&#39;);<br>    }<br>  }<br><br>  sendButton.addEventListener(&#39;click&#39;, sendMessage);<br>  inputField.addEventListener(&#39;keypress&#39;, (e) =&gt; {<br>    if (e.key === &#39;Enter&#39;) sendMessage();<br>  });<br>&lt;/script&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>Note: Replace the API URL with the API Gateway endpoint, which we are going to deploy in the next step</strong></p><p><strong>Deploying API Layer:</strong></p><ul><li>Create a Lambda function, Chitrangi, with Python runtime</li><li>Visit the API Gateway and create an HTTP API and integrate with the Lambda function you created, and make sure CORS is configured correctly</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeBi5iA0NB7gCx4HXZD7Yg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2pQ6XdNij_gYuUsQ4cXX3Q.png" /></figure><p>Note: Lambda is the heart of this system. Will provide the code at the end of this article. Before that, let’s deploy the backend services</p><p><strong>Deploying Backend Services:</strong></p><p>We need the following 3 services ready to work with Lambda</p><ul><li><strong>Dynamo DB</strong></li><li><strong>Bedrock</strong></li><li><strong>EC2 — runs Elastic Search</strong></li></ul><p><strong>Dynamo DB:</strong></p><ul><li>Visit Dynamo DB and create 2 tables, one of which holds the movie data</li><li>Another table for holding the session data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fMje8Yz2lm8H2Q4PrzIxdA.png" /></figure><ul><li>For <strong>chatbot_sessions,</strong> keep the <strong>session_id </strong>as the <strong>Partition key</strong> and <strong>timestamp </strong>as the <strong>Sort Key</strong></li><li>For <strong>imdb_movies</strong>, keep the <strong>movie_id </strong>as the <strong>Partition Key</strong></li><li>Let’s dump the data in the imdb_movies table. I am using this dataset from Kaggle for this chatbot <a href="https://www.kaggle.com/datasets/ashpalsingh1525/imdb-movies-dataset">https://www.kaggle.com/datasets/ashpalsingh1525/imdb-movies-dataset</a></li><li>Use this script to dump this data into DynamoDB</li></ul><pre>import boto3<br>from botocore.exceptions import ClientError<br>import pandas as pd<br><br><br>file_path = &quot;imdb_movies.csv&quot;<br><br>df = pd.read_csv(file_path)<br><br>df = df[[&quot;orig_title&quot;,&quot;overview&quot;,&quot;genre&quot;,&quot;crew&quot;]]<br><br>modified_df = df.dropna(subset=[&quot;orig_title&quot;,&quot;overview&quot;,&quot;genre&quot;,&quot;crew&quot;])<br><br><br>print(modified_df.head())<br><br># Initialize DynamoDB resource<br>dynamodb = boto3.resource(&#39;dynamodb&#39;, region_name=&#39;ap-south-1&#39;)  # e.g., &#39;us-east-1&#39;<br>table = dynamodb.Table(&#39;imdb_movies&#39;)<br><br><br>for index, row in modified_df.iterrows():<br>    movie = {<br>        &#39;movie_id&#39;: index+1,<br>        &#39;title&#39;: row[&#39;orig_title&#39;],<br>        &#39;description&#39;: row[&#39;overview&#39;],<br>        &#39;genre&#39;: row[&#39;genre&#39;],<br>        &#39;crew&#39;: row[&#39;crew&#39;],<br>    }<br><br>    print(f&quot;Inserting: {movie}&quot;)<br>    <br>    try:<br>        table.put_item(Item=movie)<br>        print(f&quot;Inserted: {movie[&#39;title&#39;]}&quot;)<br>    except ClientError as e:<br>        print(f&quot;Failed to insert {movie[&#39;title&#39;]}: {e.response[&#39;Error&#39;][&#39;Message&#39;]}&quot;)</pre><p><strong>BedRock:</strong></p><ul><li>We need two models for this chatbot—one for converting this data into vectors and one for handling the prompts. I am using these 2 models from the bedrock</li><li><a href="https://ap-south-1.console.aws.amazon.com/bedrock/home#/model-catalog/serverless/amazon.titan-embed-text-v2:0">Titan Text Embeddings V2</a> — for generating vectors for the data we stored in DynamoDB</li><li><a href="https://ap-south-1.console.aws.amazon.com/bedrock/home#/model-catalog/serverless/amazon.nova-pro-v1:0">Nova Pro</a> — for handling the user prompts</li></ul><p><strong>Note: Please request access to these models to proceed further</strong></p><p><strong>EC2 — Elastic search container:</strong></p><ul><li>The reason for using EC2 for running Elastic Search instead of using open search service is, I will be working on this on and off for several days. So I need the service to turn off to avoid more when I am not working, and I need it immediately when I want. Opensearch domain creation will take a lot of time, and we can stop and start the service like EC2</li><li>To run Elastic Search container in the EC2 instance, please follow this documentation <a href="https://www.elastic.co/docs/deploy-manage/deploy/self-managed/install-elasticsearch-docker-basic?v=EF5DFA09">https://www.elastic.co/docs/deploy-manage/deploy/self-managed/install-elasticsearch-docker-basic</a></li><li>Instance configuration is t3.large and 16GB of storage, with the port open for Elastic Search is 9200</li></ul><p><strong>Dumping data to Elastic Search:</strong></p><ul><li>Use the following script to read data from the Dynamo DB and convert it into vectors, and dump it into the Elastic Search Index</li></ul><pre>import boto3<br>import json<br>import requests<br>from requests.auth import HTTPBasicAuth<br>from elasticsearch import Elasticsearch, helpers<br><br># Config<br>region = &quot;ap-south-1&quot;  # Change to your region<br>dynamodb = boto3.resource(&quot;dynamodb&quot;, region_name=region)<br>table = dynamodb.Table(&quot;imdb_movies&quot;)<br><br>bedrock = boto3.client(&quot;bedrock-runtime&quot;, region_name=region)<br><br>es = Elasticsearch(<br>    hosts=[&quot;https://elastic search endpoint:9200&quot;],  # Replace with your Elasticsearch endpoin<br>    basic_auth=(&quot;elastic&quot;, &quot;password&quot;),  # Basic auth if enabled<br>    verify_certs=False<br>    )<br><br>index_name = &quot;imdb_movies&quot;<br><br># Function to embed text using Titan<br>def get_titan_embedding(text):<br>    payload = {<br>        &quot;inputText&quot;: text<br>    }<br>    response = bedrock.invoke_model(<br>        modelId=&quot;amazon.titan-embed-text-v2:0&quot;,<br>        body=json.dumps(payload),<br>        contentType=&quot;application/json&quot;<br>    )<br>    embedding = json.loads(response[&#39;body&#39;].read())[&#39;embedding&#39;]<br>    return embedding<br><br>actions = []<br>last_evaluated_key = None<br>total_items = 0<br><br>while True:<br>    if last_evaluated_key:<br>        response = table.scan(ExclusiveStartKey=last_evaluated_key)<br>    else:<br>        response = table.scan()<br><br>    items = response.get(&#39;Items&#39;, [])<br>    total_items += len(items)<br>    print(f&quot;Fetched {len(items)} items. Total fetched: {total_items}&quot;)<br><br>    for item in items:<br>        desc = item[&#39;description&#39;]<br>        embedding = get_titan_embedding(desc)<br><br>        action = {<br>            &quot;_index&quot;: index_name,<br>            &quot;_id&quot;: item[&#39;movie_id&#39;],<br>            &quot;_source&quot;: {<br>                &quot;movie_id&quot;: item[&#39;movie_id&#39;],<br>                &quot;title&quot;: item[&#39;title&#39;],<br>                &quot;description&quot;: desc,<br>                &quot;embedding&quot;: embedding,<br>                &quot;genre&quot;: item.get(&#39;genre&#39;, &quot;&quot;),<br>                &quot;crew&quot;: item.get(&#39;crew&#39;, &quot;&quot;),<br>            }<br>        }<br>        actions.append(action)<br><br>        # Optionally flush every N records to avoid memory bloat<br>        if len(actions) &gt;= 500:<br>            helpers.bulk(es, actions)<br>            print(f&quot;Inserted 500 records to Elasticsearch.&quot;)<br>            actions.clear()<br><br>    last_evaluated_key = response.get(&#39;LastEvaluatedKey&#39;)<br>    if not last_evaluated_key:<br>        break<br><br># Insert any remaining actions<br>if actions:<br>    helpers.bulk(es, actions)<br>    print(f&quot;Inserted remaining {len(actions)} records to Elasticsearch.&quot;)<br><br>print(f&quot;Successfully processed {total_items} records from DynamoDB.&quot;)</pre><p>Now that we have everything ready. Let’s start coding in the Lambda function</p><p><strong>Lambda function:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9FTIIyF-BTaS4-5EZ7RKQ.png" /><figcaption>Dissecting the Lambda Logic Behind chat bot Responses</figcaption></figure><ul><li>Let’s go through step by step here</li><li>When the user enters a prompt, that prompt, along with the session ID, will be sent to the Lambda</li><li>If there is a session with that session ID in the DynamoDB, we will fetch the previous messages; if not will store the current message as a user role</li></ul><pre>def store_user_message(session_id, role, message):<br>    timestamp = int(time.time() * 1000)  # millisecond precision<br>    session_table.put_item(Item={<br>        &#39;session_id&#39;: session_id,<br>        &#39;timestamp&#39;: timestamp,<br>        &#39;role&#39;: role,<br>        &#39;message&#39;: message<br>    })<br><br>def get_session_history(session_id):<br>    response = session_table.query(<br>        KeyConditionExpression=Key(&#39;session_id&#39;).eq(session_id),<br>        ScanIndexForward=True  # Sort by timestamp ascending<br>    )<br>    <br>    # Convert DynamoDB items into model-ready format<br>    messages = []<br>    for item in response[&#39;Items&#39;]:<br>        messages.append({<br>            &quot;role&quot;: item[&quot;role&quot;],  # &#39;user&#39; or &#39;assistant&#39;<br>            &quot;content&quot;: [{&quot;text&quot;: item[&quot;message&quot;]}]<br>        })<br><br>    return messages</pre><ul><li>Then user prompt will be sent for the intent classification to the Nova model.</li><li>Here I am using the <strong>converse </strong>function of the <strong>bedrock runtime</strong> instead <strong>invoke_model </strong>to maintain context awareness</li><li>The intent classification prompt and calling the converse API</li></ul><pre>classify_system_prompt = &quot;&quot;&quot;You are a prompt classifier — not a chatbot. Your only job is to classify the user&#39;s **latest message**.<br><br>- Use previous messages **only as context** if the user prompt is vague.<br>- Do not react to previous assistant responses.<br>- Never generate movie suggestions or details. Do not respond like a chatbot.<br><br>Return exactly **one** JSON object matching one of the following:<br><br>1. If the user asks for movie details (e.g., who acted, synopsis, or info), return:<br>   {&quot;type&quot;: &quot;ask_details&quot;, &quot;title&quot;: &quot;&lt;movie name&gt;&quot;}<br><br>2. If the user is asking for new movie suggestions, return:<br>   {&quot;type&quot;: &quot;suggestion&quot;, &quot;genre&quot;: &quot;&lt;genre&gt;&quot;, &quot;mood&quot;: &quot;&lt;mood&gt;&quot;}<br><br>3. If the user greets (Hi, Hello, etc.), or say thanks return:<br>   {&quot;type&quot;: &quot;greeting&quot;}<br><br>4. If the user says thanks or thanks you or express his gratitude, return:<br>    {&quot;type&quot;:&quot;gratitude&quot;}<br><br>4. If the message is not related to movies, return:<br>   {&quot;type&quot;: &quot;irrelevant&quot;}<br><br><br>Important:<br>- Use only the **last user prompt** to determine classification.<br>- Use prior messages **only to resolve vague references** (like “that movie”).<br>- Respond ONLY with the JSON. Never generate answers, movie descriptions, or titles unless needed for classification.<br><br><br>&quot;&quot;&quot;<br>classify_system_prompt_obj = {&quot;text&quot;:classify_system_prompt}</pre><pre>def send_to_model(message,system_prompt,session_id,get_session_messages):<br><br><br>    previous_messages = []<br><br>    if get_session_messages:<br>        previous_messages = get_session_history(session_id)<br><br>    previous_messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: message}]})<br><br>    print(f&quot;previous messages {previous_messages}&quot;)<br><br>    system_prompts = []<br><br>    if system_prompt is not None:<br>        system_prompts.append(system_prompt)<br><br>    temperature = 0.7<br>    top_k = 200<br><br>    inference_config = {&quot;temperature&quot;: temperature}<br><br>    response = bedrock_nova.converse(<br>        modelId=&quot;model id&quot;,<br>        messages=previous_messages,<br>        system=system_prompts,<br>        inferenceConfig=inference_config<br>    )<br><br>    model_text = response[&quot;output&quot;][&quot;message&quot;][&quot;content&quot;][0][&quot;text&quot;]<br>    print(f&quot;model_text {model_text}&quot;)<br>    return model_text</pre><ul><li>Based on the classification received from the model, we will categorize each prompt and redirect to the respective task</li><li>5 Types of classification I have done here. They are:</li></ul><p><strong>greetings: </strong>If the user prompt represents a greeting kind of prompt, we will redirect them to generate a greeting response</p><p><strong>ask_details: </strong>If the user is asking for movie details, we will redirect them to fetch movie details from Elastic Search and will generate a movie info response using the model</p><p><strong>suggestions: </strong>If the user is asking for a movie suggestion, we will redirect them suggestion category where suggestions will be fetched from the Elastic Search index and will generate a movie suggestion response using the model</p><p><strong>gratitude: </strong>If the user is expressing his happiness or says thank you, then this category will prompt and respond to the user using a model response</p><p><strong>irrelevant: </strong>if the user is asking, which is not at all related to movie suggestions or details, will respond back to the user with a polite message saying it is irrelevant to the movies.</p><pre>def route_prompt(prompt,prompt_type,session_id,json_dump):<br>    if prompt_type == &quot;irrelevant&quot;:<br>        response_text = &quot;Looks like your question is irrelevant to movies. I can help you with movie suggestions. Try asking about genres, actors, or moods!&quot;<br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;body&quot;: json.dumps({&quot;response&quot;: response_text})<br>        }<br>    elif prompt_type == &quot;greeting&quot;:<br>        response_text = build_greetings_response(prompt,session_id)<br>        <br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;body&quot;: json.dumps({&quot;response&quot;: response_text})<br>        }<br>    elif prompt_type == &quot;gratitude&quot;:<br>        response_text = build_gratitude_response(prompt,session_id)<br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;body&quot;: json.dumps({&quot;response&quot;: response_text})<br>        }<br>    elif prompt_type == &quot;ask_details&quot;:<br>        print(&quot;Entered ask details&quot;)<br>        if get_movie_details(json_dump,prompt,session_id) is None:<br>            response_text = &quot;I can&#39;t find the movie title in our movies list.&quot;<br>            return {<br>                &quot;statusCode&quot;: 200,<br>                &quot;body&quot;: json.dumps({&quot;response&quot;: &quot;I can&#39;t find the movie title in our movies list.&quot;})<br>            }<br>        else:<br>            print(&quot;Entered ask details&quot;)<br>            response_text = get_movie_details(json_dump, prompt, session_id)<br>            return {<br>                &quot;statusCode&quot;: 200,<br>                &quot;body&quot;: json.dumps({&quot;response&quot;: response_text})<br>            }<br>    elif prompt_type == &quot;suggestion&quot;:<br>        response_text = get_movie_suggestions(prompt,json_dump,session_id)<br>        return response_text<br>    else:<br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;body&quot;: json.dumps({&quot;response&quot;: &quot;I am not sure what you are asking for&quot;})<br>        }</pre><ul><li>The prompts for generating respective category responses are here</li></ul><pre>greeting_system_prompt = &quot;&quot;&quot;<br>You are a movie chat bot named Chitrangi. Read the user query and prepare a polite response and respond to the user by introducting yourselft as chitrangi.<br>These are the things you can do. You can suggest movies. You can get a specific movie details. That&#39;s it. Nothing morethan that. Try to keep response in a single line<br>&quot;&quot;&quot;<br><br>gratitude_system_prompt = &quot;&quot;&quot;<br>You are a movie chat bot named Chitrangi.<br>If the user expresses gratitude (e.g., says &quot;Thanks&quot;, &quot;Thank you&quot;, etc.), respond warmly, letting them know you&#39;re also happy to help. Try to keep response in a single line<br>&quot;&quot;&quot;<br><br>movie_details_system_prompt = &quot;&quot;&quot;<br>You are a movie chat bot. Based on user_query and movie_object, prepare a polite response and respond to the user.<br>Only consider the data from the user_query and movie_object. Don&#39;t hallucinate. Try to keep everything in a single line<br>&quot;&quot;&quot;<br>movie_details_system_prompt_obj = {&quot;text&quot;:movie_details_system_prompt}<br><br>movie_suggestion_system_prompt = f&quot;&quot;&quot;<br>You are a friendly movie chatbot that suggest movies based movies list provided.  Movies list is final suggestions you need to provide. Nothing from the internet and no hallucinations.  <br>Don&#39;t express your opinion on each movie in the response. Even though you feel the movies in the movies list are not good match for user query.<br>Your responsibility is to take the movies from the movies list and respond to the user based on user query.<br>Only suggest the movies from the given movies list. Mention every movie mentioned in the list<br>Don’t suggest anything outside the list. Don&#39;t hallucinate.<br>The movies list will contain the movie suggestions based on user query.<br>Don&#39;t suggest movies from internet. If the movies list is empty respond to the user that there are no suggestion right now<br>Respond like you are suggesting the movies from the list by yourself. But don&#39;t hallucinate and don&#39;t provide movie info from the internet. Try to keep entire response in a single line<br>&quot;&quot;&quot;<br>movie_suggestion_system_prompt_obj = {&quot;text&quot;:movie_suggestion_system_prompt}</pre><ul><li>I hope you got some clarity on how the Lambda function works with Elastic Search, DynamoDB, and Bedrock to respond back to the user</li></ul><p><strong>Note: The converse API is a very tricky one. Even though you give specific rules to follow, if it identifies any messages that break the given rules in the entire conversation, it will completely ignore the classification rules. Make sure to use it wisely.</strong></p><h3><strong>The complete Lambda is here:</strong></h3><pre>import json<br>import boto3<br>import os<br>from elasticsearch import Elasticsearch<br>import ast<br>from boto3.dynamodb.conditions import Key<br>import time<br><br><br>region = &quot;ap-south-1&quot;<br>bedrock = boto3.client(&quot;bedrock-runtime&quot;, region_name=region)<br>dynamodb = boto3.resource(&quot;dynamodb&quot;)<br>session_table = dynamodb.Table(&quot;chatbot_sessions&quot;)<br>bedrock_nova = boto3.client(&quot;bedrock-runtime&quot;, region_name=&#39;us-east-1&#39;)<br><br>es = Elasticsearch(<br>    hosts=[&quot;https://endpoint:9200&quot;],<br>    basic_auth=(&quot;elastic&quot;, &quot;passowrd&quot;),<br>    verify_certs=False<br>)<br>index_name = &quot;imdb_movies&quot;<br>session_memory = {}<br>session_id = &quot;&quot;<br><br>classify_system_prompt = &quot;&quot;&quot;You are a prompt classifier — not a chatbot. Your only job is to classify the user&#39;s **latest message**.<br><br>- Use previous messages **only as context** if the user prompt is vague.<br>- Do not react to previous assistant responses.<br>- Never generate movie suggestions or details. Do not respond like a chatbot.<br><br>Return exactly **one** JSON object matching one of the following:<br><br>1. If the user asks for movie details (e.g., who acted, synopsis, or info), return:<br>   {&quot;type&quot;: &quot;ask_details&quot;, &quot;title&quot;: &quot;&lt;movie name&gt;&quot;}<br><br>2. If the user is asking for new movie suggestions, return:<br>   {&quot;type&quot;: &quot;suggestion&quot;, &quot;genre&quot;: &quot;&lt;genre&gt;&quot;, &quot;mood&quot;: &quot;&lt;mood&gt;&quot;}<br><br>3. If the user greets (Hi, Hello, etc.), or say thanks return:<br>   {&quot;type&quot;: &quot;greeting&quot;}<br><br>4. If the user says thanks or thanks you or express his gratitude, return:<br>    {&quot;type&quot;:&quot;gratitude&quot;}<br><br>4. If the message is not related to movies, return:<br>   {&quot;type&quot;: &quot;irrelevant&quot;}<br><br><br>Important:<br>- Use only the **last user prompt** to determine classification.<br>- Use prior messages **only to resolve vague references** (like “that movie”).<br>- Respond ONLY with the JSON. Never generate answers, movie descriptions, or titles unless needed for classification.<br><br><br>&quot;&quot;&quot;<br>classify_system_prompt_obj = {&quot;text&quot;:classify_system_prompt}<br><br><br><br>greeting_system_prompt = &quot;&quot;&quot;<br>You are a movie chat bot named Chitrangi. Read the user query and prepare a polite response and respond to the user by introducting yourselft as chitrangi.<br>These are the things you can do. You can suggest movies. You can get a specific movie details. That&#39;s it. Nothing morethan that. Try to keep response in a single line<br>&quot;&quot;&quot;<br><br>gratitude_system_prompt = &quot;&quot;&quot;<br>You are a movie chat bot named Chitrangi.<br>If the user expresses gratitude (e.g., says &quot;Thanks&quot;, &quot;Thank you&quot;, etc.), respond warmly, letting them know you&#39;re also happy to help. Try to keep response in a single line<br>&quot;&quot;&quot;<br><br>movie_details_system_prompt = &quot;&quot;&quot;<br>You are a movie chat bot. Based on user_query and movie_object, prepare a polite response and respond to the user.<br>Only consider the data from the user_query and movie_object. Don&#39;t hallucinate. Try to keep everything in a single line<br>&quot;&quot;&quot;<br>movie_details_system_prompt_obj = {&quot;text&quot;:movie_details_system_prompt}<br><br>movie_suggestion_system_prompt = f&quot;&quot;&quot;<br>You are a friendly movie chatbot that suggest movies based movies list provided.  Movies list is final suggestions you need to provide. Nothing from the internet and no hallucinations.  <br>Don&#39;t express your opinion on each movie in the response. Even though you feel the movies in the movies list are not good match for user query.<br>Your responsibility is to take the movies from the movies list and respond to the user based on user query.<br>Only suggest the movies from the given movies list. Mention every movie mentioned in the list<br>Don’t suggest anything outside the list. Don&#39;t hallucinate.<br>The movies list will contain the movie suggestions based on user query.<br>Don&#39;t suggest movies from internet. If the movies list is empty respond to the user that there are no suggestion right now<br>Respond like you are suggesting the movies from the list by yourself. But don&#39;t hallucinate and don&#39;t provide movie info from the internet. Try to keep entire response in a single line<br>&quot;&quot;&quot;<br>movie_suggestion_system_prompt_obj = {&quot;text&quot;:movie_suggestion_system_prompt}<br><br><br><br>def store_user_message(session_id, role, message):<br>    timestamp = int(time.time() * 1000)  # millisecond precision<br>    session_table.put_item(Item={<br>        &#39;session_id&#39;: session_id,<br>        &#39;timestamp&#39;: timestamp,<br>        &#39;role&#39;: role,<br>        &#39;message&#39;: message<br>    })<br><br>def get_session_history(session_id):<br>    response = session_table.query(<br>        KeyConditionExpression=Key(&#39;session_id&#39;).eq(session_id),<br>        ScanIndexForward=True  # Sort by timestamp ascending<br>    )<br>    <br>    # Convert DynamoDB items into model-ready format<br>    messages = []<br>    for item in response[&#39;Items&#39;]:<br>        messages.append({<br>            &quot;role&quot;: item[&quot;role&quot;],  # &#39;user&#39; or &#39;assistant&#39;<br>            &quot;content&quot;: [{&quot;text&quot;: item[&quot;message&quot;]}]<br>        })<br><br>    return messages<br><br><br><br># Embedding generator<br>def invoke_bedrock(model_id, payload):<br>    response = bedrock.invoke_model(<br>        modelId=model_id,<br>        body=json.dumps(payload),<br>        contentType=&quot;application/json&quot;<br>    )<br>    return json.loads(response[&quot;body&quot;].read())<br><br><br><br><br>def send_to_model(message,system_prompt,session_id,get_session_messages):<br><br><br>    previous_messages = []<br><br>    if get_session_messages:<br>        previous_messages = get_session_history(session_id)<br><br>    previous_messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: message}]})<br><br>    print(f&quot;previous messages {previous_messages}&quot;)<br><br>    system_prompts = []<br><br>    if system_prompt is not None:<br>        system_prompts.append(system_prompt)<br><br>    temperature = 0.7<br>    top_k = 200<br><br>    inference_config = {&quot;temperature&quot;: temperature}<br><br>    response = bedrock_nova.converse(<br>        modelId=&quot;arn:aws:bedrock:us-east-1:556343216872:inference-profile/us.amazon.nova-pro-v1:0&quot;,<br>        messages=previous_messages,<br>        system=system_prompts,<br>        inferenceConfig=inference_config<br>    )<br><br>    model_text = response[&quot;output&quot;][&quot;message&quot;][&quot;content&quot;][0][&quot;text&quot;]<br>    print(f&quot;model_text {model_text}&quot;)<br>    return model_text<br><br><br>#prompt classifer<br>def extract_intents_entities(prompt,session_id):<br>    result = send_to_model(prompt,classify_system_prompt_obj,session_id,True)<br>    <br>    <br>    try:<br>        return result<br>    except Exception as e:<br>        print(f&quot;Error parsing JSON: {e}&quot;)<br>        return {}<br><br><br>#movies search<br>def search_movies(query_embedding, exclude_ids=None, top_k=5):<br>    must_clauses = [{&quot;match_all&quot;: {}}]<br>    must_not_clause = []<br>    if exclude_ids:<br>        must_not_clause = [{&quot;terms&quot;: {&quot;movie_id&quot;: exclude_ids}}]<br><br>    search_query = {<br>        &quot;size&quot;: top_k,<br>        &quot;query&quot;: {<br>            &quot;script_score&quot;: {<br>                &quot;query&quot;: {<br>                    &quot;bool&quot;: {<br>                        &quot;must_not&quot;: must_not_clause<br>                    }<br>                },<br>                &quot;script&quot;: {<br>                    &quot;source&quot;: &quot;cosineSimilarity(params.query_vector, &#39;embedding&#39;) + 1.0&quot;,<br>                    &quot;params&quot;: {&quot;query_vector&quot;: query_embedding}<br>                }<br>            }<br>        }<br>    }<br><br><br>    results = es.search(index=index_name, body=search_query)<br>    return [{<br>        &quot;movie_id&quot;: hit[&quot;_source&quot;][&quot;movie_id&quot;],<br>        &quot;title&quot;: hit[&quot;_source&quot;][&quot;title&quot;],<br>        &quot;description&quot;: hit[&quot;_source&quot;][&quot;description&quot;]<br>    } for hit in results[&quot;hits&quot;][&quot;hits&quot;]]<br><br>#return titan embedding<br>def get_titan_embedding(text):<br>    result = invoke_bedrock(&quot;amazon.titan-embed-text-v2:0&quot;, {&quot;inputText&quot;: text})<br>    return result[&quot;embedding&quot;]<br><br>#nova suggestion response building<br>def build_response(prompt, movies,session_id):<br>    movie_list = []<br>    for movie in movies:<br>        if isinstance(movie, dict) and &quot;title&quot; in movie:<br>            movie_list.append(movie[&#39;title&#39;])<br>    <br>    prompt_text = f&quot;&quot;&quot;<br>    User query: {prompt}<br>    Movies list: {movie_list}&quot;&quot;&quot;<br><br>    response = send_to_model(prompt_text,movie_suggestion_system_prompt_obj,session_id,True)<br><br>    return response<br><br>#nova movie details response building<br>def build_movie_details_response(user_query,movie_data,session_id):<br>    prompt_text = f&quot;&quot;&quot;<br>    user_query= {user_query}<br>    movie_object= {movie_data}&quot;&quot;&quot;<br>    response = send_to_model(prompt_text, movie_details_system_prompt_obj, session_id,True)<br>    return response<br><br>def build_greetings_response(user_query,session_id):<br>    response = send_to_model(greeting_system_prompt,None,session_id,False)<br>    return response<br><br>def build_gratitude_response(user_query,session_id):<br>    response = send_to_model(gratitude_system_prompt,None,session_id,False)<br>    return response<br><br>#movies suggestions fetch<br>def get_movie_suggestions(prompt,extracted, session_id):<br>        session_data = session_memory.get(session_id, {&quot;suggested_movie_ids&quot;: []})<br>        suggested_movie_ids = session_data[&quot;suggested_movie_ids&quot;]<br><br>        query_embedding = get_titan_embedding(json.dumps(extracted))<br>        movies = search_movies(query_embedding, exclude_ids=suggested_movie_ids)<br><br>        new_movie_ids = [m[&#39;movie_id&#39;] for m in movies if &#39;movie_id&#39; in m]<br>        session_memory[session_id] = {<br>            &quot;suggested_movie_ids&quot;: suggested_movie_ids + new_movie_ids<br>        }<br><br>        reply = build_response(prompt, movies,session_id)<br>        # store_user_message(session_id, &quot;assistant&quot;, reply)<br><br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;body&quot;: json.dumps({&quot;response&quot;: reply})<br>        }<br><br>#movie details fetch<br>def get_movie_details(extracted, user_query, session_id):<br>    title = extracted.get(&#39;title&#39;, &#39;&#39;).strip()<br>    <br>    # fallback to session memory title<br>    if not title:<br>        title = session_memory.get(session_id, {}).get(&quot;last_title&quot;, &quot;&quot;)<br>        print(f&quot;Fallback to session stored title: {title}&quot;)<br>    <br>    if not title:<br>        return &quot;I can&#39;t find the movie title. Please provide a specific movie title.&quot;<br><br>    # update session with this title<br>    session_data = session_memory.get(session_id, {})<br>    session_data[&quot;last_title&quot;] = title<br>    session_memory[session_id] = session_data<br><br>    response = es.search(index=index_name, body={<br>        &quot;query&quot;: {<br>            &quot;match&quot;: {<br>                &quot;title&quot;: title<br>            }<br>        }<br>    })<br><br>    if response[&quot;hits&quot;][&quot;hits&quot;]:<br>        movie = response[&quot;hits&quot;][&quot;hits&quot;][0][&quot;_source&quot;]<br>        movie_object = {<br>            &quot;title&quot;: movie.get(&quot;title&quot;, &quot;&quot;),<br>            &quot;description&quot;: movie.get(&quot;description&quot;, &quot;&quot;),<br>            &quot;genre&quot;: movie.get(&quot;genre&quot;, &quot;&quot;),<br>            &quot;crew&quot;: movie.get(&quot;crew&quot;, &quot;&quot;)<br>        }<br>        return build_movie_details_response(user_query, movie_object,session_id)<br>    else:<br>        return &quot;I can&#39;t find the movie title in our movies list.&quot;<br><br><br><br><br><br>def route_prompt(prompt,prompt_type,session_id,json_dump):<br>    if prompt_type == &quot;irrelevant&quot;:<br>        response_text = &quot;Looks like your question is irrelevant to movies. I can help you with movie suggestions. Try asking about genres, actors, or moods!&quot;<br>        <br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;body&quot;: json.dumps({&quot;response&quot;: response_text})<br>        }<br>    elif prompt_type == &quot;greeting&quot;:<br>        response_text = build_greetings_response(prompt,session_id)<br>        <br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;body&quot;: json.dumps({&quot;response&quot;: response_text})<br>        }<br>    elif prompt_type == &quot;gratitude&quot;:<br>        response_text = build_gratitude_response(prompt,session_id)<br>        <br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;body&quot;: json.dumps({&quot;response&quot;: response_text})<br>        }<br>    elif prompt_type == &quot;ask_details&quot;:<br>        print(&quot;Entered ask details&quot;)<br>        if get_movie_details(json_dump,prompt,session_id) is None:<br>            response_text = &quot;I can&#39;t find the movie title in our movies list.&quot;<br>            <br>            return {<br>                &quot;statusCode&quot;: 200,<br>                &quot;body&quot;: json.dumps({&quot;response&quot;: &quot;I can&#39;t find the movie title in our movies list.&quot;})<br>            }<br>        else:<br>            print(&quot;Entered ask details&quot;)<br>            response_text = get_movie_details(json_dump, prompt, session_id)<br>           <br>            return {<br>                &quot;statusCode&quot;: 200,<br>                &quot;body&quot;: json.dumps({&quot;response&quot;: response_text})<br>            }<br>    elif prompt_type == &quot;suggestion&quot;:<br>        response_text = get_movie_suggestions(prompt,json_dump,session_id)<br>        return response_text<br>    else:<br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;body&quot;: json.dumps({&quot;response&quot;: &quot;I am not sure what you are asking for&quot;})<br>        }<br># ------------------ HANDLER FUNCTION ------------------<br><br>def lambda_handler(event, context):<br>    try:<br>        body = json.loads(event[&quot;body&quot;])<br>        prompt = body.get(&quot;message&quot;, &quot;&quot;)<br>        session_id = body.get(&quot;session_id&quot;)<br>        print(f&quot;prompt and session id {prompt} and {session_id}&quot;)<br>        store_user_message(session_id, &quot;user&quot;, prompt)<br><br>        <br>        extracted = extract_intents_entities(prompt,session_id)<br><br>        store_user_message(session_id,&quot;assistant&quot;,extracted)<br><br>        json_dump = json.loads(extracted)<br><br>        prompt_type = json_dump[&#39;type&#39;]<br><br>        print(f&quot;prompt_type {prompt_type}&quot;)<br><br>        <br><br>        return route_prompt(prompt,prompt_type,session_id,json_dump)<br><br>        <br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br>        return {<br>            &quot;statusCode&quot;: 500,<br>            &quot;body&quot;: json.dumps({&quot;response&quot;: &quot;Sorry I can&#39;t understand your query&quot;})<br>        }</pre><p><strong>I hosted my chatbot at the link below. Give it a try and see how it’s working. If you have any suggestions or struck anywhere, please feel free to comment. I am open to suggestions.</strong></p><p><strong>I named my chatbot Chitrangi. Yeah, I know it’s a weird name. Got it from the old Telugu movies </strong>😅</p><p><a href="https://chitrangi.cloudnirvana.in/">🎬 Chitrangi - Movie Chatbot</a></p><p><strong>Chitrangi will be live for 3 days — after that, the EC2 instance goes down, and my AWS bill gets to breathe again 💸😂</strong></p><p><strong>Thanks for reading.. Have a great day…</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=391d47ed1bac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Friends-Themed Chatbot: Exploring Amazon Bedrock for Dialogue Refinement]]></title>
            <link>https://medium.com/@shaiksalam9182/building-a-friends-themed-chatbot-exploring-amazon-bedrock-for-dialogue-refinement-13497cc5b0a5?source=rss-6579539aa7a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/13497cc5b0a5</guid>
            <category><![CDATA[friends]]></category>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[ai-ml-solution]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Salam shaik]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 18:52:14 GMT</pubDate>
            <atom:updated>2025-01-06T18:52:14.113Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fOlWnGBgAOvGodJLf9Z5Jw.jpeg" /></figure><p>Hi Everyone,</p><p>While browsing the datasets in Kaggle, I came across this dataset where dialogues are provided character-wise from the Friends Series.</p><p><a href="https://www.kaggle.com/datasets/sujaykapadnis/friends">Friends Sitcom Dataset</a></p><p>The dialogues in the dataset brought back the fun time I had watching the Friends series. There comes the thought of building a chatbot using this dataset.</p><p><strong>Initial Thought Process:</strong> This is how the initial thought process was, Divide the dialogues character-wise and generate embeddings for each dialogue. Store them in open-search, query them based on the user prompt, and return the most suitable dialog from the index.</p><p><strong>Challenges:</strong> With the initial thought process converted each dialogue into an embedding using Amazon Bedrock models and stored them in the OpenSearch. However, while querying them, there is a big gap between the user prompt and the returned dialogue.</p><p><strong>Solution:</strong> Even though it finds the most relevant dialogue based on the user prompt from the available dataset, sometimes it looks completely different. So I thought of adding one more Bedrock model to refine the queried dialogue and provide a relevant response.</p><p><strong>Final Conclusion:</strong> So what I have done finally is, after querying a similar dialogue, I used a bedrock model which is good in Natural Language Processing to refine the dialogue and provide a relevant response without changing the tone of the dialogue. For this model, I prompted the context with some example prompts.</p><p>Finally, the bot came in good shape(To my knowledge 😁).</p><p>You can access the bot using this link. Give it a try with your input. I am open to suggestions. Feel free to comment</p><p><strong>HERE IS THE LINK: </strong><a href="https://friendschat.cloudnirvana.in/"><strong>https://friendschat.cloudnirvana.in/</strong></a></p><h3><strong>Step-by-step implementation:</strong></h3><ul><li>Refine the dataset and store the dialogues character-wise</li><li>Generate embeddings and store them in OpenSearch</li><li>Query the OpenSearch index and refine the received dialogues using the Titan Model</li><li>Deploy a Front-End application to chat</li></ul><h3><strong>Refine the dataset and store the dialogues character-wise:</strong></h3><ul><li>Download the dataset from Kaggle using the link shared above</li><li>Extract the zip file. It contains 3 files. We are gonna use <strong>friends.csv</strong> file</li><li>Use the below script to divide the dialogues character-wise and store them in a folder</li></ul><pre>import pandas as pd<br>import os<br><br>df = pd.read_csv(&#39;friends.csv&#39;)<br><br>refined_df = df[[&#39;text&#39;,&#39;speaker&#39;]]<br><br>characters = [&#39;Monica Geller&#39;, &#39;Joey Tribbiani&#39;, &#39;Chandler Bing&#39;, &#39;Phoebe Buffay&#39;, &#39;Ross Geller&#39;, &#39;Rachel Green&#39;]<br><br>output_dir = &quot;char_wise_dialogs&quot;<br><br>os.makedirs(output_dir, exist_ok=True)<br><br>for character in characters:<br>    char_dialogs = refined_df[refined_df[&#39;speaker&#39;] == character]<br>    <br>    file_name = f&quot;{character.replace(&#39; &#39;,&#39;_&#39;)}_dialogues.csv&quot;<br>    output_file = os.path.join(output_dir, file_name)<br>    <br>    char_dialogs.to_csv(output_file, index=False)<br>    print(f&quot;Saved {character}&#39;s dialogues to {output_file}&quot;)</pre><h3><strong>Generate Embeddings and store them in OpenSearch:</strong></h3><ul><li>Visit the OpenSearch service and create a domain with <strong>t3.medium.search</strong> instance type with <strong>10GB</strong> of Storage in a <strong>single AZ</strong></li><li>Make the OpenSearch domain public and create a master user for login</li><li>Use the below script to iterate through the dialogues, Generate embeddings, and store them in an index</li><li>We will be using the model <strong>amazon.titan-embed-text-v2:0</strong></li></ul><pre>import boto3<br>import pandas as pd<br>import os<br>import json<br>from opensearchpy import OpenSearch, RequestsHttpConnection, helpers<br><br># AWS OpenSearch domain details<br>OPENSEARCH_HOST = &quot;open search endpoint without https&quot;  # Replace with your endpoint<br>INDEX_NAME = &quot;friends-dialogues&quot;<br><br># Initialize OpenSearch client<br>client = OpenSearch(<br>    hosts=[{&#39;host&#39;: OPENSEARCH_HOST, &#39;port&#39;: 443}],<br>    http_auth=(&#39;admin&#39;, &#39;******&#39;),  # Replace with your OpenSearch credentials<br>    use_ssl=True,<br>    verify_certs=True,<br>    connection_class=RequestsHttpConnection<br>)<br><br># Initialize Bedrock client<br>bedrock_client = boto3.client(&#39;bedrock-runtime&#39;, region_name=&#39;us-east-1&#39;)  # Replace with your region<br><br># Folder containing dialogues<br>input_folder = &quot;char_wise_dialogs&quot;<br><br># Batch size for processing<br>BATCH_SIZE = 20<br><br># Function to generate an embedding using Bedrock<br>def generate_embedding(text):<br>    payload = {<br>        &quot;inputText&quot;: text<br>    }<br>    response = bedrock_client.invoke_model(<br>        modelId=&quot;amazon.titan-embed-text-v2:0&quot;,<br>        contentType=&quot;application/json&quot;,<br>        accept=&quot;application/json&quot;,<br>        body=json.dumps(payload)<br>    )<br>    response_body = json.loads(response[&#39;body&#39;].read())<br>    return response_body.get(&#39;embedding&#39;)<br><br># Function to index documents in bulk in OpenSearch<br>def bulk_index_documents(batch):<br>    actions = [<br>        {<br>            &quot;_index&quot;: INDEX_NAME,<br>            &quot;_source&quot;: {<br>                &quot;character&quot;: doc[&quot;character&quot;],<br>                &quot;dialogue&quot;: doc[&quot;dialogue&quot;],<br>                &quot;embedding&quot;: doc[&quot;embedding&quot;]<br>            }<br>        }<br>        for doc in batch<br>    ]<br>    helpers.bulk(client, actions)<br><br># Create the index in OpenSearch (if not already created)<br>if not client.indices.exists(INDEX_NAME):<br>    client.indices.create(index=INDEX_NAME, body={<br>        &quot;settings&quot;: {<br>            &quot;number_of_shards&quot;: 1,<br>            &quot;number_of_replicas&quot;: 1,<br>            &quot;index&quot;: {<br>                &quot;knn&quot;: True  # Enable kNN search for this index<br>            }<br>        },<br>        &quot;mappings&quot;: {<br>            &quot;properties&quot;: {<br>                &quot;character&quot;: {&quot;type&quot;: &quot;keyword&quot;},<br>                &quot;dialogue&quot;: {&quot;type&quot;: &quot;text&quot;},<br>                &quot;embedding&quot;: {<br>                    &quot;type&quot;: &quot;knn_vector&quot;,<br>                    &quot;dimension&quot;: 1024  # Replace with the embedding size<br>                }<br>            }<br>        }<br>    })<br>    print(f&quot;Created index with knn_vector: {INDEX_NAME}&quot;)<br><br># Process each character file<br>for file_name in os.listdir(input_folder):<br>    if file_name.endswith(&#39;.csv&#39;):<br>        # Read character dialogues<br>        character_file = os.path.join(input_folder, file_name)<br>        df = pd.read_csv(character_file)<br><br>        # Process in batches<br>        batch = []<br>        for index, row in df.iterrows():<br>            dialogue = row[&#39;text&#39;]<br>            character = row[&#39;speaker&#39;]<br><br>            try:<br>                # Generate embedding for each dialogue<br>                embedding = generate_embedding(dialogue)<br>                batch.append({&quot;dialogue&quot;: dialogue, &quot;character&quot;: character, &quot;embedding&quot;: embedding})<br>                <br>                # Process the batch if it reaches the batch size<br>                if len(batch) == BATCH_SIZE:<br>                    # Bulk index the batch into OpenSearch<br>                    bulk_index_documents(batch)<br>                    print(f&quot;Indexed batch of size {len(batch)}&quot;)<br>                    batch = []  # Reset the batch<br>            except Exception as e:<br>                print(f&quot;Error processing dialogue: {dialogue[:50]} - {e}&quot;)<br><br>        # Process any remaining documents in the last batch<br>        if batch:<br>            bulk_index_documents(batch)<br>            print(f&quot;Indexed remaining batch of size {len(batch)}&quot;)</pre><h3><strong>Query the OpenSearch index and refine the received dialogues using the Titan Model:</strong></h3><ul><li>Once the index has our data, Let’s create a script to query the index</li><li>Create a Lambda function with Python 3.9</li><li>Copy and paste the following code in the Lambda function and provide the necessary permissions</li><li>This script will query similar dialogues from the index and pass the received dialogue to the next model</li><li>We will be using <strong>amazon.titan-text-express-v1 </strong>model to refine the dialogue and add some relevant data to match the user prompt</li><li>Once the Lamba is ready, Create an API in API Gateway and add <strong>POST</strong> method for sending user message</li></ul><pre>import boto3<br>import json<br>from opensearchpy import OpenSearch, RequestsHttpConnection<br><br># OpenSearch configuration<br>OPENSEARCH_HOST = &quot;open search endpoint without https&quot;<br>INDEX_NAME = &quot;friends-dialogues&quot;<br><br># Initialize OpenSearch client<br>client = OpenSearch(<br>    hosts=[{&#39;host&#39;: OPENSEARCH_HOST, &#39;port&#39;: 443}],<br>    http_auth=(&#39;admin&#39;, &#39;******&#39;),<br>    use_ssl=True,<br>    verify_certs=True,<br>    connection_class=RequestsHttpConnection<br>)<br><br># Bedrock clients for embedding and refinement<br>bedrock_client = boto3.client(&#39;bedrock-runtime&#39;, region_name=&#39;us-east-1&#39;)<br><br># Function to generate embedding for user input<br>def generate_embedding(text):<br>    payload = {&quot;inputText&quot;: text}<br>    response = bedrock_client.invoke_model(<br>        modelId=&quot;amazon.titan-embed-text-v2:0&quot;,<br>        contentType=&quot;application/json&quot;,<br>        accept=&quot;application/json&quot;,<br>        body=json.dumps(payload)<br>    )<br>    response_body = json.loads(response[&#39;body&#39;].read())<br>    return response_body.get(&#39;embedding&#39;)<br><br># Function to query OpenSearch for similar dialogues<br>def query_opensearch(user_embedding):<br>    query = {<br>        &quot;size&quot;: 1,<br>        &quot;query&quot;: {<br>            &quot;knn&quot;: {<br>                &quot;embedding&quot;: {<br>                    &quot;vector&quot;: user_embedding,<br>                    &quot;k&quot;: 1<br>                }<br>            }<br>        }<br>    }<br>    response = client.search(index=INDEX_NAME, body=query)<br>    hits = response[&quot;hits&quot;][&quot;hits&quot;]<br>    if hits:<br>        return hits[0][&quot;_source&quot;]<br>    return None<br><br>def refine_response(user_prompt, character, retrieved_dialogue):<br>    # Construct a guided and controlled prompt<br>    prompt = (<br>        f&quot;You are an assistant generating responses for a Friends-themed chatbot. Your task is to:\n&quot;<br>        f&quot;1. Respond in the tone and style of the specified character.\n&quot;<br>        f&quot;2. Avoid adding irrelevant details or extra sentences.\n&quot;<br>        f&quot;3. Ensure responses are casual and character-specific.\n&quot;<br>        f&quot;4. Exclude any metadata or instructional text in the response.\n\n&quot;<br>        f&quot;Examples:\n&quot;<br>        f&quot;- User Prompt: \&quot;What&#39;s your favorite food?\&quot;\n&quot;<br>        f&quot;  Character: Joey Tribbiani\n&quot;<br>        f&quot;  Dialogue: \&quot;Joey doesn&#39;t share food!\&quot;\n&quot;<br>        f&quot;  Response: \&quot;Joey doesn&#39;t share food! But I do love a big meatball sub.\&quot;\n\n&quot;<br>        f&quot;- User Prompt: \&quot;Let&#39;s go for a vacation.\&quot;\n&quot;<br>        f&quot;  Character: Ross Geller\n&quot;<br>        f&quot;  Dialogue: \&quot;Spring vacation.\&quot;\n&quot;<br>        f&quot;  Response: \&quot;Spring vacation! I’ll pack my fossils!\&quot;\n\n&quot;<br>        f&quot;User Prompt: {user_prompt}\n&quot;<br>        f&quot;Retrieved Dialogue: \&quot;{retrieved_dialogue}\&quot;\n&quot;<br>        f&quot;Character: {character}\n\n&quot;<br>        f&quot;Now, generate a response as the specified character, ensuring it aligns with the dialogue and the user&#39;s prompt.&quot;<br>    )<br><br>    payload = {&quot;inputText&quot;: prompt}<br><br>    try:<br>        # Invoke the Titan Text G1 - Express model<br>        response = bedrock_client.invoke_model(<br>            modelId=&quot;amazon.titan-text-g1-express:0&quot;,<br>            contentType=&quot;application/json&quot;,<br>            accept=&quot;application/json&quot;,<br>            body=json.dumps(payload)<br>        )<br>        response_body = json.loads(response[&#39;body&#39;].read())<br>        generated_response = response_body[&#39;results&#39;][0][&#39;outputText&#39;]<br><br>        # Post-process the response<br>        # 1. Remove metadata or prompt details<br>        if &quot;User Prompt&quot; in generated_response:<br>            generated_response = generated_response.split(&quot;User Prompt&quot;)[0].strip()<br><br>        # 2. Limit response length<br>        max_length = 150<br>        if len(generated_response) &gt; max_length:<br>            generated_response = generated_response[:max_length].rsplit(&quot; &quot;, 1)[0] + &quot;...&quot;<br><br>        # 3. Ensure relevance: Fallback to retrieved dialogue if response is invalid<br>        if not generated_response or &quot;irrelevant&quot; in generated_response.lower():<br>            return retrieved_dialogue<br><br>        return generated_response<br><br>    except Exception as e:<br>        print(f&quot;Error refining response: {e}&quot;)<br>        # Fallback to the retrieved dialogue in case of an error<br>        return retrieved_dialogue<br><br>    # Construct a controlled and guided prompt<br>    prompt = (<br>        f&quot;You are an assistant generating responses for a Friends-themed chatbot. Your task is to:\n&quot;<br>        f&quot;1. Maintain the original tone and personality of the character.\n&quot;<br>        f&quot;2. Avoid adding irrelevant details or extra sentences.\n&quot;<br>        f&quot;3. Ensure the response aligns with the retrieved dialogue.\n&quot;<br>        f&quot;4. Make responses casual and consistent with the character&#39;s personality.\n\n&quot;<br>        f&quot;Examples:\n&quot;<br>        f&quot;- User Prompt: \&quot;What&#39;s your favorite food?\&quot;\n&quot;<br>        f&quot;  Character: Joey Tribbiani\n&quot;<br>        f&quot;  Dialogue: \&quot;Joey doesn&#39;t share food!\&quot;\n&quot;<br>        f&quot;  Response: \&quot;Joey doesn&#39;t share food! But I do love a big meatball sub.\&quot;\n\n&quot;<br>        f&quot;- User Prompt: \&quot;I feel sad.\&quot;\n&quot;<br>        f&quot;  Character: Chandler Bing\n&quot;<br>        f&quot;  Dialogue: \&quot;I&#39;m sorry you&#39;re feeling this way.\&quot;\n&quot;<br>        f&quot;  Response: \&quot;I&#39;m sorry you&#39;re feeling this way. But remember, I can make you laugh. Want a joke?\&quot;\n\n&quot;<br>        f&quot;User Prompt: {user_prompt}\n&quot;<br>        f&quot;Retrieved Dialogue: \&quot;{retrieved_dialogue}\&quot;\n&quot;<br>        f&quot;Character: {character}\n\n&quot;<br>        f&quot;Now, generate a response that refines the retrieved dialogue to better match the user&#39;s prompt while staying true to the character&#39;s tone and avoiding verbosity.&quot;<br>    )<br><br>    # Payload for the Bedrock API<br>    payload = {&quot;inputText&quot;: prompt}<br>    <br>    try:<br>        # Invoke the Titan Text G1 - Express model<br>        response = bedrock_client.invoke_model(<br>            modelId=&quot;amazon.titan-text-express-v1&quot;,<br>            contentType=&quot;application/json&quot;,<br>            accept=&quot;application/json&quot;,<br>            body=json.dumps(payload)<br>        )<br>        response_body = json.loads(response[&#39;body&#39;].read())<br>        generated_response = response_body[&#39;results&#39;][0][&#39;outputText&#39;]<br><br>        # Post-processing: Ensure the refined response adheres to guidelines<br>        # 1. Limit response length<br>        max_length = 150<br>        if len(generated_response) &gt; max_length:<br>            generated_response = generated_response[:max_length] + &quot;...&quot;<br><br>        # 2. Ensure relevance: If response is missing or irrelevant, fallback to retrieved dialogue<br>        if not generated_response or &quot;irrelevant&quot; in generated_response.lower():  # Replace with advanced checks if needed<br>            return retrieved_dialogue<br><br>        return generated_response<br><br>    except Exception as e:<br>        print(f&quot;Error refining response: {e}&quot;)<br>        # Fallback to the retrieved dialogue in case of an error<br>        return retrieved_dialogue<br><br>    # Construct a controlled prompt<br>    prompt = (<br>        f&quot;You are an assistant generating responses for a Friends-themed chatbot. Your task is to:\n&quot;<br>        f&quot;1. Maintain the original tone and personality of the character.\n&quot;<br>        f&quot;2. Avoid adding irrelevant details or extra sentences.\n&quot;<br>        f&quot;3. Ensure the response aligns with the retrieved dialogue.\n\n&quot;<br>        f&quot;Here is the context:\n&quot;<br>        f&quot;- User Prompt: {user_prompt}\n&quot;<br>        f&quot;- Retrieved Dialogue: \&quot;{retrieved_dialogue}\&quot;\n&quot;<br>        f&quot;- Character: {character}\n\n&quot;<br>        f&quot;Now, generate a response that refines the retrieved dialogue to better match the user&#39;s prompt while staying true to the character&#39;s tone and avoiding verbosity.&quot;<br>    )<br><br>    # Payload for the Bedrock API<br>    payload = {&quot;inputText&quot;: prompt}<br>    <br>    try:<br>        # Invoke the Titan Text G1 - Express model<br>        response = bedrock_client.invoke_model(<br>            modelId=&quot;amazon.titan-text-express-v1&quot;,<br>            contentType=&quot;application/json&quot;,<br>            accept=&quot;application/json&quot;,<br>            body=json.dumps(payload)<br>        )<br>        response_body = json.loads(response[&#39;body&#39;].read())<br>        generated_response = response_body[&#39;results&#39;][0][&#39;outputText&#39;]<br>        <br>        # Post-processing: Ensure the refined response adheres to guidelines<br>        # 1. Limit response length<br>        max_length = 150<br>        generated_response = generated_response[:max_length]<br>        <br>        # 2. Ensure relevance by comparing with the retrieved dialogue<br>        # If generated response deviates significantly, fallback to the retrieved dialogue<br>        if not generated_response or &quot;irrelevant&quot; in generated_response.lower():  # Placeholder for advanced checks<br>            return retrieved_dialogue<br>        <br>        return generated_response<br><br>    except Exception as e:<br>        print(f&quot;Error refining response: {e}&quot;)<br>        # Fallback to the retrieved dialogue in case of an error<br>        return retrieved_dialogue<br><br><br># Lambda function handler<br>def lambda_handler(event, context):<br>    try:<br>        # Extract user input<br>        body = json.loads(event[&quot;body&quot;])<br>        user_input = body[&quot;message&quot;]<br><br>        # Generate embedding for user input<br>        user_embedding = generate_embedding(user_input)<br><br>        # Query OpenSearch for the most relevant dialogue<br>        result = query_opensearch(user_embedding)<br><br>        if not result:<br>            return {<br>                &quot;statusCode&quot;: 200,<br>                &quot;headers&quot;: {<br>                    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>                    &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;<br>                },<br>                &quot;body&quot;: json.dumps({&quot;character&quot;: &quot;Unknown&quot;, &quot;response&quot;: &quot;I&#39;m not sure how to respond to that!&quot;})<br>            }<br><br>        # Refine the response<br>        # refined_response = f&quot;{result[&#39;dialogue&#39;]}&quot;<br>        refined_response = refine_response(user_input, result[&quot;character&quot;], result[&quot;dialogue&quot;])<br>        print(refined_response)<br><br>        # Return the refined response<br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;headers&quot;: {<br>                &quot;Content-Type&quot;: &quot;application/json&quot;,<br>                &quot;Access-Control-Allow-Origin&quot;: &quot;https://friendschat.cloudnirvana.in&quot;<br>            },<br>            &quot;body&quot;: json.dumps({<br>                &quot;character&quot;: result[&quot;character&quot;],<br>                &quot;response&quot;: refined_response<br>            })<br>        }<br><br>    except Exception as e:<br>        return {<br>            &quot;statusCode&quot;: 500,<br>            &quot;headers&quot;: {<br>                &quot;Content-Type&quot;: &quot;application/json&quot;,<br>                &quot;Access-Control-Allow-Origin&quot;: &quot;https://friendschat.cloudnirvana.in&quot;<br>            },<br>            &quot;body&quot;: json.dumps({&quot;error&quot;: str(e)})<br>        }</pre><h3><strong>Deploy a Front-End application to chat:</strong></h3><ul><li>Once everything is ready, let’s build a simple front-end application and host it on the S3 Static web hosting.</li><li>If you have your own domain, Add it to Route 53 and point it to the S3 bucket.</li><li>Use the below code to create an HTML file and host it in an S3 bucket</li><li>Replace the API link with your own API</li></ul><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;title&gt;Friends Chatbot&lt;/title&gt;<br>    &lt;style&gt;<br>        #chat-container {<br>            width: 90%;<br>            max-width: 600px;<br>            margin: 20px auto;<br>            font-family: Arial, sans-serif;<br>        }<br>        #messages {<br>            height: 400px;<br>            overflow-y: auto;<br>            border: 1px solid #ccc;<br>            padding: 10px;<br>            border-radius: 5px;<br>            background-color: #f9f9f9;<br>        }<br>        .message {<br>            margin: 10px 0;<br>        }<br>        .user {<br>            text-align: right;<br>            color: blue;<br>        }<br>        .bot {<br>            text-align: left;<br>            color: green;<br>        }<br>        #input-container {<br>            display: flex;<br>            margin-top: 10px;<br>        }<br>        #user-input {<br>            flex: 1;<br>            padding: 10px;<br>            border: 1px solid #ccc;<br>            border-radius: 5px;<br>        }<br>        button {<br>            margin-left: 5px;<br>            padding: 10px 20px;<br>            background-color: #007bff;<br>            color: white;<br>            border: none;<br>            border-radius: 5px;<br>            cursor: pointer;<br>        }<br>        button:hover {<br>            background-color: #0056b3;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div id=&quot;chat-container&quot;&gt;<br>        &lt;div id=&quot;messages&quot;&gt;&lt;/div&gt;<br>        &lt;div id=&quot;input-container&quot;&gt;<br>            &lt;input type=&quot;text&quot; id=&quot;user-input&quot; placeholder=&quot;Type your message...&quot;&gt;<br>            &lt;button onclick=&quot;sendMessage()&quot;&gt;Send&lt;/button&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;script&gt;<br>        const apiEndpoint = &quot;replace with you api gateway endpoint&quot;;<br><br>        function sendMessage() {<br>            const inputField = document.getElementById(&quot;user-input&quot;);<br>            const message = inputField.value.trim();<br>            if (!message) return;<br><br>            const messagesContainer = document.getElementById(&quot;messages&quot;);<br><br>            // Add user message<br>            const userMessage = document.createElement(&quot;div&quot;);<br>            userMessage.className = &quot;message user&quot;;<br>            userMessage.textContent = message;<br>            messagesContainer.appendChild(userMessage);<br><br>            // Clear input<br>            inputField.value = &quot;&quot;;<br><br>            // Send API request<br>            fetch(apiEndpoint, {<br>                method: &quot;POST&quot;,<br>                headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>                body: JSON.stringify({ message }),<br>            })<br>                .then((response) =&gt; response.json())<br>                .then((data) =&gt; {<br>                    // Add bot response<br>                    const botMessage = document.createElement(&quot;div&quot;);<br>                    botMessage.className = &quot;message bot&quot;;<br>                    botMessage.textContent = `${data.character}: ${data.response}`;<br>                    messagesContainer.appendChild(botMessage);<br><br>                    // Scroll to bottom<br>                    messagesContainer.scrollTop = messagesContainer.scrollHeight;<br>                })<br>                .catch((error) =&gt; {<br>                    console.error(&quot;Error:&quot;, error);<br>                    const botMessage = document.createElement(&quot;div&quot;);<br>                    botMessage.className = &quot;message bot&quot;;<br>                    botMessage.textContent = &quot;Error connecting to the chatbot.&quot;;<br>                    messagesContainer.appendChild(botMessage);<br>                });<br>        }<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>That’s it. Visit my hosted solution using the above link shared and share your feedback through the comments.</p><p>Thanks 😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13497cc5b0a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Event-Driven Architecture for Content Embedding Generation with AWS Bedrock, DynamoDb…]]></title>
            <link>https://medium.com/@shaiksalam9182/building-an-event-driven-architecture-for-content-embedding-generation-with-aws-bedrock-dynamodb-285f9c013609?source=rss-6579539aa7a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/285f9c013609</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[opensearch]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[vector-embeddings]]></category>
            <category><![CDATA[aws-batch]]></category>
            <dc:creator><![CDATA[Salam shaik]]></dc:creator>
            <pubDate>Fri, 20 Dec 2024 06:06:37 GMT</pubDate>
            <atom:updated>2024-12-20T06:06:37.773Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an Event-Driven Architecture for Content Embedding Generation with AWS Bedrock, DynamoDb, and AWS Batch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TD3k5f9ufQRwg1_2DFJoUw.jpeg" /></figure><p>Hello everyone,</p><p>In this blog, I’ll walk you through building an <strong>event-driven pipeline</strong> that converts the contents in <strong>Dynamo DB</strong> into E<strong>mbeddings</strong>, making them searchable via <strong>OpenSearch</strong> for vector search. The goal of this pipeline is to automatically handle the entire process whenever new content is added or existing content is modified in Dynamo DB</p><p>This event-driven architecture triggers each step in the process seamlessly, converting newly added or updated items into embeddings and storing them in OpenSearch</p><p>One of my key design goals is to minimize the level of coding for connecting services and reduce the reliance on Lambda Functions. Instead, I focused on leveraging AWS Services and <strong>Event Bridge</strong> to connect and automate the workflow.</p><p>This is how the workflow will look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_WsX65GP9g7B42_YK-Oo8w.png" /></figure><p>Before diving into the implementation Let’s prepare the scripts for inserting data and converting contents into embeddings and inserting them into OpenSearch</p><p>For this POC I am using this dataset from Kaggle <a href="https://www.kaggle.com/datasets/fernandogarciah24/top-1000-imdb-dataset">https://www.kaggle.com/datasets/fernandogarciah24/top-1000-imdb-dataset</a></p><p><strong>Code for inserting data into Dynamo DB:</strong></p><pre>import csv<br>import boto3<br>import uuid<br><br># DynamoDB table name<br>DYNAMODB_TABLE_NAME = &quot;content&quot;<br><br># Initialize DynamoDB client<br>dynamodb = boto3.resource(&#39;dynamodb&#39;,region_name=&quot;us-east-1&quot;)<br>table = dynamodb.Table(DYNAMODB_TABLE_NAME)<br><br>def process_csv_and_insert_to_dynamodb(csv_file_path):<br>    try:<br>        # Open and read the CSV file<br>        with open(csv_file_path, mode=&#39;r&#39;, encoding=&#39;utf-8&#39;) as file:<br>            csv_reader = csv.DictReader(file)<br>            content_id = 0  # Start content_id from 0<br>            <br>            # Iterate over each row in the CSV<br>            for row in csv_reader:<br>                # Prepare item for DynamoDB<br>                item = {<br>                    &#39;content_id&#39;: content_id,<br>                    &#39;content_title&#39;: row[&#39;Series_Title&#39;],<br>                    &#39;genre&#39;: row[&#39;Genre&#39;],<br>                    &#39;overview&#39;: row[&#39;Overview&#39;]<br>                }<br>                <br>                # Insert item into DynamoDB<br>                table.put_item(Item=item)<br>                <br>                print(f&quot;Inserted: {item}&quot;)<br>                content_id += 1  # Increment content_id<br>                if content_id == 65: #stopping at first 65 records for testing<br>                    break<br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br><br># Provide the path to your CSV file<br>csv_file_path = &quot;movies.csv&quot;<br><br># Call the function<br>process_csv_and_insert_to_dynamodb(csv_file_path)</pre><p><strong>Code for converting content into Embeddings:</strong></p><pre>import boto3<br>import json<br>import os<br>import time<br>from opensearchpy import OpenSearch, RequestsHttpConnection<br>from requests.auth import HTTPBasicAuth<br>from requests_aws4auth import AWS4Auth<br><br><br>credentials = boto3.Session().get_credentials()<br>aws_auth = AWS4Auth(<br>    credentials.access_key,<br>    credentials.secret_key,<br>    &#39;us-east-1&#39;,<br>    &#39;aoss&#39;,  # Service name for OpenSearch Serverless<br>    session_token=credentials.token<br>)<br><br><br>QUEUE_URL = &quot;queue url&quot;<br>OPENSEARCH_ENDPOINT = &quot;open search serverless endpoint&quot;<br>INDEX_NAME = &quot;contents&quot;<br>AWS_REGION = &#39;us-east-1&#39;<br><br># AWS Clients<br>sqs = boto3.client(&#39;sqs&#39;, region_name=AWS_REGION)<br>bedrock_runtime = boto3.client(&#39;bedrock-runtime&#39;, region_name=AWS_REGION)<br><br># OpenSearch Client<br>def get_opensearch_client():<br>    return OpenSearch(<br>        hosts=[{&#39;host&#39;: OPENSEARCH_ENDPOINT, &#39;port&#39;: 443}],<br>        http_auth=aws_auth,<br>        use_ssl=True,<br>        verify_certs=True,<br>        connection_class=RequestsHttpConnection<br>    )<br><br># Function to poll messages from SQS<br>def poll_sqs_messages():<br>    response = sqs.receive_message(<br>        QueueUrl=QUEUE_URL,<br>        MaxNumberOfMessages=10,  # Fetch up to 10 messages<br>        WaitTimeSeconds=10<br>    )<br>    return response.get(&#39;Messages&#39;, [])<br><br># Function to call Amazon Titan for embedding generation<br>def generate_embeddings(text):<br>    payload = {<br>        &quot;inputText&quot;: text<br>    }<br>    response = bedrock_runtime.invoke_model(<br>        modelId=&quot;amazon.titan-embed-text-v1&quot;,<br>        contentType=&quot;application/json&quot;,<br>        accept=&quot;application/json&quot;,<br>        body=json.dumps(payload)<br>    )<br>    response_body = json.loads(response[&#39;body&#39;].read())<br>    return response_body.get(&#39;embedding&#39;)<br><br># Function to store embeddings in OpenSearch<br>def store_embeddings_in_opensearch(content_id, embedding, content_title,genre):<br>    client = get_opensearch_client()<br>    print(&quot;got the client&quot;)<br>    document = {<br>        &quot;title&quot;: content_title,<br>        &quot;overview&quot;: embedding,<br>        &quot;genre&quot;: genre,<br>        &quot;content_id&quot;: content_id<br>    }<br>    print(&quot;got the document&quot;)<br>    response = client.index(<br>        index=INDEX_NAME,<br>        body=document<br>    )<br>    print(&quot;got the response&quot;)<br>    return response<br><br># Main Processing Function<br>def main():<br>    print(&quot;Starting Batch Job to process SQS messages...&quot;)<br><br>    messages = poll_sqs_messages()<br>    if not messages:<br>        print(&quot;No messages found in the queue. Exiting.&quot;)<br>        return<br><br>    for message in messages:<br>        try:<br>            body = json.loads(message[&#39;Body&#39;])<br>            db_record = body[&#39;dynamodb&#39;][&#39;NewImage&#39;]<br>            content_title = db_record[&#39;content_title&#39;][&#39;S&#39;]<br>            overview = db_record[&#39;overview&#39;][&#39;S&#39;]<br>            content_id = db_record[&#39;content_id&#39;][&#39;N&#39;]<br>            genre = db_record[&#39;genre&#39;][&#39;S&#39;]<br>            <br>            # Generate Embedding<br>            embedding = generate_embeddings(overview)<br>            print(f&quot;Generated embedding for content: {content_title}&quot;)<br>            <br>            # Store in OpenSearch<br>            store_embeddings_in_opensearch(content_id, embedding, content_title,genre)<br>            # Delete message from SQS after successful processing<br>            # sqs.delete_message(<br>            #     QueueUrl=QUEUE_URL,<br>            #     ReceiptHandle=message[&#39;ReceiptHandle&#39;]<br>            # )<br>        #     print(f&quot;Deleted message {document_id} from SQS.&quot;)<br><br>        except Exception as e:<br>            print(f&quot;Error processing message: {str(e)}&quot;)<br>            continue<br><br>    print(&quot;Batch Job completed successfully.&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><ul><li>Create a Dockerfile and Create a Docker image to push it to ECR</li></ul><pre>FROM python:3.9-slim<br>USER root<br><br># Install dependencies<br>RUN pip install boto3 opensearch-py requests requests-aws4auth<br><br># Copy the script into the container<br>COPY process_embeddings_batch.py /app/process_embeddings_batch.py<br><br># Default command<br>CMD [&quot;python&quot;, &quot;/app/process_embeddings_batch.py&quot;]</pre><ul><li>Visit the ECR section and Click on Create a Repo. Provide a name for the Repo and Click on Push Commands button once the Repo is Created</li><li>Use the push command to build and push the docker image</li></ul><p><strong>Step-by-step implementation:</strong></p><ul><li>Create a DynamoDB table and enable streams</li><li>Create a SQS Queue for holding the records of DB</li><li>Create an Event Bridge Pipe to Connect Dynamo DB and SQS</li><li>Create a Cloud Watch Alarm When messages in the Queue exceed more than 50 messages</li><li>Create a AWS Batch job definition to run jobs</li><li>Create a State Machine to Submit a job to AWS Batch</li><li>Create a rule in Even Bridge to listen for Alarm and Trigger the Step Function state machine</li><li>Create an OpenSearch Serverless collection and index</li></ul><h3><strong>Create a DynamoDB table and enable streams:</strong></h3><ul><li>Visit DynamoDB Service, click on the Create Tables button, Provide a name for the table, make <strong>content_id</strong> as the partition key, and type as <strong>Number</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihAdYStTnrh75u-cbAP5tA.png" /></figure><ul><li>Visit the <strong>Exports and Streams</strong> tab and enable the <strong>Streams</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cn0SZya-5qPoRsmUDgJGoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urS5yGN4RFRlve76-OTX1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2zkvseMVdlgAhkNiD3UVlw.png" /></figure><h3><strong>Create a SQS Queue for holding the records of DB:</strong></h3><ul><li>Visit the SQS service from the AWS console and click on Create a Queue. There is no need for a message order. So Go for the standard queue. Provide a name for the Queue and click on Create Queue</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCTy4mHMrmYRCbacQQRpsQ.png" /></figure><h3><strong>Create an Event Bridge Pipe to Connect Dynamo DB and SQS:</strong></h3><ul><li>Visit Event Bridge Service and click on Create pipe</li><li>Select Source as DyanoDB and Target as SQS</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uv9jODjBS077V37lmMWS3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldzEzxg8iKiPYjR4PMNAdw.png" /></figure><ul><li>Click on Create Pipe. This will push the dynamo db records to SQS</li></ul><h3><strong>Create a Cloud Watch Alarm When messages in the Queue exceed more than 50 messages:</strong></h3><ul><li>Visit the cloud watch service in the AWS console. From the Side panel Click on All Alarms and Click on Create Alarm</li><li>Select SQS <strong>ApproximateNumberOfMessagesVisible</strong> as the metric</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5rxa4NEOiCrot3UvBhw6g.png" /></figure><ul><li>Keep the conditions like greater than 50 messages</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FALjCG7QOpYaqBsr_n4lcw.png" /></figure><ul><li>Skip the actions, provide a name for the alarm, and click on Create Alarm</li></ul><p><strong>Create a AWS Batch job definition to run jobs:</strong></p><ul><li>Click on Create a job definition, select Fargate as Orchestration type provide storage as 21GB and keep the rest of the fields as it is and visit the next section</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*83jNAHOV9RcMoP7PyLu5tw.png" /></figure><ul><li>Copy the URI of the ECR image and paste it here which we created at the start of the blog and keep the rest of the fields as it is</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gBj-5gJqJijXS-WFJM4PXQ.png" /></figure><ul><li>Keep the user as <strong>root</strong> and select logging as AWS Logs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AzYhtkmDPFuDn3ZmGns0cg.png" /></figure><ul><li>Review everything and create the job definition</li><li><strong>We also need to create a job queue and computing environment. Provide basic details and create a job queue with a compute environment</strong></li><li>Here is how to create a computing environment</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-X0FQushNCGBD-KY78-xqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QOoy13zFeuO-6hUobS2jg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XA5_uR7YLyJwByeVnH9Naw.png" /></figure><ul><li>Visit the Job Queue and click on create a job queue with the environment we created</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*57T1xhXIdTaLnECZg9S66g.png" /></figure><ul><li>Now We have Job Definition and Job Queue with us. Let’s create a state machine to trigger jobs</li></ul><h3><strong>Create a State Machine to Submit a job to AWS Batch:</strong></h3><ul><li>Visit the step functions service and click on Create a state machine.</li><li>Select submit job state and select job definition and queue we created above</li><li>For the sample, I am using only the one required state. Keep adding more states based on your needs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*7Aczw5v37j4aCr4M3YfPxg.png" /></figure><ul><li>Click on the submit job state and select job queue and definition from the right-side panel</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWq5R38BOWAgpA1ddpA3Mw.png" /></figure><ul><li>Now save the state machine and Let’s connect the SQS and this state machine based on the cloud watch Alarm We Created above</li></ul><h3><strong>Create a rule in Even Bridge to listen for Alarm and Trigger the Step Function state machine:</strong></h3><ul><li>Visit the Event Bridge service and select Rules from the side menu</li><li>Provide a name for the rule and select an event with a pattern</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fONgxwNxtTLA3b9zsxug2w.png" /></figure><ul><li>In the event pattern paste the following JSON</li></ul><pre>{<br>  &quot;source&quot;: [&quot;aws.cloudwatch&quot;],<br>  &quot;detail-type&quot;: [&quot;CloudWatch Alarm State Change&quot;],<br>  &quot;detail&quot;: {<br>    &quot;state&quot;: {<br>      &quot;value&quot;: [&quot;ALARM&quot;]<br>    },<br>    &quot;alarmName&quot;: [&quot;sqs-threshold-alarm&quot;]<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgDegHh8E1W0QGvGdZ2WLA.png" /></figure><ul><li>Select the target as the state machine we created and click on Create rule</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3-MScE3fVlwlQCQbYCIow.png" /></figure><h3><strong>Create an OpenSearch Serverless collection and index:</strong></h3><ul><li>Visit the Serverless section from OpenSearch Service, Click on Create a Collection, Provide the details like this, and click on Create collection</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6hXjRBBry1Fby5SSGniCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3WIz-dnLO4Jd6Oj63LtVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yOm4UWV54yEIcDq_jFmDxg.png" /></figure><ul><li>Once the collection is created Click on Create an index with the following configuration</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avgOvfzBaB104nZcBbrnkQ.png" /></figure><p><strong>That’s it We have everything ready and connected to every service. Let’s run the inserting python script to insert data into Dynamo DB and check everything is Trigged well or not.</strong></p><p><strong>Note: Once the Threshold is reached it will take some time to get the state machine to be triggered</strong></p><ul><li><strong>These are the jobs that got triggered whenever I inserted data into Dynamo DB</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ujnM617YTwFkBfEZdfaeMA.png" /></figure><ul><li><strong>Verify whether records are inserted or not in the index. You can check the records count or dashboard to see the records</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qY4x0yw_bI1bh-hXl60eEA.png" /></figure><p>Once the data is ready you can build a vector search engine by following my previous article here</p><p><a href="https://medium.com/@shaiksalam9182/building-a-vector-based-search-engine-using-amazon-bedrock-and-amazon-open-search-service-cee58636dabc">Building a vector-based search engine using Amazon Bedrock and Amazon Open Search Service</a></p><p>Please let me know if you are struck at any place and need any assistance through the comment section. Thanks. Have a great day</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=285f9c013609" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a movie suggestion Bot using AWS Bedrock, Amazon Lex, and OpenSearch]]></title>
            <link>https://medium.com/@shaiksalam9182/building-a-movie-suggestion-bot-using-aws-bedrock-amazon-lex-and-opensearch-9ef0b7f349c1?source=rss-6579539aa7a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ef0b7f349c1</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[lex]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Salam shaik]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 22:54:21 GMT</pubDate>
            <atom:updated>2024-11-26T22:54:21.640Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JsPvkdo_PFS4uRm0GIQF0w.jpeg" /></figure><p>Hi Everyone,</p><p>For the last few weeks, I have been trying to build a chatbot that suggests movies based on user prompts.</p><p>I am not an expert in the AI/ML field. With the knowledge I have in this field and the AWS services I know I tried to build this chatbot by using the following AWS Services</p><ul><li>Bedrock(Titan and Claude models)</li><li>OpenSearch</li><li>AWS Lex</li><li>Lambda</li></ul><p>Whenever I try to spell AWS Lex it reminds me of the villain <strong>Lex Luthor</strong> from the <strong>Superman </strong>series</p><p>Let me introduce each service I used and the role of that service in building this chatbot</p><p><strong>BedRock: </strong>This service will provide the models by Amazon and several third parties. From the available models, we will be using the <strong>Claude v2 </strong>model for processing the User Prompts and the <strong>Titan</strong> model for generating the embedding for the movie content we have.</p><p>If you don&#39;t know what is embedding, think of it as an array with numbers which helps the ML Model to understand the relationship between real-world data.</p><p><strong>OpenSearch:</strong> We will be using this service to store the embeddings generated by the bedrock Titan model and to query those embeddings to find similar movies</p><p><strong>AWS Lex: </strong>This service will help us to build a chatbot. This will be a bridge that takes the user prompt and triggers the movie-suggesting logic based on the intent detection and will respond back to the user with movie suggestions.</p><p><strong>Lambda: </strong>This is where the core logic executes, which will take the user prompt from the Lex Bot, query the OpenSearch index, and respond back to the Lex Bot with movie Suggestions</p><p>Let’s dive into the implementation</p><p><strong>This is the movie dataset I am using for this task </strong><a href="https://www.kaggle.com/datasets/kayscrapes/movie-dataset"><strong>https://www.kaggle.com/datasets/kayscrapes/movie-dataset</strong></a></p><p><strong>Implementation Steps:</strong></p><ul><li>Create an OpenSearch Cluster and an index for dumping Embeddings</li><li>Generate Embeddings and dump them into the OpenSearch Index</li><li>Implement a Lambda function to query the OpenSearch Index</li><li>Create a chatbot and connect it to the Lambda</li></ul><h3><strong>Create an OpenSearch Cluster and an index for dumping Embeddings:</strong></h3><ul><li>Visit the OpenSearch service in the AWS console and click on the Create Domain button</li><li>Provide a name for the domain, Choose the Standard Create option and the dev/test template like below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*Ot90Cd8jjMhvDVB7vHo88Q.png" /></figure><ul><li>Deploying it in a Single AZ without any standby</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*VBAEVkhd2Vo0zV8vj0QTsg.png" /></figure><ul><li>Choose General Purpose instances and select <strong>t3.medium.search</strong> instance for this task and with 1 node. Per node, I gave 10GB of storage</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*w_soYDxSNRbzA6oWM4qkeg.png" /></figure><ul><li>I am giving public access with IPV4 only for this task</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*I9UgyBUfZqhQmRYf6oP8dg.png" /></figure><ul><li>Enable fine-grained access and create a master user like below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*_6DndAib1h0bbCyL4V6AxA.png" /></figure><ul><li>Change the access control to allow all users to access the endpoint for this task</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*Ei56OqkxMU9GjmM8rMtq5g.png" /></figure><ul><li>Keep the rest of the options as it is and click on the create endpoint button. It will take some time for the endpoint to be created</li><li>Once the endpoint is created, access the OpenSearch dashboard from the console and provide the master user credentials to access it</li><li>Visit the D<strong>ev Tools </strong>option from the side menu and paste the following code to create the index <strong>movies</strong></li></ul><pre>PUT movies<br>{<br>  &quot;settings&quot;: {<br>    &quot;index.knn&quot;: true<br>  },<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;title_org&quot;: {<br>        &quot;type&quot;: &quot;text&quot;<br>      },<br>      &quot;title&quot;: {<br>        &quot;type&quot;: &quot;knn_vector&quot;,<br>        &quot;dimension&quot;: 1536<br>      },<br>      &quot;summary&quot;: {<br>        &quot;type&quot;: &quot;knn_vector&quot;,<br>        &quot;dimension&quot;: 1536<br>      },<br>      &quot;short_summary&quot;: {<br>        &quot;type&quot;: &quot;knn_vector&quot;,<br>        &quot;dimension&quot;: 1536<br>      },<br>      &quot;director&quot;: {<br>        &quot;type&quot;: &quot;knn_vector&quot;,<br>        &quot;dimension&quot;: 1536<br>      },<br>      &quot;writers&quot;: {<br>        &quot;type&quot;: &quot;knn_vector&quot;,<br>        &quot;dimension&quot;: 1536<br>      },<br>      &quot;cast&quot;: {<br>        &quot;type&quot;: &quot;knn_vector&quot;,<br>        &quot;dimension&quot;: 1536<br>      }<br>    }<br>  }<br>}</pre><h3><strong>Generate Embeddings and dump them into the OpenSearch Index:</strong></h3><p>As we have the Open Search cluster and index ready. Let’s generate the embeddings and dump them into the index</p><ul><li>Download the movie dataset using this link <a href="https://www.kaggle.com/datasets/kayscrapes/movie-dataset">https://www.kaggle.com/datasets/kayscrapes/movie-dataset</a></li><li>Extract the Zip file and have a look at the CSV file which contains movie data</li><li>Create a <strong>gen_emb.py</strong> with the following code to generate embeddings and dump them into the index. Install <strong>Pandas</strong>, <strong>Boto3</strong>, <strong>Botocore, </strong>and <strong>Opensearch-py </strong>libraries using <strong>PIP</strong></li></ul><pre>import boto3<br>import json<br>import botocore<br>import pandas as pd<br><br>from opensearchpy import OpenSearch<br><br><br>##opensearch configs<br>host = &#39;paste open-search-endpoint here&#39;  <br>port = 443 <br>auth = (&#39;username&#39;, &#39;password&#39;)<br>index_name = &quot;movies&quot;<br><br><br>##creating opensearch client<br>client = OpenSearch(<br>    hosts=[{&#39;host&#39;: host, &#39;port&#39;: port}],<br>    http_auth=auth,<br>    use_ssl=True,<br>    verify_certs=True<br>)<br><br><br>##filterting columns using pandas<br>df = pd.read_csv(&#39;hydra_movies.csv&#39;)<br>refined_df = df[[&quot;Title&quot;,&quot;Summary&quot;,&quot;Short Summary&quot;,&quot;Director&quot;,&quot;Writers&quot;,&quot;Cast&quot;]]<br>refined_df.info()<br>refined_df = refined_df.fillna(&quot;Unknown&quot;)<br><br><br><br><br>##connecting to bedrock runtime<br>session = boto3.Session(region_name=&#39;us-east-1&#39;)<br>bedrock_client = session.client(&#39;bedrock-runtime&#39;)<br><br><br>##generate embedding using titan model<br>def generate_embedding(value):<br>    try:<br>        body = json.dumps({&quot;inputText&quot;: value})<br>        modelId = &quot;amazon.titan-embed-text-v1&quot;<br>        accept = &quot;application/json&quot;<br>        contentType = &quot;application/json&quot;<br><br>        response = bedrock_client.invoke_model(<br>            body=body, modelId=modelId, accept=accept, contentType=contentType<br>        )<br>        response_body = json.loads(response.get(&quot;body&quot;).read())<br><br>        return response_body<br>    except botocore.exceptions.ClientError as error:<br>        print(error)<br><br>##creating a document to insert<br>def create_document(title,title_emb,summary_emb,short_summary_emb,director_emb,writers_emb,cast_emb):<br>    document = {<br>        &#39;title_org&#39;:title,<br>        &#39;title&#39;:title_emb[&#39;embedding&#39;],<br>        &#39;summary&#39;:summary_emb[&#39;embedding&#39;],<br>        &#39;short_summary&#39;:short_summary_emb[&#39;embedding&#39;],<br>        &#39;director&#39;:director_emb[&#39;embedding&#39;],<br>        &#39;writers&#39;:writers_emb[&#39;embedding&#39;],<br>        &#39;cast&#39;:cast_emb[&#39;embedding&#39;]<br>    }<br><br>    insert_document(document)<br><br>##inserting document into opensearch<br>def insert_document(document):<br>    client.index(index=index_name, body=document)<br><br><br>##iterating thorough each row in data frame created through pandas and requesting embedding<br>for index, row in refined_df.iterrows():<br>    title = row[&#39;Title&#39;]<br>    summary = row[&#39;Summary&#39;]<br>    short_summary = row[&#39;Short Summary&#39;]<br>    director = row[&#39;Director&#39;]<br>    writers = row[&quot;Writers&quot;]<br>    cast = row[&quot;Cast&quot;]<br>    title_embedding = generate_embedding(title)<br>    summary_embedding = generate_embedding(summary)<br>    short_summary_embedding = generate_embedding(short_summary)<br>    director_embedding = generate_embedding(director)<br>    writers_embedding = generate_embedding(writers)<br>    cast_embedding = generate_embedding(cast)<br>    create_document(title,title_embedding,summary_embedding,short_summary_embedding,director_embedding,writers_embedding,cast_embedding)<br>    print(f&quot;inserted:{index}&quot;)</pre><ul><li>Run this file using Python, visit the Query WorkBench from the OpenSearch console side menu, and use the SQL queries to see whether embeddings are inserted or not</li></ul><h3><strong>Implement a Lambda function to query the OpenSearch Index:</strong></h3><p>Now that we have the index ready with embeddings, Let’s create a Lambda function to query the index for getting similar movies</p><ul><li>Visit the Lambda service from the AWS Console and click on the Create function button</li><li>Give a name to the function and choose the runtime as <strong>Python 3.9</strong></li><li>Paste the following code in the Lambda function code</li></ul><pre>from opensearchpy import OpenSearch<br>import json<br><br>import boto3<br>import botocore<br><br><br>##open search configs<br>host = &#39;paste-open-search-endpoint-here&#39;  <br>port = 443 <br>auth = (&#39;username&#39;, &#39;password&#39;)<br>index_name = &quot;movies&quot;<br><br>##bedrock connection<br>session = boto3.Session(region_name=&#39;us-east-1&#39;)<br>bedrock_client = session.client(&#39;bedrock-runtime&#39;)<br><br><br><br>##creating opensearch client<br>client = OpenSearch(<br>    hosts=[{&#39;host&#39;: host, &#39;port&#39;: port}],<br>    http_auth=auth,<br>    use_ssl=True,<br>    verify_certs=True<br>)<br><br>def lambda_handler(event,context):<br>  <br>  print(&quot;Event: &quot;, event)<br><br>  prompt = event[&#39;inputTranscript&#39;]<br>  print(f&quot;received prompt is{prompt}&quot;)<br>  generate_embedding(prompt)<br>  embedding = generate_embedding(prompt)<br>  response = run_query(embedding)<br>  return response<br><br>#generating embedding for user input <br>def generate_embedding(value):<br>    try:<br>        body = json.dumps({&quot;inputText&quot;: value})<br>        modelId = &quot;amazon.titan-embed-text-v1&quot;<br>        accept = &quot;application/json&quot;<br>        contentType = &quot;application/json&quot;<br><br>        response = bedrock_client.invoke_model(<br>            body=body, modelId=modelId, accept=accept, contentType=contentType<br>        )<br>        response_body = json.loads(response.get(&quot;body&quot;).read())<br><br>        return response_body[&#39;embedding&#39;]<br>    except botocore.exceptions.ClientError as error:<br>        print(error)<br><br><br><br><br>def run_query(query_embedding):<br>    try:<br>        # Define the query<br>        query = {<br>    &quot;query&quot;: {<br>        &quot;bool&quot;: {<br>            &quot;should&quot;: [{<br>                    &quot;knn&quot;: {<br>                        &quot;title&quot;: {<br>                            &quot;vector&quot;: query_embedding,<br>                            &quot;k&quot;: 100<br>                        }<br>                    }<br>                },<br>                {<br>                    &quot;knn&quot;: {<br>                        &quot;summary&quot;: {<br>                            &quot;vector&quot;: query_embedding,<br>                            &quot;k&quot;: 100<br>                        }<br>                    }<br>                },<br>                {<br>                    &quot;knn&quot;: {<br>                        &quot;short_summary&quot;: {<br>                            &quot;vector&quot;: query_embedding,<br>                            &quot;k&quot;: 100<br>                        }<br>                    }<br>                },<br>                {<br>                    &quot;knn&quot;: {<br>                        &quot;cast&quot;: {<br>                            &quot;vector&quot;: query_embedding,<br>                            &quot;k&quot;: 100<br>                        }<br>                    }<br>                },<br>                {<br>                    &quot;knn&quot;: {<br>                        &quot;writers&quot;: {<br>                            &quot;vector&quot;: query_embedding,<br>                            &quot;k&quot;: 100<br>                        }<br>                    }<br>                },<br>                {<br>                    &quot;knn&quot;: {<br>                        &quot;director&quot;: {<br>                            &quot;vector&quot;: query_embedding,<br>                            &quot;k&quot;: 100<br>                        }<br>                    }<br>                }<br>                <br>            ]<br>        }<br>    }<br>}<br><br>        # Run the query<br>        response = client.search(index=index_name, body=query)<br><br>        # Extract and print the results<br>        hits = response[&#39;hits&#39;][&#39;hits&#39;]<br>        titles = &quot;, &quot;.join(hit[&#39;_source&#39;][&#39;title_org&#39;] for hit in hits)<br><br>    <br><br>        return respond_with_message(f&quot;Based on your prompt, I suggest the following movies {titles}&quot;)<br><br>    except Exception as e:<br>        print(f&quot;Error running query: {e}&quot;)<br>        return None<br>      <br>def respond_with_message(message):<br>    &quot;&quot;&quot;<br>    Helper function to create a response message for Lex V2.<br>    &quot;&quot;&quot;<br>    return {<br>        &quot;sessionState&quot;: {<br>            &quot;dialogAction&quot;: {<br>                &quot;type&quot;: &quot;Close&quot;<br>            },<br>            &quot;intent&quot;: {<br>                &quot;name&quot;: &quot;SuggestMovie&quot;,<br>                &quot;state&quot;: &quot;Fulfilled&quot;<br>            }<br>        },<br>        &quot;messages&quot;: [<br>            {<br>                &quot;contentType&quot;: &quot;PlainText&quot;,<br>                &quot;content&quot;: message<br>            }<br>        ]<br>    }<br><br></pre><ul><li>This Lambda function needs the <strong>Opensearch-py</strong>, <strong>Boto3, </strong>and <strong>Botocore </strong>libraries.</li><li>Install all the libraries in a folder named <strong>python </strong>and keep that folder in another folder with the name <strong>lambda-layer. </strong>Use the following command to install libraries in a specific folder</li></ul><pre>pip install opensearch-py boto3 botocore -t .</pre><ul><li>Zip the entire folder Create a <strong>Lambda Layer </strong>and attach it to the Lambda function so that the function can access the libraries</li><li>Make sure to add necessary permissions to the Lambda role to invoke the bedrock models</li></ul><h3><strong>Create a chatbot and connect it to the Lambda:</strong></h3><p>As we have the Lambda and cluster ready with the data and queries, Let’s create the bot</p><ul><li>Visit the <strong>Lex </strong>service from the AWS Console</li><li>Click on the Create bot button and Give a name for the bot. Choose the <strong>Generative AI</strong> Creation Method</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*OkOJ04SMCHuv-p6QYjBA5Q.png" /></figure><ul><li>Choose to create an IAM role and choose NO for COOPA for now</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*-K4aoBJtBaePbU0KX3SdCg.png" /></figure><ul><li>Leave the other fields as it is and click on the Next Button. Keep the Language options as it is and provide the description for the bot to be created.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*WLA2w_l3NNYg0hhY8rrMHg.png" /></figure><ul><li>Click on the Done button and wait for some time for the bot to be created</li><li>Once the bot is created visit the <strong>Intent </strong>section of the bot from the side under <strong>All Languages</strong></li><li>Click on the <strong>Add Intent </strong>button and choose <strong>Empty Intent</strong> from the dropdown</li><li>Provide a name for the intent Here I am giving <strong>SuggestMovie</strong> as the title</li><li>Provide the Utterance generation description like below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*4hMFzZJZxD0BbsEmzSbgsA.png" /></figure><ul><li>Add the sample Utterance like below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*XveAhbLFvzNBinDbIxtTLA.png" /></figure><ul><li>Scroll down to the end of the page Choose the Lambda function trigger</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*UzJaocqnnrE_PqfMidHwZA.png" /></figure><ul><li>Here what we did is we have added a sample intent to the bot to identify any prompt that is similar to the prompt we provided and trigger the Lambda function we created.</li><li>Click on the save intent button and come back to the previous section</li></ul><p>Attaching Lambda to the bot</p><ul><li>From the side menu under the <strong>Deployment </strong>section click on <strong>Aliases</strong> and choose the aliases that are listed</li><li>Click on the Language you created under the Language section</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*9lWE4qH_2o8ZzZleOeD6IA.png" /></figure><ul><li>Choose the Lambda we created and Click on Save</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*kIFKYPSAE1p_EjFxaVEC6g.png" /></figure><ul><li>Now Click on the Aliases from the Side Menu and click on the Build Button to build the bot with all the changes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I1J5pWWN171MJJQ3VTa-dw.png" /></figure><ul><li>Once the build is successful click on the Test button and provide the prompts like this</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*puyZmvE-sdIHr6ijnpkTVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*e2PhExBkYPcUrFSF_WN_Ew.png" /></figure><ul><li>You can see suggestion prompts like this. Now edit the fallback intent like this so that we will get some good response from the bot when user prompts other than movie suggestions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*UMALYGyCI6qajvQBrUO3Dw.png" /></figure><ul><li>After editing this fallback intent also build the bot once and give some random prompt to the bot and see what it is providing</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*oew-fh_hJJiQmXJlsW9dGA.png" /></figure><ul><li>This is how the bot will respond if the prompt does not belong to a movie suggestion.</li></ul><p>That’s it for now. I will come up with more customizations to the bot with different features in my upcoming blogs.</p><p>Meanwhile, let me know if you face any issues while trying out this task, and Feel free to comment if there are any suggestions. I am open to suggestions. Have a good day</p><p>Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ef0b7f349c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Part 2: A Guide to Application Deployment, Autoscaling, and Rollout Strategies]]></title>
            <link>https://medium.com/@shaiksalam9182/kubernetes-part-2-a-guide-to-application-deployment-autoscaling-and-rollout-strategies-3759abc86111?source=rss-6579539aa7a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3759abc86111</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ecr]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Salam shaik]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 16:18:39 GMT</pubDate>
            <atom:updated>2024-11-19T16:18:39.213Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kd8c8SdgUhXlYE6Ecy7TAQ.jpeg" /></figure><p>Hi everyone,</p><p>This is the second installment of the Kubernetes series. You can find the previous article using the below link</p><p><a href="https://medium.com/@shaiksalam9182/introduction-to-kubernetes-and-aws-eks-part-1-19d0e8978209">Introduction to Kubernetes and AWS EKS — Part 1</a></p><p><strong>Tasks we are going to do in this article:</strong></p><ul><li>Create a docker image of a web app and upload it to AWS ECR</li><li>Pulling docker image from AWS ECR and deploying it in EKS Cluster</li><li>Scaling your application basic on traffic</li><li>Different deployment strategies</li></ul><p>Let’s dive into the article</p><h3><strong>Creating a docker image and uploading to AWS ECR:</strong></h3><ul><li>I am using an open-source HTML/CSS website in this article as a deployment application</li><li>You can download the application using this link <a href="https://github.com/codewithsadee/portfolio">codewithsadee/portfolio: Fully responsive personal portfolio website</a></li><li>This is a web application. We’re gonna deploy this in our Kubernetes cluster</li><li>For deploying it, we need to make a docker image of this app</li><li>So clone the project using the below command</li></ul><pre>git clone https://github.com/codewithsadee/portfolio</pre><ul><li>Create a <strong>Dockerfile </strong>with below code at the root directory of the application</li></ul><pre>FROM nginx:alpine<br>COPY . /usr/share/nginx/html<br>EXPOSE 80</pre><ul><li>Here I am using the <strong>nginx: alpine </strong>image for the application deployment. We will serve the web application using the <strong>Nginx </strong>server</li><li>The second line will copy every file from the current folder to the path specified. Here it is <strong>/usr/share/nginx/html</strong></li><li>This is the default path of nginx server, it will serve the files inside that folder in port 80</li><li>The third line will expose port 80 from the container</li></ul><p>Let’s build the docker image and upload it to the AWS ECR</p><ul><li>Visit the ECR service from the AWS search bar</li><li>Click on the Create Repository button</li><li>Provide a name for the repository, keep the remaining fields as it is, and click on Create</li><li>Once the repo is created. In the top right corner, you can see the button view push commands. Click on it and follow the instructions one by one</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*zk5prHOS2ri1G4K9FaFv0w.png" /></figure><ul><li>After running all the commands you can see the list of the images you uploaded like this</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Jxo58NzVhR2oEaO7xUkFQ.png" /></figure><h3><strong>Deploying docker image to EKS cluster from ECR:</strong></h3><ul><li>Create an EKS cluster and a node group</li><li>You can find how to create an EKS cluster and a node group in my previous article mentioned at the start of the article</li><li>The only change I am doing here is, I am changing the EC2 machine type from <strong>t3.medium</strong> to <strong>t3.small</strong> in the node group</li><li>Keeping the Desired, Minimum nodes as 1 and Maximum size of 2.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*JvK2grGJ1TZ5l5GeNof29g.png" /></figure><ul><li>Point your kubectl to use the EKS cluster we created using the following command</li></ul><pre>aws eks --region &lt;region-code&gt; update-kubeconfig --name &lt;cluster-name&gt;</pre><ul><li>To check whether the kubectl is correctly configured or not. Use the following commands</li></ul><pre>kubectl get nodes</pre><ul><li>The command will return the nodes list created in the cluster.</li></ul><p><strong>Installing the metric server for Auto Scaling:</strong></p><ul><li>Metric server is a light-weight Kubernetes add-on that provides resource usage metrics</li><li>Use the below command to install the metric server in the cluster</li></ul><pre>kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml</pre><ul><li>Once the metric server is ready, Let’s deploy the application</li><li>Create a <strong>Deployment.yaml</strong> file with the following code. This code will deploy our application in the cluster</li></ul><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: sample<br>spec:<br>  replicas: 1 # Start with one replica<br>  selector:<br>    matchLabels:<br>      app: sample<br>  template:<br>    metadata:<br>      labels:<br>        app: sample<br>    spec:<br>      containers:<br>        - name: my-app-container<br>          image: &lt;account-id&gt;.dkr.ecr.us-east-1.amazonaws.com/sample:latest<br>          ports:<br>            - containerPort: 80<br>          resources:<br>            requests:<br>              cpu: &quot;100m&quot; # Minimum CPU required for a pod<br>            limits:<br>              cpu: &quot;500m&quot; # Maximum CPU allocated for a pod</pre><ul><li>Run the following command to deploy the application</li></ul><pre>kubectl apply -f deployment.yaml</pre><ul><li>Let’s create a service load balancer to expose the application outside of the cluster</li><li>Create another file with the name <strong>service.yaml </strong>which will create a load balancer that exposes 80 port to outside and points incoming traffic to the pod 80 port</li></ul><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: sample-service<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app: sample<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 80</pre><ul><li>Once service is also deployed. Use the below command to see the list of the services deployed</li></ul><pre>kubectl get services</pre><ul><li>Output will look something like this</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kSNBHTDVC6oPrwprO1wdkg.png" /></figure><ul><li>Copy the External IP of the service we deployed and try to access the applications using the browser. It should display the web page of the application we deployed</li><li>If it’s not loading wait till the load balancer comes online and is in a working state</li></ul><h3><strong>Scaling the deployment:</strong></h3><p><strong>Horizontal Pod AutoScaler(HPA):</strong></p><ul><li>It is a Kubernetes feature that helps in adjusting the pod replicas based on metrics like CPU usage</li><li>This will use the metric server for collecting the metrics, and based on those metrics it will try to adjust the pod replicas</li><li>Create a file name scale.yaml file with the following code</li></ul><pre>apiVersion: autoscaling/v1<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: sample-hpa<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: sample<br>  minReplicas: 1<br>  maxReplicas: 10<br>  targetCPUUtilizationPercentage: 50f</pre><ul><li>This will deploy the pod auto-scaler with our deployment as target and with minimum replicas as 1 and max replicas as 10 based on CPU utilization reaching more than 50%</li><li>Deploy this HPA using the following command</li></ul><pre>kubectl apply -f scale.yaml</pre><ul><li>Wait for a few minutes till it is deployed. After that run the following command to check the HPA deployment</li></ul><pre>kubectl get hpa</pre><ul><li>The output should look like this</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*VxZRTPlifbge1GFLebZOtw.png" /></figure><ul><li>Let’s hit the endpoint with multiple requests and try to see whether auto-scaling works or not</li><li>I am using J-meter to create the requests</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCGrKHlKVYc8dJ6v6Q86vg.png" /></figure><ul><li>I am creating 10k requests in 10 seconds to increase the CPU utilization so that auto-scaling will trigger and try to create more replicas</li><li>Use the following commands to check the CPU-Utilization percentage while creating the requests</li></ul><pre>kubectl get hpa</pre><ul><li>Once it is in peaks you can see Utilization reached more than the threshold of 50%</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*C6xdhEiEnkJLT8435bku6Q.png" /></figure><ul><li>Let’s see how many pods are running using <strong>kubectl get pods</strong> command</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*baHIuOkm8bvgzEMYoFdm4g.png" /></figure><ul><li>You can see that 3 pods are running to manage the traffic. Wait for at least five minutes, so that it will auto-scale down the pod replicas</li><li>After 5 minutes I ran the <strong>kubectl get pods </strong>command again to check the pods count</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*oWYKyD6vV3KsNeTSi6s7AQ.png" /></figure><ul><li>That’s it. Like this, we can manage the scaling up/down of the pod replicas for managing the incoming traffic</li></ul><h3><strong>Deployment Strategies:</strong></h3><ul><li>Kubernetes supports different types of deployments for rolling out updates</li></ul><p>Some of the methods are</p><p><strong>Rolling update(Default):</strong></p><ul><li>It will replace the pods gradually for a smooth transition</li></ul><p><strong>Recreate:</strong></p><ul><li>It will terminate all the current running pods and then create new updated pods</li></ul><p><strong>Canary Deployment:</strong></p><ul><li>It will deploy the new version to the subset of the user. Like redirecting some of the users to the new deployment and keeping the other users to the old deployment until everything is stable</li></ul><p><strong>Blue-green deployment:</strong></p><ul><li>Run two complete environments blue for the old and green for the new. Once everything is verified in the green environment traffic will be redirected to the Green environment from the blue environment</li></ul><p>These are all the different deployment methods that Kubernetes supports for rolling out the updates</p><p>Will try to practice these deployments in the upcoming article. That’s it for this article</p><p>Please let me know if there are any mistakes or suggestions to improve. I am open to suggestions</p><p>Thanks and Have a good day</p><p><strong>Note: Before leaving try to delete the cluster, node group, and the load balancer you created to avoid un-necessary charges</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3759abc86111" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Kubernetes and AWS EKS — Part 1]]></title>
            <link>https://medium.com/@shaiksalam9182/introduction-to-kubernetes-and-aws-eks-part-1-19d0e8978209?source=rss-6579539aa7a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/19d0e8978209</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Salam shaik]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 08:47:13 GMT</pubDate>
            <atom:updated>2024-10-30T08:47:13.108Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Kubernetes and AWS EKS — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3KayGM3pvolj8nZ7H6y7tw.jpeg" /></figure><p>Hi everyone,</p><p>This article will provide you with an overview of what Kubernetes is and how to start working with Kubernetes</p><p>Before learning Kubernetes, You need to know about Docker. Kubernetes is nothing but an Open-Source container Orchestration Technology</p><p><strong>Docker: </strong>Docker is an open-source platform that helps automate application deployments, scaling, and management.</p><p>Before docker developers used to face problems like “<strong>It worked on my system but not on production</strong>”. Docker helped to resolve this kind of problem by making your application and all its dependencies as a package. You can run this package anywhere in any system without any issues. However, the application worked on your system. It works the same way in other systems too</p><p><strong>Docker Image: </strong>As I explained above docker will create a package of your application with everything it needs like dependencies, env files, config files, etc. You can upload this docker image to any docker repo like DockerHub, or ECR. From the repo, you can pull the image into your system and run it in a container</p><p><strong>Container:</strong> A container is an isolated environment where your docker image runs. Each container will be isolated from one another. But they share the same host OS Kernal making them lightweight and efficient when compared to virtual machines</p><p><strong>Creating a docker image:</strong></p><ul><li>For creating a docker image of your application, create a <strong>Dockerfile</strong> in your application folder</li><li>A Sample Dockerfile looks like this with possible commands</li></ul><pre># 1. Specify the base image<br># This defines the OS and pre-installed packages the Docker container will be built on.<br>FROM ubuntu:20.04<br><br># 2. Set environment variables<br># ENV sets environment variables that can be used by applications inside the container.<br>ENV APP_HOME=/usr/src/app<br>ENV LANG=C.UTF-8<br><br># 3. Install dependencies<br># RUN executes commands inside the container to install software packages.<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    python3 \<br>    python3-pip \<br>    curl \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br># 4. Create a directory in the container file system<br># WORKDIR sets the working directory for any subsequent RUN, CMD, ENTRYPOINT, or COPY commands.<br>WORKDIR $APP_HOME<br><br># 5. Copy files from host to the container<br># COPY copies files from your local machine (host) to the container&#39;s file system.<br>COPY . .<br><br># 6. Install Python dependencies<br># RUN can also be used to install specific project dependencies.<br>RUN pip3 install --no-cache-dir -r requirements.txt<br><br># 7. Expose a port<br># EXPOSE documents which ports the container listens on during runtime.<br>EXPOSE 5000<br><br># 8. Define the default command to run the application<br># CMD specifies the default command that gets executed when running a container from the image.<br># It can be overridden when running the container.<br>CMD [&quot;python3&quot;, &quot;app.py&quot;]<br><br># 9. Set up an entry point<br># ENTRYPOINT defines a command that will always run when the container starts.<br># Unlike CMD, ENTRYPOINT cannot be easily overridden.<br>ENTRYPOINT [&quot;python3&quot;, &quot;app.py&quot;]<br><br># 10. Add a health check<br># HEALTHCHECK defines how Docker should check the health of the container.<br>HEALTHCHECK --interval=30s --timeout=5s CMD curl -f http://localhost:5000/health || exit 1<br><br># 11. Volume to persist data<br># VOLUME allows sharing of a directory between the host and the container, ensuring persistent data.<br>VOLUME [&quot;/data&quot;]<br><br># 12. Labels<br># LABEL adds metadata to your image, such as version, description, or maintainer information.<br>LABEL version=&quot;1.0&quot; description=&quot;Sample Python Flask App&quot; maintainer=&quot;you@example.com&quot;</pre><ul><li>A simple Example Dockerfile</li></ul><pre>FROM python:3.9-slim<br>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install -r requirements.txt<br>COPY . .<br>EXPOSE 8000<br>CMD [&quot;python&quot;, &quot;app.py&quot;]<br></pre><p>Let’s understand what the file says:</p><ul><li>The base image of the docker container is Python 3.9</li><li><strong>WORKDIR </strong>will set the working directory as <strong>/app</strong> in the container</li><li><strong>COPY </strong>will copy the <strong>requirements.txt</strong> file to the dot which means the current directory</li><li><strong>RUN </strong>will run the command specified here to install the <strong>requirements.xml</strong> file</li><li><strong>COPY . .</strong> this will copy everything from the current directory to the working directory</li><li><strong>EXPOSE</strong> will expose port 8000</li><li>The final <strong>CMD </strong>will run the command <strong>python app.py </strong>to start script execution</li></ul><p>Commands for creating a docker image and running it in a container</p><pre>docker build -t &lt;image-name&gt;:&lt;tag&gt; &lt;path-to-dockerfile&gt; <br>docker run -d -p &lt;host-port&gt;:&lt;container-port&gt; --name &lt;container-name&gt; &lt;image-name&gt;:&lt;tag&gt;</pre><ul><li>For storing and versioning your Docker images you can use Docker Hub or AWS ECR</li></ul><p>Here comes <strong>Kubernetes </strong>also known as <strong>K8s</strong></p><p><strong>Kubernetes:</strong></p><p>Kubernetes is an open-source platform that helps automate deployment and scaling of your containerized applications. Kubernetes manages the lifecycles of containers across multiple machines, ensuring they are running as expected</p><p><strong>Key Concepts in Kubernetes:</strong></p><p><strong>Pods:</strong> A pod is the simplest and smallest Kubernetes object. It represents a single instance of a running process in the cluster and contains one or more tightly coupled containers</p><p><strong>Node:</strong> A Node is a working machine in Kubernetes where pods are deployed</p><ul><li><strong>Master Node:</strong> A master node will manage all cluster operations, such as pod deployment, scaling, etc.</li><li><strong>Worker Node:</strong> This is where the pod runs. You can consider this also a machine that is capable of running docker containers</li></ul><p><strong>Deployment:</strong> Consider this as a YAML file where you will define how the deployment should happen like how many replicas you need, how the container should be, and what image you need to use in the container. You will declare all this in a YAML file. Based on these instructions deployments will happen. A sample YAML deployment file</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: my-app-deployment<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: my-app<br>  template:<br>    metadata:<br>      labels:<br>        app: my-app<br>    spec:<br>      containers:<br>      - name: my-app-container<br>        image: my-app-image:v1.0<br>        ports:<br>        - containerPort: 8080</pre><p><strong>Service:</strong> Usually services will provide endpoints to access the set pods. It will expose types of endpoints like cluster IP, Node Port, Load Balancer, etc, A sample Service YAML file</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: my-app-service<br>spec:<br>  selector:<br>    app: my-app<br>  ports:<br>  - protocol: TCP<br>    port: 80<br>    targetPort: 8080<br>  type: ClusterIP</pre><p><strong>NameSpaces:</strong> By using namespaces you can divide your cluster into different parts and run different workloads in each of them like one for dev, one for staging, and one for production.</p><p>Let’s get inside the nodes.</p><p><strong>Master Node:</strong> also known as Control Plane. These are the major components in the control plane</p><ul><li><strong>API Server: </strong>It is the gateway to the Kubernetes. It exposes the APIs by which we can interact with the control plane</li><li><strong>etcd:</strong> This is a key-value-based storage that holds all the data about the cluster what application are running in the cluster and where they are running etc...</li><li><strong>Scheduler:</strong> It will decide in which node pods need to be deployed. Based on the resources availability of nodes, it assigns the workloads</li><li><strong>Controller Manager:</strong> It makes sure everything is under control if you specified I need 3 instances to maintain the application availability it will make sure to maintain all 3 instances. If one goes down it will spawn a new one.</li></ul><p><strong>Worker Node:</strong> where the actual work happens</p><ul><li><strong>Kubelet:</strong> It will take instructions from the control plane and make sure pods are running as instructed by the control plane</li><li><strong>Container Runtime:</strong> This is the software responsible for running the containers. It will pull the images and run them</li><li><strong>Kube-Proxy:</strong> It maintains the network operation in the cluster, allowing communication between the pods in the cluster and directing requests to correct pods</li></ul><p>I hope you have a basic understanding of Kubernetes now and how it works</p><p><strong>How to interact with Kubernetes cluster:</strong></p><p><strong>Kubectl:</strong> It’s a tool you can install in your system to interact with the Kubernetes cluster control plane. It’s available for all operating systems. You can download this tool using this link <a href="https://kubernetes.io/docs/tasks/tools/">Install Tools | Kubernetes</a></p><h3><strong>AWS EKS(Elastic Kubernetes Service):</strong></h3><p>AWS offers a managed Kubernetes service called EKS, allowing you to easily create Kubernetes clusters with minimal input and deploy your containerized applications.</p><p>When you create a cluster in EKS, you are actually creating a control plane. Once the cluster is ready you can create nodes based on your need or you can use <strong>AWS Fargate</strong> for the serverless option</p><p>You will be charged $0.10 per hour for every cluster you create. On top of that whatever computing resources you create in the cluster, it will be charged based on that like EC2 pricing, storage, etc.</p><p>You can deploy multiple applications in a single cluster by taking advantage of <strong>NameSpaces </strong>in the Kubernetes.</p><p><strong>Creating and deploying an application in the EKS cluster:</strong></p><ul><li>Search for EKS in the AWS Console search bar and visit the EKS home page</li><li>Click on Create a Cluster</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*CLeClidQdfKsSLbqlKk7kQ.png" /></figure><ul><li>Give a name to the cluster and create an <strong>IAM </strong>role that allows the cluster to perform the operations it needs.</li><li>I created an IAM role named <strong>eks-testing</strong> with a policy named <a href="https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/policies/details/arn%3Aaws%3Aiam%3A%3Aaws%3Apolicy%2FAmazonEKSClusterPolicy">AmazonEKSClusterPolicy</a> attached to it. This permission almost covers all the needs of your cluster for now. Change or create a new policy based on your needs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*O0iOOLa7VEx9U_sJqOL0Bw.png" /></figure><ul><li>I took the extended support, you chose based on your need. For the cluster access, I opted for <strong>EKS API</strong></li><li><strong>EKS API:</strong> It will allow access to only IAM users and roles only</li><li><strong>EKS API and ConfigMap</strong>: It will allow access to both IAM users and roles and <strong>aws-auth</strong> config map. This map is a Kubernetes resource to map IAM users and roles to Kubernetes users and roles</li><li><strong>ConfigMap:</strong> This mode restricts the cluster to authenticate IAM principals only from the<strong> aws-auth ConfigMap</strong>. In this case, IAM users or roles must be manually mapped to Kubernetes roles in the ConfigMap before they can interact with the cluster</li><li>Leave the rest of the fields in the config cluster section as it is and click on the Next button to proceed to the network section</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*mu1kKjyfABM490JhuRkCLw.png" /></figure><ul><li>Select the VPC you want the cluster to be deployed and the subnets and select Security group. Please allow the ports you need in the security group</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*I5mSxnwZUz55Md_tJGnD-A.png" /></figure><ul><li>For the cluster endpoint access, I am choosing both public and Private so that the cluster endpoint can be accessed from outside the VPC and worker nodes traffic will be within the VPC. Click on next for the next section</li><li>From the observability section, I am not enabling anything for now. If you want logs for the cluster you can enable whatever you need</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*WwYUKHOLl1hUFzpacDM15g.png" /></figure><ul><li>I am going with the default selection here. We need core DNS, Kube-proxy, and VPC CNI for basic cluster functioning</li><li>You can leave add-on settings as it is and click on the next button to review the cluster creation</li><li>If everything is looking good, click on Create. Wait for a few minutes for the cluster to be created</li><li>Now that we have the cluster ready means we have control plane ready. Let’s create the worker nodes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7abPoB4QKQk-oXkik48ww.png" /></figure><ul><li>Click on the <strong>Compute</strong> tab and click on the <strong>Add Node Group</strong> button to create the worker nodes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*9fxHGELQKaRJ_qBKhrFAHw.png" /></figure><p>. Give a name for the node group and select the role that has the following policies attached</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*LFHQdc7OIgxU7w9GxsdAgA.png" /></figure><ul><li>These policies will allow the node group to pull images from ECR, Enable pod networking with the Amazon VPC CNI plugin, and grant worker nodes permission to interact with the control plane and cloud watch</li><li>Leave the rest of the fields as it is and proceed to compute and scaling configuration</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*6gxw20LmeEkpr37UapiPaQ.png" /></figure><ul><li>I am taking Amazon Linux AMI and an on-demand instance which is t3.medium and disk size of 10GB.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*SKh201pgEiaroZgj8yNbzg.png" /></figure><ul><li>I am keeping the desired, minimum as 1 and a max of 2 nodes and the maximum unavailable as 1</li><li>Click on next to select the subnets</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*6FezBwyO3U5riCN33oiRHg.png" /></figure><ul><li>Review everything and click on the Create button. It will take a few minutes to nodes come online</li><li>Now that we have our control plane and worker nodes ready, Let’s connect to the cluster and deploy an application</li></ul><p><strong>Connect and deploy the application to the cluster:</strong></p><ul><li>For connecting to the cluster create a user in the IAM console and download the creds to your system and configure your using <strong>AWS CONFIGURE</strong> command</li><li>Click on the Access tab from the cluster and click on the Create access entry button to allow the user you created in the above step</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*3iAfyYQYE6EmrMeKDE2Hsw.png" /></figure><ul><li>select the IAM user from the first input box and keep the type as standard for now. Don’t forget to click on <strong>Add Policy </strong>and then the Next Button</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*LQEjpB5YoUPi0BquAzu34A.png" /></figure><ul><li>From the policy, I am allowing my user to have EKS cluster admin level access and create the access</li></ul><p><strong>Connecting to your cluster:</strong></p><ul><li>Use this command to configure the EKS</li></ul><pre>aws eks - region &lt;your-region&gt; update-kubeconfig - name &lt;cluster-name&gt;</pre><ul><li>Replace region and cluster name with your values</li><li>Then run the following command whether the connection is successful or not</li></ul><pre>kubectl get nodes</pre><ul><li>It will display the node you created previously like this</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*HdvttamNtU4Tyu_Fi8CXsA.png" /></figure><p><strong>Deploying the app:</strong></p><ul><li>Create a namespace <strong>demo</strong> for deploying our application using this command</li></ul><pre>kubectl create namespace demo</pre><ul><li>We will create one deployment file with nginx image running in the container with port 80 open</li><li>Then we will create a service file to create a load balancer that targets the container port 80 and exposes the port 80 to the public</li><li>Create a file name nginx-deployment.yaml file and paste the following code</li></ul><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-deployment<br>  namespace: demo # Specify the namespace if created earlier<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>      - name: nginx<br>        image: nginx:1.21.6<br>        ports:<br>        - containerPort: 80</pre><ul><li>Create a nginx-service.yaml file and paste the following code</li></ul><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: nginx-service<br>  namespace: demo # Specify the namespace<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app: nginx<br>  ports:<br>  - protocol: TCP<br>    port: 80<br>    targetPort: 80</pre><ul><li>Now run the following commands to deploy and nginx and expose the 80 port</li></ul><pre>kubectl apply -f nginx-deployment.yaml<br>kubectl apply -f nginx-service.yaml</pre><ul><li>It will create 3 pods in the cluster under the demo namespace. Run the following commands to see whether pods are running or not</li></ul><pre>kubectl get pods</pre><ul><li>You can see 3 pods in a running state like this</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*Y0hbvC2NKd-oGjz05AntOw.png" /></figure><ul><li>Run the following command to get the external IP to access the nginx server home page</li></ul><pre>kubectl get service nginx-service -n demo</pre><ul><li>Output should look something like this</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xfX8VCpmU5huwXnHVzHFQ.png" /></figure><ul><li>Copy the external IP and make a URL like this http<a href="http://http//externalIP">://externalIP</a> hit the URL from your browser</li><li>You should see the nginx welcome page like this</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*ezsxhNiKcbnp3x3S5Aib0A.png" /></figure><p>That’s it. We created an EKS cluster deployed an NGINX container and verified the deployment.</p><p>In the upcoming articles, we will deep dive into Kubernetes and EKS. Till then have a good time. Thanks</p><p><strong>Note: After done with this task please delete the node group and cluster to avoid unnecessary charges.</strong></p><p>If you faced any issues or were blocked at any step. Please feel free to comment here. I am happy to help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19d0e8978209" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring AWS OpenSearch Serverless Pricing: How It Differs from Traditional Serverless Services]]></title>
            <link>https://medium.com/@shaiksalam9182/exploring-aws-opensearch-serverless-pricing-how-it-differs-from-traditional-serverless-services-ab072a574fae?source=rss-6579539aa7a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab072a574fae</guid>
            <category><![CDATA[opensearch-serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[opensearch]]></category>
            <category><![CDATA[aws-pricing]]></category>
            <dc:creator><![CDATA[Salam shaik]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 04:15:05 GMT</pubDate>
            <atom:updated>2024-10-21T04:15:05.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2AK9EF_A_gIMnp5S437qaA.jpeg" /></figure><p>Hi everyone,</p><p>Before diving into this topic, Let me introduce what OpenSearch is.</p><p><strong>OpenSearch:</strong> It’s an AWS-managed service alternative to Elastic Search. It offers various search features. It comes with a dashboard called <strong>Kibana </strong>where you can manage and visualize the data, work with the indexes, etc.</p><p><strong>Scenario: </strong>Recently I started exploring AWS <strong>bedrock </strong>service. I went to see what is Knowledge bases in bedrock and what it offers. As a part of creating the <strong>Knowledge base</strong>, It created an OpenSearch serverless collection.</p><p>-After around 1 hour I deleted the Knowledge Base, thinking that the OpenSearch collection also be destroyed. But after 2 days I received an E-mail from <strong>AWS Budgets</strong> that the bill amount was hitting the budget limit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*tEl1u-9vJEXvpMCQ0vSpIA.gif" /></figure><p>In the past, I had some incidents where my AWS bill hit around <strong>$800</strong> without my knowledge. By talking to the AWS support team and explaining the scenario of what caused this huge bill they waved off the bill.</p><p>After that incident I created different levels of budget alerts, to know about the unexpected rise in the bill amount at the earliest. Like</p><p><strong>Alert 1:</strong> with a <strong>$5</strong> limit</p><p><strong>Alert 2:</strong> with a <strong>$15</strong> limit</p><p><strong>Alert 3:</strong> with a <strong>$50</strong> limit</p><p>I immediately opened my AWS console, went to AWS bills, and saw that the OpenSearch service was causing this issue. Then I deleted that collection.</p><p><strong>Assumption:</strong></p><p>After using Lambda for a long time, I assumed that serverless services would only be charged when the service got a hit or based on the execution time. I only know about my OpenSearch Serverless endpoint and I didn’t use the endpoint at all in the last 2 days. Then why will I be charged?</p><p><strong>Reality:</strong></p><ul><li>Open Search Serverless pricing works differently when compared to other serverless services</li><li>You will be charged for <strong>Computing Power</strong> and <strong>Storage</strong></li><li>Computing power is measured in <strong>OpenSearch Computing Units(OCU)</strong></li><li><strong>1 OCU</strong> comes with <strong>6GB of RAM</strong> and corresponding vCPUs and <strong>GP3 Storage</strong></li><li>You need at least <strong>2 OCUs </strong>running one for <strong>indexing</strong> and one for <strong>searching</strong></li><li>All data is stored in the S3 bucket. So storage costs will be there</li><li>Here is the pricing from the AWS docs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*4r5gwaq8cy375m1hkkaeaQ.png" /></figure><ul><li>So even though you are not hitting the server and not running anything in the open search index you will charged based on the OCU units you are using</li></ul><p>Let’s calculate how much it costs for you for a month if you want to have a collection with the bare minimum of <strong>2 OCUs </strong>and <strong>10GB</strong> of storage</p><ul><li>2 OCUs = 2 x 0.24 = <strong>$0.48/hour</strong></li><li>0.48 x 24(1 day) x 30(days) = <strong>$345.6 Per Month</strong></li><li>Storage 10 x 0.024 =<strong> $0.24 Per month</strong></li><li>Total cost = $345.6 + $0.24 = <strong>$345.84 Per Month</strong></li></ul><p>So Even though you are not hitting the server, or not running anything on the index you will be charged around 345$ per month. That’s a very huge amount</p><p><strong>My Thoughts on this:</strong></p><ul><li>AWS doesn’t mention anything about how much load an OCU can take. It mostly depends on the complexity of the query we are running and the simultaneous requests that are hitting the server</li><li>We can set limits for OCUs we need to prevent un-intentional cost</li><li>Even though it is a serverless service we need to have an idea of Open Search Serverless Infra</li><li>I feel it looks like a typical EC2 Auto-Scaling service. We can set the limits on the desired instances and it will scale up and down based on the traffic</li><li>If we are not sure about the load we are gonna get, we don’t know how many OCUs we need and I personally feel paying around a minimum of 345$ dollars to set up a server up and running</li><li>It offers dev/test mode you can use 1 OCU, half for searching and half for indexing. It might cut the cost to half around $170 which is also not a small amount</li></ul><p>I recommend if you are new to OpenSearch and want to experiment or try it, it is good to create an endpoint with dev/test mode on instances</p><p>AWS offers a <strong>free tier</strong> on this service with 750 hours of usage per month on t2.small.search or t3.small.search instances and 10GB per month. It is good enough for trying and testing this service</p><p>It is always better to keep budget alerts with different amount limits will help you a lot to identify any cost spikes at the earliest.</p><p>Hope you find this helpful. Please share your thoughts on this. I am happy to hear your views on this pricing. Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab072a574fae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing AWS’s Invoke Model State for Efficient Embedding Creation in Workflows]]></title>
            <link>https://medium.com/@shaiksalam9182/harnessing-awss-invoke-model-state-for-efficient-embedding-creation-in-workflows-1c8448beee26?source=rss-6579539aa7a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c8448beee26</guid>
            <category><![CDATA[embeddings-search]]></category>
            <category><![CDATA[aws-step-functions]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Salam shaik]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 14:21:54 GMT</pubDate>
            <atom:updated>2023-12-22T14:21:54.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDagPfV80GQojuH6CcGt6A.png" /></figure><p>Hi everyone,</p><p>AWS recently released bedrock integration to step functions. They are providing <strong>InvokeModel </strong>and <strong>CreateModelCustomizationJob </strong>states in the step functions. If you can search in the search bar of the step function with the <strong>Bedrock</strong> name it will provide a list of the actions available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*e_ON_GlwaA47TqLknV5W5w.png" /></figure><p>Now we can create the workflows by invoking the models available in the Amazon Bedrock from the step functions.</p><p>If you are not aware of the embeddings and bedrock service, refer to my previous article using this link</p><p><a href="https://dev.to/aws-builders/building-a-vector-based-search-engine-using-amazon-bedrock-and-amazon-open-search-service-3jom">Building a vector-based search engine using Amazon Bedrock and Amazon Open Search Service</a></p><p>Let’s dive into the article</p><p>In this article, we are going to create a state machine workflow to generate embeddings from a CSV file stored in an S3 bucket and store the generated embeddings in the OpenSearch index for further processing.</p><p>AWS services we are going to use in this experiment</p><ul><li><strong>S3 bucket </strong>for storing the data</li><li><strong>Step function </strong>to create a workflow for generating embeddings and storing them OpenSearch index</li><li><strong>BedRock </strong>contains the models for generating the embeddings</li><li><strong>Lambda </strong>for storing the generating embedding in the OpenSearch</li><li><strong>OpenSearch </strong>for storing the embeddings for implementing semantic search</li></ul><h3><strong>Step 1: Collecting and storing the data:</strong></h3><ul><li>For this experiment, using this link I downloaded a dataset containing a set of movie info <a href="https://www.kaggle.com/datasets/kayscrapes/movie-dataset">https://www.kaggle.com/datasets/kayscrapes/movie-dataset</a></li><li>Create an S3 bucket and upload the CSV file to the bucket.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*7KU8e6McWw5bcnQI_c9I6Q.png" /></figure><h3><strong>Step 2: Create an open Search Service cluster</strong></h3><ul><li>For storing the embeddings we will create an open search cluster</li><li>Visit the open search service from the AWS search bar</li><li>Click on the Create Domain button</li><li>Provide the Name for the domain, choose standard create, and select dev/test template</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*n_dx9zpuLbWIAIAMEYe2yQ.png" /></figure><ul><li>Deployment will be without standby as we are not doing this for production purposes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*2eqgor62Hvf-XN004zCOaQ.png" /></figure><ul><li>From the general purpose instances select t3.small.search instances, as we are experimenting and nodes will only have 1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*ux7bZhFwjlrALQmgdNV17g.png" /></figure><ul><li>Instead of VPC deploy it publicly and provide a master username and password</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*FXjEdv0YQ0u-V8mQZ64Otw.png" /></figure><ul><li>Configure the access policy to allow all to access OpenSearch dashboards and endpoints. But for production make it according to your security requirements</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*9ftuVUuTvZowmNHXfjEcXg.png" /></figure><ul><li>Click on Create Domain and wait for a few minutes for the cluster to come online</li><li>Once the cluster is ready copy the open search endpoints from the dashboard to use in the Lambda function</li><li>Visit the OpenSearch dashboard and create an index for storing the data</li><li>Visit dev tools<strong> </strong>from the dashboard and use the following code to create an index</li></ul><pre>PUT contents<br>{<br>  &quot;settings&quot;: {<br>    &quot;index.knn&quot;: true<br>  },<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;Summary&quot;:{<br>        &quot;type&quot;: &quot;text&quot;<br>      },  <br>      &quot;Title&quot;: {<br>        &quot;type&quot;: &quot;text&quot;<br>      },<br>      &quot;Embedding&quot;: {<br>        &quot;type&quot;: &quot;knn_vector&quot;,<br>        &quot;dimension&quot;: 1536<br>      }<br>    }<br>  }<br>}</pre><h3><strong>Step 3: Create a Lambda function for storing the embeddings</strong></h3><ul><li>Visit the Lambda service and create a Lambda function with the Python 3.9 environment</li><li>Here is the lambda code</li></ul><pre>import boto3<br>import requests<br>from requests_aws4auth import AWS4Auth<br><br>def lambda_handler(event, context):<br>    # Extract the relevant data<br>    summary = event[&#39;Summary&#39;]#summary column of csv file<br>    title = event[&#39;Title&#39;]#Title column of the csv file<br>    embedding = event[&#39;output&#39;][&#39;Body&#39;][&#39;embedding&#39;] #contains embedding generataed for Summary columns<br><br>    # Define the document to be indexed<br>    document = {<br>        &#39;Summary&#39;: summary,<br>        &#39;Title&#39;: title,<br>        &#39;Embedding&#39;: embedding<br>    }<br><br>    #Username and password of the opensearch endpoint<br>    auth = (&#39;username&#39;,&quot;password&quot;)<br><br>    # OpenSearch domain endpoint<br>    opensearch_domain_endpoint = &quot;https://search-contents-oflzhkvsjgukdwvszyd5erztza.us-east-1.es.amazonaws.com&quot;  # e.g., https://search-mydomain.us-west-1.es.amazonaws.com<br>    index_name = &#39;contents&#39;<br>    url = f&quot;{opensearch_domain_endpoint}/{index_name}/_doc&quot;<br><br>    headers = { &quot;Content-Type&quot;: &quot;application/json&quot; }<br><br>    # Make the signed HTTP request<br>    response = requests.post(url, auth=auth, json=document, headers=headers)<br><br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: response.text<br>    }</pre><ul><li>This is how we are going to send the data to Lambda from the state machine</li></ul><pre>{<br>  &quot;Summary&quot;: &quot;value1&quot;,<br>  &quot;Title&quot;: &quot;value2&quot;,<br>  &quot;output&quot;: {<br>    &quot;Body&quot;: {<br>      &quot;embedding&quot;: &quot;[0,1,2,3]&quot;<br>    }<br>  }<br>}</pre><h3><strong>Step 4: Create a state machine in step functions</strong></h3><ul><li>Visit step functions from the AWS search bar</li><li>From the flow, we are using <strong>Map </strong>for iterating through the CSV file records</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*mPGxrYTrnl0YCJ8nDMYU1g.png" /></figure><ul><li>From the bedrock section <strong>Invoke Model</strong> action</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*Xe07OS54_r41LiBmyhgg8Q.png" /></figure><ul><li><strong>Invoke Lambda </strong>action for sending embeddings to Open Search</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*kAeBIwOLIN4sWz93LpTvpA.png" /></figure><ul><li>Create a workflow like the below picture. You can drag and drop items from the left menu</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*32aox1cpiMmt7hZ_6RoQUw.png" /></figure><ul><li>After creating, configure each state like this</li><li><strong>Map</strong>: configure it to use the S3 bucket CSV file we stored in the first step and make it iterate through the <strong>Summary, Title </strong>Columns of the document</li><li>Output of the Map function to another s3 bucket for avoiding limit exceed errors from the state machine</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*beXMnkL1adL8Wt-u1IyMMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*CQdhg5it50l-TsBp3nmrxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*TWL7f65WZ7lhHM4DT9hl_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*ecaJ5jZOUDBDWg1rZ97vGA.png" /></figure><ul><li>Configure<strong> the Invoke Model </strong>state to use <strong>amazon.titan-embed-text-v1 </strong>model and input from the Map function like this</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*wCMmJSTbm_VGqbYEc1YI0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*o7zpQB3vhMsSByeM0XCWBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*88GNRJt4yzOcjeXRgL5_fw.png" /></figure><ul><li>Configure the <strong>Lambda Invoke </strong>state with the function name</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*CzZ1-vRA5iqe7fw3Li3IjA.png" /></figure><ul><li>This is the final code of the state machine after configuring all the states</li></ul><pre>{<br>  &quot;Comment&quot;: &quot;A description of my state machine&quot;,<br>  &quot;StartAt&quot;: &quot;Map&quot;,<br>  &quot;States&quot;: {<br>    &quot;Map&quot;: {<br>      &quot;Type&quot;: &quot;Map&quot;,<br>      &quot;ItemProcessor&quot;: {<br>        &quot;ProcessorConfig&quot;: {<br>          &quot;Mode&quot;: &quot;DISTRIBUTED&quot;,<br>          &quot;ExecutionType&quot;: &quot;STANDARD&quot;<br>        },<br>        &quot;StartAt&quot;: &quot;Invoke Model&quot;,<br>        &quot;States&quot;: {<br>          &quot;Invoke Model&quot;: {<br>            &quot;Type&quot;: &quot;Task&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:states:::bedrock:invokeModel&quot;,<br>            &quot;Parameters&quot;: {<br>              &quot;ModelId&quot;: &quot;arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-embed-text-v1&quot;,<br>              &quot;Body&quot;: {<br>                &quot;inputText.$&quot;: &quot;$.Summary&quot;<br>              }<br>            },<br>            &quot;Next&quot;: &quot;Lambda Invoke&quot;,<br>            &quot;ResultPath&quot;: &quot;$.output&quot;<br>          },<br>          &quot;Lambda Invoke&quot;: {<br>            &quot;Type&quot;: &quot;Task&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:states:::lambda:invoke&quot;,<br>            &quot;OutputPath&quot;: &quot;$.Payload&quot;,<br>            &quot;Parameters&quot;: {<br>              &quot;Payload.$&quot;: &quot;$&quot;,<br>              &quot;FunctionName&quot;: &quot;arn:aws:lambda:us-east-1:556343216872:function:dump-embeddings:$LATEST&quot;<br>            },<br>            &quot;Retry&quot;: [<br>              {<br>                &quot;ErrorEquals&quot;: [<br>                  &quot;Lambda.ServiceException&quot;,<br>                  &quot;Lambda.AWSLambdaException&quot;,<br>                  &quot;Lambda.SdkClientException&quot;,<br>                  &quot;Lambda.TooManyRequestsException&quot;<br>                ],<br>                &quot;IntervalSeconds&quot;: 1,<br>                &quot;MaxAttempts&quot;: 3,<br>                &quot;BackoffRate&quot;: 2<br>              }<br>            ],<br>            &quot;End&quot;: true<br>          }<br>        }<br>      },<br>      &quot;Label&quot;: &quot;Map&quot;,<br>      &quot;MaxConcurrency&quot;: 10,<br>      &quot;ItemReader&quot;: {<br>        &quot;Resource&quot;: &quot;arn:aws:states:::s3:getObject&quot;,<br>        &quot;ReaderConfig&quot;: {<br>          &quot;InputType&quot;: &quot;CSV&quot;,<br>          &quot;CSVHeaderLocation&quot;: &quot;GIVEN&quot;,<br>          &quot;MaxItems&quot;: 10,<br>          &quot;CSVHeaders&quot;: [<br>            &quot;Summary&quot;,<br>            &quot;Title&quot;<br>          ]<br>        },<br>        &quot;Parameters&quot;: {<br>          &quot;Bucket&quot;: &quot;netflix-titles-csv&quot;,<br>          &quot;Key&quot;: &quot;Hydra-Movie-Scrape.csv&quot;<br>        }<br>      },<br>      &quot;End&quot;: true,<br>      &quot;ResultWriter&quot;: {<br>        &quot;Resource&quot;: &quot;arn:aws:states:::s3:putObject&quot;,<br>        &quot;Parameters&quot;: {<br>          &quot;Bucket&quot;: &quot;embeddings-ouput&quot;,<br>          &quot;Prefix&quot;: &quot;output&quot;<br>        }<br>      }<br>    }<br>  }<br>}</pre><h3><strong>Step 5: Execute the state machine workflow and check the output</strong></h3><ul><li>From the step function console top right corner click on the <strong>Execute </strong>button</li><li>Leave the input of the state machine as it is and click on execute</li><li>After the successful execution of the workflow, you can see the results like this</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30wTg-pcxCbqnbXutb8szQ.png" /></figure><ul><li>Visit the OpenSearch dashboard and click on <strong>Query Workbench</strong> to execute the query and check whether embeddings are stored or not</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhlgfgxqsC50x3MEoDvKXA.png" /></figure><ul><li>As embeddings are a very large dataset they won’t be visible on the dashboard</li></ul><p>That’s it. We successfully create a workflow to generate embedding using a bedrock model.</p><p>If you want to use the generated embeddings for further implementing search engine, you can visit the link provided at the start of the article. It will contain the steps on how to build the vector search engine in OpenSearch</p><p>If you are having any doubts or need more clarification or help, Please feel free to comment on this article. Will surely get back to you.</p><p>Thanks :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c8448beee26" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>