<?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 Ali Arabi on Medium]]></title>
        <description><![CDATA[Stories by Ali Arabi on Medium]]></description>
        <link>https://medium.com/@aliasghar.arabi?source=rss-6c9263f24d73------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ATWGCThT6iFqmJmNJT7uuA.jpeg</url>
            <title>Stories by Ali Arabi on Medium</title>
            <link>https://medium.com/@aliasghar.arabi?source=rss-6c9263f24d73------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:22:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aliasghar.arabi/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[Prompt Operation Workflow]]></title>
            <link>https://medium.com/@aliasghar.arabi/prompt-operation-workflow-a6eadca72212?source=rss-6c9263f24d73------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6eadca72212</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[sagemaker]]></category>
            <dc:creator><![CDATA[Ali Arabi]]></dc:creator>
            <pubDate>Thu, 09 May 2024 16:01:09 GMT</pubDate>
            <atom:updated>2024-05-10T16:43:11.717Z</atom:updated>
            <content:encoded><![CDATA[<p>In my prior blog post, “<a href="https://medium.com/@aliasghar.arabi/llmops-mlops-for-llms-on-aws-4be4e6a08bdf">LLMOps Architecture &amp; AWS Deployment</a>” which was part of the LLM series, I presented an overview of deploying LLM applications in AWS platform and introduced the concept of LLMOps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p84NsLhSorvpVSnx" /><figcaption><strong>LLMOps Architecture (Image by Author)</strong></figcaption></figure><p>Today, I will delve deeper into the “Prompt Engineering and Prompt Catalog” section, providing a sample solution architecture for Prompt Operation Workflow.</p><p><strong>Introduction:</strong></p><p>Whether it’s a simple prompt engineering initiative or part of a larger RAG application, monitoring LLM performance based on prompts used, inference parameters, and other pertinent metrics is crucial. This ensures rigorous continuous integration testing before adding any prompt templates to the prompt catalog, accessible for any LLM application across the company. Following DevOps best practices, I propose a CI/CD and monitoring pipeline focused on prompts.</p><p><strong>Experimentation:</strong></p><p>Like any ML project, it begins with experimenting with different models and tweaking parameters to find the optimal configuration. This phase is iterative, where the prompt engineer ingests data from various sources, including ground truth,if applicable,, and explores different FM models or fine-tuned LLMs using SageMaker or Bedrock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dg-fU-_1t7zkNEal" /><figcaption><strong>SageMaker Notebook (Image by Author)</strong></figcaption></figure><p><strong>Tracking:</strong></p><p>In the AWS platform, SageMaker Notebooks and its native integration with SageMaker Experiment can be leveraged to log and track all parameters, including prompts and inference parameters such as topP, topK, and temperature, alongside benchmarks like latency, throughput, input tokens, output tokens, and other performance metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kXxRIPtnE-Oq6Q0o" /><figcaption><strong>SageMaker Experiment Tracking (Image by Author)</strong></figcaption></figure><p><strong>Continuous Integration &amp; Continuous Delivery (CICD):</strong></p><p>Once experimentation is finalized and the prompt engineers are ready to submit the developed prompt or prompt template, they create a pull request for the CodeCommit repository containing the latest approved prompts for the project. This pull request includes the location of evaluation artifacts and proposed prompt changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgjUjDR2ueCNqTfKBuXtzg.png" /><figcaption><strong>Pull Request (Image by Author)</strong></figcaption></figure><p>A senior team member reviews the pull request, manually approving or rejecting it. Upon approval, a lambda function triggers the push of the approved prompt to the prompt catalog, a DynamoDB table. Deployed LLM applications can then retrieve prompts from this catalog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NYyLqd3lWv8MD0UU" /><figcaption><strong>Prompt Operation CICD (Image by Author)</strong></figcaption></figure><p><strong>Monitoring:</strong></p><p>Evaluating and monitoring prompt performance over time is essential to detect any drift or changes. For users of Foundation Models on Bedrock, <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/model-evaluation.html">Bedrock Model Evaluation</a> with Automated or Human In The Loop (HITL) options can be utilized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4V7I_YXxdfgJgSeumQI2Vg.png" /><figcaption><strong>Bedrock Model Evaluation</strong></figcaption></figure><p>For more flexibility in evaluating any Foundation Model or fine-tuned model, <a href="https://aws.amazon.com/blogs/machine-learning/operationalize-llm-evaluation-at-scale-using-amazon-sagemaker-clarify-and-mlops-services/">Amazon SageMaker Clarify</a> allows the definition of custom metrics beyond default options. Alternatively, for those preferring open-source packages, <a href="https://github.com/aws/fmeval">FMEval</a>, with built-in support for Amazon SageMaker Endpoints and JumpStart models, offers another viable option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w9_bjssGMg9iz0vH" /><figcaption><strong>Prompt Operation Monitoring (Image by Author)</strong></figcaption></figure><p><strong>Final Solution Architecture:</strong></p><p>Combining the aforementioned components, we arrive at the following architecture, capturing an end-to-end prompt operation CI/CD process that enhances LLM application monitoring and scalability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XO_pJxolAfiQzib-COjwyA.png" /><figcaption><strong>Prompt Operation Workflow Solution Architecture (Image by Author)</strong></figcaption></figure><p>My name is <a href="https://www.linkedin.com/in/aliarabi1/">Ali Arabi</a> and I work as Senior Machine Learning Architect at <a href="https://caylent.com/">Caylent</a>. You can check all of my blog posts on Caylent website as well <a href="https://caylent.com/blog?author=f2f812ff30164f18b6d3ea6d8a768e85">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6eadca72212" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Llama3 on AWS Inferentia using SageMaker LMI and DJL Serving]]></title>
            <link>https://medium.com/@aliasghar.arabi/deploy-llama3-on-aws-inferentia-using-sagemaker-lmi-and-djl-serving-aa241db17aa3?source=rss-6c9263f24d73------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa241db17aa3</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[inferentia]]></category>
            <dc:creator><![CDATA[Ali Arabi]]></dc:creator>
            <pubDate>Sat, 04 May 2024 05:42:38 GMT</pubDate>
            <atom:updated>2024-05-06T16:30:09.172Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploy LLama3 on AWS Inferentia with SageMaker LMI and DJL Serving</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZBwvjac1DXxwvVzmsmNOA.jpeg" /></figure><p><strong>Introduction:</strong></p><p>Meta Llama3 model is available both on Amazon Bedrock and SageMaker Jumpstart. You can use Llama3 on Bedrock in few lines of code:</p><pre>import boto3<br>import json<br><br>bedrock = boto3.client(&quot;bedrock-runtime&quot;)<br><br>response = bedrock.invoke_model(<br>    body=json.dumps({&quot;prompt&quot;: &quot;this is where you place your prompt&quot;, &quot;temperature&quot;: 0, &quot;max_gen_len&quot;:512, &quot;temperature&quot;:0.5,&quot;top_p&quot;:0.9}),<br>    contentType=&#39;application/json&#39;,<br>    accept=&#39;application/json&#39;,<br>    modelId=&#39;meta.llama3-8b-instruct-v1:0&#39;<br>)</pre><p>You can also use Llama3 model on SageMaker JumpStart as below:</p><pre>from sagemaker.jumpstart.model import JumpStartModel<br><br>model = JumpStartModel(model_id = &quot;meta-textgeneration-llama-3-70b-instruct&quot;)<br>predictor = model.deploy(accept_eula=False)<br><br>response = predictor.predict({&quot;inputs&quot;: &quot;this is where you place your prompt&quot;, &quot;parameters&quot;: {&quot;max_new_tokens&quot;:128, &quot;do_sample&quot;:&quot;true&quot;}})</pre><p>These two options are great and serve a lot of purposes. But there are cases where you need:</p><ul><li>more flexibility on choosing the backend engine,</li><li>customization on your inference code</li><li>optimizing inference container configuration</li><li>improving the latency and/or throughput based on your need</li><li>lowering hosting cost by leveraging cheaper instances</li></ul><p>while you still want to benefit from ease of use of SageMaker. In this case you can leverage <a href="https://github.com/aws/deep-learning-containers/blob/master/available_images.md#large-model-inference-containers">SageMaker LMI containers</a>. SageMaker Large Model Inference Containers are prebuilt containers that support variety of backend engine such as vLLM, DeepSpeed, TensorRT-LLM, and Transformers NeuronX with possibility of model parallelism and dynamic batching to optimize the llm hosting.</p><p>Today I will show you how to deploy Llama3 to SageMaker Inf2 instance and host a real-time endpoint using DJL Serving with Transformers NeuronX backend engine. Transformers NeuronX is a software package that enables LLM inference on Neuron hardware and is advised to be used when you expect low variability of input and output lengths. Examples of such cases are summarization or Information extraction unlike a chatbot application in which you can expect uneven traffic across requests between input and output lengths. They are also designed to deploy LLMs on Amazon EC2 Inf2 instances which are cheaper instance class.</p><p><strong>Deployment Instruction:</strong></p><p>Lets now deploy <a href="https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct">meta-Llama-3–8b-Instruct</a> model. We start with installing the updated version of SageMaker and Huggingface_hub and importing required packages.</p><pre># updating packages<br>%pip install -U sagemaker<br>%pip install huggingface_hub</pre><pre># importing required packages<br>import boto3<br>import sagemaker<br>from huggingface_hub import notebook_login<br>from huggingface_hub import snapshot_download<br>from sagemaker import Model, image_uris, serializers, deserializers<br>from pathlib import Path</pre><pre># defining the role, S3 bucket and region for later steps<br><br>role = sagemaker.get_execution_role()<br>sess = sagemaker.session.Session()<br>region = sess._region_name<br>account_id = sess.account_id()<br>bucket = sess.default_bucket()</pre><p>Then we download Llama3 weights snapshot from Hugging Face repo. You need to review and accept Llama3 License agreement in your account on hugging face before you can access the weights. DJL leverages <a href="https://github.com/peak/s5cmd">s5cmd</a> to download model files from S3 with fast speed and consequently this will speed up our deployment time.</p><pre># login to hf hub by entering your api token which you can grab from your hf account<br><br>notebook_login()</pre><pre># downloading the llama3 weights into your local environment/sagemake notebook<br>local_model_path = Path(&quot;./llama3-model&quot;)<br>local_model_path.mkdir(exist_ok=True)<br>model_name = &quot;meta-llama/Meta-Llama-3-8B-Instruct&quot;<br>snapshot_download(repo_id=model_name, cache_dir=local_model_path)</pre><pre># uploading the model artifacts to S3 bucket<br>s3_model_prefix = &quot;hf-llama3-8b-instruct-djl-nx/model&quot;  <br>model_snapshot_path = list(local_model_path.glob(&quot;**/snapshots/*&quot;))[0]<br><br>!aws s3 cp --recursive {model_snapshot_path} s3://{bucket}/{s3_model_prefix}</pre><p>Now I define serving configuration as below:</p><pre># S3 bucket that holds the Llama3 model weights<br>s3_uri = f&quot;s3://{bucket}/{s3_model_prefix}/&quot;</pre><pre>%%writefile serving.properties<br>engine=Python<br>option.entryPoint=djl_python.transformers_neuronx<br>option.model_id=s3_uri<br>option.max_rolling_batch_size=8<br>option.tensor_parallel_degree=24<br>option.n_positions=512<br>option.rolling_batch=auto<br>option.enable_mixed_precision_accumulation=true<br>option.model_loading_timeout=3600</pre><p>Here I set engine to “Python”, entry point to“transformers_neuronx” and rolling_batch option to “auto” for Transformers_Neuronx. “model_id” should point to S3 path where I uploaded the Llama3 weights in earlier step. “n_positions” option specifies the number of input and output tokens that your application expects. I set “tensor_parallel_degree” to 24 (inf2.48xlarge instance has 12 “Inferentia2 Accelerator” and each neuron device has two cores). Since we are deploying large model I then set timeout option to a big number to avoid timeout.</p><p>Then I zip and upload the model artifact to S3:</p><pre>%%sh<br>mkdir mymodel<br>mv serving.properties mymodel/<br>tar czvf mymodel.tar.gz mymodel/<br>rm -rf mymodel</pre><pre>s3_code_prefix = &quot;llama3-8b-instruct-lmi/code&quot;<br>bucket = sess.default_bucket()  # bucket to house artifacts<br>code_artifact = sess.upload_data(&quot;mymodel.tar.gz&quot;, bucket, s3_code_prefix)<br>print(f&quot;S3 Code or Model tar ball uploaded to --- &amp;gt; {code_artifact}&quot;)</pre><p>We can retrieve the latest relevant SageMaker LMI container for Transformers NeuronX backend engine using code:</p><pre>image_uri = image_uris.retrieve(<br>        framework=&quot;djl-neuronx&quot;,<br>        region=sess.boto_session.region_name,<br>        version=&quot;0.27.0&quot;<br>    )</pre><p>We can now create the model:</p><pre>model = Model(image_uri=image_uri, model_data=code_artifact, role=role)</pre><p>Finally we deploy the model to “ml.inf2.48xlarge” instance. Please note this may take ~20–30 mins to finish.</p><pre>instance_type = &quot;ml.inf2.48xlarge&quot;<br>endpoint_name = sagemaker.utils.name_from_base(&quot;llama3-8b-instruct-model&quot;)<br><br>model.deploy(initial_instance_count=1,<br>             instance_type=instance_type,<br>             container_startup_health_check_timeout=3600,<br>             volume_size=512,<br>             endpoint_name=endpoint_name)</pre><p>After the model is in-service you can define the predictor as below and make prediction:</p><pre>predictor = sagemaker.Predictor(<br>    endpoint_name=endpoint_name,<br>    sagemaker_session=sess,<br>    serializer=serializers.JSONSerializer(),<br>)<br><br>predictor.predict(<br>    {&quot;inputs&quot;: &quot;Your prompt goes here&quot;, &quot;parameters&quot;: {&quot;max_new_tokens&quot;:128, &quot;do_sample&quot;:&quot;true&quot;}}<br>)</pre><p><strong>Output Streaming:</strong></p><p>If you need to stream the LLM response you need to update the serving.properties as below:</p><pre>%%writefile serving.properties<br>engine=Python<br>option.entryPoint=djl_python.transformers_neuronx<br>option.model_id=s3_uri<br>option.max_rolling_batch_size=8<br>option.tensor_parallel_degree=24<br>option.n_positions=512<br>option.rolling_batch=auto<br>option.enable_mixed_precision_accumulation=true<br>option.enable_streaming=true<br>option.output_formatter=jsonlines<br>option.model_loading_timeout=3600</pre><p>This will enable streaming and use jsonlines as output format. When the endpoint is in-service then you can use the following code to stream the LLM response:</p><pre># https://api.python.langchain.com/en/latest/_modules/langchain_community/llms/sagemaker_endpoint.html<br>class TokenIterator:<br>    <br>    def __init__(self, stream):<br>        self.byte_iterator = iter(stream)<br>        self.buffer = io.BytesIO()<br>        self.read_pos = 0<br><br>    def __iter__(self):<br>        return self<br><br>    def __next__(self):<br>        while True:<br>            self.buffer.seek(self.read_pos)<br>            line = self.buffer.readline()<br>            if line and line[-1] == ord(&#39;\n&#39;):<br>                self.read_pos += len(line)<br>                return line[:-1]<br>            try:<br>                chunk = next(self.byte_iterator)<br>            except StopIteration:<br>                if self.read_pos &lt; self.buffer.getbuffer().nbytes:<br>                    continue<br>                raise<br>            if &#39;PayloadPart&#39; not in chunk:<br>                continue<br>            self.buffer.seek(0, io.SEEK_END)<br>            self.buffer.write(chunk[&#39;PayloadPart&#39;][&#39;Bytes&#39;])</pre><p>The following function takes the deployed endpoint name, payload and sagemaker-runtime client and streams the LLM response on screen:</p><pre>def sm_stream(client, endpoint_name, payload):<br>    resp = client.invoke_endpoint_with_response_stream(EndpointName=endpoint_name, Body=json.dumps(payload), ContentType=&quot;application/json&quot;)<br>    event_stream = resp[&#39;Body&#39;]<br>    for line in TokenIterator(event_stream):<br>        resp = json.loads(line)<br>        print(resp.get(&quot;token&quot;)[&#39;text&#39;], end=&#39;&#39;)</pre><p>Here is an example of the way we invoke the endpoint for streaming:</p><pre>endpoint_name = model.endpoint_name<br>payload = {&quot;inputs&quot;: &quot;YOUR PROMPT GOES HERE&quot;, &quot;parameters&quot;: {&quot;max_new_tokens&quot;:400}}<br>client = boto3.client(&#39;sagemaker-runtime&#39;)<br><br>sm_stream(client, endpoint_name, payload)</pre><p>make sure to delete the endpoint when you are done to avoid incurring unnecessary cost.</p><pre>sm_client = boto3.client(&#39;sagemaker&#39;)<br>response = sm_client.delete_endpoint(EndpointName=endpoint_name)</pre><p><strong>Conclusion:</strong></p><p>Today I showcased how to deploy Llama3 8B model on SageMaker Inf2 instance and host real time endpoint using DJL Serving with Transformers NeuronX backend. This gives us opportunity to benefit from low cost, high throughput and lower latency supported by Amazon Elastic Compute Cloud (Amazon EC2) Inf2 instances.</p><p>My name is <a href="https://www.linkedin.com/in/aliarabi1/">Ali Arabi</a> and I work as Senior Machine Learning Architect at <a href="https://caylent.com/">Caylent</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa241db17aa3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chatbot Intents: Using Amazon Bedrock to Unlock Better Interactions for Customers]]></title>
            <link>https://medium.com/@aliasghar.arabi/chatbot-intents-using-amazon-bedrock-to-unlock-better-interactions-for-customers-260a4b64d042?source=rss-6c9263f24d73------2</link>
            <guid isPermaLink="false">https://medium.com/p/260a4b64d042</guid>
            <dc:creator><![CDATA[Ali Arabi]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 05:26:23 GMT</pubDate>
            <atom:updated>2024-04-05T05:26:23.288Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>|</strong> <em>Can also see this post </em><a href="https://caylent.com/blog/chatbot-intents-using-anthropic-claude-and-aws-bedrock-to-unlock-better-interactions-for-customers"><em>on the Caylent blog</em></a><em>.</em></p><p>This is the second part of my <a href="https://medium.com/@aliasghar.arabi/chatbot-intents-using-anthropic-claude-and-amazon-bedrock-agent-to-unlock-better-interactions-for-b21b74f17b75">previous post</a> about Using LLM for dynamically enriching user prompts by identifying intent in the chatbot. In the previous post I used Anthropic Claude on Amazon Bedrock and in this post I will explain how to use Amazon Bedrock agents to achieve the same result.</p><p>Consider a use case where the end users of your chatbot are not familiar with prompt engineering best practices and they may interact with the chatbot with only short and simple questions but you want to make sure they still get proper results with all the information and with correct formatting according to their specific requirements. And this might be different from question to question. Moreover, for some of the questions you may need to provide a few-shot examples to make sure the correct response is created by LLM. Therefore we need to ensure the appropriate prompt template is selected or augmented with relevant instruction depending on the user question.</p><p>In the below image I have elaborated desired end to end steps that LLM should take to fulfill the user question appropriately which include intent resolution and prompt optimization step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U25GnT399f4QEqhPaZ1DXQ.png" /></figure><h3>Data Preparation</h3><p>For the dataset I am using the topical chat dataset that contains conversations between pairs of agents. Specifically I used the <a href="https://github.com/alexa/Topical-Chat/blob/master/conversations/train.json">“train.json”</a> file and kept the conversation id and the conversations only.</p><pre><br>&quot;t_bde29ce2-4153-4056-9eb7-f4ad710505fe&quot;: {<br>      &quot;content&quot;: [<br>          {<br>              &quot;message&quot;: &quot;Are you a fan of Google or Microsoft?&quot;,<br>              &quot;agent&quot;: &quot;agent_1&quot;<br>          },<br>          {<br>              &quot;message&quot;: &quot;Both are excellent technology they are helpful in many ways. For the security purpose both are super.&quot;,<br>              &quot;agent&quot;: &quot;agent_2&quot;<br>          },<br>          {<br>              &quot;message&quot;: &quot;I&#39;m not  a huge fan of Google, but I use it a lot because I have to. I think they are a monopoly in some sense. &quot;,<br>              &quot;agent&quot;: &quot;agent_1&quot;<br>          },<br>         //// TRUNCATED CONVERSATION ////<br>          {<br>              &quot;message&quot;: &quot;I heard that too. Well, it was nice chatting with you. Have a good day. &quot;,<br>              &quot;agent&quot;: &quot;agent_1&quot;<br>          }<br>      ]<br>  }</pre><h3>User Intent Identification using Bedrock Agent</h3><p>There are 3 main components required here. This includes:</p><ul><li>Tools available to our agent to fulfill a request,</li><li>APIs that our agent can invoke in a JSON or YAML file following the <a href="https://www.openapis.org/">OpenAPI schema</a>,</li><li>Action group in the form of a <a href="https://aws.amazon.com/lambda/">AWS Lambda</a> function which the agent will use to invoke APIs based on its reasoning</li></ul><h4>Agent Tools</h4><p>Let’s take a quick look at the tools I defined for our agent. Note the function docstring where I provided the goal of each tool which will help our agent to decide which one to use to solve a problem.</p><pre>import json<br>import boto3<br><br>def summary_gen_tool():<br>  &quot;&quot;&quot;<br>  Use this tool only to return instruction for conversation summary analysis questions before calling get_conversation() tool. The input is the customer&#39;s question.<br>  &quot;&quot;&quot;<br><br>  instruction = &quot;Carefully consider a walkthrough of all the messages in the provided conversion history. Present the list of topics in the conversation in numbered bullet points. Using this, answer the question.&quot;<br>  return instruction<br><br>def sentiment_gen_tool():<br>  &quot;&quot;&quot;<br>  Use this tool only to return instruction for conversation sentiment analysis questions before calling get_conversation() tool. The input is the customer&#39;s question.<br>  &quot;&quot;&quot;<br><br>  instruction = &quot;Pay attention to the provided conversation history while answering the questions. Make sure you have sufficient data to back your reasoning when answering the question. The identified sentiment must be taken from these following categories: Angry, Fearful, Happy, Neutral, Sad, Disgusted, Surprised, Curious to dive deeper. A conversation may contain a mix of sentiment from the categories. Also make sure to provide reasoning behind your decision in bullet points&quot;<br>  return instruction<br><br><br>def other_question_gen_tool():<br>  &quot;&quot;&quot;<br>  Use this tool only to return instruction for a general question where it is not about summary or sentiment before calling get_conversation() tool. The input is the customer&#39;s question.<br>  &quot;&quot;&quot;<br><br>  instruction = &quot;Carefully consider all the messages in the provided conversion history. Using this, answer the question.&quot;<br>  return instruction<br><br><br><br>def get_conversation_tool(id, question, instruction):<br>  &quot;&quot;&quot;<br>  Use this tool to receive instruction from either summary_gen_tool or sentiment_gen_tool or general_gen_tool function and return instruction, user question and 1 JSON object containing the conversation history for the given conversation id.<br>  &quot;&quot;&quot;<br>  s3_bucket = &#39;YOUR-BUCKET&#39;<br>  file_key = &#39;train.json&#39;<br><br>  s3 = boto3.client(&#39;s3&#39;)<br><br>  response = s3.get_object(Bucket=s3_bucket, Key=file_key)<br>  f = response[&#39;Body&#39;].read().decode(&#39;utf-8&#39;)<br>  data = json.loads(f)<br><br>  conversation_history = data[id][&#39;content&#39;]<br><br>  return {&quot;conversation&quot;: conversation_history, &quot;question&quot;: question, &quot;instruction&quot;: instruction}</pre><h4>OpenAPI Schema</h4><p>Now we define the APIs to invoke by agent in the following JSON file following OpenAPI schema. You will need to upload this file to an S3 bucket and point to it when defining the agent. As before we have 3 APIs for the instruction specific to the user question namely summary, sentiment or any other question. And last API is to pass the user question, selected instruction by LLM and the conversation history to LLM to make the final response. Notably in each path you need to provide the description, input parameters and the output. Below the schema for the APIs is listed.</p><pre>{<br>  &quot;openapi&quot;: &quot;3.0.0&quot;,<br>  &quot;info&quot;: {<br>      &quot;title&quot;: &quot;Agent Assistant API&quot;,<br>      &quot;version&quot;: &quot;1.0.0&quot;,<br>      &quot;description&quot;: &quot;APIs helping users with creating summarization or sentiment or general answer to the user question.&quot;<br>  },<br>  &quot;paths&quot;: {<br>      &quot;/get_summary_instruction&quot;: {<br>          &quot;get&quot;: {<br>              &quot;summary&quot;: &quot;Retrieve instruction for conversation summary analysis question&quot;,<br>              &quot;description&quot;: &quot;It does not take any input parameter and returns instruction for questions asked specifically about summarizing the conversation&quot;,<br>              &quot;operationId&quot;: &quot;querySummaryInstruction&quot;,            <br>              &quot;responses&quot;: {<br>                  &quot;200&quot;: {<br>                      &quot;description&quot;: &quot;Retrieve instruction for conversation summary analysis question&quot;,<br>                      &quot;content&quot;: {<br>                          &quot;application/json&quot;: {<br>                              &quot;schema&quot;: {<br>                                  &quot;type&quot;: &quot;object&quot;,<br>                                  &quot;properties&quot;: {<br>                                      &quot;instruction&quot;: {<br>                                          &quot;type&quot;: &quot;string&quot;,<br>                                          &quot;description&quot;: &quot;The instruction for the user question&quot;<br>                                      }<br>                                  }<br>                              }<br>                          }<br>                      }<br>                  }<br>              }<br>          }<br>      },<br>      &quot;/get_sentiment_instruction&quot;: {<br>          &quot;get&quot;: {<br>              &quot;summary&quot;: &quot;Retrieve instruction for conversation sentiment analysis question&quot;,<br>              &quot;description&quot;: &quot;It does not take any input parameter and returns instruction for question ask specifically about sentiment of conversation&quot;,<br>              &quot;operationId&quot;: &quot;querySentimentInstruction&quot;,            <br>              &quot;responses&quot;: {<br>                  &quot;200&quot;: {<br>                      &quot;description&quot;: &quot;Retrieve instruction for conversation sentiment analysis question&quot;,<br>                      &quot;content&quot;: {<br>                          &quot;application/json&quot;: {<br>                              &quot;schema&quot;: {<br>                                  &quot;type&quot;: &quot;object&quot;,<br>                                  &quot;properties&quot;: {<br>                                      &quot;instruction&quot;: {<br>                                          &quot;type&quot;: &quot;string&quot;,<br>                                          &quot;description&quot;: &quot;The instruction for the user question&quot;<br>                                      }<br>                                  }<br>                              }<br>                          }<br>                      }<br>                  }<br>              }<br>          }<br>      },<br>      &quot;/get_other_question_instruction&quot;: {<br>          &quot;get&quot;: {<br>              &quot;summary&quot;: &quot;Retrieve instruction for a general question not about sentiment or summary of the conversation&quot;,<br>              &quot;description&quot;: &quot;It does not take any input parameter and returns instruction for a general question where it is not about summary or sentiment&quot;,<br>              &quot;operationId&quot;: &quot;queryGeneralInstruction&quot;,            <br>              &quot;responses&quot;: {<br>                  &quot;200&quot;: {<br>                      &quot;description&quot;: &quot;Retrieve instruction for a general question not about sentiment or summary of the conversation&quot;,<br>                      &quot;content&quot;: {<br>                          &quot;application/json&quot;: {<br>                              &quot;schema&quot;: {<br>                                  &quot;type&quot;: &quot;object&quot;,<br>                                  &quot;properties&quot;: {<br>                                      &quot;instruction&quot;: {<br>                                          &quot;type&quot;: &quot;string&quot;,<br>                                          &quot;description&quot;: &quot;The instruction for the user question&quot;<br>                                      }<br>                                  }<br>                              }<br>                          }<br>                      }<br>                  }<br>              }<br>          }<br>      },<br>      &quot;/gen_conversation&quot;: {<br>          &quot;get&quot;: {<br>              &quot;summary&quot;: &quot;Retrieve conversation history given conversation id&quot;,<br>              &quot;description&quot;: &quot;Retrieve conversation history for the conversation id passed in the user question&quot;,<br>              &quot;operationId&quot;: &quot;genConversation&quot;,<br>              &quot;parameters&quot;: [<br>                  {<br>                      &quot;name&quot;: &quot;ConversationId&quot;,<br>                      &quot;in&quot;: &quot;path&quot;,<br>                      &quot;description&quot;: &quot;Conversation id&quot;,<br>                      &quot;required&quot;: true,<br>                      &quot;schema&quot;: {<br>                          &quot;type&quot;: &quot;string&quot;<br>                      }<br>                  },<br>                  {<br>                      &quot;name&quot;: &quot;question&quot;,<br>                      &quot;in&quot;: &quot;path&quot;,<br>                      &quot;description&quot;: &quot;User question&quot;,<br>                      &quot;required&quot;: true,<br>                      &quot;schema&quot;: {<br>                          &quot;type&quot;: &quot;string&quot;<br>                      }<br>                  },<br>                  {<br>                      &quot;name&quot;: &quot;instruction&quot;,<br>                      &quot;in&quot;: &quot;path&quot;,<br>                      &quot;description&quot;: &quot;instruction for answering the question&quot;,<br>                      &quot;required&quot;: true,<br>                      &quot;schema&quot;: {<br>                          &quot;type&quot;: &quot;string&quot;<br>                      }<br>                  }<br>              ],<br>              &quot;responses&quot;: {<br>                  &quot;200&quot;: {<br>                      &quot;description&quot;: &quot;conversation history&quot;,<br>                      &quot;content&quot;: {<br>                          &quot;application/json&quot;: {<br>                              &quot;schema&quot;: {<br>                                  &quot;type&quot;: &quot;object&quot;,<br>                                  &quot;properties&quot;: {<br>                                      &quot;conversation&quot;: {<br>                                          &quot;type&quot;: &quot;string&quot;,<br>                                          &quot;description&quot;: &quot;conversation history&quot;<br>                                      },<br> <br>                                   &quot;question&quot;: {<br>                                          &quot;type&quot;: &quot;string&quot;,<br>                                          &quot;description&quot;: &quot;user question&quot;<br>                                      },<br>                                      &quot;instruction&quot;: {<br>                                          &quot;type&quot;: &quot;string&quot;,<br>                                          &quot;description&quot;: &quot;instruction for answering the question &quot;<br>                                      }<br>                                  }<br>                              }<br>                          }<br>                      }<br>                  }<br>              }<br>          }<br>      }<br>  }<br>}</pre><h4>Action group</h4><p>Finally I have implemented the Lambda function that receives the event from the Agent and invokes relevant tools using the APIs we defined earlier.</p><pre>import tools<br>import json<br><br><br>def lambda_handler(event, context):<br>  # Print the received event to the logs<br>  print(&quot;Received event: &quot;)<br>  print(event)<br><br>  # Initialize response code to None<br>  response_code = None<br><br>  # Extract the action group, api path, and parameters from the prediction<br>  action = event[&quot;actionGroup&quot;]<br>  api_path = event[&quot;apiPath&quot;]<br>  inputText = event[&quot;inputText&quot;]<br>  httpMethod = event[&quot;httpMethod&quot;]<br><br><br><br>  # Check the api path to determine which tool function to call<br>  if api_path == &quot;/get_summary_instruction&quot;:<br>      # Call the summary_gen_tool from the tools module<br>      body = tools.summary_gen_tool()<br>      # Create a response body with the result<br>      response_code = 200<br>  elif api_path == &quot;/get_sentiment_instruction&quot;:<br>      # Call the sentiment_gen_tool from the tools module<br>      body = tools.sentiment_gen_tool()<br>      # Create a response body with the result<br>      response_code = 200<br>  elif api_path == &quot;/get_other_question_instruction&quot;:<br>      # Call the general_gen_tool from the tools module<br>      body = tools.other_question_gen_tool()<br>      # Create a response body with the result<br>      response_code = 200<br>  elif api_path == &quot;/gen_conversation&quot;:<br>      parameters = event[&#39;parameters&#39;]<br>      for parameter in parameters:<br>          if parameter[&quot;name&quot;] == &quot;ConversationId&quot;:<br>              id_ = parameter[&quot;value&quot;]<br>          if parameter[&quot;name&quot;] == &quot;question&quot;:<br>              question = parameter[&quot;value&quot;]<br>          if parameter[&quot;name&quot;] == &quot;instruction&quot;:<br>              instruction = parameter[&quot;value&quot;]<br>      # Call the get_conversation_tool from the tools module with the query<br>      body = tools.get_conversation_tool(id_, question, instruction)<br>      # Create a response body with the result<br>      response_code = 200<br>  else:<br>      # If the api path is not recognized, return an error message<br>      body = {&quot;{}::{} is not a valid api, try another one.&quot;.format(action, api_path)}<br>      response_code = 400<br>     <br>  response_body = {&quot;application/json&quot;: {&quot;body&quot;: json.dumps(body)}}<br><br>  # Print the response body to the logs<br>  print(f&quot;Response body: {response_body}&quot;)<br><br>  # Create a dictionary containing the response details<br>  action_response = {<br>      &quot;actionGroup&quot;: action,<br>      &quot;apiPath&quot;: api_path,<br>      &quot;httpMethod&quot;: httpMethod,<br>      &quot;httpStatusCode&quot;: response_code,<br>      &quot;responseBody&quot;: response_body,<br>  }<br><br>  # Return the list of responses as a dictionary<br>  api_response = {&quot;messageVersion&quot;: &quot;1.0&quot;, &quot;response&quot;: action_response}<br><br>  return api_response</pre><p>Ideally the LLM must first call instruction APIs to choose the right instruction and then invoke the “get_conversation” API to fetch the conversation history given the conversation id and consequently create the final response. In order to make sure the agent follows the exact order you need to provide the instructions when defining the agent. Here are the instructions I provide to the agent:</p><pre>you are an AI summarizer assistant that helps users to answer their questions. <br>first find the appropriate instruction from the summary_gen_tool or sentiment_gen_tool or other_question_gen_tool functions before running another function. <br>If the question is not about the sentiment or summary of the conversation then use instruction provided by other_question_gen_tool. <br>Remember you can only use retrieved instructions from the above 3 provided functions.  </pre><h3>Agent in action</h3><p>Let’s test our agent with the same questions we used to test our function calling logic. I will showcase one question here but you can test it with other 2 questions to verify the desired behavior of our agent.</p><h4>User Question</h4><p>Here I ask the following question from my agent:<strong> “</strong><strong>what is the sentiment of the conversation with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?”</strong></p><h4>First event</h4><p>In the first call our agent correctly invoked &#39;/get_sentiment_instruction&#39; API from the available options given the user question which is about the sentiment of the conversation.</p><pre>{&#39;messageVersion&#39;: &#39;1.0&#39;, &#39;actionGroup&#39;: &#39;Agent-AWS-API&#39;, &#39;agent&#39;: {&#39;alias&#39;: &#39;TSTALIASID&#39;, &#39;name&#39;: &#39;test-agent&#39;, &#39;version&#39;: &#39;DRAFT&#39;, &#39;id&#39;: &#39;IJ4PSGSCBO&#39;}, &#39;inputText&#39;: &#39;what is the sentiment of the conversation with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?&#39;, &#39;sessionId&#39;: &#39;131578276461585&#39;, &#39;sessionAttributes&#39;: {}, &#39;promptSessionAttributes&#39;: {}, &#39;apiPath&#39;: &#39;/get_sentiment_instruction&#39;, &#39;httpMethod&#39;: &#39;GET&#39;}<br><br><br>Response body: {&#39;application/json&#39;: {&#39;body&#39;: &#39;&quot;Pay attention to the provided conversation history while answering the questions. Make sure you have sufficient data to back your reasoning when answering the question. The identified sentiment must be taken from these following categories: Angry, Fearful, Happy, Neutral, Sad, Disgusted, Surprised, Curious to dive deeper. A conversation may contain a mix of sentiment from the categories. Also make sure to provide reasoning behind your decision in bullet points&quot;&#39;}}</pre><h4>Second event</h4><p>In the second call agent has successfully identified &#39;/gen_conversation&#39; API after collecting all the required info and populating the parameters (question, instruction, and conversation id). After invoking the API the conversation history is retrieved along with other required info to invoke Claude endpoint.</p><pre>{&#39;messageVersion&#39;: &#39;1.0&#39;, &#39;actionGroup&#39;: &#39;Agent-AWS-API&#39;, &#39;agent&#39;: {&#39;alias&#39;: &#39;TSTALIASID&#39;, &#39;name&#39;: &#39;test-agent&#39;, &#39;version&#39;: &#39;DRAFT&#39;, &#39;id&#39;: &#39;IJ4PSGSCBO&#39;}, &#39;inputText&#39;: &#39;what is the sentiment of the conversation with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?&#39;, &#39;sessionId&#39;: &#39;131578276461585&#39;, &#39;sessionAttributes&#39;: {}, &#39;promptSessionAttributes&#39;: {}, &#39;apiPath&#39;: &#39;/gen_conversation&#39;, &#39;httpMethod&#39;: &#39;GET&#39;, &#39;parameters&#39;: [{&#39;name&#39;: &#39;question&#39;, &#39;type&#39;: &#39;string&#39;, &#39;value&#39;: &#39;what is the sentiment of the conversation with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?&#39;}, {&#39;name&#39;: &#39;instruction&#39;, &#39;type&#39;: &#39;string&#39;, &#39;value&#39;: &#39;Pay attention to the provided conversation history while answering the questions. Make sure you have sufficient data to back your reasoning when answering the question. The identified sentiment must be taken from these follwoing categories: Angry, Fearful, Happy, Neutral, Sad, Disgusted, Surprised, Curious to dive deeper. A conversation may contain mix of sentiment from the categories. Also make sure to provided reasoning behind your decision in bullet points&#39;}, {&#39;name&#39;: &#39;ConversationId&#39;, &#39;type&#39;: &#39;string&#39;, &#39;value&#39;: &#39;t_bde29ce2-4153-4056-9eb7-f4ad710505fe&#39;}]}<br><br><br><br>Response body: {&#39;application/json&#39;: {&#39;body&#39;: &#39;{<br>          &quot;conversation&quot;: [<br>              {<br>                  &quot;message&quot;: &quot;Are you a fan of Google or Microsoft?&quot;,<br>                  &quot;agent&quot;: &quot;agent_1&quot;<br>              },<br>              {<br>                  &quot;message&quot;: &quot;Both are excellent technology they are helpful in many ways. For the security purpose both are super.&quot;,<br>                  &quot;agent&quot;: &quot;agent_2&quot;<br>              },<br>              //// TRUNCATED CONVERSATION /////<br>              {<br>                  &quot;message&quot;: &quot;I heard that too. Well, it was nice chatting with you. Have a good day. &quot;,<br>                  &quot;agent&quot;: &quot;agent_1&quot;<br>              }<br>          ],<br>          &quot;question&quot;: &quot;what is the sentiment of the conversation with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?&quot;,<br>          &quot;instruction&quot;: &quot;Pay attention to the provided conversation history while answering the questions. Make sure you have sufficient data to back your reasoning when answering the question. The identified sentiment must be taken from these following categories: Angry, Fearful, Happy, Neutral, Sad, Disgusted, Surprised, Curious to dive deeper. A conversation may contain a mix of sentiment from the categories. Also make sure to provide reasoning behind your decision in bullet points&quot;<br>      }&#39;<br>  }<br>}</pre><h4>Final Call</h4><p>In the final step the agent has invoked Claude model to create the final answer as presented in the below screenshot. On AWS Console you can also show the traces of steps the agent is taking, review the prompt it is using as well as its reasoning to fulfill the user’s request. The agent has successfully identified the two available tools Agent-AWS-API::genConversation and Agent-AWS-API::querySentimentInstruction to answer the questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZ8xPoM4H_SXunrwX1lSrw.png" /></figure><h3>Conclusion</h3><p>This post presented a creative method for intent identification within chatbot applications, harnessing the power of Bedrock agent. As we saw LLM agents will abstract away a lot of things for us such as creating the prompt, parsing output, adding the tools to the agent’s toolbox, and more importantly the iteratively invoking LLM. Moreover, the ability to define tools as APIs based on OpenAPI schema in the form of JSON or YAML files makes the process more structured.</p><p>We demonstrated a way to take the complexity of authoring the best prompt for the task away from the user and move it inside the application logic. This potentially can lead to dynamic and responsive chatbots that excel in understanding and fulfilling user intents, ultimately enhancing the user experience within conversational interfaces. You can find the code for this post <a href="https://github.com/caylent/Prompt-Optimization-LLM/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=260a4b64d042" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chatbot Intents: Using Anthropic Claude to Unlock Better Interactions for Customers]]></title>
            <link>https://medium.com/@aliasghar.arabi/chatbot-intents-using-anthropic-claude-and-amazon-bedrock-agent-to-unlock-better-interactions-for-b21b74f17b75?source=rss-6c9263f24d73------2</link>
            <guid isPermaLink="false">https://medium.com/p/b21b74f17b75</guid>
            <dc:creator><![CDATA[Ali Arabi]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 05:04:50 GMT</pubDate>
            <atom:updated>2024-04-05T05:33:07.462Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>|</strong> <em>Can also see this post </em><a href="https://caylent.com/blog/chatbot-intents-using-anthropic-claude-and-aws-bedrock-to-unlock-better-interactions-for-customers"><em>on the Caylent blog</em></a><em>.</em></p><p>Within a chatbot application framework, predefined intents streamline user interactions by offering a selection of options. Chatbot intent refers to the objective or aim that a user has when interacting with a customer service chatbot during a conversation. These intents are subsequently processed through established logic to fulfill user requests. Chatbots can now leverage Large Language Model (LLM) agents to efficiently partition tasks into manageable units to ultimately fulfill user objectives. In AWS one may use <a href="https://aws.amazon.com/lex/">Amazon Lex</a> as a traditional chatbot solution and combine it with an LLM agent to fulfill complicated user requests.</p><p>In today’s post I propose an innovative approach leveraging LLMs not only for request fulfillment but also for user intent identification for prompt optimization using <a href="https://aws.amazon.com/bedrock/claude/">Anthropic Claude</a>’s function calling capability via <a href="https://aws.amazon.com/bedrock/">Amazon Bedrock</a>. In a <a href="https://medium.com/@aliasghar.arabi/chatbot-intents-using-amazon-bedrock-to-unlock-better-interactions-for-customers-260a4b64d042">follow up post</a> I will use <a href="https://aws.amazon.com/bedrock/agents/">Bedrock Agent</a> using Claude as the LLM to achieve the same result.</p><p>Consider a use case where the end users of your chatbot are not familiar with prompt engineering best practices and they may interact with the chatbot with only short and simple questions but you want to make sure they still get proper results with all the information and with correct formatting according to their specific requirements. And this might be different from question to question. Moreover, for some of the questions you may need to provide a few-shot examples to make sure the correct response is created by LLM. Therefore we need to ensure the appropriate prompt template is selected or augmented with relevant instruction depending on the user question.</p><p>In the below image I have elaborated desired end to end steps that LLM should take to fulfill the user question appropriately which include intent resolution and prompt optimization step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U25GnT399f4QEqhPaZ1DXQ.png" /></figure><h3>Data Preparation</h3><p>For the dataset I am using the topical chat dataset that contains conversations between pairs of agents. Specifically I used the <a href="https://github.com/alexa/Topical-Chat/blob/master/conversations/train.json">“train.json”</a> file and kept the conversation id and the conversations only.</p><pre><br>&quot;t_bde29ce2-4153-4056-9eb7-f4ad710505fe&quot;: {<br>      &quot;content&quot;: [<br>          {<br>              &quot;message&quot;: &quot;Are you a fan of Google or Microsoft?&quot;,<br>              &quot;agent&quot;: &quot;agent_1&quot;<br>          },<br>          {<br>              &quot;message&quot;: &quot;Both are excellent technology they are helpful in many ways. For the security purpose both are super.&quot;,<br>              &quot;agent&quot;: &quot;agent_2&quot;<br>          },<br>          {<br>              &quot;message&quot;: &quot;I&#39;m not  a huge fan of Google, but I use it a lot because I have to. I think they are a monopoly in some sense. &quot;,<br>              &quot;agent&quot;: &quot;agent_1&quot;<br>          },<br>         //// TRUNCATED CONVERSATION ////<br>          {<br>              &quot;message&quot;: &quot;I heard that too. Well, it was nice chatting with you. Have a good day. &quot;,<br>              &quot;agent&quot;: &quot;agent_1&quot;<br>          }<br>      ]<br>  }</pre><h3>User Intent Identification using Claude Function Calling</h3><p>There are 3 main components required here. These include:</p><ul><li>Functions (Tools) available to be called for fulfilling a request,</li><li>Definition of the tools in form of XML tags.</li><li>Function calling logic customized to work with Claude on Bedrock</li></ul><h3>Tools</h3><p>First we need to create all the essential functions necessary for Claude to address user inquiries effectively. Notably, functions such as `get_summary_instruction()`, `get_sentiment_instruction()`, and `get_general_instruction()` play a crucial role in directing user queries towards pertinent instructions tailored for the LLM. It is imperative to observe the inclusion of XML tags, as they are requisite within the Claude framework. Please take a moment to familiarize yourself with the provided code. Each function has a description that helps LLM to decide which one to use based on the user question.</p><pre>get_summary_instruction_description = &quot;&quot;&quot;<br>          &lt;tool_description&gt;<br>          &lt;tool_name&gt;get_summary_instruction&lt;/tool_name&gt;<br>          &lt;description&gt; It does not take any input parameter and returns instruction for conversation summary analysis question&lt;/description&gt;<br>          &lt;/tool_description&gt;<br>          &quot;&quot;&quot;<br><br>get_sentiment_instruction_description = &quot;&quot;&quot;<br>          &lt;tool_description&gt;<br>          &lt;tool_name&gt;get_sentiment_instruction&lt;/tool_name&gt;<br>          &lt;description&gt;<br>          It does not take any input parameter and returns instruction for conversation sentiment analysis question&lt;/description&gt;<br>          &lt;/tool_description&gt;<br>          &quot;&quot;&quot;<br><br>get_general_instruction_description = &quot;&quot;&quot;<br>          &lt;tool_description&gt;<br>          &lt;tool_name&gt;get_general_instruction&lt;/tool_name&gt;<br>          &lt;description&gt; It does not take any input parameter and returns instruction for a general question where it is not about summary or sentiment&lt;/description&gt;<br>          &lt;/tool_description&gt;<br>          &quot;&quot;&quot;</pre><p>In this particular example I am specifying three instructions. The first one is to answer questions about summarizing the conversation, the next will specify the instruction to retrieve the sentiment of the conversation and the last one is for any other question. In other words the chatbot is optimized to answer questions about conversation summary and sentiment while it can still be used for any other question. Below you can review the detailed instructions for each scenario. You will need to add any specific instruction (ex. formatting, step by step guide, few-shot examples, …) here to be picked up by the LLM accordingly when answering the user question.</p><pre>## Provide the instruction for summary question to be passed to the prompt<br>def get_summary_instruction():<br>  instruction = &quot;Carefully consider a walkthrough of all the messages in the provided conversion history. Present the list of topics in the conversation in numbered bullet points. Using this, answer the question.&quot;<br>  return {&quot;instruction&quot;: instruction}<br><br>## Provide the instruction for sentiment question to be passed to the prompt<br>def get_sentiment_instruction():<br>  instruction = &quot;Pay attention to the provided conversation history while answering the questions. Make sure you have sufficient data to back your reasoning when answering the question. The identified sentiment must be taken from these following categories: Angry, Fearful, Happy, Neutral, Sad, Disgusted, Surprised, Curious to dive deeper. A conversation may contain a mix of sentiment from the categories. Also make sure to provide reasoning behind your decision in bullet points&quot;<br>  return {&quot;instruction&quot;: instruction}<br><br>## Provide the instruction for general question to be passed to the prompt<br>def get_general_instruction():<br>  instruction = &quot;Carefully consider all the messages in the provided conversion history. Using this, answer the question.&quot;<br>  return {&quot;instruction&quot;: instruction}</pre><p>The last tool here is to retrieve the conversation history based on the conversation id passed in the user question. In Particular, it reads the conversation history from a JSON file on the disk and returns it along with the question and the selected instruction.</p><pre>get_conversation_description = &quot;&quot;&quot;<br>          &lt;tool_description&gt;<br>          &lt;tool_name&gt;get_conversation&lt;/tool_name&gt;<br>          &lt;description&gt;<br>          receive instruction from either get_sentiment_instruction_description, get_summary_instruction_description or get_general_instruction_description function and return instruction, user question and 1 JSON object containing the conversation history for the given conversation id.&lt;/description&gt;<br>          &lt;parameters&gt;<br>          &lt;parameter&gt;<br>          &lt;name&gt;id&lt;/name&gt;<br>          &lt;type&gt;string&lt;/type&gt;<br>          &lt;description&gt;conversation id&lt;/description&gt;<br>          &lt;/parameter&gt;<br>          &lt;parameter&gt;<br>          &lt;name&gt;question&lt;/name&gt;<br>          &lt;type&gt;string&lt;/type&gt;<br>          &lt;description&gt;user question&lt;/description&gt;<br>          &lt;/parameter&gt;<br>          &lt;parameter&gt;<br>          &lt;name&gt;instruction&lt;/name&gt;<br>          &lt;type&gt;string&lt;/type&gt;<br>          &lt;description&gt;instruction&lt;/description&gt;<br>          &lt;/parameter&gt;<br>          &lt;/parameters&gt;<br>          &lt;/tool_description&gt;<br>          &quot;&quot;&quot;<br><br><br>def get_conversation(id: str, question: str, instruction: str):<br>  with open(&#39;train.json&#39;, &#39;r&#39;) as f:<br>      data = json.load(f)<br>  return {&quot;conversation&quot;: data[id][&#39;content&#39;], &quot;question&quot;: question, &quot;instruction&quot;: instruction}</pre><p>The final step requires listing all the tools available to LLM.</p><pre><br>list_of_tools_specs = [<br>  get_general_instruction_description,<br>  get_summary_instruction_description,<br>  get_sentiment_instruction_description,<br>  get_conversation_description<br>  ]</pre><h3>Function Calling</h3><p>Having established the requisite tools, this section will outline the prompt template for the function calling purpose. The prompt template consists of four primary sections, commencing with the definition of the system role, followed by the Claude-required function template and an exhaustive list of available tools. Crucially, the subsequent instructions direct Claude to initially identify the relevant instruction from the available options before proceeding with additional function calls. This approach ensures the prompt is augmented with any necessary instructions, thus facilitating the desired response.</p><pre>def create_prompt(tools_string, user_input):<br>  prompt_template = f&quot;&quot;&quot;<br>  \n\nHuman:<br>      You are an expert AI assistant that has been equipped with the following function(s) to help you answer user questions with information about a given conversation history. Your goal is to answer the user&#39;s question to the best of your ability, using the function(s) to gather more information if necessary to better answer the question. The result of a function call will be added to the conversation history as an observation.<br>      In this environment you have access to a set of tools you can use to answer the user&#39;s question.<br>     <br>      You may call them like this. Only invoke one function at a time and wait for the results before invoking another function:<br>      &lt;function_calls&gt;<br>      &lt;invoke&gt;<br>      &lt;tool_name&gt;$TOOL_NAME&lt;/tool_name&gt;<br>      &lt;parameters&gt;<br>      &lt;$PARAMETER_NAME&gt;$PARAMETER_VALUE&lt;/$PARAMETER_NAME&gt;<br>      ...<br>      &lt;/parameters&gt;<br>      &lt;/invoke&gt;<br>      &lt;/function_calls&gt;<br>     <br>      Here are the tools available:<br>      &lt;tools&gt;<br>      {tools_string}<br>      &lt;/tools&gt;<br>     <br>      first find the appropriate instruction from the get_general_instruction_description, get_sentiment_instruction_description or get_summary_instruction_description before running another function.<br>      if the question is not about the sentiment or summary of the conversation then use instruction provided by get_general_instruction_description.<br>     <br>      {user_input}<br>     <br>      \n\nAssistant:<br>      &quot;&quot;&quot;<br>  return prompt_template</pre><h3>Solution in action!</h3><p>Now we have everything needed to test our solution. I have asked 3 questions about conversation summary, conversation sentiment and one general question which is not about sentiment or summary of the conversation. Let’s try them and note the end to end process.</p><p><strong>Question about summary of the conversation:</strong></p><p>Here I ask the following question from Claude:<strong> “</strong><strong>Can you summarize the conversion with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?”</strong></p><p>And here are the run logs:</p><pre>Human:<br>       You are an expert AI assistant that has been equipped with the following function(s) to help you answer user questions with information about a given conversation history. Your goal is to answer the user&#39;s question to the best of your ability, using the function(s) to gather more information if necessary to better answer the question. The result of a function call will be added to the conversation history as an observation.<br>       In this environment you have access to a set of tools you can use to answer the user&#39;s question.<br>       <br>       You may call them like this. Only invoke one function at a time and wait for the results before invoking another function:<br>       &lt;function_calls&gt;<br>       &lt;invoke&gt;<br>       &lt;tool_name&gt;$TOOL_NAME&lt;/tool_name&gt;<br>       &lt;parameters&gt;<br>       &lt;$PARAMETER_NAME&gt;$PARAMETER_VALUE&lt;/$PARAMETER_NAME&gt;<br>       ...<br>       &lt;/parameters&gt;<br>       &lt;/invoke&gt;<br>       &lt;/function_calls&gt;<br>       <br>       Here are the tools available:<br>       &lt;tools&gt;<br>       <br>           &lt;tool_description&gt;<br>           &lt;tool_name&gt;get_general_instruction&lt;/tool_name&gt;<br>           &lt;description&gt; It does not take any input parameter and returns instruction for a general question where it is not about summary or sentiment&lt;/description&gt;<br>           &lt;/tool_description&gt;<br>           <br>           &lt;tool_description&gt;<br>           &lt;tool_name&gt;get_summary_instruction&lt;/tool_name&gt;<br>           &lt;description&gt; It does not take any input parameter and returns instruction for conversation summary analysis question&lt;/description&gt;<br>           &lt;/tool_description&gt;<br>           <br>           &lt;tool_description&gt;<br>           &lt;tool_name&gt;get_sentiment_instruction&lt;/tool_name&gt;<br>           &lt;description&gt;<br>           It does not take any input parameter and returns instruction for conversation sentiment analysis question&lt;/description&gt;<br>           &lt;/tool_description&gt;<br>           <br>           &lt;tool_description&gt;<br>           &lt;tool_name&gt;get_conversation&lt;/tool_name&gt;<br>           &lt;description&gt;<br>           receive instruction from either get_sentiment_instruction_description or get_summary_instruction_description function and return instruction, user question and 1 JSON object containing the conversation history for the given conversation id.&lt;/description&gt;<br>           &lt;parameters&gt;<br>           &lt;parameter&gt;<br>           &lt;name&gt;id&lt;/name&gt;<br>           &lt;type&gt;string&lt;/type&gt;<br>           &lt;description&gt;conversation id&lt;/description&gt;<br>           &lt;/parameter&gt;<br>           &lt;parameter&gt;<br>           &lt;name&gt;question&lt;/name&gt;<br>           &lt;type&gt;string&lt;/type&gt;<br>           &lt;description&gt;user question&lt;/description&gt;<br>           &lt;/parameter&gt;<br>           &lt;parameter&gt;<br>           &lt;name&gt;instruction&lt;/name&gt;<br>           &lt;type&gt;string&lt;/type&gt;<br>           &lt;description&gt;instruction&lt;/description&gt;<br>           &lt;/parameter&gt;<br>           &lt;/parameters&gt;<br>           &lt;/tool_description&gt;<br>           <br>       &lt;/tools&gt;<br>       <br>       first find the appropriate instruction from the get_general_instruction_description, get_sentiment_instruction_description or get_summary_instruction_description before running other function.<br>       if the question is not about the sentiment or summary of the conversation then use instruction provided by get_general_instruction_description.<br>       <br>       Can you summarize the conversion with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?<br><br>Assistant:<br>       <br>&lt;function_calls&gt;<br>&lt;invoke&gt;<br>&lt;tool_name&gt;get_summary_instruction&lt;/tool_name&gt;<br>&lt;parameters&gt;<br>&lt;/parameters&gt;<br>&lt;/invoke&gt;<br><br>&lt;/function_calls&gt;<br><br>           &lt;function_results&gt;<br>           &lt;result&gt;<br>           &lt;tool_name&gt;get_summary_instruction&lt;/tool_name&gt;<br>           &lt;stdout&gt;<br>           {&#39;instruction&#39;: &#39;Carefully consider a walkthrough of all the messages in the provided conversion history. Present the list of topics in the conversation in numbered bullet points. Using this, answer the question.&#39;}<br>           &lt;/stdout&gt;<br>           &lt;/result&gt;<br>           &lt;/function_results&gt;<br><br>To summarize the conversation, I will first gather the conversation details by calling the get_conversation function:<br><br>&lt;function_calls&gt;<br>&lt;invoke&gt;<br>&lt;tool_name&gt;get_conversation&lt;/tool_name&gt;<br>&lt;parameters&gt;<br>&lt;id&gt;t_bde29ce2-4153-4056-9eb7-f4ad710505fe&lt;/id&gt;<br>&lt;question&gt;Can you summarize the conversion with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?&lt;/question&gt;<br>&lt;instruction&gt;{&#39;instruction&#39;: &#39;Carefully consider a walkthrough of all the messages in the provided conversion history. Present the list of topics in the conversation in numbered bullet points. Using this, answer the question.&#39;}&lt;/instruction&gt;<br>&lt;/parameters&gt;<br>&lt;/invoke&gt;<br><br>&lt;/function_calls&gt;<br><br>           &lt;function_results&gt;<br>           &lt;result&gt;<br>           &lt;tool_name&gt;get_conversation&lt;/tool_name&gt;<br>           &lt;stdout&gt;<br>           {&#39;conversation&#39;: [{&#39;message&#39;: &#39;Are you a fan of Google or Microsoft?&#39;, &#39;agent&#39;: &#39;agent_1&#39;}, {&#39;message&#39;: &#39;Both are excellent technology they are helpful in many ways. For the security purpose both are super.&#39;, &#39;agent&#39;: &#39;agent_2&#39;},—----- TRUNCATED CONVERSATION HISTORY —---- {&#39;message&#39;: &#39;I heard that too. Well, it was nice chatting with you. Have a good day. &#39;, &#39;agent&#39;: &#39;agent_1&#39;}], &#39;question&#39;: &#39;Can you summarize the conversion with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?&#39;, &#39;instruction&#39;: &quot;{&#39;instruction&#39;: &#39;Carefully consider a walkthrough of all the messages in the provided conversion history. Present the list of topics in the conversation in numbered bullet points. Using this, answer the question.&#39;}&quot;}<br>           &lt;/stdout&gt;<br>           &lt;/result&gt;<br>           &lt;/function_results&gt;<br><br>Based on the conversation history, here is a summary of the key topics discussed:<br><br>1. Opinions on Google and Microsoft - Both agents shared their thoughts on these tech companies.<br><br>2. Google&#39;s products and services - This included search, ads, cloud computing, Chrome browser, YouTube, etc.<br><br>3. Interesting Google facts - Like using goats to cut grass.<br><br>4. Fish and sea creatures - Including seahorses, jellyfish, dolphins.<br><br>5. Cats - Agent 1 mentioned liking dogs more. Discussed cats sleeping a lot.  <br><br>6. Cat hearing abilities.<br><br>So in summary, the agents discussed various tech companies, Google&#39;s offerings, some fun trivia, and also talked about their thoughts on fish, seahorses, jellyfish, dolphins and cats.</pre><p>We can confirm that the final response has correctly picked up our instruction to summarize the topics discussed in the conversation and they are presented in a numbered list.</p><p><strong>Question about sentiment of the conversation:</strong></p><p>Here I ask the following question from Claude:<strong> “</strong><strong>What is the sentiment of the conversation with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?”</strong></p><p>And here are the truncated run logs:</p><pre>—----- TRUNCATED LOG —----<br><br>Assistant:<br>       <br>&lt;function_calls&gt;<br>&lt;invoke&gt;<br>&lt;tool_name&gt;get_sentiment_instruction&lt;/tool_name&gt;<br>&lt;parameters&gt;<br>&lt;/parameters&gt;<br>&lt;/invoke&gt;<br><br>&lt;/function_calls&gt;<br><br>           &lt;function_results&gt;<br>           &lt;result&gt;<br>           &lt;tool_name&gt;get_sentiment_instruction&lt;/tool_name&gt;<br>           &lt;stdout&gt;<br>           {&#39;instruction&#39;: &#39;Pay attention to the provided conversation history while answering the questions. Make sure you have sufficient data to back your reasoning when answering the question. The identified sentiment must be taken from these following categories: Angry, Fearful, Happy, Neutral, Sad, Disgusted, Surprised, Curious to dive deeper. A conversation may contain a mix of sentiment from the categories. Also make sure to provide reasoning behind your decision in bullet points&#39;}<br>           &lt;/stdout&gt;<br>           &lt;/result&gt;<br>           &lt;/function_results&gt;<br><br>&lt;function_calls&gt;<br>&lt;invoke&gt;<br>&lt;tool_name&gt;get_conversation&lt;/tool_name&gt;<br>&lt;parameters&gt;<br>&lt;id&gt;t_bde29ce2-4153-4056-9eb7-f4ad710505fe&lt;/id&gt;<br>&lt;question&gt;what is the sentiment of the conversation with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?&lt;/question&gt;<br>&lt;instruction&gt;{&#39;instruction&#39;: &#39;Pay attention to the provided conversation history while answering the questions. Make sure you have sufficient data to back your reasoning when answering the question. The identified sentiment must be taken from these following categories: Angry, Fearful, Happy, Neutral, Sad, Disgusted, Surprised, Curious to dive deeper. A conversation may contain a mix of sentiment from the categories. Also make sure to provide reasoning behind your decision in bullet points&#39;}&lt;/instruction&gt;<br>&lt;/parameters&gt;<br>&lt;/invoke&gt;<br><br>&lt;/function_calls&gt;<br><br>           &lt;function_results&gt;<br>           &lt;result&gt;<br>           &lt;tool_name&gt;get_conversation&lt;/tool_name&gt;<br>           &lt;stdout&gt;<br>           {&#39;conversation&#39;: [{&#39;message&#39;: &#39;Are you a fan of Google or Microsoft?&#39;, &#39;agent&#39;: &#39;agent_1&#39;}, {&#39;message&#39;: &#39;Both are excellent technology they are helpful in many ways. For the security purpose both are super.&#39;, &#39;agent&#39;: &#39;agent_2&#39;}, —----- TRUNCATED CONVERSATION HISTORY —---- {&#39;message&#39;: &#39;I heard that too. Well, it was nice chatting with you. Have a good day. &#39;, &#39;agent&#39;: &#39;agent_1&#39;}], &#39;question&#39;: &#39;what is the sentiment of the conversation with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?&#39;, &#39;instruction&#39;: &quot;{&#39;instruction&#39;: &#39;Pay attention to the provided conversation history while answering the questions. Make sure you have sufficient data to back your reasoning when answering the question. The identified sentiment must be taken from these follwoing categories: Angry, Fearful, Happy, Neutral, Sad, Disgusted, Surprised, Curious to dive deeper. A conversation may contain mix of sentiment from the categories. Also make sure to provided reasoning behind your decision in bullet points&#39;}&quot;}<br>           &lt;/stdout&gt;<br>           &lt;/result&gt;<br>           &lt;/function_results&gt;<br><br>Based on the conversation history, the sentiments expressed include:<br><br>- Happy: The conversation starts out curious and friendly, with the agents discussing technology companies like Google in a positive way. There is laughter and lighthearted banter about goats and cats. This indicates happiness and amusement.  <br><br>- Neutral: Much of the conversation is also neutral in tone, with the agents exchanging factual information about technology, fish, cats, etc. There is no strong sentiment attached to these factual statements.<br><br>- Curious: Both agents seem curious to learn more, asking each other questions about various topics. This shows an interest to dive deeper into the subjects.<br><br>So in summary, the predominant sentiments expressed in this conversation are happy, neutral and curious. There is a sense of amusement, along with genuine curiosity to learn more about each other&#39;s interests. The tone remains friendly and positive overall.</pre><p>As you can see the response incorporated our instruction to summarize sentiment of the conversation in the predefined categories.</p><p><strong>General question about the conversation:</strong></p><p>Here I ask the following question from Claude that is not about the sentiment or the summarization of the conversation.<strong> “</strong><strong>how many turns of conversation exists in conversation with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?”</strong> This showcases the scenario where LLM has correctly used the general instruction given the question is neither about “conversation summary” nor “conversation sentiment”.</p><p>And here are the run logs:</p><pre>—----- TRUNCATED LOG —----<br><br>Assistant:<br>       <br>&lt;function_calls&gt;<br>&lt;invoke&gt;<br>&lt;tool_name&gt;get_general_instruction&lt;/tool_name&gt;<br>&lt;parameters&gt;<br>&lt;/parameters&gt;<br>&lt;/invoke&gt;<br><br>&lt;/function_calls&gt;<br><br>           &lt;function_results&gt;<br>           &lt;result&gt;<br>           &lt;tool_name&gt;get_general_instruction&lt;/tool_name&gt;<br>           &lt;stdout&gt;<br>           {&#39;instruction&#39;: &#39;Carefully consider all the messages in the provided conversion history. Using this, answer the question.&#39;}<br>           &lt;/stdout&gt;<br>           &lt;/result&gt;<br>           &lt;/function_results&gt;<br><br>To answer the question about the number of turns in the conversation, I will call the get_conversation function to retrieve the conversation history:<br><br>&lt;function_calls&gt;<br>&lt;invoke&gt;<br>&lt;tool_name&gt;get_conversation&lt;/tool_name&gt;<br>&lt;parameters&gt;<br>&lt;id&gt;t_bde29ce2-4153-4056-9eb7-f4ad710505fe&lt;/id&gt;<br>&lt;question&gt;how many turns of conversation exists in conversation with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?&lt;/question&gt;<br>&lt;instruction&gt;{&#39;instruction&#39;: &#39;Carefully consider all the messages in the provided conversion history. Using this, answer the question.&#39;}&lt;/instruction&gt;<br>&lt;/parameters&gt;<br>&lt;/invoke&gt;<br><br>&lt;/function_calls&gt;<br><br>           &lt;function_results&gt;<br>           &lt;result&gt;<br>           &lt;tool_name&gt;get_conversation&lt;/tool_name&gt;<br>           &lt;stdout&gt;<br>           {&#39;conversation&#39;: [{&#39;message&#39;: &#39;Are you a fan of Google or Microsoft?&#39;, &#39;agent&#39;: &#39;agent_1&#39;}, {&#39;message&#39;: &#39;Both are excellent technology they are helpful in many ways. For the security purpose both are super.&#39;, &#39;agent&#39;: &#39;agent_2&#39;}, —----- TRUNCATED CONVERSATION HISTORY —---- {&#39;message&#39;: &#39;I heard that too. Well, it was nice chatting with you. Have a good day. &#39;, &#39;agent&#39;: &#39;agent_1&#39;}], &#39;question&#39;: &#39;how many turns of conversation exists in conversation with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe?&#39;, &#39;instruction&#39;: &quot;{&#39;instruction&#39;: &#39;Carefully consider all the messages in the provided conversion history. Using this, answer the question.&#39;}&quot;}<br>           &lt;/stdout&gt;<br>           &lt;/result&gt;<br>           &lt;/function_results&gt;<br><br>Based on the conversation history, there are 29 messages between the two agents. Since each message represents a turn in the conversation, there are 29 turns of conversation in this conversation with id t_bde29ce2-4153-4056-9eb7-f4ad710505fe.<br><br>Therefore, the answer is 29 turns of conversation.</pre><h3>Conclusion</h3><p>This post presented a creative method for intent identification within chatbot applications, harnessing the power of Anthropic Claude’s function calling capabilities on Bedrock.</p><p>We demonstrated a way to take the complexity of authoring the best prompt for the task away from the user and move it inside the application logic. This potentially can lead to dynamic and responsive chatbots that excel in understanding and fulfilling user intents, ultimately enhancing the user experience within conversational interfaces. You can find the code for this post <a href="https://github.com/caylent/Prompt-Optimization-LLM/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b21b74f17b75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating LLM Performance: A Benchmarking Framework on Amazon Bedrock]]></title>
            <link>https://medium.com/@aliasghar.arabi/evaluating-llm-performance-a-benchmarking-framework-on-amazon-bedrock-7bd6e609ccb8?source=rss-6c9263f24d73------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bd6e609ccb8</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sagemaker]]></category>
            <dc:creator><![CDATA[Ali Arabi]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 20:55:16 GMT</pubDate>
            <atom:updated>2024-02-13T20:55:16.280Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Can also see this post <a href="https://caylent.com/blog/benchmarking-workflow-for-ll-ms-on-bedrock">on the Caylent blog</a>.</blockquote><p>New LLMs are being released on a daily/weekly basis, and practitioners need to evaluate their performance to identify the most suitable ones for specific tasks. For that, different benchmark/evaluation tools and datasets are developed depending on the task the LLM is designed to tackle, whether it is coding, chatbot, summarization, instruction following ability, etc. Some of the popular benchmark datasets and metrics are the <a href="https://arxiv.org/abs/2107.03374v2">HumanEval dataset</a> (code generation benchmark), the <a href="https://arxiv.org/abs/2306.05685">MT Bench</a> (instruction-following ability benchmark), the <a href="https://arxiv.org/abs/2108.07732v1">MBPP</a> (python code generation benchmark), and the <a href="https://lmsys.org/blog/2023-05-03-arena/">Chatbot Arena</a> (chatbot assistant benchmark).</p><p>Assessing LLM performance through automated benchmarking poses a considerable challenge due to the open-ended nature of the tasks, making it highly challenging to develop a program for automated evaluation of response quality. Hence, Human-in-the-loop (HITL), where human evaluators provide feedback on the quality of the text generated by the LLMs for different tasks, proves to be a viable solution. <a href="https://aws.amazon.com/comprehend/">Amazon Comprehend’s</a> <a href="https://aws.amazon.com/comprehend/trust-and-safety/">LLM Trust and Safety</a> features offer an automated approach that can complement human review. AWS also launched the <a href="https://aws.amazon.com/blogs/aws/evaluate-compare-and-select-the-best-foundation-models-for-your-use-case-in-amazon-bedrock-preview/?sc_channel=sm&amp;sc_campaign=Machine_Learning&amp;sc_publisher=LINKEDIN&amp;sc_geo=GLOBAL&amp;sc_outcome=awareness&amp;trk=aiml_reinvent&amp;linkId=251777186">“Model Evaluation on Amazon Bedrock’’</a> feature in re:Invent 2023 which is still in preview mode to create and view model evaluation jobs. It provides three options to evaluate LLMs: 1) to automatically evaluate a single model using recommended metrics for built-in task types, text summarization, question and answer, text classification, and open-ended text generation, 2) to evaluate up to 2 models using a work team of your choice to provide feedback, or 3) to customize the number of models to evaluate using a work-team designated by AWS. If you choose the human evaluation options you can also define a custom task on top of the built-in tasks.</p><p>In this post, we will walk you through an example of a HITL framework to evaluate the performance of LLMs available on Bedrock on your own generated datasets and specific tasks. You may find the code in this <a href="https://github.com/caylent/bedrock-benchmark">github</a> repository.</p><h3><strong>Overall Solution Architecture:</strong></h3><p>From a high-level perspective, our solution consists of the following sections:</p><ul><li>Model Repository</li><li>Prompt Repository</li><li>Prompt/Response Workflow Orchestration</li><li>UI to collect human evaluator feedback</li></ul><p>We will be using Bedrock as the model repository for LLM and <a href="https://aws.amazon.com/dynamodb/">Amazon DynamoDB</a> as a prompt catalog to store our datasets/prompts to be used later in the process. To orchestrate calling Bedrock APIs, parse the response and record the desired output, we use <a href="https://aws.amazon.com/step-functions/">AWS Step Functions</a>. Finally, we will use <a href="https://streamlit.io/">Streamlit</a> to build a quick UI to collect user feedback. Please refer to the following diagram demonstrating how the components are interconnected to build our LLM benchmarking solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fQCk4w7rKUNRVyhH" /></figure><h3><strong>Model Repository</strong></h3><p>For our example, we have included the following LLMs from Bedrock:</p><p><a href="https://aws.amazon.com/bedrock/titan/"><strong>Amazon</strong></a><strong>:</strong></p><ul><li>Amazon Titan Large</li><li>Amazon Titan Express</li></ul><p><a href="https://aws.amazon.com/bedrock/claude/"><strong>Anthropic</strong></a><strong>:</strong></p><ul><li>Anthropic Claude Instant</li><li>Anthropic Claude V2</li></ul><p><a href="https://aws.amazon.com/bedrock/cohere-command-embed/"><strong>Cohere</strong></a><strong>:</strong></p><ul><li>Cohere Command</li></ul><p><a href="https://aws.amazon.com/bedrock/jurassic/"><strong>AI21</strong></a><strong>:</strong></p><ul><li>Jurassic Mid</li><li>Jurassic Ultra</li></ul><p>We will extend this list as new LLMs become available on Bedrock.</p><h3><strong>Prompt Repository</strong></h3><p>We need to store all the prompts for benchmarking LLMs, and DynamoDB is a great option to catalog and version prompts for repeatability. For our example, we have leveraged the following categories/datasets adapted from <a href="https://benchmarks.llmonitor.com/prompts">here</a>. This includes knowledge, code, instruct, creativity, and reflexion. Below is a snapshot of the DynamoDB table that includes our curated prompts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OcYirzo1k-FknbIs" /></figure><h3><strong>Prompt/Response Workflow Orchestration</strong></h3><p>We use Step Function to orchestrate several AWS Lambda functions in parallel by calling Bedrock APIs for each selected LLM and storing the responses in the DynamoDB table. Below, you can find the state machine language and resulting graph after a successful run.</p><h3><strong>Step Function Definition</strong></h3><pre>{<br> &quot;Comment&quot;: &quot;Bedrock Models Benchmark&quot;,<br> &quot;StartAt&quot;: &quot;Parallel&quot;,<br> &quot;States&quot;: {<br>   &quot;Parallel&quot;: {<br>     &quot;Type&quot;: &quot;Parallel&quot;,<br>     &quot;End&quot;: true,<br>     &quot;Branches&quot;: [<br>       {<br>         &quot;StartAt&quot;: &quot;Amazon Models&quot;,<br>         &quot;States&quot;: {<br>           &quot;Amazon Models&quot;: {<br>             &quot;Type&quot;: &quot;Task&quot;,<br>             &quot;Resource&quot;: &quot;arn:aws:states:::lambda:invoke&quot;,<br>             &quot;OutputPath&quot;: &quot;$.Payload&quot;,<br>             &quot;Parameters&quot;: {<br>               &quot;Payload.$&quot;: &quot;$&quot;,<br>               &quot;FunctionName&quot;: &quot;${AmazonFunctionArn}&quot;<br>             },<br>             &quot;Retry&quot;: [<br>               {<br>                 &quot;ErrorEquals&quot;: [<br>                   &quot;Lambda.ServiceException&quot;,<br>                   &quot;Lambda.AWSLambdaException&quot;,<br>                   &quot;Lambda.SdkClientException&quot;,<br>                   &quot;Lambda.TooManyRequestsException&quot;<br>                 ],<br>                 &quot;IntervalSeconds&quot;: 1,<br>                 &quot;MaxAttempts&quot;: 3,<br>                 &quot;BackoffRate&quot;: 2<br>               }<br>             ],<br>             &quot;End&quot;: true<br>           }<br>         }<br>       },<br>       {<br>         &quot;StartAt&quot;: &quot;Anthropic Models&quot;,<br>         &quot;States&quot;: {<br>           &quot;Anthropic Models&quot;: {<br>             &quot;Type&quot;: &quot;Task&quot;,<br>             &quot;Resource&quot;: &quot;arn:aws:states:::lambda:invoke&quot;,<br>             &quot;OutputPath&quot;: &quot;$.Payload&quot;,<br>             &quot;Parameters&quot;: {<br>               &quot;Payload.$&quot;: &quot;$&quot;,<br>               &quot;FunctionName&quot;: &quot;${AnthropicFunctionArn}&quot;<br>             },<br>             &quot;Retry&quot;: [<br>               {<br>                 &quot;ErrorEquals&quot;: [<br>                   &quot;Lambda.ServiceException&quot;,<br>                   &quot;Lambda.AWSLambdaException&quot;,<br>                   &quot;Lambda.SdkClientException&quot;,<br>                   &quot;Lambda.TooManyRequestsException&quot;<br>                 ],<br>                 &quot;IntervalSeconds&quot;: 1,<br>                 &quot;MaxAttempts&quot;: 3,<br>                 &quot;BackoffRate&quot;: 2<br>               }<br>             ],<br>             &quot;End&quot;: true<br>           }<br>         }<br>       },<br>       {<br>         &quot;StartAt&quot;: &quot;Cohere Models&quot;,<br>         &quot;States&quot;: {<br>           &quot;Cohere Models&quot;: {<br>             &quot;Type&quot;: &quot;Task&quot;,<br>             &quot;Resource&quot;: &quot;arn:aws:states:::lambda:invoke&quot;,<br>             &quot;OutputPath&quot;: &quot;$.Payload&quot;,<br>             &quot;Parameters&quot;: {<br>               &quot;Payload.$&quot;: &quot;$&quot;,<br>               &quot;FunctionName&quot;: &quot;${CohereFunctionArn}&quot;<br>             },<br>             &quot;Retry&quot;: [<br>               {<br>                 &quot;ErrorEquals&quot;: [<br>                   &quot;Lambda.ServiceException&quot;,<br>                   &quot;Lambda.AWSLambdaException&quot;,<br>                   &quot;Lambda.SdkClientException&quot;,<br>                   &quot;Lambda.TooManyRequestsException&quot;<br>                 ],<br>                 &quot;IntervalSeconds&quot;: 1,<br>                 &quot;MaxAttempts&quot;: 3,<br>                 &quot;BackoffRate&quot;: 2<br>               }<br>             ],<br>             &quot;End&quot;: true<br>           }<br>         }<br>       },<br>       {<br>         &quot;StartAt&quot;: &quot;AI21 Models&quot;,<br>         &quot;States&quot;: {<br>           &quot;AI21 Models&quot;: {<br>             &quot;Type&quot;: &quot;Task&quot;,<br>             &quot;Resource&quot;: &quot;arn:aws:states:::lambda:invoke&quot;,<br>             &quot;OutputPath&quot;: &quot;$.Payload&quot;,<br>             &quot;Parameters&quot;: {<br>               &quot;Payload.$&quot;: &quot;$&quot;,<br>               &quot;FunctionName&quot;: &quot;${Ai21FunctionArn}&quot;<br>             },<br>             &quot;Retry&quot;: [<br>               {<br>                 &quot;ErrorEquals&quot;: [<br>                   &quot;Lambda.ServiceException&quot;,<br>                   &quot;Lambda.AWSLambdaException&quot;,<br>                   &quot;Lambda.SdkClientException&quot;,<br>                   &quot;Lambda.TooManyRequestsException&quot;<br>                 ],<br>                 &quot;IntervalSeconds&quot;: 1,<br>                 &quot;MaxAttempts&quot;: 3,<br>                 &quot;BackoffRate&quot;: 2<br>               }<br>             ],<br>             &quot;End&quot;: true<br>           }<br>         }<br>       }<br>     ]<br>   }<br> }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_01-2d7LxXyyb11B" /></figure><h3><strong>Lambda Functions:</strong></h3><p>We have developed a Lambda function template and provided LLM-specific prompt configuration and parameters to build 4 Lambda functions, one for each LLM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nZLrGmdO4JaL8CIY" /></figure><p>The outputs of these Lambda functions capture the LLM response, token size (if the output token size is part of the model response otherwise number of characters), latency and model parameters. The results are recorded in another DynamoDB table called “bedrock_benchmark”. The Step Function is scheduled to trigger the Lambda functions daily. If the latest response from an LLM in any category differs from its previous response, then a record is added to this table to detect and track drift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PMZAHTQqqkrQkM-Z" /></figure><p>Below you can see the Lambda function code.</p><pre>import boto3<br>from boto3.dynamodb.conditions import Attr<br>import json<br>import pandas as pd<br>import time<br>import hashlib<br>from datetime import date<br>import os<br>import ast<br><br>bedrock = boto3.client(&quot;bedrock&quot;)<br>bedrock_runtime = boto3.client(&quot;bedrock-runtime&quot;)<br>ddb = boto3.resource(&#39;dynamodb&#39;)<br>dynamodb = boto3.client(&#39;dynamodb&#39;)<br><br>response_s = dynamodb.scan(<br>    TableName=os.environ[&#39;prompt_catalog&#39;])<br><br>table = ddb.Table(os.environ[&#39;benchmark_table&#39;])<br><br>model_shape = json.loads(os.environ[&#39;model_shape&#39;])<br>model_shape = ast.literal_eval(str(model_shape))<br> <br>supported_models = os.environ[&#39;supported_models&#39;]<br>supported_models = ast.literal_eval(supported_models)<br><br>today_date = date.today()<br><br>def computeMD5hash(my_string):<br>    m = hashlib.md5()<br>    m.update(my_string.encode(&#39;utf-8&#39;))<br>    return m.hexdigest()<br><br>def get_prompt_result(model_id,body):<br>    body = json.dumps(body)<br>    print(body)<br>    start_time = time.time()<br>    resp = bedrock_runtime.invoke_model(modelId=model_id, body=body)<br>    end_time = time.time()<br>    elapsed_time = end_time - start_time<br>    return json.loads(resp[&#39;body&#39;].read()), elapsed_time<br><br>def put_item_anthropic(model, response, today_date, resp, elapsed_time, model_shape):<br>    table.put_item(<br>    Item={<br>        &quot;model_prompt_id&quot; : model + &quot;_&quot; + response[&#39;id&#39;].get(&#39;S&#39;) ,<br>        &quot;date&quot; : str(today_date),<br>        &quot;token_size&quot; : len(resp[&quot;completion&quot;].replace(&quot; &quot;,&quot;&quot;)),<br>        &quot;output&quot; : resp[&quot;completion&quot;],<br>        &quot;output_hash&quot; : computeMD5hash(resp[&quot;completion&quot;]),<br>        &quot;prompt_model_id&quot; : response[&#39;id&#39;].get(&#39;S&#39;) + &quot;_&quot; + model,<br>        &quot;latency&quot;: str(elapsed_time),<br>        &quot;model_config&quot;: str(model_shape)<br>    })<br><br>def put_item_amazon(model, response, today_date, resp, elapsed_time, model_shape):<br>    table.put_item(<br>        Item={<br>            &quot;model_prompt_id&quot; : model + &quot;_&quot; + response[&#39;id&#39;].get(&#39;S&#39;),<br>            &quot;date&quot; : str(today_date),<br>            &quot;token_size&quot; : resp[&quot;results&quot;][0][&quot;tokenCount&quot;],<br>            &quot;output&quot; : resp[&quot;results&quot;][0][&quot;outputText&quot;],<br>            &quot;output_hash&quot; : computeMD5hash(resp[&quot;results&quot;][0][&quot;outputText&quot;]),<br>            &quot;prompt_model_id&quot; : response[&#39;id&#39;].get(&#39;S&#39;) + &quot;_&quot; + model,<br>            &quot;latency&quot;: str(elapsed_time),<br>            &quot;model_config&quot;: str(model_shape)<br>    }) <br><br>def put_item_ai21(model, response, today_date, resp, elapsed_time, model_shape):<br>    table.put_item(<br>        Item={<br>            &quot;model_prompt_id&quot; : model + &quot;_&quot; + response[&#39;id&#39;].get(&#39;S&#39;) ,<br>            &quot;date&quot; : str(today_date),<br>            &quot;token_size&quot; : len(resp[&quot;completions&quot;][0][&quot;data&quot;][&quot;tokens&quot;]),<br>            &quot;output&quot; : resp[&quot;completions&quot;][0][&quot;data&quot;][&quot;text&quot;],<br>            &quot;output_hash&quot; : computeMD5hash(resp[&quot;completions&quot;][0][&quot;data&quot;][&quot;text&quot;]),<br>            &quot;prompt_model_id&quot; : response[&#39;id&#39;].get(&#39;S&#39;) + &quot;_&quot; + model,<br>            &quot;latency&quot;: str(elapsed_time),<br>            &quot;model_config&quot;: str(model_shape)<br>    })<br>   <br>def put_item_cohere(model, response, today_date, resp, elapsed_time, model_shape): <br>    table.put_item(<br>        Item={<br>            &quot;model_prompt_id&quot; : model + &quot;_&quot; + response[&#39;id&#39;].get(&#39;S&#39;) ,<br>            &quot;date&quot; : str(today_date),<br>            &quot;token_size&quot; : len(resp[&quot;generations&quot;][0][&quot;text&quot;].replace(&quot; &quot;,&quot;&quot;)),<br>            &quot;output&quot; : resp[&quot;generations&quot;][0][&quot;text&quot;],<br>            &quot;output_hash&quot; : computeMD5hash(resp[&quot;generations&quot;][0][&quot;text&quot;]),<br>            &quot;prompt_model_id&quot; : response[&#39;id&#39;].get(&#39;S&#39;) + &quot;_&quot; + model,<br>            &quot;latency&quot;: str(elapsed_time),<br>            &quot;model_config&quot;: str(model_shape)<br>    })<br><br>def try_prompts():<br>    for response in response_s[&quot;Items&quot;]:<br>        for model in supported_models:<br>            print(f&quot;\tModel: {model}&quot;)<br>            body = model_shape.copy()<br><br>            if model.startswith(&quot;anthropic&quot;):<br>                body[&quot;prompt&quot;] = f&quot;\n\nHuman:{response[&#39;prompt&#39;].get(&#39;S&#39;)}\n\nAssistant:&quot;<br>            elif model.startswith(&quot;amazon.titan&quot;):<br>                body[&quot;inputText&quot;] = response[&#39;prompt&#39;].get(&#39;S&#39;)<br>            elif model.startswith(&quot;ai21&quot;):<br>                body[&quot;prompt&quot;] = response[&#39;prompt&#39;].get(&#39;S&#39;)<br>            elif model.startswith(&quot;cohere&quot;):<br>                body[&quot;prompt&quot;] = response[&#39;prompt&#39;].get(&#39;S&#39;)<br>           <br>            resp, elapsed_time = get_prompt_result(model, body)<br>           <br>            data_old = []<br>            scan_kwargs = {<br>                &quot;FilterExpression&quot;: Attr(&#39;model_prompt_id&#39;).eq(f&quot;{model}_{response[&#39;id&#39;].get(&#39;S&#39;)}&quot;)<br>            }<br>           <br>            done = False<br>            start_key = None<br>            while not done:<br>                if start_key:<br>                    scan_kwargs[&quot;ExclusiveStartKey&quot;] = start_key<br>                response_old = table.scan(**scan_kwargs)<br>                data_old.extend(response_old.get(&quot;Items&quot;, []))<br>                start_key = response_old.get(&quot;LastEvaluatedKey&quot;, None)<br>                done = start_key is None<br>           <br>            if model.startswith(&quot;anthropic&quot;):<br>                if len(data_old) == 0:<br>                    put_item_anthropic(model, response, today_date, resp, elapsed_time, model_shape)<br>                elif computeMD5hash(resp[&quot;completion&quot;]) != data_old[-1][&#39;output_hash&#39;]:<br>                    put_item_anthropic(model, response, today_date, resp, elapsed_time, model_shape)<br>   <br>            elif model.startswith(&quot;amazon.titan&quot;):<br>                if len(data_old) == 0:<br>                    put_item_amazon(model, response, today_date, resp, elapsed_time, model_shape)<br>                elif computeMD5hash(resp[&quot;results&quot;][0][&quot;outputText&quot;]) != data_old[-1][&#39;output_hash&#39;]:<br>                    put_item_amazon(model, response, today_date, resp, elapsed_time, model_shape)<br>           <br>            elif model.startswith(&quot;ai21&quot;):<br>                if len(data_old) == 0:<br>                    put_item_ai21(model, response, today_date, resp, elapsed_time, model_shape)<br>                elif computeMD5hash(resp[&quot;completions&quot;][0][&quot;data&quot;][&quot;text&quot;]) != data_old[-1][&#39;output_hash&#39;]:<br>                    put_item_ai21(model, response, today_date, resp, elapsed_time, model_shape)<br>               <br>            elif model.startswith(&quot;cohere&quot;):<br>                if len(data_old) == 0:<br>                    put_item_cohere(model, response, today_date, resp, elapsed_time, model_shape)<br>                elif computeMD5hash(resp[&quot;generations&quot;][0][&quot;text&quot;]) != data_old[-1][&#39;output_hash&#39;]:<br>                    put_item_cohere(model, response, today_date, resp, elapsed_time, model_shape)<br><br>def lambda_handler(event, context):<br><br>    try_prompts()<br><br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: json.dumps(&#39;Done!&#39;)<br>    }</pre><p>We had to time the invocation latency and calculate output token size in the code, but while writing this blog post, Bedrock invocation metrics including InputTokenCount, OutputTokenCount, and InvocationLatency were added to CloudWatch Metrics and as part of the response as well. Thanks to AWS’s continuous improvement, one can update the above code to retrieve the metrics and simplify the code.</p><p>As you can see in screenshots below, each LLM on Bedrock has a different input configuration, which is provided to the corresponding Lambda function as environment variables. You may tweak parameters influencing the LLM response, including temperature, top P, max token count, and top K. The naming convention across models might be different, which has made the Lambda function lengthy to accommodate all variations. If you implement this workflow for a real application, modify the parameters to fit your requirements.</p><p><strong>Amazon Titan Lambda Function Variables:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HVMA7FE1NraRYVaA" /></figure><p><strong>Anthropic Claude Lambda Function Variables:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*leyeUPD3XnnsPV0J" /></figure><p><strong>Cohere Lambda Function Variables:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xYsXq8M92YXDz_Qc" /></figure><p><strong>AI21 Lambda Function Variables:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*unj9tBTgNBoGcWZi" /></figure><h3>User Interface — feedback collection</h3><p>We used Streamlit to build a simple but effective UI to present the cases where the response for any LLM in any category is different from its previous one and to collect feedback from a human evaluator. The user can choose between 0 to indicate “INCORRECT”, 1 for “CORRECT” response, and 2 for “EXCELLENT” to guide improvements.</p><p>In our Streamlit app, it first fetches all of the curated prompts as well as the most recent LLM response and their previous different response. Then it iterates through them by presenting the identified cases to the user, collecting user feedback accordingly and finally storing the feedback in the DynamoDB table.<strong> </strong>We deployed our Streamlit app in SageMaker Studio using a Terminal instance, and here is how it looks with an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PJXoEcUxBjWbEqLd" /></figure><p>If you keep running this workflow and collect user feedback accordingly, you can create informative radar charts to demonstrate each LLM’s capabilities in different tasks quickly. You can also monitor the trend to observe the stability of a certain model over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/0*xzdjuKMdYl8W3-Y0" /></figure><h3><strong>Conclusion</strong></h3><p>In this quick guide we presented a simple solution where you can build your curated dataset and the human-in-the-loop workflow using AWS services and Streamlit to benchmark LLMs available on Bedrock to choose the best option for your specific tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bd6e609ccb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLMOps — MLOps for LLMs on AWS]]></title>
            <link>https://medium.com/@aliasghar.arabi/llmops-mlops-for-llms-on-aws-4be4e6a08bdf?source=rss-6c9263f24d73------2</link>
            <guid isPermaLink="false">https://medium.com/p/4be4e6a08bdf</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Ali Arabi]]></dc:creator>
            <pubDate>Thu, 12 Oct 2023 17:51:33 GMT</pubDate>
            <atom:updated>2025-02-11T20:06:10.511Z</atom:updated>
            <content:encoded><![CDATA[<h3>LLMOps — MLOps for LLMs on AWS</h3><blockquote><em>Can also see this post </em><a href="https://caylent.com/blog/ml-ops-for-large-language-models"><em>on the Caylent blog</em></a><em>.</em></blockquote><p>In my last <a href="https://medium.com/@aliasghar.arabi/aws-mlops-a-reference-architecture-a6999c022045">post</a>, I presented a reference architecture for building end-to-end MLOps solutions on AWS based on the SageMaker ecosystem. With the emergence of the Large Language Models (LLMs), enterprises are eager to adopt the latest AI advances to transform their business.</p><p>To succeed with generative AI, it is crucial to design a cost-effective, scalable, differentiated, and well-governed solution to manage the model lifecycle and account for the rapid pace of change. Enterprises need to leverage their substantial private data to tailor these applications for their specialized domain and competitive advantages. Seamlessly and efficiently integrating all of these concerns can be a complex undertaking, but this post will give the reader actionable advice to begin building their LLMOps platform.</p><p>Today I am proposing an extension of MLOps for the operationalization of Language Model (LLM) solutions, denoted as LLMOps, specifically on the Amazon Web Services (AWS) platform. The emphasis will be on the required modifications and augmentations necessary to tailor our MLOps framework to accommodate LLM projects. Keep in mind that this is a rapidly evolving field and our recommendations will evolve as AWS releases additional products in this field.</p><h3>Data Preparation:</h3><p>LLMs are typically trained on a huge amount of text data to learn how to generate the next token. To adapt them for a downstream task such as text classification, you need to prepare the relevant text and corresponding labels/annotations. In AWS, there are a few possible options among others to prepare data for training/tuning LLMs such as Amazon Textract and/or Amazon Comprehend part of AI Services that AWS offer to extract entities from images or documents, or classify documents. Furthermore, If you need to implement your own logic then you may leverage the lambda function. Finally Amazon SageMaker Ground Truth enables you to annotate or label the text data using human or by setting up an active learning workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qj0-As8J2yDuPdyKbKPWQ.png" /><figcaption>Image 1: Data Preparation for LLM (image by the author)</figcaption></figure><h3>Prompt Engineering and Prompt Catalogs:</h3><p>The simplest and cheapest approach to harness the capabilities of an LLM in your Gen AI application is to use “In-context learning”. It provides instructions at inference time using techniques like “zero-shot”, “one-shot”, and “few-shot” learning depending on how many demonstrations are provided as proposed in the paper called “<a href="https://arxiv.org/pdf/2005.14165.pdf">Language Models are Few-Shot Learner</a>s”. There are also more advanced techniques such as chain-of-thought where steps of reasoning are provided when prompting the language model to be able to perform sophisticated tasks that require reasoning. When the number of projects utilizing LLMs in an organization grows, it is recommended that all the engineered prompts are cataloged and versioned for repeatability. This makes it simple to reuse prompts for additional projects and, more importantly, to be monitored for any drift over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFYeRe58juafJTZD_-1GDQ.png" /><figcaption>Image 2: Prompt Catalog (image by the author)</figcaption></figure><h3>Model Fine-Tuning:</h3><p>Although using Prompt Engineering is comparably easiest to implement, it can only provide initial instructions to the model. Moreover, all the LLMs are constrained by the number of tokens that can be passed to them at the time of inference and using a long prompt can increase the total cost of ownership (TCO) if a paid service (per-token) is used. The next logical step is to fine tune an LLM on a curated dataset to make it more domain specific. Depending on the availability of labeled data and availability of computational power you will have two options: full fine-tuning or Parameter-Efficient fine tuning (PEFT). Full fine tuning the FM requires thousands of examples with high computational power to tune all the weights and biases of the selected model. On the other hand, PEFT can still be performed with tens of examples and way less computational power required making it a more cost effective option. Some of the common PEFT techniques include:</p><ul><li><a href="https://arxiv.org/abs/2106.09685">Low-Rank Adaptation (LoRA)</a> which reduces the number of trainable parameters for downstream tasks by freezing the pre-trained model weights. This method involves adding adapters after each of the transformer sub-layers.</li><li><a href="https://arxiv.org/abs/2305.14314">QLoRA</a> extends LoRA by quantizing original weight values, from high-resolution data types, such as Float32, to lower-resolution data types like int4 resulting in reduced memory demand.</li><li><a href="https://arxiv.org/abs/2104.08691">Prompt-tuning</a> / <a href="https://aclanthology.org/2021.acl-long.353/">Prefix-tuning</a> by attaching a soft prompt to the top most embedding layer in the beginning of the transformer layers and training only the added prompt tokens while keeping trained LLM frozen.</li><li><a href="https://arxiv.org/abs/2303.16199">LLaMa-Adapter</a> a modified version of prefix tuning in which soft prompts are added at the N top-most transformer layers beside initializing the parameters near the attention mechanism to zero instead of at random to avoid “corruption” of LLaMa’s original knowledge.</li></ul><p>You can use LLMs available from leading AI startups through APIs on <a href="https://aws.amazon.com/bedrock/">Amazon Bedrock</a>, LLMs maintained on <a href="https://aws.amazon.com/sagemaker/jumpstart/">SageMaker JumpStart</a>, or any open-source or proprietary LLM model on SageMaker to train or fine-tune on custom datasets. If you prefer to keep full control on the training pipeline and you do not need out-of the box capability provided by SageMaker such as data capture, model monitoring, auto scaling you may choose to run the workload on EKS or <a href="https://aws.amazon.com/ec2/instance-types/dl1/">Amazon EC2 DL1 instances</a> a low cost-to-train option for deep learning models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXF2yNp5Cxdc3P9DU0ptSg.png" /><figcaption>Image 3: LLM Tuning Pipeline (image by the author)</figcaption></figure><h3>Retrieval Augmented Generation (RAG):</h3><p>If you need LLM to create a response that can leverage additional context present in the proprietary data then RAG is the solution. This technique uses semantic search to retrieve relevant and timely context to augment the LLM’s responses for more accurate results. It typically involves creating embeddings and setting up vector stores. In AWS there are several options to choose for the vector store, including pgvector in Amazon RDS for PostgreSQL or Amazon Aurora PostgreSQL, Amazon OpenSearch Serverless Vector Store, and Amazon Kendra. The benefit of using Amazon Kendra though is that it can be used both to create embeddings as well as to perform semantic search, so you are not dependent on another FM model for embedding. This makes your Gen AI application design much simpler and modular. It is also worth noting that compared to fine tuning, RAG has higher flexibility and is more cost effective. Many solutions will use a combination of fine-tuning and RAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oN8JEdi8yqCVSTmbrj4eSg.png" /><figcaption>Image 4: Retrieval Augmented Generation (RAG) (image by the author)</figcaption></figure><h3>Processing Power:</h3><p>Due to the large size of Large language models and the large datasets required to train or fine-tune a language model, using GPUs is typically required to be able to fit the model or the data in the memory of the instance. AWS has additional options beyond GPUs like the AWS Trainium instance which is a machine learning (ML) accelerator purposely built for deep learning training of 100B+ parameter models. You can further leverage AWS’s custom silicon for inference with AWS Infrentia2, which provides high performance at the lowest cost for deep learning inference.</p><p>In many cases distributing the model or data in several GPU units is required. SageMaker supports distributed training on single and multiple instances out of the box. It also supports other frameworks and packages such as PyTorch DistributedDataParallel (DDP) for which all you need to do is to add additional configuration in your training estimator as illustrated in the below code snippet.</p><pre>from sagemaker.pytorch import PyTorch<br>estimator = PyTorch(<br>    instance_count=2,<br>    instance_type=&quot;ml.p4d.24xlarge&quot;,<br>    distribution={&quot;pytorchddp&quot;: {&quot;enabled&quot;: True}}  <br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_tnqzOmUF5rDH8zXrLKYg.png" /><figcaption>Image 5: Distributed Training on Sagemaker (image by the author)</figcaption></figure><p>When using data or model parallelism features in SageMaker it is recommended to use instances with high-throughput, low-latency.</p><h3>Evaluation:</h3><p>If you are using LLMs for traditional ML problems such as sentiment analysis or classification in general you can still use traditional ML performance metrics such as accuracy, precision, and recall. However, to evaluate the LLM’s performance depending on the task it is used for, we may use different metrics. Some of well known ones are:</p><ul><li>BLEU for machine translation which compares precision of n-grams between reference input and generated output</li><li>METEOR for machine translation which is based on the harmonic mean of unigram precision and recall, with recall weighted higher than precision.</li><li>ROUGE for summarization which considers precision, recall, and F1-Score over a sequence.</li><li>Perplexity for text generation which measures how well the trained model has learned the distribution in text.</li><li><a href="https://arxiv.org/abs/1904.09675">BERTScore</a> for text generation (embedding similarity)</li><li>CIDEr that measures the similarity between a generated caption for an image and the reference captions.</li><li>SPICE that evaluates caption generated for an image by placing importance on capturing details about objects, attributes, relationships (semantic propositions)</li><li>Using larger models with a bigger number of parameters to evaluate responses generated by smaller language models</li><li>Universal benchmarks for a range of tasks: machine translation, summarization, natural language generation, question answering, and more. Some of the famous benchmarks are <a href="https://arxiv.org/pdf/2101.00027.pdf">Pile</a>, <a href="https://arxiv.org/abs/1804.07461">GLUE</a>, <a href="https://arxiv.org/abs/1905.00537">SuperGLUE</a>, <a href="https://arxiv.org/abs/2009.03300">MMLU</a>, <a href="https://arxiv.org/abs/1606.06031">LAMBADA</a>, and <a href="https://arxiv.org/abs/2206.04615">Big Bench Collaboration Benchmarks</a>,</li><li>Code specific benchmarks: <a href="https://github.com/openai/human-eval">HumanEval</a>, and Mostly Basic Python Programming (<a href="https://github.com/google-research/google-research/tree/master/mbpp">MBPP</a>)</li><li>Human in the loop (HITL) where human evaluators provide feedback on the quality of the generated text by the model</li></ul><h3>Hosting Options:</h3><p>Traditional hosting solutions used for smaller models do not provide required optimization functionality to host LLM models with optimal inference latency and/or throughput. With SageMaker you can use <a href="https://github.com/aws/deep-learning-containers/blob/master/available_images.md#large-model-inference-containers">large model inference container</a> images with <a href="https://github.com/deepjavalibrary/djl-serving">Deep Java Library (DJL) Serving.</a> SageMaker supports model parallelism and inference optimization libraries including:</p><ul><li><a href="https://www.deepspeed.ai/">DeepSpeed</a> an open-source inference optimization library</li><li><a href="https://huggingface.co/docs/accelerate/index">Hugging Face Accelerate</a> an open-source model parallel inference library</li><li><a href="https://github.com/NVIDIA/FasterTransformer">FasterTransformer</a> an Nvidia open source library for efficiently running transformer-based neural network inference</li></ul><p>Additionally you can host LLMs on SageMaker using <a href="https://huggingface.co/blog/sagemaker-huggingface-llm">Hugging Face LLM Deep Learning Container</a> (DLC) enabling high-performance text generation through tensor parallelism, dynamic batching, and model quantization.</p><h3>Monitoring:</h3><p>Prompts, generated response, and RAG performance need to be closely monitored in production along with data quality, model quality, infrastructure utilization, endpoint latency and throughput.</p><p>It is also important to compare their capabilities to a baseline overtime for any drift or eventual degradation of quality in the generated response.</p><p>Some of the proposed metrics to monitor prompts/responses are: context, relevance to prompt, existence of pattern (repetitiveness), repeatability, readability, token size, jailbreaking, injection, refusal, sentiment, toxicity, response hallucination. For RAG it is recommended to monitor chunk size, produced embeddings, embedding speed, and semantic search results. All of these aspects need to be monitored over time to facilitate timely remediation through retraining.</p><p>It is also possible to implement a Shadow Testing or AB Testing pipeline to compare different prompts, embeddings, and/or LLMs over time to choose the best one for different use cases. SageMaker provides these features out of the box and they can also be combined with other open source tools such as MLflow to get the best of all of them.</p><p>In many cases where automated monitoring is not possible or relevant benchmark is not available for your specific domain you can use the human-in-the-loop capabilities of SageMaker through SageMaker Augmented AI (A2I) to implement human review of LLM predictions in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acWR0PbUtjLwha6CicHF_g.png" /><figcaption>Image 6: Human in the loop — SageMaker A2I</figcaption></figure><h3>Final LLMOps Solution Architecture:</h3><p>If we add all the above components to our existing MLOps solution it will turn to the following high level architecture which serves as an end-to-end solution to automate and operationalize the LLM models. Of course, AWS is always releasing new services so you should expect this architecture to change slightly after re:Invent 2023.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7R1g214_aZoTqj5IQlYdQQ.png" /><figcaption>Image 7: LLMOps Reference Architecture on AWS (image by th author)</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4be4e6a08bdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS MLOps — A Reference Architecture]]></title>
            <link>https://medium.com/@aliasghar.arabi/aws-mlops-a-reference-architecture-a6999c022045?source=rss-6c9263f24d73------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6999c022045</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[cicd]]></category>
            <dc:creator><![CDATA[Ali Arabi]]></dc:creator>
            <pubDate>Tue, 13 Dec 2022 17:38:34 GMT</pubDate>
            <atom:updated>2022-12-13T17:38:34.491Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS MLOps — A Reference Architecture</h3><p><em>Can also see this post on the </em><a href="https://caylent.com/blog/aws/from-machine-learning-code-to-mlops-a-reference-architecture"><em>Caylent blog</em></a><em>.</em></p><p><a href="https://aws.amazon.com/sagemaker/">Amazon SageMaker</a> is a fully managed service that makes it easy for enterprises to build end-to-end production-ready machine learning pipelines without sacrificing speed, security, and accessibility. This article will propose a reference architecture based on the Amazon SageMaker ecosystem so you can get started right away with your own ML projects operating on the AWS platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*7Wlmo6GzW_9DAevnKdvdGg.png" /><figcaption><strong>Fig 1: MLOps components (image by the author)</strong></figcaption></figure><p>We will start with the simplest form of Machine Learning Operations (MLOps) and gradually add other building blocks to have a complete picture in the end. Let’s dive in!</p><p><strong>Exploration block:</strong></p><p>Given a business problem or a process improvement opportunity identified and documented by the business analyst, the machine learning operation starts with exploratory data analysis “EDA” where data scientists familiarize themselves with a sample of data and apply several machine learning techniques and algorithms to find the best ML solution. They will leverage <strong>Amazon SageMaker Studio</strong> which is a web-based integrated development environment (IDE) for machine learning to ingest the data, perform data analysis, process the data, and train and deploy models for making inferences using a non-production endpoint. Inside <a href="https://aws.amazon.com/sagemaker/studio/">Amazon SageMaker Studio</a> they have access to Amazon SageMaker Data Wrangler which contains over 300 built-in data transformations to quickly prepare the data without having to write any code. <a href="https://aws.amazon.com/athena/">Amazon Athena</a> and<a href="https://aws.amazon.com/glue/"> AWS Glue</a> are other tools that can be used to explore and prepare data. All the experiments by the data scientists will be tracked using SageMaker Experiment capability for reproducibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q1qtIK10lS4apLLSQ7tlVA.png" /><figcaption><strong>Fig 2: MLOps Exploration block (Image by the author)</strong></figcaption></figure><p><strong>ML Workflow block:</strong></p><p>Next, machine learning engineers convert the proposed solution by the data scientist to the production-ready ML code and create end-to-end machine learning workflow including data processing, feature engineering, training, model evaluation, and model creation for deployment using a variety of available hosting options. In AWS there are 4 options for orchestrating end-to-end ML workflow with Amazon SageMaker integration:</p><ul><li><strong>Amazon SageMaker Pipeline</strong>: Using <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-sdk.html">Pipelines SDK</a> a series of interconnected steps will build the entire ML pipeline that is defined using a directed acyclic graph (DAG).</li><li><strong>Amazon Managed Workflow for Apache Airflow (MWAA)</strong>: Using Airflow SageMaker operators or using Airflow PythonOperator end-to-end ML pipeline can be configured, scheduled, and monitored.</li><li><strong>AWS Step Function workflow</strong>: Integration between AWS SageMaker and AWS Step Functions through the <a href="https://github.com/aws/aws-step-functions-data-science-sdk-python">AWS Step Function Data Science SDK</a> allows one to easily create multi-step machine learning workflows.</li><li><strong>Kubeflow Orchestration</strong>: SageMaker components for Kubeflow pipelines allows you to submit SageMaker processing, training, HPO jobs, and deploy the model directly from the Kubeflow pipeline workflow.</li></ul><p>As part of the model evaluation/test step, <strong>AWS Step Function</strong> is launched to run a comprehensive suite of ML-related tests. Additionally, <strong>Amazon SageMaker Feature Store</strong> is used to store, share, and manage features for machine learning (ML) models during training (offline storage) and inference (online storage). Finally, <strong>SageMaker ML Lineage tracking</strong> is enabled to track data, and model lineage metadata which is crucial for ML workflow reproducibility, model governance, and audit standards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RnSBIXUyhrskW-DkaFXoOg.png" /><figcaption><strong>Fig. 3: MLOps ML Workflow block (image by the author)</strong></figcaption></figure><p><strong>Continuous Integration block:</strong></p><p>After implementing the first two blocks we already have a fully functioning ML workflow and endpoint that can be called by users or applications to consume the ML prediction. To take this to the next level and to eliminate manual work as a result of making any update to the code or infrastructure, an MLOps engineer will build up the Continuous Integration (CI) block enabling data scientists or ML engineers to regularly merge their changes into <a href="https://aws.amazon.com/codecommit/">AWS CodeCommit</a>, after which automated builds and tests are run using <a href="https://aws.amazon.com/codebuild/">AWS CodeBuild</a> including building any custom ML image based on the latest container hosted on <a href="https://aws.amazon.com/ecr/">Amazon ECR</a> which will be referenced by the ML workflow consequently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1tgfqCNedtZxR-T7LasI4g.png" /><figcaption><strong>Fig. 4: MLOps Continuous Integration block (Image by the author)</strong></figcaption></figure><p><strong>Continuous Deployment block:</strong></p><p>Not only we want to build and test our ML application each time a code change is pushed to <strong>AWS CodeCommit</strong>, but also, we want to deploy the ML application in production continuously. In the Continuous Deployment (CD) block the proposed solution is extended to decouple the model training workflow from the model deployment section. This provides an opportunity to update the model configuration and infrastructure without affecting the training workflow. To manage model versions, model metadata, and automate the model deployment with CI/CD, the <strong>Amazon SageMaker Model Registry</strong> is used. Here, the manual approver (e.g. the senior data scientist), will approve the model which triggers a new automated deployment through <strong>CodePipeline</strong>, <strong>CodeBuild</strong>, and <strong>AWS CloudFormation</strong>.. The Automatic Rollback feature of AWS CloudFormation is key here, in case anything goes wrong during the deployment. <strong>SageMaker elastic endpoint</strong> autoscaling is also configured to handle changes in the inference workload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6gujp2Oj-0RRDB3TLdNLw.png" /><figcaption><strong>Fig. 5: MLOps Continuous Deployment block (Image by the author)</strong></figcaption></figure><p><strong>Monitoring &amp; Continuous Training block:</strong></p><p>When building machine learning models we assume that the data that the model was trained on will be similar to the data used when making predictions. Therefore, any drift in data distribution or model performance on the new inference data will result in data scientists needing to revisit the features or retrain the model to reflect the most recent changes. The Continuous Training (CT) block continuously monitors the data and model quality to detect any bias or drift and inform a timely remediation . This will be achieved by enabling <strong>Amazon SageMaker Model Monitor</strong> in the inference endpoint configuration, creating baseline jobs during data prep and training along with <strong>SageMaker Clarify</strong> feature and <a href="https://aws.amazon.com/cloudwatch/">Amazon CloudWatch</a> event to automatically monitor for any drift, trigger re-training, and notify the relevant parties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y32XovEGRHwNg7EqfobDAQ.png" /><figcaption><strong>Fig. 6: MLOps Continuous Training block (Image by the author)</strong></figcaption></figure><p><strong>Security and governance consideration:</strong></p><p>To make our MLOps architecture secure, some important security and governance requirements are recommended. This includes:</p><ul><li>Deploying the solution in a VPC and securely connecting resources to SageMaker Studio through VPC endpoints.</li><li>Separation of concerns through multi-account architecture. <strong>AWS Control Tower</strong> offers a mechanism to easily set up and secure multi-account AWS environments.</li><li>Defining proper user and service roles to perform required operations on the AWS account and running tasks such as SageMaker training and ML workflow. <strong>AWS IAM</strong> is a powerful service for this purpose.</li><li>Implementing the least-privilege policy. <strong>AWS Service Catalog</strong> allows customers to implement products with required resources centrally provisioned without requiring each user to launch them separately.</li><li>Enforcing guardrails such as requiring proper resource tagging or limiting the type of resources used, for different users and roles. <strong>AWS Organizations</strong> and its <strong>Service Control Policies</strong> (SCP) feature can be used as an enterprise scale guardrail management.</li><li>Encrypting the traffic at rest and in transit. Beyond the default encryption of model artifacts and storage attached to training instances by SageMaker, <strong>AWS KMS</strong> key can be used to encrypt sensitive data.</li></ul><p>In this blog post, we have proposed a reference architecture to build an end-to-end secure, scalable, repeatable, and reproducible MLOps solution to process data, train, create/update model, deploy and monitor deployed model using SageMaker features with CI/CD/CT concepts incorporated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6999c022045" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Which AWS SageMaker Model Hosting Option to choose for your specific need?]]></title>
            <link>https://medium.com/@aliasghar.arabi/which-aws-sagemaker-model-hosting-option-to-choose-for-your-specific-need-8fa35ab82e31?source=rss-6c9263f24d73------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fa35ab82e31</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[aws-sagemaker]]></category>
            <category><![CDATA[ml-model-deployment]]></category>
            <dc:creator><![CDATA[Ali Arabi]]></dc:creator>
            <pubDate>Tue, 18 Oct 2022 03:02:56 GMT</pubDate>
            <atom:updated>2022-10-19T01:19:20.894Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS SageMaker Model Hosting Options</h3><blockquote>Can also see this post <a href="https://caylent.com/blog/aws/sagemaker-endpoint-options">on the Caylent blog</a>.</blockquote><p>AWS SageMaker Inference Endpoints are a powerful tool to deploy your machine learning models in the cloud and make predictions on new data at scale. However, it can be challenging to understand which deployment options to pick. This article aims to provide an overview of the various options and help you decide which endpoint deployment type is best for your use case. Depending on the business use case, inference workload, required latency, and cost factors, to name a few, one can choose from one of the options below:</p><ul><li><a href="https://docs.aws.amazon.com/sagemaker/latest/dg/serverless-endpoints.html">Serverless Inference</a></li><li><a href="https://docs.aws.amazon.com/sagemaker/latest/dg/realtime-endpoints.html">Real-Time Inference</a></li><li><a href="https://docs.aws.amazon.com/sagemaker/latest/dg/async-inference.html">Asynchronous Inference</a></li><li><a href="https://docs.aws.amazon.com/sagemaker/latest/dg/batch-transform.html">Batch Transform</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k5Y25cfrsGfoImoD" /><figcaption>Fig. 1: ML Model Hosting options on AWS (Image created by the author)</figcaption></figure><h3><strong>SageMaker Inference Endpoint Options:</strong></h3><h4><strong>Serverless Inference:</strong></h4><p>Serverless Inference is a fully managed inference endpoint, suitable for workloads with intermittent or infrequent traffic patterns, with built-in high-availability and fault tolerance capabilities. There is no need to select instance types, provision capacity, or set scaling policies as the service automatically provisions and scales up or down the compute capacity based on the volume of inference requests. Two things to remember: the maximum request payload for serverless inference endpoints is 4 MB with a 60-second timeout. The main configuration for serverless inference includes memory size selection, up to 6GB. A suitable workload for these endpoints is form processing for a bank’s mortgage department or chatbots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZKIajMjEFQ_CyKzf" /><figcaption>Fig. 2: Serverless Inference (Image created by the author)</figcaption></figure><h4><strong>Real-time Inference:</strong></h4><p>These endpoint types are also fully managed and suitable for workloads with high throughput and low latency requirements. The main configuration for real-time inference includes setting the autoscaling policy, compute resource selection, and the deployment mode. The deployment modes include single model, multi-model, and inference pipeline. The maximum request payload is 6 MB with a 60-second timeout. However, real-time inference endpoints can leverage many different <a href="https://aws.amazon.com/sagemaker/pricing/#On-Demand_Pricing">instance types</a> with up to eight NVIDIA A100 Tensor Core GPUs, 100Gbps networking, 96 vCPUs, 1.1TB instance memory, and 8TB of NVMe storage. When configuring the endpoint, customers can use <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/model-ab-testing.html">production variants</a> to deploy different model versions with A/B testing or shadow deployment strategies. An example of a typical workload is personalized recommendations for users on an e-commerce website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DBJcpRlfVXF7m7eu" /><figcaption>Fig. 3: Real-time Inference (Image created by the author)</figcaption></figure><h4><strong>Asynchronous Inference:</strong></h4><p>If your request payload is large (up to 1GB), involves long-running processes (up to 15 mins), and latency is not a concern, then asynchronous Inference is the best option for you. In this scenario, inference requests are handled asynchronously using an internal queue system. Unlike serverless and real-time inference endpoints, the request and the response for asynchronous inference are placed and referenced in an S3 bucket. Typical workloads suitable for asynchronous endpoints are computer vision or NLP problems where the payloads can be large, such as videos or documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sn9IETnMYso-qrNe" /><figcaption>Fig. 4: Asynchronous Inference (Image created by the author)</figcaption></figure><h4><strong>Batch Transform:</strong></h4><p>In some cases, the persistent compute resource is not necessary, and the application needs to make inferences against a large dataset which can be scheduled as an Ad-hoc job. For this scenario, long-running Batch Transform jobs can be used to handle large payloads using a batch strategy (mini batches of up to 100 MB each). Similar to the asynchronous inference endpoints, the request and the response are placed in an S3 bucket. Batch Transform inference endpoints can also be a viable option to test different models by implementing multiple transform jobs per each model. An example of a typical workload is propensity modelling for user conversion to inform correct treatment and offer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ivwj47YPBT6QCgKV" /><figcaption>Fig. 5: Batch Transform inference (Image created by the author)</figcaption></figure><p>The table below summarizes the four options and can be used to inform the best model hosting option on AWS SageMaker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SbBlqHr-DjrtsoRd-bkM-w.png" /><figcaption>Table 1: AWS SageMaker Model Hosting Option comparison</figcaption></figure><h3><strong>Latency vs Cost considerations:</strong></h3><p>Beyond understanding the available AWS SageMaker hosting options, there are also some strategies and capabilities that we can leverage to pick the right balance between latency and cost which we will review a few of them below.</p><h4><strong>AWS PrivateLink deployment:</strong></h4><p>Overall, ML application latency consists of overhead latency and model inference latency. AWS PrivateLink deployments make it possible to reduce overhead latency and improve security by keeping all the inference traffic within your VPC and by using the endpoint deployed in the AZ closest to the origin inference traffic to process the invocations. By default, SageMaker endpoints deploy in 2 different AZs.</p><h4><strong>Elastic Inference:</strong></h4><p>If you need to host a deep learning model for inferencing and are on a budget, you can leverage Amazon SageMaker Elastic Inference (EI) which costs less than a full GPU instance but with comparable high throughput and low latency. You must use an EI-enabled version of TensorFlow, PyTorch, MXNet, or other frameworks using ONNX. Be warned, Elastic Inference doesn’t support all operations across all ML frameworks. Make sure you test your model with EI.</p><h4><strong>Nvidia Triton Inference:</strong></h4><p>If the inference workflow is composed of several complicated steps, including preprocessing, transformation, model selection, and post-processing, then Triton can maximize throughput while also providing ultra-low inference latency. With Triton Inference Server integrated with SageMaker supporting ML frameworks such as TensorFlow, PyTorch, XGBoost, NVIDIA TensorRT, and other frameworks using ONNX, users can choose among NVIDIA GPUs, CPUs, and AWS Inferentia for the compute resource.</p><h4><strong>Multi-model inference endpoint</strong></h4><p>Another cost-effective hosting option is a multi-model endpoint. Multi-model inference endpoints allow customers to improve endpoint utilization by hosting multiple models on the same serving container and sharing the memory across models. Models can be added or removed from the real-time multi-model inference endpoint. This is a good option for hosting similar models in size and latency behind a single endpoint. This option works with Auto Scaling and AWS PrivateLink.</p><h4><strong>AWS SageMaker Inference Recommender:</strong></h4><p>It is always a good idea to test different configurations for the inference endpoint for the best performance at the lowest cost for your particular use case. Users can now leverage the AWS SageMaker Inference recommender capability to load test the real-time endpoint with different configurations based on the specified ML Framework, ML Domain, and ML Task right in a SageMaker notebook, which will eliminate weeks of manual testing and tuning time. Users can then choose the best configuration options based on the reported metrics for latency, price, performance, and throughput.</p><p>In this blog post, we’ve reviewed the different possible ML inference endpoints on AWS SageMaker and their typical use cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fa35ab82e31" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>