<?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">
  <channel>
    <title><![CDATA[Udayasimha Theepireddy - Elasticsearch Labs]]></title>
    <description><![CDATA[Articles and tutorials from the Search team at Elastic]]></description>
    <copyright><![CDATA[© 2026. Elasticsearch B.V. All Rights Reserved]]></copyright>
    <image>
      <title><![CDATA[Udayasimha Theepireddy - Elasticsearch Labs]]></title>
      <url>https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt1121c0bf0e8a6e65/6a88da6340a1841030ef456f/search-labs-thumbnail.png</url>
      <link>https://www.elastic.co/search-labs/author/udayasimha-theepireddy</link>
    </image>
    <link>https://www.elastic.co/search-labs/author/udayasimha-theepireddy</link>
    <atom:link href="https://www.elastic.co/search-labs/rss/author/udayasimha-theepireddy.xml" rel="self" type="application/rss+xml"/>
    <language><![CDATA[en]]></language>
    <lastBuildDate>Fri, 18 Sep 2026 17:51:26 GMT</lastBuildDate>
  <item>
    <title><![CDATA[Transforming data interaction: Deploying Elastic’s MCP server on Amazon Bedrock AgentCore Runtime for crafting agentic AI applications]]></title>
    <description><![CDATA[Transform complex database queries into simple conversations by deploying Elastic's search capabilities on Amazon Bedrock AgentCore Runtime platform.]]></description>
    <content:encoded><![CDATA[<p>Imagine asking your data questions in plain English: "Fitness/diet recommendations based on my health goals," or "Help find investment opportunities based on my risk level?" and getting accurate answers without writing a single query. Today, we'll explore how to achieve this by deploying Elastic's <a href="https://www.anthropic.com/news/model-context-protocol">Model Context Protocol</a> (MCP) server on <a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-how-it-works.html">Amazon Bedrock AgentCore Runtime</a>, creating a powerful bridge between conversational AI and your data.</p><p>At its core, this solution combines the power of Elasticsearch's search capabilities with Amazon's serverless AI infrastructure. Here's how it works:</p><ul><li><p>Your natural language questions are processed through the MCP server that is deployed on Amazon Bedrock AgentCore Runtime</p></li><li><p>The MCP server translates these questions into precise Elasticsearch queries</p></li><li><p>Results are returned in human-readable format, making your data instantly accessible</p></li><li><p>All of this happens in a secure, scalable environment that's production-ready, deployed on Amazon Bedrock AgentCore Runtime</p></li></ul><p>In this blog post, we'll explore how to:</p><ul><li><p>Deploy Elastic's MCP server on Amazon Bedrock AgentCore Runtime</p></li><li><p>Transform local MCP prototypes into production-ready solutions</p></li><li><p>How to Build Conversational Interfaces on top of Elasticsearch</p></li><li><p>Implement secure, scalable AI agent architectures</p></li></ul><h2>Background</h2><h3>Model Context Protocol (MCP)</h3><p>MCP is an open protocol that revolutionizes how businesses interact with their data through AI. Unlike traditional Retrieval-Augmented Generation (RAG) systems that simply retrieve documents, MCP enables AI agents to dynamically construct and execute complex tasks in real-time, mirroring the flexibility of human problem-solving</p><p>In practice, this means a business analyst can ask a series of increasingly specific questions about market trends, and the MCP-powered system will intelligently select and combine the appropriate data sources and analytical tools to provide comprehensive answers, while still maintaining context, allowing for follow-up questions without repetition.</p><p>For instance, when analyzing a product launch, the AI might integrate data from sales reports, customer feedback, and social media sentiment, orchestrating multiple tools simultaneously to provide a holistic view, thus enabling businesses to uncover deeper insights and make informed decisions, all through natural language interactions with their data systems.</p><h3>Agents</h3><p>Agents are AI-powered software applications that can think, plan, and act to achieve specific goals with minimal human supervision. They use foundation models (advanced AI models) to understand and complete complex tasks.</p><p>There are two types of AI agents.</p><p><strong>Knowledge AI agents</strong></p><p>These agents focus on enterprise knowledge. They gather context from company data — documents, logs, dashboards, communications, and customer records — and use that information to complete business tasks.</p><p><em>Example: A knowledge AI agent that can search across contracts, policies, and past tickets to help a customer support representative instantly resolve an issue.</em></p><p><strong>General AI agents</strong></p><p>These agents go further. They can understand goals and autonomously execute tasks on behalf of a user in broader, cross-domain workflows.</p><p><em>Example: A general AI agent that books travel, manages schedules, and negotiates with other systems to complete a user’s request end-to-end.</em></p><h3>Elastic’s role in agentic AI</h3><p><strong>For knowledge AI agents</strong>: Elastic enables secure access to enterprise data, retrieves relevant context, and grounds responses in facts.</p><p><strong>For general AI agents</strong>: Elastic serves as the knowledge store and context engine, providing trusted information so agents can perform more complex, goal-driven tasks.</p><p>In short, Elastic isn’t just storing data; it’s making enterprise knowledge usable, actionable, and AI-ready. This is the foundation for building intelligent agents that both understand and act.</p><h3>AWS partnership and MCP server</h3><p>Elastic has earned the AWS Generative AI Competency status. This recognition is awarded to AWS partners who deliver cutting-edge generative AI solutions that drive measurable gains in business efficiency, creativity, and productivity</p><p>Elastic also integrates with the Model Context Protocol (MCP), providing a seamless way for AI agents and applications to interact with Elasticsearch data through natural language conversations.</p><p>With the MCP server, you can connect to Elasticsearch directly from any MCP client — such as Claude Desktop, MCP Inspector, or an agentic application. The Elasticsearch MCP server is free to use (though infrastructure and Elasticsearch cluster costs may apply).</p><p>And with Amazon Bedrock models (such as Anthropic’s Claude) supporting MCP clients, organizations can now deploy intelligent, data-aware agents more easily and powerfully than ever before.</p><h3>Amazon Bedrock AgentCore</h3><p><a href="https://aws.amazon.com/bedrock/agentcore/?trk=e61dee65-4ce8-4738-84db-75305c9cd4fe&amp;sc_channel=el">Amazon Bedrock AgentCore</a> is an enterprise-grade orchestration platform designed for scalable AI agent deployment and management. </p><ul><li><p>The platform provides serverless runtime environments with session isolation capabilities, enabling concurrent agent operations across multiple frameworks.</p></li><li><p>It implements memory management systems for both session-state and persistent storage, facilitating context-aware model interactions and learning capabilities.</p></li><li><p>The architecture includes observability features with granular logging, metrics collection, and advanced debugging capabilities for agent trajectory analysis.</p></li><li><p>The platform's robust identity and access management layer enables secure service-to-service authentication and fine-grained authorization controls for AWS and third-party service integrations.</p></li></ul><p>It features a protocol-agnostic gateway for API transformations and tool discovery, supporting MCP-compliant interfaces. The infrastructure also includes containerized browser instances for web automation workflows and isolated compute environments for secure code execution. This end-to-end solution eliminates the need for building custom infrastructure components while maintaining enterprise security and compliance standards.</p><h2><strong>Solution overview</strong></h2><h3><strong>High-level architecture</strong></h3><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltb55c578d65fd5085/6a17f3046864a47abeb688cc/40812bd3424c21232c6d03e24b74e01034ab2c76-1600x503.png" alt="" /><p>The architecture consists of four main components:</p><ol><li><p><strong> Python client: </strong>Handles user interactions and AWS authentication</p></li><li><p><strong>Amazon Bedrock</strong> AgentCore Runtime: Provides serverless hosting and session management</p></li><li><p><strong>Elastic MCP server</strong>: Processes MCP protocol requests and queries Elasticsearch</p></li><li><p><strong>Elasticsearch cluster</strong>: Stores and indexes the searchable data</p></li></ol><h3>Step-by-step workflow walkthrough</h3><ol><li><p>User authenticates using an authentication mechanism such as OAuth.</p></li><li><p>User access secured Client application running in a Customer AWS account using authenticated credentials.</p></li><li><p>The client application invokes a Supervisor Agent that further invokes and orchestrates other Agents.</p></li><li><p>All the agents are deployed on Amazon AgentCore Runtime and their tools are made available for the Agents, including Elastic’s MCP server and its tools.</p></li><li><p>Foundation Models are available for the agentic AI application through Amazon Bedrock.</p></li><li><p>Elastic Cloud is deployed on AWS and its endpoints are accessed by the Elastic MCP Server. Elastic MCP server automatically crafts the required queries, runs the queries against the Elastic data and fetches the response back to the Supervisor Agent.</p></li><li><p>Supervisor Agent responds back to the end user via the Client Application.</p></li></ol><h2>Implementation guide</h2><p>Please refer to <a href="https://github.com/aws-samples/aws-generativeai-partner-samples/tree/main/elastic/mcp/elastic-mcp-on-agentcore">this GitHub repo</a> to get a hands-on experience of how this solution can be implemented. Pay close attention to the <a href="https://github.com/aws-samples/aws-generativeai-partner-samples/tree/main/elastic/mcp/elastic-mcp-on-agentcore#-prerequisites">prerequisites</a> before getting started.</p><h3>Step 1: Deploy Elastic MCP server to ECR</h3><p>The <a href="https://github.com/aws-samples/aws-generativeai-partner-samples/blob/main/elastic/mcp/elastic-mcp-on-agentcore/deploy-elastic-mcp.sh">automated deployment script</a> handles the entire container build and upload process:</p>./deploy-elastic-mcp.sh<p>Here is what the script does when you execute:</p><ol><li><p>Downloads the official Elastic MCP server repository</p></li><li><p>Builds Docker container using <code>Dockerfile-8000</code></p></li><li><p>Creates ECR repository with image scanning enabled</p></li><li><p>Uploads container image to ECR with proper tagging</p></li></ol><h3>Step 2: Create AgentCore Runtime host</h3><p>Navigate to the AWS Console and configure your AgentCore Runtime:</p><p>1. Access AgentCore: Go to Amazon Bedrock AgentCore &gt; Build and Deploy &gt; Agent Runtime &gt; Host Agent</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt4750c7fd2c1cdc5c/6a17f3062f4a5c7105fa8a1a/6818bafc00fdcba4c311b8ea1199c3d4ba9e979c-1428x396.png" alt="" /><p>2. Basic configuration: Click on “Host Agent” and give it a meaningful name if you prefer. Point to the Container Image you have uploaded to Amazon ECR.</p>   Name: hosted_agent_elastic_mcp
   Container Image: [ECR URI from Step 1]
<img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt22fa13daf65713e3/6a17f30896142a918aeb1c29/beea587f4d1c022216c03f8f2895072c7075c1aa-1600x654.png" alt="" /><p>3. Service role: Choose "Create and use a new service role"</p><p>4. Protocol settings: Choose MCP, and for the Inbound Identity, select <code>Use IAM username</code></p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltc4e24abbc56b21b2/6a17f309414c647a149452a9/a0cc50ebdfaf657cb2a5fbb0e60f1b5b45aa60fe-1600x505.png" alt="" /><p>5. Environment variables: Finally, configure your Elasticsearch endpoints and pass them as environment variables to your Docker container.</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltdec0c051b141511c/6a17f30b414c6499b59452ad/b3c1e97513b516bf5604c87950811a444b93745e-1432x358.png" alt="" /><p>6. After creating the host agent, go ahead and copy the Agent Runtime ARN from the "View invocation code" section. Here is an example:</p>arn:aws:bedrock-agentcore:us-west-2:XXXXXXXXXX:runtime/hosted_agent_elastic_mcp-xWSaxNGjf5<img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blte88f4a7205373342/6a17f30d96142a177feb1c2d/27330cf1d735d1240f4ce292f032d0a22cf6d986-1600x651.png" alt="" /><h3>Step 3: Configure Python client</h3><p><strong>Install dependencies:</strong></p><p>Go ahead and initialize a virtual environment and install the Python libraries.</p>python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt<p>Update Agent ARN in <code>my_mcp_client_remote.py</code>:</p><p>Next, update the Python MCP client with the agent ARN you obtained in the previous steps.</p>agent_arn = "arn:aws:bedrock-agentcore:us-west-2:XXXXXXXX:runtime/hosted_agent_elastic_mcp-xWSbYNGjf5"<p>Here are the key client components in this Python file.</p><p><strong>AWS authentication class:</strong></p>class AWSAuth:
    def __init__(self, service='bedrock-agentcore', region='us-west-2'):
        self.session = boto3.Session()
        self.credentials = self.session.get_credentials()
        self.region = region
        self.service = service
        
    def get_auth_headers(self, url, method='POST', body=None):
        request = AWSRequest(method=method, url=url, data=body)
        SigV4Auth(self.credentials, self.service, self.region).add_auth(request)
        return dict(request.headers)<p><strong>MCP request formation / payload:</strong></p>chat_request = {
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
        "name": "search",
        "arguments": {
            "index": "events",
            "query_body": {
                "query": {
                    "bool": {
                        "should": [
                            {"match": {"name": "paris"}},
                            {"match": {"description": "paris"}},
                            {"match": {"venue": "paris"}},
                            {"match": {"address": "paris"}}
                        ]
                    }
                },
                "size": 10
            }
        }
    }
}<h3>Step 4: Run the client</h3><p>Execute the <a href="https://github.com/aws-samples/aws-generativeai-partner-samples/blob/main/elastic/mcp/elastic-mcp-on-agentcore/my_mcp_client_remote.py">Python client</a> to test the integration. This Python program implements an asynchronous client for interacting with Amazon Bedrock AgentCore, specifically designed to query event information. The code utilizes AWS SigV4 authentication and consists of two main functions: <code>test_mcp_endpoint()</code> and <code>chat_with_agentcore()</code>. The first function demonstrates basic API interaction by listing available tools and performing a search query, while the second function implements a more sophisticated search functionality specifically for events in Paris.</p><p>The program uses the <code>httpx</code> library for async HTTP requests and handles Server-Sent Events (SSE) responses, parsing and displaying event details including names, venues, dates, and descriptions. The authentication is managed through a custom <code>AWSAuth</code> class that handles AWS SigV4 signing of requests. The code includes comprehensive error handling and formatted output display, making it suitable for both testing and production use cases.</p>python my_mcp_client_remote.py<h2>Use case demonstrations</h2><h3>Use case 1: Data discovery</h3><p>Scenario: Finding events in a specific city using natural language.</p><p>Query: "Events in Paris"</p><p>MCP request: Here is the payload you supply to the Amazon Bedrock Agentcore Runtime.</p>{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "search",
    "arguments": {
      "index": "events",
      "query_body": {
        "query": {
          "bool": {
            "should": [
              {"match": {"name": "paris"}},
              {"match": {"description": "paris"}},
              {"match": {"venue": "paris"}},
              {"match": {"address": "paris"}}
            ]
          }
        }
      }
    }
  }
}<p><strong>Response</strong>: And here is the response you get after Elastic’s MCP server runs a query in Elastic Search AI Platform and returns the result.</p>🎉 I found 1 events in Paris:


1. Paris Fashion Week
   📍 Murray-Howell Theater - 17814 Mills Mountains Apt. 815, Poncetown, DE 29241
   📅 2026-04-02
   📝 Major fashion event showcasing the latest collections from top designers.
   💰 $$$
   🎫 https://tickets.reed.net/event/DEST0001_EVT002<h3>Use case 2: Elastic MCP tool discovery</h3><p><strong>Scenario</strong>: Discovering the available MCP tools that Elastic’s MCP server offers.</p><p><strong>MCP request:</strong></p>{
  "jsonrpc": "2.0",
  "method": "tools/list",
  "id": 1
}<p>This returns a list of available tools that the MCP server provides, enabling dynamic tool discovery.</p><h3>Use case 3: Complex search queries</h3><p><strong>Scenario</strong>: Advanced filtering with multiple criteria.
You can run more advanced Elastic Search Query Language based queries, like one shown below.</p><p><strong>Query</strong>: Events with specific price ranges, dates, and categories.</p><p><strong>MCP request:</strong></p>{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "search",
    "arguments": {
      "index": "events",
      "query_body": {
        "query": {
          "bool": {
            "must": [
              {"range": {"start_date": {"gte": "2026-01-01"}}},
              {"term": {"price_range": "$$$"}}
            ],
            "should": [
              {"match": {"type": "Fashion"}},
              {"match": {"type": "Music"}}
            ]
          }
        },
        "size": 20
      }
    }
  }
}<h2>How it works (technical deep dive)</h2><h3>MCP implementation</h3><p>The Model Context Protocol uses JSON-RPC 2.0 format for all communications:</p>Client Request → AgentCore → MCP Server → Elasticsearch → Response Chain<p><strong>Key protocol features:</strong></p><ul><li><p>Stateless operation: Each request is independent with session isolation</p></li><li><p>Tool discovery: Dynamic discovery of available capabilities</p></li><li><p>Structured responses: Consistent response format across all tools</p></li><li><p>Error handling: Standardized error reporting and recovery</p></li></ul><p><strong>AWS authentication flow:</strong></p># 1. Create AWS request object
request = AWSRequest(method='POST', url=mcp_url, data=body)


