<?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 Sojeong Baek on Medium]]></title>
        <description><![CDATA[Stories by Sojeong Baek on Medium]]></description>
        <link>https://medium.com/@SojeongBaek?source=rss-8160fa162e32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nLA2WH_oWAQ9stpDcw0zRA.jpeg</url>
            <title>Stories by Sojeong Baek on Medium</title>
            <link>https://medium.com/@SojeongBaek?source=rss-8160fa162e32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 00:39:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@SojeongBaek/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[Hosting VoyageAI Embeddings Privately on AWS SageMaker]]></title>
            <link>https://medium.com/@SojeongBaek/hosting-voyageai-embeddings-privately-on-aws-sagemaker-a5d84637683a?source=rss-8160fa162e32------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5d84637683a</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sagemaker]]></category>
            <dc:creator><![CDATA[Sojeong Baek]]></dc:creator>
            <pubDate>Tue, 21 Apr 2026 12:40:19 GMT</pubDate>
            <atom:updated>2026-04-21T12:40:19.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qe9MjvuN-GG0m4yUk4lp9w.png" /></figure><p>You may be considering VoyageAI embedding models to enhance the retrieval quality of your RAG system — hopefully sparked by my previous articles. However, a common hurdle often arises which is data privacy and security. As concerns regarding data exposure grow, many organizations prefer to host models within their own isolated environments. If your infrastructure is built on AWS, you can address this by leveraging AWS SageMaker. This allows you to deploy models within your preferred region and VPC, ensuring all communication remains secure through VPC interface endpoints.</p><p>To keep traffic private, you create four resources in order. Together they give your application a private path to a model and deploy a model in your desired region.</p><ol><li>A SageMaker deployable model (from the VoyageAI Marketplace subscription)</li><li>A SageMaker endpoint configuration</li><li>A SageMaker endpoint</li><li>A VPC interface endpoint for SageMaker runtime</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GsH1dIacuwSDQtJ_vbcclA.png" /></figure><p>Subscribe to the VoyageAI model listing on AWS Marketplace first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRbzqibqvGNKbMzI47n8fg.png" /></figure><p>Then move to <strong>SageMakerAI</strong> to create a model and pick the Marketplace listing you just subscribed to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fq1aXLwYhOP8IZpQcxg6jA.png" /></figure><p>If you have a compliance reason to attach a VPC configuration to the model (audit trail, or a custom container that needs to reach internal services), select your private subnet and security group here. For pure inference against a Marketplace model, you can leave VPC config off — it doesn’t affect whether your invocation traffic is private.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xPczPCy0JQrvJXqjDqSNPw.png" /></figure><p>Now move to <strong>Endpoints</strong> page to create an endpoint configuration. This is what tells SageMaker which model to serve and on what instance. For the type of endpoint, only <strong>Provisioned</strong> endpoint type is supported for models from marketplace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SmLaKYHGrUt9mqEhxTqtjA.png" /></figure><p>Under <strong>Variants</strong>, select the model you just created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-DB4DTdhiTC55sNIBaGMg.png" /></figure><p>Then click Edit to set the instance type that will host it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aet_3wLCYJl8P1TolXymFA.png" /></figure><p>Once the endpoint configuration is saved, create the endpoint and point it at that configuration. The configuration carries the model, the target VPC, and the instance spec.</p><p>The endpoint you just created lives in a SageMaker-managed VPC — your application can’t reach it privately until you give it a private door in. A VPC interface endpoint creates an ENI in your VPC that forwards traffic to the SageMaker Runtime service over AWS PrivateLink. SageMaker Runtime then routes it to the VoyageAI container in the SageMaker-managed VPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xvYZISRFRhBvS5vSexB8cg.png" /></figure><p>In the VPC console, create an interface endpoint for SageMaker runtime. Deploy it into the same private subnet as your application, and set the security group to allow inbound 443 from your EC2 instance&#39;s security group. In VPC settings, enable Private DNS on the endpoint.</p><p>From my EC2 instance in the private subnet, I invoked the endpoint with the AWS CLI below.</p><pre>aws sagemaker-runtime invoke-endpoint \<br>    --endpoint-name voyage-4-lite-endpoint \<br>    --region ap-northeast-2 \<br>    --content-type &quot;application/json&quot; \<br>    --cli-binary-format raw-in-base64-out \<br>    --body &#39;{<br>        &quot;input&quot;: [&quot;Hello from my private subnet!&quot;],<br>        &quot;input_type&quot;: &quot;document&quot;,<br>        &quot;output_dimension&quot;: 256<br>    }&#39; \<br>    output.json</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAxSUuR0ueeBAMBSj6sCCQ.png" /></figure><p>The call returned embeddings from the voyage-4-lite model as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tx8ktv1usjWapP0WyZLw_w.png" /></figure><p>From client-side, two quick checks confirm the path. nslookup returned a private IP inside my VPC and proves that the hostname resolves to the interface endpoint ENI. With traceroute, it shows first hop is the interface endpoint’s ENI in my private subnet and the same hostname stayed inside the VPC.</p><p>With this architecture, you achieve the high retrieval quality of a managed embedding model without compromising on latency or data sovereignty. Furthermore, you can integrate VPC interface endpoints for MongoDB Atlas to implement a truly end-to-end private RAG workflow!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5d84637683a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB Skills: Smarter AI Agents with Better Instructions]]></title>
            <link>https://medium.com/@SojeongBaek/mongodb-skills-smarter-ai-agents-with-better-instructions-5c3d38ef3c22?source=rss-8160fa162e32------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c3d38ef3c22</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mcps]]></category>
            <dc:creator><![CDATA[Sojeong Baek]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 13:25:30 GMT</pubDate>
            <atom:updated>2026-04-06T13:25:30.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6w-6giDKES-684wof9yRZw.png" /></figure><p>Last week, MongoDB released MongoDB Skills following MongoDB MCP that was launched last year. Together, they form a more complete foundation for building AI Agents that interact with MongoDB reliably and efficiently.</p><p>The MongoDB MCP server standardizes how AI agents access MongoDB capabilities as tools. Instead of having to write custom MongoDB tooling for each agent, you get a single protocol-compliant server that any MCP-compatible agent can talk to. That’s already useful. But tools alone only tell an agent what it can do, but not when or how to do it well.</p><p>This is where Skills shine. Skills are a directory containing diverse assets such as markdown instruction files, and any supporting code. This package gives an LLM precise, contextual guidance on how to use a set of capabilities for a specific task.</p><p>For MongoDB Skills, the MCP server is where the actual code executes. The Skill sits above that layer and tells the agent when to reach for a particular capability and how to use it most effectively.</p><p>One important design detail — Skills use lazy loading. Rather than dumping all instructions into the context upfront, the agent loads a lightweight manifest first and pulls in detailed skill files only when relevant. This keeps token usage lean, which matters at scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-6Ow6YFhEWimqyF_XN_XQ.png" /></figure><p>To install Skills locally, I cloned MongoDB Skills <a href="https://github.com/mongodb/agent-skills">repo</a> and ran the command below to package each skill directory into a .skill file. The .skill format is a zip archive of the skill directory.</p><pre>for skill in mongodb-mcp-setup mongodb-connection mongodb-natural-language-querying mongodb-query-optimizer mongodb-search-and-ai; do<br>  zip -r ~/claude/skills/$skill.skill $skill/<br>done</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZERADryb4LGt2waghoenkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMPlvEaM769bSWJHNqcrxg.png" /></figure><p>Once packaged, you can install a skill simply by clicking the .skill file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CbYM-XeNFM1-bdSksAxPPQ.png" /></figure><p>Alternatively, you can upload it manually through Claude Desktop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMW7SSMSzWySp8ZrYS2OVg.png" /></figure><p>Now I can see that all the skills are added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_-0DlesgLAKMQeS6X2tOg.png" /></figure><p>With MongoDB Skills enabled, when I passed a search-oriented prompt to Claude Cowork, the agent correctly reached for Atlas Search. The Skill had given it the context to recognize that this was the right tool for the job.</p><p>MongoDB supports both full-text and vector search, and standard query operators like regex. For most text-matching scenarios, Atlas Search is significantly more efficient — both in query performance and in how naturally it maps to user intent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXFrd-lFwLi8uyyVXnFyKw.png" /></figure><p>I opted out of MongoDB Skills to see how it acts differently. Without Skills, the same prompt produced a regex query. Not wrong but not optimal either. Without explicit guidance baked into the Skill, the agent defaulted to a more generic approach.</p><p>This isn’t just about Atlas Search vs. regex. Skills let you encode your organization’s conventions, performance best practices, and domain-specific patterns. It surfaces that knowledge to an agent precisely when it’s needed, without bloating every prompt with documentation.</p><p>The quality of instructions provided to an LLM matters just as much as the quality of its tools. With MongoDB Skills, you can start giving your agents the context they need to interact with MongoDB more effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c3d38ef3c22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenClaw LLM Setup using AWS Bedrock and LM Studio]]></title>
            <link>https://medium.com/@SojeongBaek/openclaw-llm-setup-usingaws-bedrock-and-lm-studio-8ef515e2f4ed?source=rss-8160fa162e32------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ef515e2f4ed</guid>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[openclaw]]></category>
            <category><![CDATA[lm-studio]]></category>
            <dc:creator><![CDATA[Sojeong Baek]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 09:51:55 GMT</pubDate>
            <atom:updated>2026-02-22T09:53:54.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BrP7BVlJvkgeT3tB-MVDZA.png" /></figure><p>When integrating an LLM with OpenClaw, one of my first concerns was keeping inference costs low. I explored two approaches to achieve this — using AWS Bedrock to leverage existing AWS credits if you have some, and using LM Studio to run open-source models locally.</p><p>When setting up OpenClaw for the first time, you can start with any provider and authentication method, and switch to a different model afterwards.</p><h4>Using LM Studio</h4><p>There are many ways to run open-source models in your local environment but I find LM studio most convenient. First you would need LM Studio running in your local environment. You can download it via this l<a href="https://lmstudio.ai/download">ink</a>. LM Studio provides a convenient way to install and run inference on open-source models.</p><p>When LM Studio is downloaded, navigate to the last tab “Model search”. You can look for the model you would like to use and download it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Lq-OEH8-S7jOTmK-WzrDw.png" /></figure><p>Once the model is downloaded, move to second tab “Developers”- Server Settings, enable “Serve on Local Network”. Then move to the third tab “My models” and increase the context length as the image below. You also need to check the name of LLM in the same page for config in later step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r_sKuQnWNxB7Yu7T89t9Ag.png" /></figure><p>Now that open source LLM that I want to use is ready with LM Studio, I need to set up OpenClaw to use it. Modify the openclaw.json file as below.</p><p>I set `baseUrl` as below because I was running Openclaw in docker environment but if you are using it in your local environment without docker, specify the` baseUrl` as the address that you checks in LM Studio Developer second tab such as `<a href="http://172.30.1.68:1234/">http://172.30.1.68:1234</a>`.</p><pre>{<br> &quot;models&quot;: {<br>    &quot;providers&quot;: {<br>      &quot;lmstudio&quot;: {<br>        &quot;baseUrl&quot;: &quot;http://host.docker.internal:1234/v1&quot;,<br>        &quot;apiKey&quot;: &quot;lmstudio&quot;,<br>        &quot;api&quot;: &quot;openai-responses&quot;,<br>        &quot;models&quot;: [<br>          {<br>            &quot;id&quot;: &quot;qwen2.5-3b-instruct-mlx&quot;,<br>            &quot;name&quot;: &quot;qwen2.5-3b-instruct-mlx&quot;,<br>            &quot;reasoning&quot;: true,<br>            &quot;input&quot;: [<br>              &quot;text&quot;<br>            ],<br>            &quot;cost&quot;: {<br>              &quot;input&quot;: 0,<br>            &quot;cost&quot;: {<br>              &quot;input&quot;: 0,<br>              &quot;output&quot;: 0,<br>              &quot;cacheRead&quot;: 0,<br>              &quot;cacheWrite&quot;: 0<br>            },<br>            &quot;contextWindow&quot;: 32768,<br>            &quot;maxTokens&quot;: 8192<br>          }<br>        ]<br>      }<br>    }<br>  },<br>  &quot;agents&quot;: {<br>    &quot;defaults&quot;: {<br>      &quot;model&quot;: {<br>        &quot;primary&quot;: &quot;lmstudio/qwen2.5-3b-instruct-mlx&quot;<br>      },<br>      &quot;models&quot;: {<br>        &quot;lmstudio/qwen2.5-3b-instruct-mlx&quot;: {},<br>        &quot;amazon-bedrock/anthropic.claude-3-haiku-20240307-v1:0&quot;: {},<br>        &quot;qwen2.5-3b-instruct-mlx&quot;: {}<br>      },<br>      &quot;workspace&quot;: &quot;/home/node/.openclaw/workspace&quot;,<br>      &quot;compaction&quot;: {<br>        &quot;mode&quot;: &quot;safeguard&quot;<br>      },<br>      &quot;maxConcurrent&quot;: 4,<br>      &quot;subagents&quot;: {<br>        &quot;maxConcurrent&quot;: 8<br>      }<br>    }<br>  }<br>}</pre><p>When the config file is modified, run openclaw onboard to see if the change is reflected.</p><h4>Using Bedrock</h4><p>If you already have AWS environment it might be better to use Bedrock to consolidate billing or leverage AWS credits.</p><p>When you simply follow OpenClaw documentation and put the model ID as a value model, you will get the error below.</p><pre>&quot;message&quot;: &quot;Invocation of model ID anthropic.claude-sonnet-4–5–20250929-v1:0 with on-demand throughput isn&#39;t supported. Retry your request with the ID or ARN of an inference profile that contains this model.&quot;</pre><p>In order to call a model through Bedrock, I need to use inference profiles and note the ARN of it.</p><p>Make sure that AWS CLI is configured and run the command below. You can check your profile name by running cat ~/.aws/config.</p><pre>aws bedrock list-inference-profiles --region &lt;your region&gt; --profile &lt;your profile name&gt;</pre><p>It will return output as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0hedlA2VcGc-kwFbW8fFw.png" /></figure><p>You need to check the `inferenceProfileArn` of the model that you want to use from the output.</p><p>Modify openclaw.json as below. Below is part of my openclaw.json.</p><pre>{  &quot;models&quot;: {<br>    &quot;providers&quot;: {<br>      &quot;amazon-bedrock&quot;: {<br>        &quot;baseUrl&quot;: &quot;https://bedrock-runtime.&lt;AWS Region&gt;:.amazonaws.com&quot;,<br>        &quot;auth&quot;: &quot;aws-sdk&quot;,<br>        &quot;api&quot;: &quot;bedrock-converse-stream&quot;,<br>        &quot;models&quot;: [<br>          {<br>            &quot;id&quot;: &quot;arn:aws:bedrock:&lt;AWS Region&gt;:&lt;AWS Account&gt;:inference-profile/apac.anthropic.claude-3-7-sonnet-20250219-v1:0&quot;,<br>            &quot;name&quot;: &quot;Sonnet4.5&quot;,<br>            &quot;reasoning&quot;: true,<br>            &quot;input&quot;: [<br>              &quot;text&quot;,<br>              &quot;image&quot;<br>            ],<br>            &quot;contextWindow&quot;: 200000,<br>            &quot;maxTokens&quot;: 8192<br>          }<br>        ]<br>      }<br>    },<br>    &quot;bedrockDiscovery&quot;: {<br>      &quot;enabled&quot;: true,<br>      &quot;region&quot;: &quot;&lt;AWS Region&gt;&quot;<br>    }<br>  },<br>  &quot;agents&quot;: {<br>    &quot;defaults&quot;: {<br>      &quot;model&quot;: {<br>        &quot;primary&quot;: &quot;arn:aws:bedrock:&lt;AWS Region&gt;:&lt;AWS Account&gt;:inference-profile/apac.anthropic.claude-3-7-sonnet-20250219-v1:0&quot;<br>      },<br>      &quot;workspace&quot;: &quot;/home/ec2-user/.openclaw/workspace&quot;,<br>      &quot;compaction&quot;: {<br>        &quot;mode&quot;: &quot;safeguard&quot;<br>      },<br>      &quot;maxConcurrent&quot;: 4,<br>      &quot;subagents&quot;: {<br>        &quot;maxConcurrent&quot;: 8<br>      }<br>    }<br>  }<br>} </pre><p>When I run openclaw onboard again, I can see that it detects the LLM that I specified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U1Jpujlr95CTCX5YufvSAQ.png" /></figure><p>I entered OpenClaw dashboard to initiate my first conversation with OpenClaw and I can see that it’s working just fine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WTrMN9QCeuk6djNm_RYFg.png" /></figure><p>You can choose your preferred way to set up and start interacting with OpenClaw!</p><p>Reference:</p><ul><li><a href="https://docs.openclaw.ai/providers/bedrock">https://docs.openclaw.ai/providers/bedrock</a></li><li><a href="https://aws.plainenglish.io/configuring-claude-code-extension-with-aws-bedrock-and-how-you-can-avoid-my-mistakes-090dbed5215b">https://medium.com/r/?url=https%3A%2F%2Faws.plainenglish.io%2Fconfiguring-claude-code-extension-with-aws-bedrock-and-how-you-can-avoid-my-mistakes-090dbed5215b</a></li><li><a href="https://www.youtube.com/watch?v=Bn_hkXCwO-U&amp;list=WL&amp;index=4&amp;t=2s">https://www.youtube.com/watch?v=Bn_hkXCwO-U&amp;list=WL&amp;index=4&amp;t=2s</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ef515e2f4ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use MongoDB as Feast Online Store]]></title>
            <link>https://medium.com/@SojeongBaek/use-mongodb-as-feast-online-store-e8c1e280f4d1?source=rss-8160fa162e32------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8c1e280f4d1</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[feature-store]]></category>
            <category><![CDATA[feast]]></category>
            <dc:creator><![CDATA[Sojeong Baek]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 14:38:53 GMT</pubDate>
            <atom:updated>2025-12-30T06:12:40.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_LXE9UXSNh7ml9BGIEl1eQ.png" /></figure><p>Feast is an open source feature store framework. With Feast, you can easily deploy a feature store using your existing infra, and efficiently managing and reusing feature data to avoid data silos.</p><p>A feature store consists of an online and an offline store, each serving a respective purpose. The online store serves the latest subset of data for real-time inference, while the offline store is used for training models with large volumes of historical feature data.</p><p>Feast supports multiple options for online and offline stores. If a solution is not supported natively, you can add a custom store. In this blog, I will show you how to use MongoDB as a Feast online store. As MongoDB is a high-performance document database, it is a great fit for an online feature store.</p><h4>1. Configuration</h4><p>Install feast and intiate your feast project.</p><pre>pip install feast<br>feast init demo</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*u9SZIR4n6T8n-2L5ly7OTA.png" /></figure><p>This creates a directory with the name you specified, containing the necessary scaffold files. I will configure the feature store in the example_repo.py file. But first, I need to create a custom online store to use MongoDB as it’s not natively support at this moment.</p><p>I created mongodb_online_store.py in the demo/feature_repo directory and you can find the full code <a href="https://github.com/PhoebeBaek/feast/blob/main/demo/feature_repo/mongodb_online_store.py">here</a>.</p><p>I loaded sample driver data into my BigQuery table. When I tried to insert the demo/feature_repo/data/driver_stats.parquet sample data into BigQuery, I encountered a data type error, so I ran the SQL below to fix it.</p><pre>ALTER TABLE `demo.feast.driver-stats`<br>ADD COLUMN event_timestamp2 TIMESTAMP;<br><br>UPDATE `demo.feast.driver-stats`<br>SET event_timestamp2 = TIMESTAMP_SECONDS(CAST(event_timestamp / 1000000000 AS INT64))<br>WHERE event_timestamp IS NOT NULL;<br><br>ALTER TABLE `demo.feast.driver-stats` DROP COLUMN event_timestamp<br><br>ALTER TABLE `demo.feast.driver-stats` RENAME COLUMN event_timestamp2 TO event_timestamp;<br><br>SELECT * FROM `demo.feast.driver-stats` LIMIT 5;<br>SELECT driver_id, COUNT(*) as row_cnt<br>FROM `sojeong-training.feast.driver-stats`<br>GROUP BY driver_id;</pre><p>Now the historical data is stored in my BigQuery table. When I run a group by query to inspect the data, I can see that there are 5 unique drivers and each has around historical 300 rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrNuWbNLUsfbEq5qdpSDmg.png" /></figure><p>Next, I need to specify the BigQuery data source in the `repo.py` file. I added the code below to `example_repo.py`.</p><pre>from feast import BigQuerySource<br><br>bigquery_source = BigQuerySource(<br>    table = &quot;demo.feast.driver-stats&quot;,<br>    timestamp_field = &quot;event_timestamp&quot;<br>)<br><br><br>    name=&quot;driver_hourly_stats&quot;,<br>    entities=[driver],<br>    schema=[<br>        Field(name=&quot;conv_rate&quot;, dtype=Float32),<br>        Field(name=&quot;acc_rate&quot;, dtype=Float32),<br>        Field(name=&quot;avg_daily_trips&quot;, dtype=Int64, description=&quot;Average daily trips&quot;),<br>    ],<br>    online=True,<br>    source=bigquery_source,<br>    tags={&quot;team&quot;: &quot;driver_performance&quot;},<br>)<br><br>driver_stats_push_source = PushSource(<br>    name=&quot;driver_stats_push_source&quot;,<br>    batch_source=bigquery_source,<br>)</pre><p>Configure the `feature_store.yaml` file to specify which data stores to use for the online and offline feature stores. To connect to BigQuery, I ran gcloud auth login to authenticate my session.</p><p>After updating the configuration, run feast plan and feast apply inside the demo/feature_repo directory.</p><pre>project: demo<br>registry: data/registry.db<br>provider: local<br>online_store:<br>    type: mongodb_online_store.MongoDBOnlineStore<br>    connection_string: &quot;mongodb://localhost:27017/&quot;<br>    database: &quot;feast&quot;<br>offline_store:<br>    type: bigquery<br>entity_key_serialization_version: 3<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*96PyejT--qQOb1dR5DKbYQ.png" /></figure><p>After feast apply is completed, I could see that the Feast database and collections have been created in MongoDB but there is no data yet.</p><h4>2. Run queries</h4><p>Now that the offline and online stores are configured, I can use Feast methods to run some queries.</p><pre>import pandas as pd<br>from feast import FeatureStore<br><br>df = pd.read_parquet(&quot;demo/feature_repo/data/driver_stats.parquet&quot;)<br>entity_df = df[[&quot;driver_id&quot;, &quot;event_timestamp&quot;]]<br>fs = FeatureStore(&#39;demo/feature_repo/&#39;)<br><br>trainning_df = fs.get_historical_features(<br>    features = [<br>        &quot;driver_hourly_stats:conv_rate&quot;,<br>        &quot;driver_hourly_stats:acc_rate&quot;<br>    ],<br>    entity_df=entity_df<br>).to_df()<br><br>trainning_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*qDi862Y6EDDLoobooVfiTw.png" /></figure><p>I can retrieve data from offline feature store using `get_historical_features ` method. By specifying entity_df=entity_df , Feast uses both driver_id and event_timestampt fields to perform poin-in-time join.</p><p>Syncing data from offline store to online store is called Materialization. In order to run materialization, I ran feast materialize-incremental $(date -u +&quot;%Y-%m-%dT%H:%M:%S), then received the output indicating the materialized date range.</p><p>During materialization, only the latest data per unique identifier is synced based on the timestamp field. This ensures that the most recent data can be served from the online store with low latency.</p><p>Once materialization was complete, I saw that 5 documents had been synced to MongoDB. In other words, only the latest data for each of the 5 drivers was synced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*8ry9uhV0AwnZEw8DdmHejw.png" /></figure><pre>from pprint import pprint<br>from feast import FeatureStore<br><br>fs = FeatureStore(&#39;demo/feature_repo/&#39;)<br><br>feature_vector = fs.get_online_features(<br>    features = [<br>        &quot;driver_hourly_stats:conv_rate&quot;,<br>        &quot;driver_hourly_stats:acc_rate&quot;,<br>        &quot;driver_hourly_stats:avg_daily_trips&quot;<br>    ],<br>    entity_rows = [<br>        {&quot;driver_id&quot;: 1004},<br>        {&quot;driver_id&quot;: 1005},<br>    ]<br>).to_dict()<br>pprint(feature_vector)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*qibg98u4a-3Bdi0BeDvahg.png" /></figure><p>I can also get data from online feature store using `get_online_features ` method.</p><p>Configuring Feast with MongoDB as an online store allows you to leverage existing document database infrastructure for real-time machine learning. We’ve bridged the gap between historical data in BigQuery and low-latency serving in MongoDB. I hope this guide helps you streamline your feature engineering pipeline!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8c1e280f4d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving RAG Retrieval with voyage-context-3 and MongoDB Atlas Vector Search]]></title>
            <link>https://medium.com/@SojeongBaek/improving-rag-retrieval-with-voyate-context-3-and-mongodb-atlas-vector-search-1bddfa0b23f1?source=rss-8160fa162e32------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bddfa0b23f1</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[voyage-ai]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[vector-embeddings]]></category>
            <dc:creator><![CDATA[Sojeong Baek]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 15:07:38 GMT</pubDate>
            <atom:updated>2025-08-06T08:27:10.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w1L8lruP9784PYpC" /><figcaption>Image Source: VoyageAI</figcaption></figure><p>As RAG architecture has become essential for GenAI applications, diverse techniques for improving retrieval quality are gaining significant attention.</p><p>Many developers have been exploring various approaches like metadata augmentation, late chunking, and late interaction. While these methods can be highly effective, they come with notable tradeoffs. Metadata augmentation and context retrieval require additional pipelines, making RAG architectures more complex. Late interaction methods demand significantly higher storage and compute resources.</p><p>I want to introduce a promising technique which can improve retrieval quality within your existing pipeline — contextual chunk embedding model. MongoDB VoyageAI has released a model that generates chunk embeddings by considering document context, showing impressive performance improvements in <a href="https://medium.com/r?url=https%3A%2F%2Fdocs.google.com%2Fspreadsheets%2Fd%2F1qLBWWvN7-4W53BveJgkQiDSoK_j2RYLh5DafDdEOPnc%2Fedit%3Fgid%3D291808049%23gid%3D291808049">benchmark results</a>.</p><p>In this blog, I’ll demonstrate how to use this model to generate contextual embeddings and leverage MongoDB Atlas vector search to perform vector searches against these enhanced embeddings.</p><pre>documents = [<br>    &quot;Berlin is the capital and largest city of Germany, \n&quot;<br>    &quot;by both area and population With 3.7 million inhabitants, \n&quot;<br>    &quot;it has the highest population within its city limits of any city in the European Union. \n&quot;<br>    &quot;The city is also one of the states of Germany, being the third smallest state in the country by area.&quot;,<br>    <br>    &quot;Seoul, city and capital of South Korea (the Republic of Korea). \n&quot;<br>    &quot;It is located on the Han River (Han-gang) in the northwestern part of the country, \n&quot;<br>    &quot;with the city center some 37 miles (60 km) inland from the Yellow Sea (west). \n&quot;<br>    &quot;Seoul is the cultural, economic, and political center of South Korea.&quot;,<br><br>]<br><br>text_splitter = RecursiveCharacterTextSplitter(<br>                                                separators = [&quot;\n&quot;], <br>                                                chunk_size = 100,<br>                                                chunk_overlap = 0<br>                                            )<br>texts = [text_splitter.split_text(d) for d in documents]<br>print(f&quot;Texts: \n{json.dumps(texts, indent=2)}&quot;)</pre><p>First, I created a simple document explaining about Berlin and Seoul, and chunked them without any overlap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgBCgG1KzZ_fM0xNrvytyA.png" /></figure><p>The chunked data looks like this. The voyage-context-3 model takes the inner list as input so the model knows what the document-level context is for each chunk.</p><pre><br>output = vo.contextualized_embed(<br>    inputs=texts,<br>    model=&quot;voyage-context-3&quot;,<br>    input_type=&quot;document&quot;,<br>    output_dimension=1024<br>)<br><br>results = output.results<br>text_embedding_dict = {}<br>embedding_list = []<br>text_list = []<br>for text_chunks in texts:<br>    text_list.extend(text_chunks)<br><br>for result in results:<br>    embeddings = result.embeddings<br>    for embedding in embeddings:<br>        embedding_list.append(embedding)<br><br>text_embedding_list = []<br>for text, embedding in zip(text_list, embedding_list):<br>    text_embedding_dict = {<br>        &quot;text&quot;: text,<br>        &quot;embedding&quot;: embedding<br>    }<br>    text_embedding_list.append(text_embedding_dict)<br><br><br>mdb_collection.insert_many(text_embedding_list)</pre><p>After creating documents containing both text and embedding data, I inserted the data into MongoDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sN1gEUAsXdxwoJ9RwPCjAw.png" /></figure><p>The data was succesfully inserted as expected.</p><pre>{<br>  &quot;fields&quot;: [<br>    {<br>      &quot;type&quot;: &quot;vector&quot;,<br>      &quot;path&quot;: &quot;embedding&quot;,<br>      &quot;numDimensions&quot;: 1024,<br>      &quot;similarity&quot;: &quot;dotProduct&quot;<br>    }<br>  ]<br>}</pre><p>I also created a vector search index to run vector search queries with the above index definition.</p><pre>query = &quot;How many people live in Berlin?&quot;<br>query_embedding = vo.contextualized_embed(inputs=[[query]], model=&quot;voyage-context-3&quot;, input_type=&quot;query&quot;).results[0].embeddings[0]<br><br>query_results = mdb_collection.aggregate([  <br>                        {<br>                            &quot;$vectorSearch&quot;:      <br>                            {<br>                                &quot;queryVector&quot;: query_embedding,<br>                                &quot;path&quot;: &quot;embedding&quot;,<br>                                &quot;numCandidates&quot;: 3,<br>                                &quot;index&quot;: &quot;vector_index&quot;,<br>                                &quot;limit&quot;: 3<br>                            }<br>                        },<br>                          {<br>                            &quot;$project&quot;: {<br>                            &quot;embedding&quot;: 0,<br>                            &quot;score&quot;: {<br>                                &quot;$meta&quot;: &quot;vectorSearchScore&quot;<br>                            }<br>                            }<br>                        }<br>                    ])<br><br><br>for result in query_results:<br>    print(result)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrKM_xroXsBnQ21it9q_kQ.png" /></figure><p>From the results, I could see that the chunk explaining about Berlin’s population showed the highest score, and chunks about Berlin followed next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*deHy_HbEuVYo_Vs6Dguk6w.png" /></figure><p>To demonstrate the effectiveness of contextual embeddings, I conducted a comparative test using a traditional embedding model with the same dataset and query. When I asked the same question about Berlin’s population, the top-ranked document was identical to the contextual model results, but with a significantly lower relevance score. Additionally, chunks about Seoul appeared in the subsequent results, indicating poor contextual understanding.</p><p>This comparison clearly illustrates how traditional chunking methods lose global context, while contextual chunk embedding preserves the broader document context within each chunk, resulting in superior vector search scores and more accurate retrieval.</p><p>As demonstrated in our comparison, the voyage-context-3 model’s ability to preserve global document context in individual chunks leads to substantially better retrieval scores and more relevant results — all without the architectural complexity of other enhancement techniques.</p><p>If you’re looking to improve your RAG system’s performance without architectural complexity, try contextual chunk embeddings with MongoDB Atlas Vector Search!</p><p>Reference</p><ul><li><a href="https://blog.voyageai.com/2025/07/23/voyage-context-3/">https://blog.voyageai.com/2025/07/23/voyage-context-3/</a></li><li><a href="https://docs.voyageai.com/docs/contextualized-chunk-embeddings">https://docs.voyageai.com/docs/contextualized-chunk-embeddings</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bddfa0b23f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building AI Agent with MongoDB MCP]]></title>
            <link>https://medium.com/@SojeongBaek/building-ai-agent-with-mongodb-mcp-1339516643c8?source=rss-8160fa162e32------2</link>
            <guid isPermaLink="false">https://medium.com/p/1339516643c8</guid>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Sojeong Baek]]></dc:creator>
            <pubDate>Sat, 05 Jul 2025 01:04:09 GMT</pubDate>
            <atom:updated>2025-07-05T01:04:34.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEQQmW-GTbj48QDfP7HFhw.png" /></figure><p>AI Agents are recognized as an important concept that can transform how humans work and how companies operate. AI Agents can automate many tasks that humans are currently handling. Some say they can even serve as a project managers to assign tasks to humans.</p><p>You can think of an AI Agent as an autonomous system with these core capabilities:</p><ul><li>Plan: it plans multiple steps to accomplish tasks.</li><li>Collaborate: it collaborates with other agents to validate or improve accuracy of tasks.</li><li>Tool: it uses appropriate tools to solve complex tasks.</li></ul><p>In this blog, I want to walk you through an AI agent which can decide which tools to use and accomplish tasks with those tools.</p><p>Since MongoDB has released its official MCP, you can easily provide tools to AI agents without writing extensive code to create MCP tools, similar to what I demonstrated in my previous blog — <a href="https://medium.com/@SojeongBaek/mcp-in-action-building-a-text2mql-tool-50c6c6104a08">MCP in Action — Building a text2mql tool</a>.</p><pre>async def movie_agent(user_input):<br>    try:<br>        mcp_client = MultiServerMCPClient(<br>            {<br>                &quot;mongodb-mcp&quot;: {<br>                    &quot;transport&quot;: &quot;stdio&quot;,<br>                    &quot;command&quot;: &quot;npx&quot;,<br>                    &quot;args&quot;: [<br>                        &quot;-y&quot;,<br>                        &quot;mongodb-mcp-server&quot;,<br>                        &quot;--connectionString&quot;,<br>                        config.URI<br>                    ]<br>                },<br>                &quot;tavily-mcp&quot;: {<br>                    &quot;transport&quot;: &quot;stdio&quot;,<br>                    &quot;command&quot;: &quot;npx&quot;,<br>                    &quot;args&quot;: [&quot;-y&quot;, &quot;tavily-mcp@0.2.4&quot;],<br>                    &quot;env&quot;: {<br>                        &quot;TAVILY_API_KEY&quot;: config.tavily_api_key<br>                    },<br>                    &quot;disabled&quot;: False,<br>                    &quot;autoApprove&quot;: []<br>                }<br>            }<br>        )<br><br>        tools = await mcp_client.get_tools()</pre><p>I configured 2 different tools using `langchain_mcp_adapters`, which allows me to use MCP with LangGraph agents.</p><pre>analysis_node = create_react_agent(<br>                model = &quot;bedrock_converse:anthropic.claude-3-5-sonnet-20240620-v1:0&quot;,<br>                tools = tools,<br>                prompt= &quot;&quot;&quot;<br>                        You are a movie expert and your task is answering questions about movies following the rules.<br>                         <br>                        &lt;rules&gt;<br>                        1. Before implementing your task, choose a tool to implement your task.<br>                        2. When you need to answer about movies, use `mongodb-mcp` tool. It is useful for movie recommendation or explanation about movie.<br>                        3. If you use `mongodb-mcp` tool, use `sample_mflix.movies` namespace and refer to the `schema` below. <br>                        4. When it requires web search, use `tavily-mcp` tool. It is useful when you need to answer about detailed information about movie such as actors.<br>                        5. Keep your answer in 3 sentences. <br>                        &lt;/rules&gt;<br><br>                        &lt;schema&gt;<br>                        {<br>                            &quot;_id&quot;:{<br>                            &quot;$oid&quot;:&quot;573a1390f29313caabcd5293&quot;<br>                            },<br>                            &quot;plot&quot;:&quot;Young Pauline is left a lot of money when her wealthy uncle dies.&quot;,<br>                            &quot;genres&quot;:[<br>                            &quot;Action&quot;<br>                            ],<br>                            &quot;title&quot;:&quot;The Perils of Pauline&quot;,<br>                            }<br>                        }<br>                        &lt;/schema&gt;<br><br><br>                        &quot;&quot;&quot;<br>            )</pre><p>Next, I created one LangGraph react agent and provided rules that the agent should follow in my prompt. I configured the agent to use two different tools: tavily-mcp for web search and mongodb-mcp for database access. In MongoDB sample_mflix.movies namespace, there is general information about movies. If a user asks about movies, the agent can use mongodb-mcp to find relevant information and generate answers. If the question is about something other than movies, it can use tavily-mcp to search for information on the web and generate answers.</p><pre>        workflow = StateGraph(MessagesState)<br>        workflow.add_node(&quot;analysis&quot;, analysis_node)<br>        workflow.add_edge(START, &quot;analysis&quot;)<br>        workflow.add_edge(&quot;analysis&quot;, END)<br>        graph = workflow.compile()<br><br><br>        input_dict = {<br>            &quot;messages&quot;: <br>            [{<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: f&quot;Generate answer to the input `{user_input}` using provided tool&quot;<br>            }]<br>        }<br>        <br>        async for chunk in graph.astream(input_dict, stream_mode=&quot;messages&quot;):<br>            print(chunk, flush=True)<br>            yield chunk<br><br>    except Exception as e:<br>        print(f&quot;Error in dining_ai: {str(e)}&quot;)<br>        raise</pre><p>I configured a very simple LangGraph flow to use the agent I created and generate answers in streaming mode.</p><p>The streaming output from the LangGraph agent is passed to a Streamlit UI application I created to display the AI Agent’s responses in a web interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*HzurLEGxj9meK-mX" /></figure><p>Here is the final UI. When I ask a question about a movie, the agent knows which tool to use — mongodb-mcp. It generates the query to run and retrieves relevant information. Based on the given information, it generates the final answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhnBGa1YlCpNOzngl71_KA.png" /></figure><p>Now when I ask a different question asking about an actor, the agent knows that the information is not stored in MongoDB and needs to use a different tool — tavily-mcp. It searches the information on the web and generates final answers based on the web search results.</p><p>In this blog, we explored how to create an AI Agent and how to use MongoDB MCP. It’s always exciting to see how MongoDB can be integrated with GenAI!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1339516643c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MCP in Action — Building a text2mql tool]]></title>
            <link>https://medium.com/@SojeongBaek/mcp-in-action-building-a-text2mql-tool-50c6c6104a08?source=rss-8160fa162e32------2</link>
            <guid isPermaLink="false">https://medium.com/p/50c6c6104a08</guid>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Sojeong Baek]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 00:52:30 GMT</pubDate>
            <atom:updated>2025-04-26T02:06:40.858Z</atom:updated>
            <content:encoded><![CDATA[<h3>MCP in Action — Building a text2mql tool</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*ooCtPqeYZ-htnUuzAG8igw.png" /></figure><p>MCP(Model Context Protocol) is a buzzword today. Using MCP, you can connect LLMs with diverse external tools.</p><p>LLMs using external tool (in other words, function calling) is not new. Then why is it such a buzzword? Because, as its name suggests, MCP provides a unified function calling protocol. There are many ways to do function calling for LLMs, but using one unified function calling method can significantly improve your code complexity and integrate different frameworks and tools smoothly.</p><p>In this blog, I’ll walk you through how to create a simple tool integrating with MongoDB and use the tool with Claude desktop as a client.</p><h3>Why MongoDB</h3><p>Before diving in, let’s briefly explain MongoDB. It’s a popular NoSQL database that stores data in flexible, JSON-like documents. Unlike traditional relational databases, MongoDB doesn’t require a fixed schema, making it ideal for AI applications requiring flexibility and scalability.</p><h3>Creating an MCP server</h3><p>Server here means a tool that you define. I created a text2sql tool running queries against MongoDB. This tool receives user input in natural language, converts it to MongoDB query API, and runs the query against MongoDB.</p><p>I used FastMCP to develop MCP server. FastMCP is a python SDK helping developers create MCP server easily.</p><p>Before starting, I installed the necessary libraries:</p><pre>pip install fastmcp</pre><p>The code to develop MCP server is straightforward.</p><pre>##mcp_server.py<br><br>import config<br>import json<br>from pymongo import MongoClient<br>from mcp.server.fastmcp import FastMCP<br>from langchain_aws import ChatBedrock<br>from langchain_core.messages import HumanMessage<br><br>mcp = FastMCP(&quot;mcp_server&quot;)<br><br>@mcp.tool()<br>def mongodb_query(input_query: str):<br>    &quot;&quot;&quot;<br>    Implement text to sql and run query in MongoDB.<br>    &quot;&quot;&quot;<br>    try:<br>        client = MongoClient(config.URI)<br>        db = client[&quot;sample_mflix&quot;]<br>        collection = db[&quot;movies&quot;]<br><br>        #Initialize the model client<br>        llm = ChatBedrock(<br>            region=&quot;us-east-1&quot;,<br>            provider = &quot;anthropic&quot;,<br>            model_id = &quot;anthropic.claude-3-sonnet-20240229-v1:0&quot;<br>        )<br>        #Define a message<br>        message = HumanMessage(<br>            content=[<br>                {<br>                    &quot;type&quot;: &quot;text&quot;,<br>                    &quot;text&quot;: f&quot;&quot;&quot;<br>                        You are a MongoDB expert. Your task is converting the input query to MongoDB pymongo API following the rules.<br>                        Below is the schema sample in sample_mflix.movies namespace in MongoDB for your reference.<br>                        <br>                        &lt;Input_query&gt;<br>                        {input_query}<br>                        &lt;/Input_query&gt;<br><br>                        &lt;Rules&gt;<br>                        1. Analzy the input thoroughly in order to understand what data needs to be found.<br>                        2. Return the query API method and filter only and do not add any explanation.<br>                        3. Do not add any extra filter on query.<br>                        4. Return the filter in valid JSON format.<br>                        5. Always exclude &#39;embedding&#39; field in the query result.<br>                        &lt;/Rules&gt;<br><br>                        &lt;Example&gt;<br>                        Input: Search for one movie which released in 2000 and with the rating higher than 4.<br>                        Return: find({{&quot;year&quot;: 2000, &quot;imdb.rating&quot;: {{&quot;$gt&quot;: 4}}}}, {{&quot;embedding&quot;: 0}}).limit(1)<br>                        &lt;/Example&gt;<br><br>                        &lt;Schema sample&gt;<br>                        {{<br>                        &quot;title&quot;: &quot;The Arrival of a Train&quot;,<br>                        &quot;year&quot;: {{<br>                            &quot;$numberInt&quot;: &quot;1896&quot;<br>                        }},<br>                        ...<br>                        }}<br>                        &lt;/Schema sample&gt;<br>                    &quot;&quot;&quot;<br>                }<br>            ]<br>        )<br>        <br>        #Invoke LLM<br>        mql = llm.invoke([message]).content<br>        response = eval(f&quot;collection.{mql}&quot;)<br>        movie_list = []<br>        if response:<br>            for movie in response:<br>                movie_list.append(movie)<br>        return mql, movie_list<br>    except Exception as e:<br>        return e<br><br>if __name__ == &quot;__main__&quot;:<br>    mcp.run(transport=&quot;stdio&quot;)<br></pre><p>In this code, I initialized a model client using AWS Bedrock and defined prompt message. In the prompt message, I included the sample schema in MongoDB so that the LLM can understand how to create MQL(MongoDB Query Language) and included rules that LLM should follow when generating answers. The implementation is straightforward — receive input, convert it to a MongoDB query via the LLM, execute the query, and return the results.</p><p>There are two main transport supported for communication between MCP servers and clients:</p><ul><li><strong>stdio</strong>: Used for communicating between local servers and clients during development</li><li><strong>SSE (Server-Sent Events)</strong>: Used for communicating with remote servers in production environments</li></ul><p>In my code, I used stdio since I ran everything locally.</p><h3>Setting Up MCP Client</h3><p>Now that MCP server is ready, I set up a MCP client to use the server. I used Claude desktop to access my MCP tool.</p><pre><br>{<br>  &quot;mcpServers&quot;: {<br>      &quot;mdb_query&quot;: {<br>          &quot;command&quot;: &quot;/Users/MongoDB/ai_agent/.env/bin/python&quot;,<br>          &quot;args&quot;: [<br>              &quot;/Users/MongoDB/ai_agent/mcp_server.py&quot;<br>          ]<br>      }<br>  }<br>}</pre><p>In order to use Claude desktop, need to define how to use the MCP server and path that the tool is defined in ~/Library/Application Support/Claude/claude_desktop_config.json. I specified command as my python virtual environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kjPT05fO1QK3WbuXVeu6jw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umLFRmsM50OTWQlkELCo5w.png" /></figure><p>In Claude desktop, moved to developer setting tab and select the path where the tool is located. You need to restart the app so that the configuration can be applied. Once you restart the app, you’ll see the the tool I defined is available in Claude’s toolset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mmxuHQHqnRYgKTMUhHxlg.png" /></figure><p>I started a new chat in Claude desktop asking “Please recommend me a movie with rating higher than 8 and release between 2000 and 2010 using an available tool”. While generating a new response, Claude asked for my approval to use the MCP tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0reJ9Xh_Abelp3478dP9g.png" /></figure><p>Once I granted the access to the tool, it generated a query to run against MongoDB to find the data I requested. Claude then returned movie recommendations that matched my criteria.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZSBWcMnN5k_qJjxx21ciPA.png" /></figure><p>To verify, I ran the same query directly against my MongoDB database and got identical results.</p><p>This integration has several practical applications:</p><ol><li><strong>Natural Language Database Queries</strong>: Allow non-technical users to query databases using plain language</li><li><strong>Content Recommendation Systems</strong>: Build personalized recommendation engines powered by LLMs</li></ol><p>Creating a tool to integrate with LLMs is so much easier with MCP and MongoDB! The standardized approach provided by MCP simplifies development and maintenance, while MongoDB’s flexible schema is perfect for storing varied data types that your LLM tools might need to access.</p><p>I will cover how to create Agentic AI with MCP and MongoDB in my next article. Till then, stay tuned! 🍃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50c6c6104a08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Search and Reranking: MongoDB Atlas + VoyageAI]]></title>
            <link>https://medium.com/@SojeongBaek/vector-search-and-reranking-mongodb-atlas-voyageai-3e1d39c4d656?source=rss-8160fa162e32------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e1d39c4d656</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[voyagai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Sojeong Baek]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 13:27:27 GMT</pubDate>
            <atom:updated>2025-03-13T08:17:30.668Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8MHVsTdanR21Qzhq" /></figure><p>MongoDB and VoyageAI are now one team! 🍃 VoyageAI is an industry-leading LLM provider. If you have checked the embedding model benchmark leaderboard in Hugging Face, I am sure that you are already familiar with VoyageAI. In this blog, I want to walk you through what VoyageAI models do.</p><p>VoyageAI provides two model types — embedding models and reranking models. Embedding models convert structured/unstructured data into vector embeddings, which are essential components for RAG architecture.</p><p>Reranking might sound less familiar compared to embedding model. Reranking models re-evaluate the initial vector search results to improve accuracy. While vector search uses distance metrics to find similar embeddings, rerankers implement more sophisticated scoring mechanisms that better capture the relevance between query and documents.</p><p>I will use the VoyageAI embedding model to create vector embeddings from <a href="https://www.mongodb.com/resources/solutions/use-cases/building-event-driven-applications-with-mongodb">“Event-Driven Apps with MongoDB” white paper</a> in pdf format describing how to implement event-driven applications with MongoDB Atlas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jbzbXUUyiUr8uZI8UCNEw.png" /></figure><p>In page 13 of “Event-Driven Apps with MongoDB” white paper, it describes the 4 key event-driven architecture use cases of MongoDB Atlas. Let’s see if we can get relevant results using RAG pattern and how it can be scored with a reranking model.</p><h4>1. Embedding Data</h4><pre>import voyageai<br>import config<br>from pymongo import MongoClient<br>from langchain_mongodb import MongoDBAtlasVectorSearch<br>from langchain_voyageai import VoyageAIEmbeddings<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_community.document_loaders import UnstructuredPDFLoader<br><br>vo_api_key = config.VO_API<br>vo = voyageai.Client(api_key=vo_api_key)<br><br>mdb_client = MongoClient(config.URI)<br>mdb_db = mdb_client[&quot;voyage_ai&quot;]<br>mdb_collection = mdb_db[&quot;mdb_event_driven_app&quot;]</pre><p>Before starting, downloaded the required libraries and set up my session.</p><pre>#chunk data from pdf<br>loader = UnstructuredPDFLoader(&quot;/Users/vector_search/Event-Driven_Apps_with_MongoDB.pdf&quot;, mode=&quot;single&quot;)<br>data = loader.load()<br><br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)<br>docs = text_splitter.split_documents(data)<br><br>#insert embedding data<br>MongoDBAtlasVectorSearch.from_documents(<br>    documents=docs,<br>    embedding=VoyageAIEmbeddings(model=&quot;voyage-3-lite&quot;, api_key=vo_api_key),<br>    collection=mdb_collection,<br>    index_name=&quot;voyage_index&quot;<br>)<br></pre><p>I loaded the pdf data, split them into chunks and data is inserted into database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HUT7PSOR9nlobB3hp_DvoQ.png" /></figure><p>You can see that the embedding data is inserted as an array type. Now that data is ready in MongoDB, it’s time to create search index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*9mWJTY3Lh7nFTB4cJkk2jw.png" /></figure><p>You need to create an Atlas Vector Search index in order to implement vector search with MongoDB Atlas. Navigate to search index tab in cluster page in Atlas console, define an index name and collection to create the index on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzi6IgYdmbxNo82IhQP4iA.png" /></figure><p>I specified the dimension of the embedding data and the distance metric. After the index is created, the status of index becomes “ready” shortly.</p><pre>#connect to vector store<br>vectorstore = MongoDBAtlasVectorSearch(<br>    mdb_collection, <br>    embedding=VoyageAIEmbeddings(model=&quot;voyage-3-lite&quot;, api_key=vo_api_key),<br>    index_name = &quot;app_index&quot;,<br>    text_key = &quot;text&quot;,<br>    embedding_key = &quot;embedding&quot;<br>    )<br><br>#run vector search <br>query = &quot;What are the 4 key use cases of event-driven architecture using Atlas trigger?&quot;<br>results = vectorstore.similarity_search_with_score(<br>    query=query,<br>    k=3<br>)<br><br>#retrieve results<br>print(&quot;=============================Initial search===============================&quot;)<br>page_contents = []<br>for result, score in results:<br>    parsed_results = [{&#39;page_content&#39;: result.page_content, &#39;score&#39;: score}]<br>    page_contents.append(result.page_content)<br>    for result in parsed_results:<br>        print(result)<br>        print(&quot;====================================================================================&quot;)</pre><p>As everything is ready, it’s time to run a vector search. You can see that I specified the index name that I created earlier when initializing the vector store in the command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pb4--c6VqQjewOnRs7T_1Q.png" /></figure><p>As a result of vector search, I got 3 relevant source data points and their similarity search scores as shown in the image above. I could see that the data from the white paper was retrieved.</p><h4>2. Reranking Data</h4><pre>#rerank the result<br>rerank = vo.rerank(query, documents=page_contents, model=&quot;rerank-2-lite&quot;, top_k=3)<br>print(&quot;====================================Rerank result===================================&quot;)<br>for result in rerank.results:<br>    parsed_rerank_results = [{&#39;page_content&#39;: result.document, &#39;score&#39;: result.relevance_score}]<br>    for result in parsed_rerank_results:<br>        print(result)<br>        print(&quot;====================================================================================&quot;)</pre><p>In order to improve the accuracy of vector search in RAG architecture, re-evaluated the search results with the reranking model from VoyageAI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdGuG61ot1Y2Uu6USCmjMw.png" /></figure><p>As a result of reranking, the scores of the documents have changed. I could also check that the scores have been recalculated with the reranking model.</p><p>We could see that I was not only able to retrieve relevant results using RAG architecture built with VoyageAI embedding model, but I also able to re-evaluate the search results to improve accuracy.</p><p>The synergy between MongoDB Atlas’s diverse capabilities and VoyageAI’s powerful models opens up possibilities for more sophisticated RAG implementations. I’m eager to see what the next roadmap will bring!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e1d39c4d656" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building RAG using Bedrock, LangChain and MongoDB Atlas]]></title>
            <link>https://medium.com/@SojeongBaek/building-rag-pattern-using-bedrock-langchain-and-mongodb-atlas-a336cf56686a?source=rss-8160fa162e32------2</link>
            <guid isPermaLink="false">https://medium.com/p/a336cf56686a</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Sojeong Baek]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 07:04:12 GMT</pubDate>
            <atom:updated>2025-10-13T08:06:19.212Z</atom:updated>
            <content:encoded><![CDATA[<p>Following the last article <a href="https://medium.com/@SojeongBaek/using-pinecone-with-bedrock-knowledge-base-e86f374d13ec">introducing Pinecone as a vector store</a>, here I share how to build a RAG pattern using Bedrock, LangChain and MongoDB Atlas.</p><h3>1. Creating MongoDB Atlas Vector Search Index</h3><p>As the first step, I created a MongoDB Atlas cluster on AWS and an Atlas Vector Search index.</p><pre>{<br>  &quot;fields&quot;: [<br>    {<br>      &quot;numDimensions&quot;: 1024,<br>      &quot;path&quot;: &quot;embedding&quot;,<br>      &quot;similarity&quot;: &quot;cosine&quot;,<br>      &quot;type&quot;: &quot;vector&quot;<br>    },<br>    {<br>      &quot;path&quot;: &quot;title&quot;,<br>      &quot;type&quot;: &quot;filter&quot;<br>    },<br>    {<br>      &quot;path&quot;: &quot;year&quot;,<br>      &quot;type&quot;: &quot;filter&quot;<br>    },<br>    {<br>      &quot;path&quot;: &quot;genres&quot;,<br>      &quot;type&quot;: &quot;filter&quot;<br>    }<br>  ]<br>}</pre><p>Move to the <strong>Database page</strong> and <strong>Atlas Search tab </strong>on MongoDB console. I created an Atlas Vector Search index and defined it as above. “embedding” is the field in the collection containing the vector data. I also specified the dimension and similarity metric. Make sure to put correct numDimensions based on embedding model you use.</p><h3>2. Embedding Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*Wu00olfuCGAgJyanKSPdNQ.png" /></figure><p>I used sample_mflix.movie data provided by MongoDB.</p><pre>import config<br>from pymongo import MongoClient<br><br>client = MongoClient(config.URI)<br>db = client[&#39;sample_mflix&#39;]<br>collection = db[&#39;movies&#39;]</pre><p>In order to insert vector data into MongoDB, I created a connection to MongoDB using pymongo.</p><pre>from langchain_aws import BedrockEmbeddings<br>from langchain_aws import BedrockLLM<br><br>embedding_model = BedrockEmbeddings(<br>    model_id=&#39;amazon.titan-embed-text-v2:0&#39;,<br>    credentials_profile_name=&#39;default&#39;<br>    )</pre><p>I used Amazon Bedrock to call LLM. In order to use Bedrock base model, you need to make sure that you have access to Bedrock base model you want to use.</p><p>After I requested access to the base model, I configured my AWS CLI profile and specified the profile in the BedrockEmbeddings parameter. You can specify your profile by running aws configure and check the profiles from ~/.aws/config. Specify model id you want to use. Model ids are available in <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids.html">this link</a>.</p><pre>def get_data():<br>    temp_data = collection.find({})<br>    movie_data = list(temp_data)<br>    return movie_data<br><br>def upsert_embedding():<br>    movie_data = get_data()<br>    total = len(movie_data)<br>    print(f&quot;Processing {total} documents...&quot;)<br>    for i, data in enumerate(movie_data, 1):<br>        try:<br>            if &#39;plot&#39; in data and data[&#39;plot&#39;]:<br>                embedding=embedding_model.embed_query(data[&#39;plot&#39;])<br>                collection.update_one(<br>                    {&#39;_id&#39;: data[&#39;_id&#39;]},<br>                    {&#39;$set&#39;: {&#39;embedding&#39;: embedding}},<br>                    upsert=True<br>                )<br>                if i % 100==0:<br>                    print(f&#39;Processed {i}/{total} documents...&#39;)<br>        except Exception as e:<br>            print(f&quot;Error processing document {data[&#39;_id&#39;]}: {e}&quot;)<br>    print(&quot;Finished processing all documents!&quot;)<br>upsert_embedding()<br>print(&quot;Embedding data insertion complete!&quot;)</pre><p>Firstly, I loaded all the data from MongoDB using get_data function. Then I converted “plot” data into vectors using the embedding model that I’ve configured earlier. Seconly, I upserted the vector data back to MongoDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*sd6IVAxPRQotoCUX6gR1-w.png" /></figure><p>Here is how the data looks like with embedding field.</p><h3>3. Configuring the QA Chain and Vector Store</h3><pre>import config<br>from pymongo import MongoClient<br>from langchain_mongodb import MongoDBAtlasVectorSearch<br><br>client = MongoClient(config.URI)<br>db = client[&quot;sample_mflix&quot;]<br>collection = db[&quot;movies&quot;]<br>embedding_model = BedrockEmbeddings(<br>    model_id=&quot;amazon.titan-embed-text-v2:0&quot;,<br>    credentials_profile_name=&quot;default&quot;<br>)<br>vectorstore = MongoDBAtlasVectorSearch(<br>    collection, <br>    embedding_model,<br>    index_name = &quot;vector_index&quot;,<br>    text_key = &quot;plot&quot;,<br>    embedding_key = &quot;embedding&quot;<br>    )</pre><p>I configured MongoDB Atlas as a vector store so that LLM can refer data in vector store.</p><pre>from langchain_aws import BedrockEmbeddings<br>from langchain_aws import ChatBedrock<br>from langchain.chains import RetrievalQA<br>from langchain.prompts import PromptTemplate<br><br>prompt_template =&quot;&quot;&quot; <br>You are a movie expert. Users asks for movie recommendation.<br>Please generate answer based on the context only and do not use any general knowledge.<br>Based on the context, answer below. Answer should be less than 3 sentences.<br>1. Summary of the movie<br>2. The reason you recommend the movie.<br>Context: {context}<br>Question: {question}<br>Answer:&quot;&quot;&quot;<br><br>PROMPT = PromptTemplate(<br>    template=prompt_template,<br>    input_variables=[&quot;context&quot;, &quot;question&quot;]<br>)<br>llm = ChatBedrock(model_id=&quot;anthropic.claude-3-5-sonnet-20240620-v1:0&quot;)<br>qa = RetrievalQA.from_chain_type(<br>    llm = llm,  <br>    chain_type = &quot;stuff&quot;,<br>    retriever = vectorstore.as_retriever(<br>        search_kwargs = {&quot;k&quot;: 1}<br>        ),<br>        chain_type_kwargs = {&quot;prompt&quot;: PROMPT},<br>        return_source_documents = True<br>    )<br>def get_response(input_text):<br>    temp_res = qa.invoke({&quot;query&quot;: input_text})<br>    title = temp_res[&#39;source_documents&#39;][0].metadata[&#39;title&#39;]<br>    response = temp_res[&#39;result&#39;]<br>    return title, response</pre><p>As prompts can play an import role to get a relevant response, I defined a prompt using PromptTemplate and created RetrievalQA.</p><h3>4. Asking Questions!</h3><pre>import streamlit as st <br><br>st.markdown(&quot;&lt;h1 style=&#39;text-align: center;&#39;&gt;MongoDB Atlas Vector Search&lt;/h1&gt;&quot;, unsafe_allow_html=True)<br>st.markdown(&quot;&lt;h1 style=&#39;text-align: center;&#39;&gt;Demo Webpage 🍃&lt;/h1&gt;&quot;, unsafe_allow_html=True)<br>st.markdown(&quot;&lt;br&gt;&lt;br&gt;&quot;, unsafe_allow_html=True)<br><br>input_text = st.text_area(&quot;Input text&quot;, label_visibility=&quot;collapsed&quot;)<br>go_button = st.button(&quot;Go&quot;, type=&quot;primary&quot;)<br><br>if go_button:<br>    title, response = get_response(input_text)<br>    st.write(title)<br>    st.write(response)</pre><p>Lastly, I created a simple webpage using streamlit to submit and retrieve question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3MiKy-RIwfj5RvtB2tj-Bw.png" /></figure><p>In the webpage, when I asked a question, LLM referenced the data from the vector store.</p><p>Using MongoDB Atlas Vector Search, creating LLM application using your own knowledge base makes it easier then ever!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a336cf56686a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Pinecone with Bedrock Knowledge Base]]></title>
            <link>https://medium.com/@SojeongBaek/using-pinecone-with-bedrock-knowledge-base-e86f374d13ec?source=rss-8160fa162e32------2</link>
            <guid isPermaLink="false">https://medium.com/p/e86f374d13ec</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[pinecone]]></category>
            <category><![CDATA[bedrock]]></category>
            <dc:creator><![CDATA[Sojeong Baek]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 11:14:34 GMT</pubDate>
            <atom:updated>2024-03-23T06:52:05.758Z</atom:updated>
            <content:encoded><![CDATA[<p>As the Gen-AI era has emerged, vector databases have gained prominence as well. Hallucination — providing wrong information that appeared to be plausible — is a commonly faced issue when it comes to generative AI applications.</p><p>By storing relevant data in a vector database and having a large language model (LLM) generate answers based on this data, users can receive more accurate responses based on their data.</p><p>Pinecone is a managed vector database on the cloud. You can easily save and query vector data in Pinecone. If you have data pipeline deployed in AWS and simply want to expand this pipeline to Generative AI, you can simply connect to Pinecone from AWS data services such as SageMaker, Glue notebook etc.</p><p>Here I will show you how you can use Pinecone for RAG and how Bedrock Knowledge base can simplify the same process.</p><h3><strong>Use Pinecone with Jupyter Notebook</strong></h3><p>I created a SageMaker notebook instance and made sure that the IAM role has permission to access S3. If SageMaker is located in private subnet, private endpoint is required. I launched the instance in public subnet as it’s just for simple test. When the proper permission is granted to the IAM role that is attached to SageMaker, we are good to go.</p><pre>!pip3 install awswrangler<br>import awswrangler as wr<br><br>df = wr.s3.read_csv(&quot;s3://test/pinecone/articles1.csv&quot;)</pre><p>I used AWS wrangler to read data from S3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GTC-NR7chjYsiElkWh6ohw.png" /></figure><p>Here is a sneak peek at the data that I downloaded from Kaggle. The data contains diverse articles covering different domains. If you want to insert data into Pinecone, the ‘id’ and ‘values’ columns are required.</p><pre>#import necessary libraries<br>!pip3 install sentence_transformers<br><br>from sentence_transformers import SentenceTransformer<br>model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;, device = &#39;cpu&#39; )<br><br>#prepare values data to insert<br>df[&#39;content&#39;] = df[&#39;content&#39;].map(lambda x: (model.encode(x)).tolist())<br>df = df.rename(columns={&#39;content&#39;:&#39;values&#39;})</pre><p>The data to insert into vector database should be in vector format. After I chose a model for vector embedding, I converted the ‘content’ column into a vector and renamed it to ‘values’ using the embedding model.</p><pre>#prepare metadata to insert<br>df[&#39;metadata&#39;] = df[&#39;content&#39;].str[:500]<br>df[&#39;metadata&#39;] = df.apply(lambda x: {<br>    &#39;content&#39;: x[&#39;metadata&#39;],<br>}, axis = 1)<br><br>#prepare id to insert<br>df[&#39;id&#39;] = df[&#39;Unnamed: 0&#39;]<br>df[&#39;id&#39;] = df[&#39;id&#39;].map(lambda x:str(x))<br><br>#prepare final data to insert<br>df_upsert = df[[&#39;id&#39;, &#39;values&#39;,&#39;metadata&#39;]]</pre><p>Besides the necessary data, I wanted to add metadata so that I can have better view for the query response. As metadata has to be in dictionary format, I added a ‘metadata’ column in dictionary format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ocTJHNsI7PlAQ1W5E9eunw.png" /></figure><p>Now the ‘id’, ‘values’ and ‘metadata’ columns are ready. This is how my data looks like after all the processing.</p><pre>pc = Pinecone(api_key = &quot;${api key}&quot;)<br>pc.create_index(<br>                name = &quot;news-index&quot;, <br>                dimension = 384,<br>                metric = &quot;cosine&quot;,<br>                spec = PodSpec(<br>                    environment = &quot;gcp-starter&quot;<br>                )<br>               )<br>idx = pc.Index(&#39;news-index&#39;)<br></pre><p>I created a Pinecone index and the object. An index in Pinecone is a collection of vectors and similar to a table in RDB. I created a Pinecone index and specified a metric. There are three metrics provided from Pinecone — Euclidean, cosine and dot products. As I’ll query vector data to retrieve relevant data, I chose cosine as the metric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HZXAGdyFA_v4SN_fW3Zysg.png" /></figure><p>I could check the newly created index from the Pinecone console.</p><pre>idx.upsert_from_dataframe(df_upsert)</pre><p>Now it’s time to upsert data into Pinecone index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AOFaFJDi5TRhdD213J3zug.png" /></figure><p>The data is all upserted into the Pinecone index.</p><pre>res = idx.query(vector = (model.encode(&quot;Tell me about USA president in 2017.&quot;)).tolist(), ##it has to be list <br>               top_k=10, include_metadata=True)</pre><p>We’re almost there! I couldn’t wait to run query. The query also needs to be converted into a vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtxiWgF3arp6yEXNLBXuWQ.png" /></figure><p>And here I got the result, which is relevant article title to my question.</p><p>So this is how you do vector embedding, upsert the vectors into a vector database, and finally query the vectors from the database.</p><h3>Use Pinecone with Bedrock Knowledge Base</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*kRZn72m_ucfK3GwEan53fA.png" /></figure><p>You could see that vector embedding and query isn’t as difficult as it sounds. BUT, with Bedrock Knowledge Base, it makes it even easier. Now let’s see how we can use Pinecone with Bedrock Knowledge Base.</p><p>Before we start creating <strong>Knowledge Base</strong>, we need to create a new secret in <strong>Secrets Manager </strong>so that it has the API key to access Pinecone safely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmm5_VPMZgrRBXRfKCUUVQ.png" /></figure><p>Choose<strong> Other type</strong> for Secret type and set ‘apiKey’ as the key. Fill your Pinecone api key in the value box. After giving a name, leave everything as default and create the Secret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eLDdjQOKVl88xFObCmmolg.png" /></figure><p>This<strong> Secret ARN</strong> is required when creating Bedrock Knowledge Base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11CA8cfeiLSXplT0wGjn6g.png" /></figure><p>And now it’s time to create the Knowledge Base. First move to<strong> Knowledge Base</strong> tab in <strong>Amazon Bedrock </strong>page and create a Knowledge Base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFMSiQhFWzmVKoRNauuSkg.png" /></figure><p>I gave a name for the Knowledge Base and granted permissions. It requires three main permissions — read from S3, invoke the Bedrock model and get the value from Secrets Manager. Alternatively, you can simply create a new role through the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9us73H_24Qht94UlTZRJVg.png" /></figure><p>I specified the S3 path where the data to be inserted into vector database is located in <strong>S3 URL </strong>field<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7FoLv3_F2XWu7yQRy2WcA.png" /></figure><p>In this step, I chose a model and vector database to use. I filled in Pinecone index host in <strong>Endpoint URL</strong> box and Secrets ARN in <strong>Credentials secret ARN</strong> box that I got earlier.</p><p>The <strong>Text field </strong>requires field name which needs to be converted in to a vector and queried.</p><p>After reviewing all the configuration, I created Knowledge Base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CgQtWpJGW9XRwrRx1_0glQ.png" /></figure><p>When the Knowledge base is created, click the <strong>Sync </strong>button to write data from S3 to the vector database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWWcdB9cxRO12O4TAOwQvg.png" /></figure><p>Voilà! After syncing is completed, I asked a simple question, and it responded based on the data I provided. My question was ‘What happened in USA in 2017?’ and it responded, ‘Donald Trump was inaugurated as the 45th President of the United States on January 20, 2017.’</p><p>With Knowledge base, it handles converting and upserting vectors into the database. It makes the whole process ofconfiguring vector database much easier.</p><h4><strong>Errors You May Encounter</strong></h4><pre>The knowledge base storage configuration provided is invalid… The vector database encountered an error while processing the request.</pre><p>When I tried to create the Knowledge Base, it kept showing me the error above. Turns out it was dimensions mismatch. My Pinecone vector index had 384 dimensions as it used <strong>all-MiniLM-L6-v2 </strong>embedding model and <strong>Titan Embeddings G1</strong> creates 1536 dimensions. After recreating the index with proper dimensions, Knowledge Base was successfully created.</p><p>AI applications are powerful yet versatile tools that can significantly improve work efficiency. As many experts advise, we should embrace and learn to effectively utilize these technologies. In line with this trend, a growing number of tools like Bedrock are becoming available, enabling us to harness the potential of AI and integrate it seamlessly into our workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e86f374d13ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>