# 2. Apply SigV4 authentication
SigV4Auth(credentials, 'bedrock-agentcore', region).add_auth(request)


# 3. Extract headers for HTTP client
headers = dict(request.headers)
headers["Content-Type"] = "application/json"
headers["Accept"] = "application/json, text/event-stream"<h3>Session management</h3><p>AgentCore automatically adds <code>Mcp-Session-Id</code> headers for session isolation:</p><ul><li><p>Each client session gets a unique identifier</p></li><li><p>Stateless servers can maintain conversation context</p></li><li><p>Automatic cleanup of inactive sessions</p></li></ul><h3>Response processing pipeline</h3><ol><li><p>Server-Sent Events (SSE): Responses come as <code>data: {...}</code> in JSON format</p></li><li><p>JSON parsing: Extract JSON from SSE wrapper</p></li><li><p>Content extraction: Parse the MCP result structure</p></li><li><p>Data formatting: Convert Elasticsearch results to user-friendly format</p></li></ol># Parse SSE response
if response.text.startswith('data: '):
    json_part = response.text[6:]  # Remove 'data: ' prefix
    response_json = json.loads(json_part)
    
    # Extract search results
    result = response_json.get('result', {})
    for content_item in result['content']:
        if content_item['type'] == 'text':
            # Process and format results
            search_results = json.loads(content_item['text'])<h3>Cleanup</h3><p>After you have played around with this setup, if you would like to clean up the environment, please follow the steps outlined below.</p><p><strong>Delete AgentCore Runtime:</strong></p><ol><li><p>Navigate to Amazon Bedrock AgentCore in AWS Console</p></li><li><p>Select your agent runtime</p></li><li><p>Click "Delete" and confirm</p></li></ol><p><strong>Remove ECR repository:</strong></p>aws ecr delete-repository \
    --repository-name elastic-mcp-server \
    --region us-west-2 \
    --force<p><strong>Clean local environment:</strong></p># Remove virtual environment
deactivate
rm -rf venv

# Remove cloned repository
rm -rf mcp-server-elasticsearch

# Remove Docker images
docker rmi elastic-mcp-server:latest
docker rmi [ECR_URI]:latest<h2>Conclusion</h2><p>By deploying Elastic's MCP server on Amazon Bedrock AgentCore Runtime, we've created a powerful, scalable, production-ready solution for natural language interaction with Elasticsearch data. This implementation opens up new possibilities for data exploration and analysis, making complex queries accessible through simple conversations.</p><p>Key takeaways include:</p><ul><li><p>Seamless integration: MCP protocol enables natural language querying of complex data</p></li><li><p>Production scalability: AgentCore provides enterprise-grade hosting with minimal configuration</p></li><li><p>Developer productivity: Transform local prototypes to production with minimal code changes</p></li><li><p>Security first: Built-in AWS security and authentication mechanisms</p></li></ul><p>Potential applications can be in any of the following areas of implementation: </p><ul><li><p>Customer support: Natural language querying of support ticket databases</p></li><li><p>Business intelligence: Conversational analytics for business metrics</p></li><li><p>Content discovery: Intelligent search across document repositories</p></li><li><p>IoT data analysis: Natural language queries for sensor and telemetry data</p></li></ul><p>Additional resources:</p><ul><li><p><a href="https://www.elastic.co/docs/api/doc/elasticsearch/operation/operation-inference-put-amazonbedrock">Amazon Bedrock integration documentation</a></p></li><li><p><a href="https://github.com/elastic/mcp-server-elasticsearch?tab=readme-ov-file#elasticsearch-mcp-server">Elastic MCP server documentation</a></p></li></ul>]]></content:encoded>
    <link>https://www.elastic.co/search-labs/blog/elastic-mcp-server-amazon-bedrock-agentcore-runtime</link>
    <guid isPermaLink="true">https://www.elastic.co/search-labs/blog/elastic-mcp-server-amazon-bedrock-agentcore-runtime</guid>
    <category><![CDATA[AI]]></category>
    <dc:creator><![CDATA[Udayasimha Theepireddy,Srinivas Pendyala,Matt Ryan,Ganesh Ramesh Shenoy]]></dc:creator>
    <enclosure url="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt576d87464937da1e/6a17f30e0b0bed0469dd36b1/7086754859ba2cbbaf673c843013462892738c30-720x420.jpg" length="0" type="image/jpeg"/>
    <pubDate>Thu, 04 Sep 2025 00:00:00 GMT</pubDate>
  </item>
  <item>
    <title><![CDATA[Retrieval Augmented Generation (RAG) using Cohere Command model through Amazon Bedrock and domain data in Elasticsearch]]></title>
    <description><![CDATA[Learn how to implement Retrieval Augmented Generation (RAG) using Cohere Command model via Amazon Bedrock &amp; domain data in Elasticsearch.]]></description>
    <content:encoded><![CDATA[<p><strong>Generative AI</strong> is a type of Artificial Intelligence (AI) that can create new content and ideas, including conversations, stories, images, videos, and music. Like all AI, generative AI is powered by Machine Learning (ML) models—very large models that are pre-trained on vast corpora of data and commonly referred to as Foundation Models (FMs).</p><p>To the public, generative AI has seemingly appeared from nowhere. But if you dig deeper, you’ll note that the ideas underlying generative AI solutions trace their lineage back to inventions such as the Mark I perceptron in 1958 and neural networks in the late twentieth century.</p><p>Advancements in statistical techniques, the vast growth of publicly available data and advancements in Machine Learning (specifically the invention of the transformer-based neural network architecture) have led to the rise of models that contain billions of parameters or variables. To give a sense for the change in scale, the largest pre-trained model in 2019 was 330M parameters. Cohere's Command XL model, one of the leading models in Stanford’s <a href="https://crfm.stanford.edu/helm/latest/">Holistic Evaluation of Language Models (HELM) benchmark</a> is trained on 52.4 billion parameters - ~1580x increase in size in just a few years.</p><p><strong>Foundation Models (FMs)</strong> are ML models trained on massive quantities of structured and unstructured data, which can be fine-tuned or adapted for more specific tasks.</p><p><strong>Large Language Models (LLMs)</strong> are a subset of FMs focused on understanding and generating human-like text. These models are ideal for needs such as translation, answering questions, summarizing information, and creating or identifying images.</p><p><strong>LLMs</strong> can perform a wide range of tasks that span multiple domains, like writing blog posts, solving math problems, engaging in dialog, and answering questions based on a document. The size and general-purpose nature of FMs make them different from traditional ML models, which typically perform specific tasks, like analyzing text for sentiment, classifying images, and forecasting trends.</p><p>The primary goal of LLMs is to enable meaningful and engaging conversation between humans and machines and have become an immensely effective resource in countless industries, helping business to improve the customer experience.</p><h2>Limitations of LLMs</h2><p>LLMs have certain limitations. One notable constraint is that they are trained on general domain corpora, making them less effective on domain-specific tasks. There are scenarios when you want models to generate text based on specific data rather than generic data. For example, a health service provider company may want their chatbot to answer questions using the latest information stored in an enterprise document repository, so that the answers are specific to the health service provider’s business.</p><p>Also, these LLMs are trained offline until a <strong>knowledge cutoff date</strong>. It will be agnostic of any developments that have happened after the knowledge cutoff date. This may lead to inaccurate interpretations. For example, in 2021 San Francisco was the most expensive Bay Area City for renters. Today, it is Mountain view - <a href="https://www.nbcbayarea.com/news/local/south-bay/mountain-view-rent-report/3152054/#:~:text=A%20new%20report%20shows%20Mountain,almost%20always%20been%20San%20Francisco.">source</a>.</p><h2>Approaches to enhance LLMs</h2><p>There are two popular ways to reference contextual data in LLMs.</p><p>The first option is to <strong>fine-tune</strong> the base LLMs with contextual data. But, using this approach generating the correctly formatted information is time consuming. Also, it is costly to fine-tune a model. In addition to that, if the domain specific data is changing frequently, it would require frequent fine-tunings and retraining to provide accurate responses. This impacts time to market and also increases overall cost of the solution. In addition to that, not all LLMs provide an option to fine-tune.</p><p>To overcome these constraints, we can use a technique called <strong>Retrieval Augmented Generation (RAG)</strong>. RAG is a process in which the model retrieves contextual documents from an external data source like Elasticsearch as part of its execution. These contextual documents are used in conjunction with the original input to produce an output.</p><p>Below are a few examples of how RAG can be used in various applications to improve the quality and relevance of generated content.</p><ul><li><p><strong>Chatbot responses</strong>: In a chatbot system, RAG refers to combining a retrieval-based approach with a generative model. The retrieval component obtains relevant responses from a pre-defined database or knowledge base, while the generative model can add additional context or generate more fluent and diverse responses. This combination helps the chatbot provide more accurate and contextually appropriate answers to user queries.</p></li><li><p><strong>Content generation</strong>: RAG can be used in content generation tasks such as summarization or paraphrasing. The retrieval component can retrieve relevant sentences or paragraphs from existing documents or articles, and the generative model can then augment or rephrase the retrieved content to create new and original summaries or paraphrases.</p></li><li><p><strong>Recommendation systems</strong>: RAG can also be applied in recommendation systems. The retrieval component can retrieve a set of candidate items or products based on user preferences or history, and the generative model can then generate personalized recommendations or provide additional information about the recommended items to enhance the user’s decision-making process.</p></li></ul><h2>RAG using Elasticsearch and Cohere Command model through Amazon Bedrock</h2><h3>Why Cohere?</h3><p><a href="https://cohere.com/">Cohere</a> is the leading AI platform for enterprise. The company builds world-class LLMs that allow computers to search, understand meaning, and converse in text. Cohere's models are uniquely suited to the needs of business, providing ease of use and strong security and privacy controls across multiple deployment options. Companies can use the models out-of-the-box or tailor them to their particular needs using their own custom data.</p><p><a href="https://cohere.com/models/command">Command </a>is Cohere’s flagship text generation model. It is trained to follow user commands and to be instantly useful in practical business applications, such as text generation, summarization, RAG, and chat. Command ranks as one of the leading language models according to the <a href="https://crfm.stanford.edu/helm/latest/?group=core_scenarios">Stanford’s HELM website</a> an evaluation leaderboard comparing large language models on a wide number of tasks from Stanford University (March 2023 results). Customers can use Cohere's Command LLM through <a href="https://aws.amazon.com/sagemaker/jumpstart/?p=pm&amp;c=sm&amp;z=2">Amazon SageMaker Jumpstart</a> and Amazon Bedrock.</p><p><a href="https://cohere.com/embed">Embed</a> is Cohere’s representative model which translates text into numerical vectors that models can understand. Cohere provides industry-leading English and multilingual models (100+ languages) for a range of use cases, including semantic search, text classification, and semantic engine for RAG.</p><h3>Why Elasticsearch?</h3><p>To make the most of generative AI, it is essential to have a unified data platform where the organization's data is stored, making it easily (and safely) accessible and searchable in one centralized location.</p><p><a href="https://www.elastic.co/?utm_campaign=B-Stack-Trials-AMER-US-E-Exact&amp;utm_content=Stack-Core&amp;utm_source=google&amp;utm_medium=cpc&amp;device=c&amp;utm_term=elasticsearch&amp;gclid=Cj0KCQjwy4KqBhD0ARIsAEbCt6gQivnVj9HtKlnH2V-vRa9cXTQ-06y4DDUe_g2Rj3sunEAqQQNZ7qMaArfnEALw_wcB"><strong>Elasticsearch</strong></a> is a distributed, open source search and analytics engine for all types of data, including textual, numerical, geospatial, structured, and unstructured. Raw data from Enterprises flows into Elasticsearch from a variety of sources, including logs, system metrics, and web applications. Elasticsearch is built on top of Lucene and it excels at full-text search. Elasticsearch is fast and excels at delivering the most relevant responses to users.</p><p>In addition to full-text search, Elasticsearch also supports vector-search.</p><p><strong>Vector search</strong> leverages <a href="https://www.elastic.co/what-is/elasticsearch-machine-learning">ML</a> to capture the meaning and context of unstructured data, including text and images, transforming it into a numeric representation. Frequently used for <strong>semantic search,</strong> vector search finds similar data using approximate nearest neighbor (ANN) algorithms. Compared to traditional keyword search, vector search yields more relevant results and executes faster. Users can enhance the search experience by combining vector search with filtering and aggregations to optimize relevance by implementing a hybrid search and combining it with traditional scoring.</p><p>Elasticsearch provides an easy-to-use and performant API to enable integration with other services. These features make Elasticsearch a preferred choice for enterprises to store business data and improve search experience.</p><p>Elasticsearch allows for the seamless integration of domain-specific context from the organization's data, thereby enhancing the performance and value of generative AI for achieving desired business objectives.</p><h3>Why Amazon Bedrock?</h3><p><a href="https://aws.amazon.com/bedrock/">Amazon Bedrock</a> is a fully managed service that offers a choice of high-performing FMs from leading AI companies like AI21 Labs, Anthropic, Cohere, Meta, Stability AI, and Amazon with a single API, along with a broad set of capabilities you need to build generative AI applications, simplifying development while maintaining privacy and security. With the comprehensive capabilities of Amazon Bedrock, you can easily experiment with a variety of top FMs, privately customize them with your data using techniques such as fine-tuning and RAG, and create managed agents that execute complex business tasks—from booking travel and processing insurance claims to creating ad campaigns and managing inventory—all without writing any code. Since Amazon Bedrock is serverless, you don't have to manage any infrastructure, and you can securely integrate and deploy generative AI capabilities into your applications using the AWS services you are already familiar with.</p><p>Amazon Bedrock offers several capabilities to support security and privacy requirements and has achieved HIPAA eligibility and GDPR compliance. With Amazon Bedrock, content is not used to improve the base models and is not shared with third-party model providers. Data in Amazon Bedrock is always encrypted in transit and at rest, and can encrypt the data using your own keys. <a href="https://aws.amazon.com/privatelink/">AWS PrivateLink</a> can be used with Amazon Bedrock to establish private connectivity between FMs and your Amazon Virtual Private Cloud (Amazon VPC) without exposing your traffic to the Internet.</p><h3>Solution overview</h3><p>Here's how to use RAG to enable Generative AI capabilities on domain-specific business data using Elasticsearch and Cohere Generate Model -Command through Amazon Bedrock.</p><p>The below architecture diagram explains how to get domain-specific responses from <strong>Cohere Command Model</strong> through Amazon Bedrock using enterprise data hosted in Elastic Enterprise Search using a technique called <strong>RAG.</strong></p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltacd3183ea4f4f1dd/6a17e783e9ea87c9eda9c5cd/1d97936d86f6e24e67d208e3cb84518a2b6eac18-1440x748.png" alt="" /><p><em>Figure 1. RAG Architecture using Elasticsearch and Amazon Bedrock</em></p><h4>Step by step explanation</h4><p><strong>Offline Data Ingestion:</strong></p><p>i. The documents are ingested using web crawler or any other ingestion mechanism.</p><p>ii. The <a href="https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-elser.html">Elastic Learned Sparse EncodeR (ELSER)</a> model will embed the text and store the resulting tokens in the Elasticsearch Index</p><p><strong>Real-time flow on user query:</strong></p><ol><li><p>The User provides a question via the RAG web application</p></li><li><p>The RAG application generates a retrieval request initialized from the vector store (Elasticsearch index). At query time, the text will be embedded using the ELSER model and the resulting tokens will be used to perform a text expansion query.</p></li><li><p>The Retriever component of RAG application fetches the relevant documents from Elasticsearch vector store.</p></li><li><p>The RAG application passes the retrieved documents (context) along with user question (prompt) to the Cohere Command Model through Amazon Bedrock</p></li><li><p>The Cohere Command Model through Amazon Bedrock generates a textual response and sends it back to RAG application</p></li><li><p>The RAG application performs any required post processing tasks. For example, it adds source to the response generated from Cohere Command Model. The User views the response in the web application.</p></li></ol><p>We used the following <strong>AWS and third-party services</strong>:</p><ol><li><p><a href="https://aws.amazon.com/bedrock/">Amazon Bedrock</a> for interacting with LLMs from Cohere.</p></li><li><p>Cohere Command Model for Text Generation.</p></li><li><p>Elasticsearch for storing embeddings of the enterprise knowledge corpus and doing similarity search with user questions.</p></li><li><p>Python, LangChain and Streamlit for building the RAG application</p></li><li><p>Amazon EC2 for hosting the Streamlit application</p></li><li><p><a href="https://aws.amazon.com/iam/">AWS Identity and Access Management</a> roles and policies for access management.</p></li></ol><p>Prerequisites:</p><ol><li><p><strong>Sign up</strong> for a free trial of Elasticsearch cluster with <a href="https://cloud.elastic.co/registration?onboarding_token=vectorsearch&amp;cta=cloud-registration&amp;tech=trial&amp;plcmt=article%20content&amp;pg=search-labs">Elastic Cloud</a></p></li><li><p><strong>Create a new deployment</strong> on AWS following the <a href="https://www.elastic.co/guide/en/cloud/current/ec-create-deployment.html">steps</a></p></li><li><p><strong>Reset and download the elastic user password</strong> following these <a href="https://www.elastic.co/guide/en/cloud/current/ec-password-reset.html">steps</a></p></li><li><p><strong>Copy the Cloud ID</strong> from the My Deployment page listed under Deployments</p></li><li><p>Deploy ELSER Model: In Kibana, navigate to Machine Learning&gt; Trained models. ELSER can be found in the list of trained models. Click the Download model button under Actions. After the download is finished, start the deployment by clicking the <strong>Start deployment</strong> button. Go to the Elastic <a href="https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-elser.html">ELSER</a> page to find more details.</p></li></ol><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt3232748eebefafaa/6a17e78563baff7b63741c3c/32a80e07f0f4e904bacc835f2f7e79c31a375f09-1433x780.png" alt="" /><ol><li><p>Install packages and import modules: Firstly, we need to install modules. Make sure <a href="https://www.python.org/downloads/release/python-381/">python</a> is installed with min version 3.8.1. Then we need to import modules.</p></li></ol>pip install -qU langchain langchain-elasticsearch boto3

from getpass import getpass
from urllib.request import urlopen
from langchain_elasticsearch import ElasticsearchStore
from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings.bedrock import BedrockEmbeddings
from langchain.llms.bedrock import Bedrock
from langchain.chains import RetrievalQA
import boto3
import json

<ol><li><p>Initialize Amazon Bedrock client using the following code</p></li></ol>default_region = "us-east-1"
AWS_REGION = input(f"AWS Region [default: {default_region}]: ") or default_region

def get_bedrock_client(region):
    bedrock_client = boto3.client("bedrock-runtime", region_name=region)
    return bedrock_client

<ol><li><p>Connect to Elasticsearch using Elastic Cloud Id, Elastic username and Elastic password. Use <strong>ElasticsearchStore</strong> to connect to our elastic cloud deployment. As we’re using ELSER we use “SparseVectorRetrievalStrategy”. This strategy uses Elasticsearch’s sparse vector retrieval to retrieve the top-k results.</p></li></ol>CLOUD_ID = getpass("Elastic deployment Cloud ID: ")
CLOUD_USERNAME = "elastic"
CLOUD_PASSWORD = getpass("Elastic deployment Password: ")


vector_store = ElasticsearchStore(
   es_cloud_id=CLOUD_ID,
   es_user=CLOUD_USERNAME,
   es_password=CLOUD_PASSWORD,
   index_name= "workplace_index",
   strategy=ElasticsearchStore.SparseVectorRetrievalStrategy()
)
<ol><li><p>Download the dataset, deserialize the document and split the document into passages. We’ll chunk the documents into passages in order to improve the retrieval specificity and to ensure that we can provide multiple passages within the context window of the final question answering prompt. Here we are chunking into 800 tokens with an overlap of 400 tokens. Here, we are using a simple splitter but LangChain offers more advanced splitters to reduce the chance of context being lost.</p></li></ol>url = "https://raw.githubusercontent.com/elastic/elasticsearch-labs/main/example-apps/workplace-search/data/data

response = urlopen(url)

workplace_docs = json.loads(response.read())

metadata = []
content = []

for doc in workplace_docs:
  content.append(doc["content"])
  metadata.append({
      "name": doc["name"],
      "summary": doc["summary"],
      "rolePermissions":doc["rolePermissions"]
})

text_splitter = CharacterTextSplitter(chunk_size=800, chunk_overlap=400)
docs = text_splitter.create_documents(content, metadatas=metadata)

<ol><li><p>Index data to Elasticsearch using <a href="https://api.python.langchain.com/en/latest/vectorstores/langchain_community.vectorstores.elasticsearch.ElasticsearchStore.html#langchain_community.vectorstores.elasticsearch.ElasticsearchStore.from_documents">ElasticsearchStore.from_documents</a>.</p></li></ol>documents = vector_store.from_documents(
    docs,
    es_cloud_id=CLOUD_ID,
    es_user=CLOUD_USERNAME,
    es_password=CLOUD_PASSWORD,
    index_name="workplace_index"
    strategy=ElasticsearchStore.SparseVectorRetrievalStrategy()
)
<ol><li><p>Initialize the Amazon Bedrock LLM. In the Amazon Bedrock instance, will pass bedrock_client and specific model_id. In this case model_id = <code>cohere.command-text-v14.</code></p></li></ol>default_model_id = "cohere.command-text-v14"
AWS_MODEL_ID = input(f"AWS model [default: {default._model_id}]: ") or default_model_id

def create_bedrock_llm(bedrock_client, model_version_id):
    bedrock_lIm=Bedrock(
        model_id=model_version_id,
        client=bedrock_client,
        model_kwargs={'temperature': 0}
        )
    return bedrock_lIm
<ol><li><p>Asking a question: Now that we have the passages stored in Elasticsearch and LLM is initialized, we can now ask a question to get the relevant passages.</p></li></ol>retriever = vector_store.as_retriever()

qa = RetrievalQA.from_llm(
     llm=llm,
     retriever=retriever,
     return_source_documents=True
)

questions = [
    'What is the nasa sales team?',
    'What is our work from home policy?',
    'Does the company own my personal project?',
    'What job openings do we have?',
    'How does compensation work?'
]
question = questions [1]
print(f"Question: {question}\n")

ans = qa({"query": question})

print("\033[92m ---- Answer ---- \033 [Om')
print(ans["result"] + "\n")
print("\033[94m ---- Sources ----\033 [0m')
for doc in ans["source_documents"]:
  print("Name: " + doc.metadata ["name"])
  print("Content: " + doc.page_content)
  print ("-------\n")

<ol><li><p>(Optional) You can also add a reranking step to the search pipeline which can further improve the ranking of the results returned in the search step. See the <a href="https://docs.cohere.com/docs/deploying-with-aws-sagemaker">Deploying with Amazon SageMaker</a> guide on using <a href="https://txt.cohere.com/rerank/">Rerank.</a></p></li></ol><h2>Conclusion</h2><p>In this post, we showed how to create a RAG web application using a combination of Elasticsearch, Amazon Bedrock, Cohere Command Model and open source python packages like LangChain and Streamlit.</p><p>We encourage you to learn more by exploring <a href="https://aws.amazon.com/sagemaker/jumpstart/?p=pm&amp;c=sm&amp;z=2">Amazon SageMaker Jumpstart</a>, <a href="https://aws.amazon.com/bedrock/">Amazon Bedrock</a>, <a href="https://cohere.com/">Cohere</a>, and <a href="https://www.elastic.co/?ultron=B-Stack-Trials-AMER-US-W&amp;gambit=Stack-Core-EXT&amp;blade=adwords-s&amp;hulk=paid&amp;Device=c&amp;thor=elasticsearch&amp;gclid=Cj0KCQjw1_SkBhDwARIsANbGpFuGD05uYzL230GZmrmDxpIIUdX5GpC0e_wwdUr8OAwseTx7dx3jjywaAuhEEALw_wcB">Elasticsearch</a> and building a solution using the sample implementation provided in this post and a dataset relevant to your business. If you have questions or suggestions, leave a comment.</p>]]></content:encoded>
    <link>https://www.elastic.co/search-labs/blog/gen-ai-using-cohere-llm</link>
    <guid isPermaLink="true">https://www.elastic.co/search-labs/blog/gen-ai-using-cohere-llm</guid>
    <category><![CDATA[AI]]></category>
    <dc:creator><![CDATA[Udayasimha Theepireddy,Meor Amer,Ayan Ray,James Yi]]></dc:creator>
    <enclosure url="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt5cd8853e995046c9/6a17e7872f4a5c03b6fa88f6/52748b9e2f082718804ed9c0d8f4272f4e4f893a-1024x1024.jpg" length="0" type="image/jpeg"/>
    <pubDate>Thu, 23 Nov 2023 00:00:00 GMT</pubDate>
  </item>
  <item>
    <title><![CDATA[Generative AI using Elastic and Amazon SageMaker JumpStart]]></title>
    <description><![CDATA[Learn how to build a generative artificial intelligence (GAI) solution with Amazon SageMaker JumpStart, Elastic, and Hugging Face open source LLMs using the sample implementation provided in this post and a data set relevant to your business.]]></description>
    <content:encoded><![CDATA[<p>In the rapidly advancing world of artificial intelligence, one of the most intriguing and transformative developments is <a href="https://www.elastic.co/what-is/generative-ai">generative artificial intelligence (GAI)</a>. GAI represents a significant leap forward in AI capabilities, enabling machines to generate original and creative content across various domains including conversations, stories, images, videos, and music. Enterprises seek not only top-performing infrastructure, but also a secure platform to harness the power of GAI without compromising their sensitive data and intellectual property. <a href="https://www.elastic.co/what-is/large-language-models">Large language models (LLMs)</a> strive to understand and produce text that resembles human language, utilizing the structure, meaning, and context of natural language.</p><p>Elastic and Amazon Web Services (AWS) understand this pressing need and have taken the lead in offering cutting-edge solutions to meet these demands. Using Amazon SageMaker JumpStart combined with Elasticsearch’s capabilities, businesses can now confidently explore and adopt the most suitable AI models for their specific use cases while maintaining cost-effectiveness, security, and <a href="https://www.elastic.co/blog/privacy-first-ai-search-langchain-elasticsearch">privacy</a>.</p><p>Elasticsearch’s integration with advanced AI models further enhances its capabilities. By leveraging Elasticsearch’s <a href="https://www.elastic.co/enterprise-search/generative-ai">retrieval prowess</a>, LLMs can access the most relevant documents to provide accurate and up-to-date responses. This synergy between Elasticsearch and LLMs ensures that users receive contextually relevant and factual answers to their queries, setting a new standard for information retrieval and AI-powered assistance.</p><p>Elasticsearch is a scalable data store and vector database that offers a range of features to ensure exceptional search performance. It supports traditional keyword and text-based search using the BM25 algorithm, as well as AI-ready <a href="https://www.elastic.co/elasticsearch/vector-database">vector search</a> with exact match and approximate kNN (k-Nearest Neighbor) search capabilities. These advanced features allow Elasticsearch to retrieve highly relevant results for queries expressed in natural language. By combining traditional, vector, or hybrid search approaches, Elasticsearch delivers precise results, making it effortless for users to find the information customers need.</p><p>The Elasticsearch platform seamlessly incorporates robust machine learning and artificial intelligence capabilities directly into its solutions, empowering you to create highly sought-after applications and accomplish tasks with remarkable efficiency. By leveraging these advanced technologies, you can harness the full potential of Elasticsearch to deliver exceptional user experiences and expedite your workflow.</p><h2>Implementing RAG using Elasticsearch and open source LLM available in Amazon SageMaker JumpStart</h2><p>The solution below explains how to use Retrieval Augmented Generation (RAG) to enable GAI capabilities on domain-specific business data using Elasticsearch, Amazon SageMaker JumpStart, and your choice of open source LLMs.</p><h3>Solution overview</h3><p>We will start by reviewing the architecture diagram below. It explains how to get domain-specific responses from an LLM hosted in Amazon SageMaker JumpStart using enterprise data hosted in Elasticsearch using RAG.</p><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt03d8da21895b6412/6a17f5455772623f5c1bcd54/f4cd684ae24b76ee5d4395394f30e0d22ce5a20a-1440x745.png" alt="Figure 1. RAG Architecture using Elasticsearch and Amazon SageMaker" /><p>We used the following AWS and third-party services:</p><ol><li><p><a href="https://aws.amazon.com/pm/sagemaker">Amazon SageMaker</a> and <a href="https://aws.amazon.com/sagemaker/jumpstart/">Amazon SageMaker JumpStart</a> for hosting the open source LLMs from Hugging Face</p></li><li><p>Falcon 40B Instruct and Flan-T5 XL LLM from Hugging Face</p></li><li><p>Elasticsearch for storing embeddings of the enterprise knowledge corpus and doing similarity search with user questions</p></li><li><p>Python, <a href="https://python.langchain.com/v0.1/docs/get_started/introduction/">LangChain</a>, and <a href="https://streamlit.io/">Streamlit</a> for building the RAG application</p></li><li><p>Amazon EC2 for hosting the Streamlit application</p></li><li><p><a href="https://aws.amazon.com/iam/">AWS Identity and Access Management</a> roles and policies for access management</p></li></ol><h3>Step-by-step explanation</h3><p><strong>Offline data ingestion:</strong></p><p>We ingest data from an enterprise knowledge corpus – for example this could be internal web pages, documents describing a company’s process, or corporate financial data.</p><ol><li><p>The documents are ingested using a web crawler or any other ingestion mechanism.</p></li><li><p>The textual content is converted into vectors and stored in a dense_vector field by a sentence transformer type ML model.</p></li></ol><p><strong>Real-time flow on user query:</strong></p><ol><li><p>The user provides a question via the Retrieval Augmented Generation (RAG) web application.</p></li><li><p>The RAG application generates a hybrid search request for Elasticsearch based on the user's question and sends it to Elasticsearch. The hybrid search request does a BM25 match on the text field and kNN search on the dense_vector field.</p></li><li><p>Elasticsearch returns the document body and source URL (if applicable) to the RAG application. The RAG application accepts only the top scored document.</p></li><li><p>The RAG application passes the top scored document body (context) along with user question (prompt) to the LLM hosted as Amazon SageMaker endpoint.</p></li><li><p>The Amazon SageMaker endpoint generates a textual response and sends it back to the RAG application.</p></li><li><p>The RAG application performs any required post processing tasks. For example, it adds a source url to the response generated from the LLM. The user views the response in the web application.</p></li></ol><p>Let’s now look at a few setup steps and a few implementation steps to create a working search solution:</p><p><strong>Setup steps:</strong></p><ol><li><p><strong>Sign up</strong> for a free trial of an Elasticsearch cluster with <a href="https://cloud.elastic.co/registration?onboarding_token=vectorsearch&amp;cta=cloud-registration&amp;tech=trial&amp;plcmt=article%20content&amp;pg=search-labs">Elastic Cloud</a>.</p></li><li><p><strong>Create a new deployment</strong> on AWS following <a href="https://www.elastic.co/guide/en/cloud/current/ec-create-deployment.html">these steps</a>.</p></li><li><p><strong>Add a new machine learning node</strong> following the steps below. This will enable you to run machine learning models in your deployment.</p></li><li><p>Click on <strong>Edit</strong> under Deployment Name in the left navigation bar.</p></li><li><p>Scroll down to the Machine Learning instances box.</p></li><li><p>Click <strong>+Add Capacity</strong>.</p></li><li><p>Under Size per zone, click and select <strong>2GB RAM</strong>.</p></li><li><p>Click on <strong>Save</strong> and then <strong>Confirm</strong>.</p></li><li><p><strong>Reset and download the elastic user password</strong> following these <a href="https://www.elastic.co/guide/en/cloud/current/ec-password-reset.html">steps</a>.</p></li><li><p><strong>Copy the deployment ID</strong> from the Overview page under Deployment name.</p></li><li><p><strong>Load an embedding model into Elasticsearch.</strong> Here, we have used<a href="https://huggingface.co/sentence-transformers/all-distilroberta-v1"><strong>all-distilroberta-v1</strong></a> model hosted in the Hugging Face model hub. You can choose other sentence transformer types based on your case. Import this Python <strong>notebook</strong> <a href="https://github.com/Udayel/RAGElastic-LLM">here</a> in Amazon SageMaker and run it. Provide the <strong>Cloud Id</strong> , <strong>Elasticsearch username</strong> , and <strong>Elasticsearch password</strong> when prompted. This will download the model from Hugging Face, chunk it up, load it into Elasticsearch, and deploy the model onto the machine learning node of the Elasticsearch cluster.</p></li><li><p><strong>Create an Elasticsearch index</strong> by opening Kibana from the Elastic Cloud console and navigating to Enterprise Search - Overview. Click on <strong>Create an Elasticsearch Index</strong>. Choose <strong>Web Crawler</strong> as the Ingestion method. Enter a suitable Index name and click <strong>Create Index</strong>.</p></li><li><p><strong>Add an Inference Pipeline</strong> by clicking on <strong>Pipelines tab &gt; Copy</strong> and customizing it in the Ingest Pipeline Box. Click <strong>Add Inference Pipeline</strong> in the Machine Learning Inference Pipelines box. Enter the Name for the new pipeline. Select the trained Model loaded in step 6 and Select title as source field. Click <strong>Continue</strong> in two subsequent screens and click <strong>Create Pipeline</strong> at the Review stage.</p></li></ol><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt99f3fcd7de79819d/6a17f5471d1b834f2e93e59c/0aa8612be25d206f962fe81c9bff08769cad6b9f-1440x779.png" alt="Figure 2. Adding Inference Pipeline in Elasticsearch" /><ol><li><p><strong>Update the mapping for dense vector</strong> by clicking on <strong>Dev Tools</strong> and running the following code. This will enable you to run kNN search on the title field vectors. From Elasticsearch version 8.8+, this step will be handled automatically.</p></li></ol>POST search-elastic-docs/_mapping
{
 "properties": {
   "title-vector": {
     "type": "dense_vector",
     "dims": 768,
     "index": true,
     "similarity": "dot_product"
   }
 }
}
<ol><li><p><strong>Configure web crawler</strong> to crawl Elastic Docs (you can replace this with your Enterprise Domain corpus). Click on the relevant index under Available indices. Click on the <strong>Manage Domains</strong> tab. Click <strong>Add domain</strong>. Enter <a href="https://www.elastic.co/guide/en"><strong>https://www.elastic.co/guide/en</strong></a> and click <strong>Validate Domain</strong>. Click <strong>Add domain</strong> and then <strong>Add Crawl rules</strong>. Add the following rules. Click <strong>Crawl</strong> and then <strong>Crawl all domains on this index</strong>. This will start Elasticsearch’s web crawler and it will crawl the targeted documents, generate vectors for the title field, and index the document and vector.</p></li></ol><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltfbdf843267a3291d/6a17f548a2929920f6d02dd7/51d6e71a3562a1f1e07d64ab40e192e9c0342a09-1440x834.png" alt="Figure 3. Adding Web Crawling rules in Elasticsearch" /><p>The <strong>implementation steps</strong> for instantiating the solution presented in this post are as follows:</p><ol><li><p><strong>Choose your LLM.</strong> Amazon SageMaker JumpStart offers a wide selection of proprietary and publicly available foundation models from various model providers. Log in to Amazon SageMaker Studio, open Amazon SageMaker JumpStart, and search for your preferred Foundation model. Please find the list of models available for each task <a href="https://aws.amazon.com/sagemaker/jumpstart/?sagemaker-data-wrangler-whats-new.sort-by=item.additionalFields.postDateTime&amp;sagemaker-data-wrangler-whats-new.sort-order=desc">here</a>.</p></li></ol><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt453df8cf0664bb04/6a17f54afbc5f8222a491c1f/86ed5cadd37078d41237502fc1cc3438446ada6c-1440x624.png" alt="Figure 4. LLMs in Amazon SageMaker JumpStart" /><ol><li><p><strong>Deploy your LLM.</strong> Amazon SageMaker JumpStart studio also provides a no-code interface to deploy the model. You can easily deploy a model with few clicks. After the deployment is successful, copy the Endpoint Name.</p></li></ol><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt0c2b995cb1db4810/6a17f54b6df731cb540a1073/d163b7593a40d7cff7170dd4aba3082227aea73b-1440x627.png" alt="Figure 5. Deploying LLMs using Amazon SageMaker JumpStart Console" /><ol><li><p><strong>Download and set up the RAG Application.</strong> Launch an EC2 instance and clone the code from this <a href="https://github.com/Udayel/RAGElastic-LLM">GitHub link</a>. Set up a virtual environment following <a href="https://docs.python.org/3/library/venv.html">these steps</a>. Install the required Python libraries by running the command pip install -r requirements.txt. Update the config.sh file with the following:</p></li><li><p>ES_CLOUD_ID: Elastic Cloud Deployment ID</p></li><li><p>ES_USERNAME: Elasticsearch Cluster User</p></li><li><p>ES_PASSWORD: Elasticsearch User password</p></li><li><p>FLAN_T5_ENDPOINT: Amazon SageMaker Endpoint Name pointing to Flan T5</p></li><li><p>FALCON_40B_ENDPOINT: Amazon SageMaker Endpoint Name pointing to Falcon 40B</p></li><li><p>AWS_REGION: AWS Region</p></li><li><p><strong>Run the application</strong> using the command streamlit run rag_elastic_aws.py. This will start a web browser and the url will be printed to the command line.</p></li><li><p><strong>Response of LLM without context.</strong></p></li></ol><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blt645d15fec3945281/6a17f54daf47b60bf0cde0ff/633edd0c512231b96badd2586aafec5d9071fb3a-1440x627.png" alt="Figure 6. Sample response of LLM without context" /><ol><li><p><strong>Response of LLM with context</strong> derived from Elasticsearch.</p></li></ol><img src="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/bltee94315b36674a22/6a17f54ebe6086573b0048f9/6c326977f60b70c4711429abf0a5e82f36713402-1440x630.png" alt="Figure 7. Sample response of LLM with domain-specific context" /><h2>Conclusion</h2><p>In this post, we showed you how to create a Retrieval Augmented Generation-based search application using a combination of Elasticsearch, Amazon SageMaker JumpStart, open-source LLMs from Hugging Face, and open source Python packages like LangChain and Streamlit.</p><p>Learn more by exploring <a href="https://aws.amazon.com/sagemaker/jumpstart/">JumpStart</a>, <a href="https://aws.amazon.com/bedrock/titan/">Amazon Titan</a> models, <a href="https://aws.amazon.com/bedrock/">Amazon Bedrock</a>, and <a href="https://www.elastic.co/">Elastic</a> to build a solution using the sample implementation provided in this post and a data set relevant to your business.</p><p>Or, start your own <a href="https://aws.amazon.com/marketplace/pp/prodview-voru33wi6xs7k?trk=5fbc596b-6d2a-433a-8333-0bd1f28e84da&amp;sc_channel=el">7-day free trial</a> by signing up via <a href="https://aws.amazon.com/marketplace/pp/prodview-voru33wi6xs7k?trk=d54b31eb-671c-49ba-88bb-7a1106421dfa%E2%89%BBchannel=el">AWS Marketplace</a> and quickly spin up a deployment in minutes on any of the <a href="https://www.elastic.co/guide/en/cloud/current/ec-reference-regions.html#ec_amazon_web_services_aws_regions">Elastic Cloud regions on AWS</a> around the world. Your AWS Marketplace purchase of Elastic will be included in your monthly consolidated billing statement and will draw against your committed spend with AWS.</p><p><em>The release and timing of any features or functionality described in this post remain at Elastic's sole discretion. Any features or functionality not currently available may not be delivered on time or at all.</em></p><p><em>In this blog post, we may have used or referred to third party generative AI tools, which are owned and operated by their respective owners. Elastic does not have any control over the third party tools and we have no responsibility or liability for their content, operation or use, nor for any loss or damage that may arise from your use of such tools. Please exercise caution when using AI tools with personal, sensitive or confidential information. Any data you submit may be used for AI training or other purposes. There is no guarantee that information you provide will be kept secure or confidential. You should familiarize yourself with the privacy practices and terms of use of any generative AI tools prior to use.</em></p><p><em>Elastic, Elasticsearch, ESRE, Elasticsearch Relevance Engine and associated marks are trademarks, logos or registered trademarks of Elasticsearch N.V. in the United States and other countries. All other company and product names are trademarks, logos or registered trademarks of their respective owners.</em></p>]]></content:encoded>
    <link>https://www.elastic.co/search-labs/blog/generative-ai-using-elastic-amazon-sagemaker-jumpstart</link>
    <guid isPermaLink="true">https://www.elastic.co/search-labs/blog/generative-ai-using-elastic-amazon-sagemaker-jumpstart</guid>
    <category><![CDATA[AI]]></category>
    <dc:creator><![CDATA[Udayasimha Theepireddy,Ayan Ray]]></dc:creator>
    <enclosure url="https://static-www.elastic.co/v3/assets/bltefdd0b53724fa2ce/blta9f7119562f10d5a/6a17f5507f6f151debc09ca3/f10a706b66a83e9df451ece25326cbcd10134e3c-721x420.jpg" length="0" type="image/jpeg"/>
    <pubDate>Tue, 25 Jul 2023 00:00:00 GMT</pubDate>
  </item>
  </channel>
</rss>