Logo Zephyrnet

Chuyển đổi các hoạt động tương tác trực tiếp với khách hàng: Xây dựng các tác nhân xử lý đơn hàng có khả năng nói bằng AWS và AI tổng quát | Dịch vụ web của Amazon

Ngày:

Trong bối cảnh tương tác trực tiếp giữa khách hàng để đặt hàng ngày nay, thông lệ phổ biến vẫn tiếp tục dựa vào người phục vụ là con người, ngay cả trong những môi trường như quán cà phê lái xe qua và cửa hàng thức ăn nhanh. Cách tiếp cận truyền thống này đặt ra một số thách thức: nó phụ thuộc nhiều vào các quy trình thủ công, gặp khó khăn trong việc mở rộng quy mô một cách hiệu quả với nhu cầu ngày càng tăng của khách hàng, tiềm ẩn sai sót của con người và hoạt động trong những giờ sẵn có cụ thể. Ngoài ra, trong các thị trường cạnh tranh, các doanh nghiệp chỉ tuân thủ các quy trình thủ công có thể gặp khó khăn trong việc cung cấp dịch vụ hiệu quả và cạnh tranh. Bất chấp những tiến bộ về công nghệ, mô hình lấy con người làm trung tâm vẫn ăn sâu vào quá trình xử lý đơn hàng, dẫn đến những hạn chế này.

Triển vọng sử dụng công nghệ để hỗ trợ xử lý đơn hàng trực tiếp đã có từ lâu. Tuy nhiên, các giải pháp hiện tại thường có thể thuộc hai loại: hệ thống dựa trên quy tắc đòi hỏi thời gian và công sức đáng kể để thiết lập và bảo trì hoặc hệ thống cứng nhắc thiếu tính linh hoạt cần thiết để tương tác giống con người với khách hàng. Do đó, các doanh nghiệp và tổ chức phải đối mặt với những thách thức trong việc triển khai các giải pháp đó một cách nhanh chóng và hiệu quả. May mắn thay, với sự ra đời của trí tuệ nhân tạomô hình ngôn ngữ lớn (LLM), giờ đây có thể tạo các hệ thống tự động có thể xử lý ngôn ngữ tự nhiên một cách hiệu quả và với dòng thời gian tăng tốc được tăng tốc.

nền tảng Amazon là một dịch vụ được quản lý hoàn toàn cung cấp nhiều lựa chọn về mô hình nền tảng (FM) hiệu suất cao từ các công ty AI hàng đầu như AI21 Labs, Anthropic, Cohere, Meta, Stability AI và Amazon thông qua một API duy nhất, cùng với một loạt các khả năng mà bạn có thể sử dụng. cần xây dựng các ứng dụng AI tổng quát với tính bảo mật, quyền riêng tư và AI có trách nhiệm. Ngoài Amazon Bedrock, bạn có thể sử dụng các dịch vụ AWS khác như Khởi động Amazon SageMakerAmazon để tạo ra các tác nhân xử lý đơn hàng AI tổng hợp hoàn toàn tự động và dễ dàng thích ứng.

Trong bài đăng này, chúng tôi sẽ hướng dẫn bạn cách xây dựng một tác nhân xử lý đơn hàng có khả năng nói bằng cách sử dụng Amazon Lex, Amazon Bedrock và AWS Lambda.

Tổng quan về giải pháp

Sơ đồ sau minh họa kiến ​​trúc giải pháp của chúng tôi.

Quy trình làm việc bao gồm các bước sau:

  1. Một khách hàng đặt hàng bằng Amazon Lex.
  2. Bot Amazon Lex diễn giải ý định của khách hàng và kích hoạt DialogCodeHook.
  3. Hàm Lambda lấy mẫu lời nhắc thích hợp từ lớp Lambda và định dạng lời nhắc mô hình bằng cách thêm thông tin đầu vào của khách hàng vào mẫu lời nhắc liên quan.
  4. Sản phẩm RequestValidation lời nhắc xác minh đơn hàng với mục menu và cho khách hàng biết qua Amazon Lex nếu có món họ muốn đặt mà không có trong menu và sẽ đưa ra đề xuất. Lời nhắc cũng thực hiện xác nhận sơ bộ về mức độ hoàn thành của đơn hàng.
  5. Sản phẩm ObjectCreator lời nhắc chuyển đổi các yêu cầu ngôn ngữ tự nhiên thành cấu trúc dữ liệu (định dạng JSON).
  6. Hàm Lambda của trình xác thực khách hàng xác minh các thuộc tính bắt buộc cho đơn hàng và xác nhận xem có tất cả thông tin cần thiết để xử lý đơn hàng hay không.
  7. Hàm Lambda của khách hàng lấy cấu trúc dữ liệu làm đầu vào để xử lý đơn hàng và chuyển tổng đơn hàng trở lại hàm Lambda điều phối.
  8. Hàm Lambda điều phối gọi điểm cuối Amazon Bedrock LLM để tạo bản tóm tắt đơn hàng cuối cùng bao gồm tổng số đơn hàng từ hệ thống cơ sở dữ liệu khách hàng (ví dụ: Máy phát điện Amazon).
  9. Bản tóm tắt đơn hàng được truyền lại cho khách hàng thông qua Amazon Lex. Sau khi khách hàng xác nhận đơn hàng, đơn hàng sẽ được xử lý.

Điều kiện tiên quyết

Bài đăng này giả định rằng bạn có tài khoản AWS đang hoạt động và quen thuộc với các khái niệm và dịch vụ sau:

Ngoài ra, để truy cập Amazon Bedrock từ các hàm Lambda, bạn cần đảm bảo thời gian chạy Lambda có các thư viện sau:

  • boto3>=1.28.57
  • awscli>=1.29.57
  • botocore>=1.31.57

Điều này có thể được thực hiện với lớp lambda hoặc bằng cách sử dụng một AMI cụ thể với các thư viện cần thiết.

Hơn nữa, những thư viện này là bắt buộc khi gọi API Amazon Bedrock từ Xưởng sản xuất Amazon SageMaker. Điều này có thể được thực hiện bằng cách chạy một ô có mã sau:

%pip install --no-build-isolation --force-reinstall 
"boto3>=1.28.57" 
"awscli>=1.29.57" 
"botocore>=1.31.57"

Cuối cùng, bạn tạo chính sách sau và sau đó gắn chính sách đó vào bất kỳ vai trò nào truy cập Amazon Bedrock:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Allow",
            "Action": "bedrock:*",
            "Resource": "*"
        }
    ]
}

Tạo bảng DynamoDB

Trong trường hợp cụ thể của chúng tôi, chúng tôi đã tạo bảng DynamoDB làm hệ thống cơ sở dữ liệu khách hàng, nhưng bạn cũng có thể sử dụng Dịch vụ cơ sở dữ liệu quan hệ của Amazon (Amazon RDS). Hoàn thành các bước sau để cung cấp bảng DynamoDB của bạn (hoặc tùy chỉnh các cài đặt nếu cần cho trường hợp sử dụng của bạn):

  1. Trên bảng điều khiển DynamoDB, chọn Bàn trong khung điều hướng.
  2. Chọn Tạo bảng.

  1. Trong Tên bảng, hãy nhập tên (ví dụ: ItemDetails).
  2. Trong Khóa phân vùng, nhập khóa (đối với bài đăng này, chúng tôi sử dụng Item).
  3. Trong Phím sắp xếp, nhập khóa (đối với bài đăng này, chúng tôi sử dụng Size).
  4. Chọn Tạo bảng.

Bây giờ bạn có thể tải dữ liệu vào bảng DynamoDB. Đối với bài đăng này, chúng tôi sử dụng tệp CSV. Bạn có thể tải dữ liệu vào bảng DynamoDB bằng mã Python trong sổ ghi chép SageMaker.

Đầu tiên, chúng ta cần thiết lập một hồ sơ có tên dev.

  1. Mở một thiết bị đầu cuối mới trong SageMaker Studio và chạy lệnh sau:
aws configure --profile dev

Lệnh này sẽ nhắc bạn nhập ID khóa truy cập AWS, khóa truy cập bí mật, Vùng AWS mặc định và định dạng đầu ra.

  1. Quay lại sổ ghi chép SageMaker và viết mã Python để thiết lập kết nối với DynamoDB bằng thư viện Boto3 trong Python. Đoạn mã này tạo một phiên sử dụng cấu hình AWS cụ thể có tên là dev, sau đó tạo ứng dụng khách DynamoDB bằng phiên đó. Sau đây là mẫu mã để tải dữ liệu:
%pip install boto3
import boto3
import csv

# Create a session using a profile named 'dev'
session = boto3.Session(profile_name='dev')

# Create a DynamoDB resource using the session
dynamodb = session.resource('dynamodb')

# Specify your DynamoDB table name
table_name = 'your_table_name'
table = dynamodb.Table(table_name)

# Specify the path to your CSV file
csv_file_path = 'path/to/your/file.csv'

# Read CSV file and put items into DynamoDB
with open(csv_file_path, 'r', encoding='utf-8-sig') as csvfile:
    csvreader = csv.reader(csvfile)
    
    # Skip the header row
    next(csvreader, None)

    for row in csvreader:
        # Extract values from the CSV row
        item = {
            'Item': row[0],  # Adjust the index based on your CSV structure
            'Size': row[1],
            'Price': row[2]
        }
        
        # Put item into DynamoDB
        response = table.put_item(Item=item)
        
        print(f"Item added: {response}")
print(f"CSV data has been loaded into the DynamoDB table: {table_name}")

Ngoài ra, bạn có thể sử dụng Bàn làm việc NoSQL hoặc các công cụ khác để tải nhanh dữ liệu vào bảng DynamoDB của bạn.

Sau đây là ảnh chụp màn hình sau khi dữ liệu mẫu được chèn vào bảng.

Tạo mẫu trong sổ ghi chép SageMaker bằng API gọi Amazon Bedrock

Để tạo mẫu lời nhắc cho trường hợp sử dụng này, chúng tôi sử dụng Amazon Bedrock. Bạn có thể truy cập Amazon Bedrock từ Bảng điều khiển quản lý AWS và thông qua các lệnh gọi API. Trong trường hợp của chúng tôi, chúng tôi truy cập Amazon Bedrock thông qua API từ sự tiện lợi của sổ ghi chép SageMaker Studio để tạo không chỉ mẫu lời nhắc mà còn tạo mã lệnh gọi API hoàn chỉnh mà sau này chúng tôi có thể sử dụng trên hàm Lambda.

  1. Trên bảng điều khiển SageMaker, truy cập miền SageMaker Studio hiện có hoặc tạo một miền mới để truy cập Amazon Bedrock từ sổ ghi chép SageMaker.

  1. Sau khi bạn tạo miền và người dùng SageMaker, hãy chọn người dùng và chọn Khởi độngStudio. Điều này sẽ mở ra một môi trường JupyterLab.
  2. Khi môi trường JupyterLab đã sẵn sàng, hãy mở sổ ghi chép mới và bắt đầu nhập các thư viện cần thiết.

Có rất nhiều FM có sẵn thông qua SDK Python của Amazon Bedrock. Trong trường hợp này, chúng tôi sử dụng Claude V2, một mô hình nền tảng mạnh mẽ do Anthropic phát triển.

Tác nhân xử lý đơn hàng cần một vài mẫu khác nhau. Điều này có thể thay đổi tùy theo trường hợp sử dụng nhưng chúng tôi đã thiết kế một quy trình làm việc chung có thể áp dụng cho nhiều cài đặt. Đối với trường hợp sử dụng này, mẫu Amazon Bedrock LLM sẽ thực hiện những việc sau:

  • Xác thực ý định của khách hàng
  • Xác thực yêu cầu
  • Tạo cấu trúc dữ liệu đơn hàng
  • Chuyển bản tóm tắt đơn hàng cho khách hàng
  1. Để gọi mô hình, hãy tạo một đối tượng thời gian chạy nền tảng từ Boto3.

#Model api request parameters
modelId = 'anthropic.claude-v2' # change this to use a different version from the model provider
accept = 'application/json'
contentType = 'application/json'

import boto3
import json
bedrock = boto3.client(service_name='bedrock-runtime')

Hãy bắt đầu bằng cách làm việc trên mẫu lời nhắc xác thực ý định. Đây là một quá trình lặp đi lặp lại, nhưng nhờ hướng dẫn kỹ thuật nhanh chóng của Anthropic, bạn có thể nhanh chóng tạo lời nhắc để hoàn thành nhiệm vụ.

  1. Tạo mẫu lời nhắc đầu tiên cùng với chức năng tiện ích sẽ giúp chuẩn bị nội dung cho các lệnh gọi API.

Sau đây là mã cho nhắc_template_intent_validator.txt:

"{"prompt": "Human: I will give you some instructions to complete my request.n<instructions>Given the Conversation between Human and Assistant, you need to identify the intent that the human wants to accomplish and respond appropriately. The valid intents are: Greeting,Place Order, Complain, Speak to Someone. Always put your response to the Human within the Response tags. Also add an XML tag to your output identifying the human intent.nHere are some examples:n<example><Conversation> H: hi there.nnA: Hi, how can I help you today?nnH: Yes. I would like a medium mocha please</Conversation>nnA:<intent>Place Order</intent><Response>nGot it.</Response></example>n<example><Conversation> H: hellonnA: Hi, how can I help you today?nnH: my coffee does not taste well can you please re-make it?</Conversation>nnA:<intent>Complain</intent><Response>nOh, I am sorry to hear that. Let me get someone to help you.</Response></example>n<example><Conversation> H: hinnA: Hi, how can I help you today?nnH: I would like to speak to someone else please</Conversation>nnA:<intent>Speak to Someone</intent><Response>nSure, let me get someone to help you.</Response></example>n<example><Conversation> H: howdynnA: Hi, how can I help you today?nnH:can I get a large americano with sugar and 2 mochas with no whipped cream</Conversation>nnA:<intent>Place Order</intent><Response>nSure thing! Please give me a moment.</Response></example>n<example><Conversation> H: hinn</Conversation>nnA:<intent>Greeting</intent><Response>nHi there, how can I help you today?</Response></example>n</instructions>nnPlease complete this request according to the instructions and examples provided above:<request><Conversation>REPLACEME</Conversation></request>nnAssistant:n", "max_tokens_to_sample": 250, "temperature": 1, "top_k": 250, "top_p": 0.75, "stop_sequences": ["nnHuman:", "nnhuman:", "nnCustomer:", "nncustomer:"]}"


  1. Lưu mẫu này vào một tệp để tải lên Amazon S3 và gọi từ hàm Lambda khi cần. Lưu mẫu dưới dạng chuỗi JSON được tuần tự hóa trong tệp văn bản. Ảnh chụp màn hình trước đó cũng hiển thị mẫu mã để thực hiện việc này.
  2. Lặp lại các bước tương tự với các mẫu khác.

Sau đây là một số ảnh chụp màn hình của các mẫu khác và kết quả khi gọi Amazon Bedrock bằng một số mẫu đó.

Sau đây là mã cho nhắc_template_request_validator.txt:

"{"prompt": "Human: I will give you some instructions to complete my request.n<instructions>Given the context do the following steps: 1. verify that the items in the input are valid. If customer provided an invalid item, recommend replacing it with a valid one. 2. verify that the customer has provided all the information marked as required. If the customer missed a required information, ask the customer for that information. 3. When the order is complete, provide a summary of the order and ask for confirmation always using this phrase: 'is this correct?' 4. If the customer confirms the order, Do not ask for confirmation again, just say the phrase inside the brackets [Great, Give me a moment while I try to process your order]</instructions>n<context>nThe VALID MENU ITEMS are: [latte, frappe, mocha, espresso, cappuccino, romano, americano].nThe VALID OPTIONS are: [splenda, stevia, raw sugar, honey, whipped cream, sugar, oat milk, soy milk, regular milk, skimmed milk, whole milk, 2 percent milk, almond milk].nThe required information is: size. Size can be: small, medium, large.nHere are some examples: <example>H: I would like a medium latte with 1 Splenda and a small romano with no sugar please.nnA: <Validation>:nThe Human is ordering a medium latte with one splenda. Latte is a valid menu item and splenda is a valid option. The Human is also ordering a small romano with no sugar. Romano is a valid menu item.</Validation>n<Response>nOk, I got: nt-Medium Latte with 1 Splenda and.nt-Small Romano with no Sugar.nIs this correct?</Response>nnH: yep.nnA:n<Response>nGreat, Give me a moment while I try to process your order</example>nn<example>H: I would like a cappuccino and a mocha please.nnA: <Validation>:nThe Human is ordering a cappuccino and a mocha. Both are valid menu items. The Human did not provide the size for the cappuccino. The human did not provide the size for the mocha. I will ask the Human for the required missing information.</Validation>n<Response>nSure thing, but can you please let me know the size for the Cappuccino and the size for the Mocha? We have Small, Medium, or Large.</Response></example>nn<example>H: I would like a small cappuccino and a large lemonade please.nnA: <Validation>:nThe Human is ordering a small cappuccino and a large lemonade. Cappuccino is a valid menu item. Lemonade is not a valid menu item. I will suggest the Human a replacement from our valid menu items.</Validation>n<Response>nSorry, we don't have Lemonades, would you like to order something else instead? Perhaps a Frappe or a Latte?</Response></example>nn<example>H: Can I get a medium frappuccino with sugar please?nnA: <Validation>:n The Human is ordering a Frappuccino. Frappuccino is not a valid menu item. I will suggest a replacement from the valid menu items in my context.</Validation>n<Response>nI am so sorry, but Frappuccino is not in our menu, do you want a frappe or a cappuccino instead? perhaps something else?</Response></example>nn<example>H: I want two large americanos and a small latte please.nnA: <Validation>:n The Human is ordering 2 Large Americanos, and a Small Latte. Americano is a valid menu item. Latte is a valid menu item.</Validation>n<Response>nOk, I got: nt-2 Large Americanos and.nt-Small Latte.nIs this correct?</Response>nnH: looks correct, yes.nnA:n<Response>nGreat, Give me a moment while I try to process your order.</Response></example>nn</Context>nnPlease complete this request according to the instructions and examples provided above:<request>REPLACEME</request>nnAssistant:n", "max_tokens_to_sample": 250, "temperature": 0.3, "top_k": 250, "top_p": 0.75, "stop_sequences": ["nnHuman:", "nnhuman:", "nnCustomer:", "nncustomer:"]}"

Sau đây là phản hồi của chúng tôi từ Amazon Bedrock khi sử dụng mẫu này.

Sau đây là mã cho prompt_template_object_creator.txt:

"{"prompt": "Human: I will give you some instructions to complete my request.n<instructions>Given the Conversation between Human and Assistant, you need to create a json object in Response with the appropriate attributes.nHere are some examples:n<example><Conversation> H: I want a latte.nnA:nCan I have the size?nnH: Medium.nnA: So, a medium latte.nIs this Correct?nnH: Yes.</Conversation>nnA:<Response>{"1":{"item":"latte","size":"medium","addOns":[]}}</Response></example>n<example><Conversation> H: I want a large frappe and 2 small americanos with sugar.nnA: Okay, let me confirm:nn1 large frappenn2 small americanos with sugarnnIs this correct?nnH: Yes.</Conversation>nnA:<Response>{"1":{"item":"frappe","size":"large","addOns":[]},"2":{"item":"americano","size":"small","addOns":["sugar"]},"3":{"item":"americano","size":"small","addOns":["sugar"]}}</Response>n</example>n<example><Conversation> H: I want a medium americano.nnA: Okay, let me confirm:nn1 medium americanonnIs this correct?nnH: Yes.</Conversation>nnA:<Response>{"1":{"item":"americano","size":"medium","addOns":[]}}</Response></example>n<example><Conversation> H: I want a large latte with oatmilk.nnA: Okay, let me confirm:nnLarge latte with oatmilknnIs this correct?nnH: Yes.</Conversation>nnA:<Response>{"1":{"item":"latte","size":"large","addOns":["oatmilk"]}}</Response></example>n<example><Conversation> H: I want a small mocha with no whipped cream please.nnA: Okay, let me confirm:nnSmall mocha with no whipped creamnnIs this correct?nnH: Yes.</Conversation>nnA:<Response>{"1":{"item":"mocha","size":"small","addOns":["no whipped cream"]}}</Response>nn</example></instructions>nnPlease complete this request according to the instructions and examples provided above:<request><Conversation>REPLACEME</Conversation></request>nnAssistant:n", "max_tokens_to_sample": 250, "temperature": 0.3, "top_k": 250, "top_p": 0.75, "stop_sequences": ["nnHuman:", "nnhuman:", "nnCustomer:", "nncustomer:"]}"


Sau đây là mã cho nhắc_template_order_summary.txt:

"{"prompt": "Human: I will give you some instructions to complete my request.n<instructions>Given the Conversation between Human and Assistant, you need to create a summary of the order with bullet points and include the order total.nHere are some examples:n<example><Conversation> H: I want a large frappe and 2 small americanos with sugar.nnA: Okay, let me confirm:nn1 large frappenn2 small americanos with sugarnnIs this correct?nnH: Yes.</Conversation>nn<OrderTotal>10.50</OrderTotal>nnA:<Response>nHere is a summary of your order along with the total:nn1 large frappenn2 small americanos with sugar.nYour Order total is $10.50</Response></example>n<example><Conversation> H: I want a medium americano.nnA: Okay, let me confirm:nn1 medium americanonnIs this correct?nnH: Yes.</Conversation>nn<OrderTotal>3.50</OrderTotal>nnA:<Response>nHere is a summary of your order along with the total:nn1 medium americano.nYour Order total is $3.50</Response></example>n<example><Conversation> H: I want a large latte with oat milk.nnA: Okay, let me confirm:nnLarge latte with oat milknnIs this correct?nnH: Yes.</Conversation>nn<OrderTotal>6.75</OrderTotal>nnA:<Response>nHere is a summary of your order along with the total:nnLarge latte with oat milk.nYour Order total is $6.75</Response></example>n<example><Conversation> H: I want a small mocha with no whipped cream please.nnA: Okay, let me confirm:nnSmall mocha with no whipped creamnnIs this correct?nnH: Yes.</Conversation>nn<OrderTotal>4.25</OrderTotal>nnA:<Response>nHere is a summary of your order along with the total:nnSmall mocha with no whipped cream.nYour Order total is $6.75</Response>nn</example>n</instructions>nnPlease complete this request according to the instructions and examples provided above:<request><Conversation>REPLACEME</Conversation>nn<OrderTotal>REPLACETOTAL</OrderTotal></request>nnAssistant:n", "max_tokens_to_sample": 250, "temperature": 0.3, "top_k": 250, "top_p": 0.75, "stop_sequences": ["nnHuman:", "nnhuman:", "nnCustomer:", "nncustomer:", "[Conversation]"]}"


Như bạn có thể thấy, chúng tôi đã sử dụng các mẫu lời nhắc của mình để xác thực các mục trong menu, xác định thông tin bắt buộc còn thiếu, tạo cấu trúc dữ liệu và tóm tắt đơn hàng. Các mô hình cơ bản có sẵn trên Amazon Bedrock rất mạnh mẽ nên bạn có thể hoàn thành nhiều nhiệm vụ hơn nữa thông qua các mẫu này.

Bạn đã hoàn thành việc thiết kế các lời nhắc và lưu mẫu vào tệp văn bản. Bây giờ bạn có thể bắt đầu tạo bot Amazon Lex và các hàm Lambda liên quan.

Tạo lớp Lambda với các mẫu lời nhắc

Hoàn thành các bước sau để tạo lớp Lambda của bạn:

  1. Trong SageMaker Studio, tạo một thư mục mới có thư mục con có tên python.
  2. Sao chép các tập tin nhắc nhở của bạn vào python thư mục.

  1. Bạn có thể thêm thư viện ZIP vào phiên bản sổ ghi chép của mình bằng cách chạy lệnh sau.
!conda install -y -c conda-forge zip

  1. Bây giờ, hãy chạy lệnh sau để tạo tệp ZIP để tải lên lớp Lambda.
!zip -r prompt_templates_layer.zip prompt_templates_layer/.

  1. Sau khi tạo tệp ZIP, bạn có thể tải xuống tệp. Đi đến Lambda, tạo lớp mới bằng cách tải tệp trực tiếp lên hoặc tải lên Amazon S3 trước.
  2. Sau đó gắn lớp mới này vào hàm Lambda điều phối.

Giờ đây, các tệp mẫu lời nhắc của bạn đã được lưu trữ cục bộ trong môi trường thời gian chạy Lambda. Điều này sẽ tăng tốc quá trình trong quá trình chạy bot của bạn.

Tạo lớp Lambda với các thư viện cần thiết

Hoàn thành các bước sau để tạo lớp Lambda của bạn với các thư viện cần thiết:

  1. Mở một Đám mây AWS9 môi trường cá thể, hãy tạo một thư mục có thư mục con có tên python.
  2. Mở một thiết bị đầu cuối bên trong python thư mục.
  3. Chạy các lệnh sau từ thiết bị đầu cuối:
pip install “boto3>=1.28.57” -t .
pip install “awscli>=1.29.57" -t .
pip install “botocore>=1.31.57” -t .

  1. chạy cd .. và định vị chính bạn bên trong thư mục mới, nơi bạn cũng có python thư mục con.
  2. Chạy lệnh sau:
zip -r lambda-layer.zip

  1. Sau khi tạo tệp ZIP, bạn có thể tải xuống tệp. Đi đến Lambda, tạo lớp mới bằng cách tải tệp trực tiếp lên hoặc tải lên Amazon S3 trước.
  2. Sau đó gắn lớp mới này vào hàm Lambda điều phối.

Tạo bot trong Amazon Lex v2

Đối với trường hợp sử dụng này, chúng tôi xây dựng một bot Amazon Lex có thể cung cấp giao diện đầu vào/đầu ra cho kiến ​​trúc để gọi Amazon Bedrock bằng giọng nói hoặc văn bản từ bất kỳ giao diện nào. Vì LLM sẽ xử lý đoạn hội thoại của tác nhân xử lý đơn hàng này và Lambda sẽ điều phối quy trình làm việc nên bạn có thể tạo bot có ba ý định và không có vị trí.

  1. Trên bảng điều khiển Amazon Lex, tạo bot mới bằng phương thức Tạo một bot trống.

Giờ đây, bạn có thể thêm ý định bằng bất kỳ câu nói ban đầu thích hợp nào để người dùng cuối bắt đầu cuộc trò chuyện với bot. Chúng tôi sử dụng lời chào đơn giản và thêm phản hồi ban đầu của bot để người dùng cuối có thể đưa ra yêu cầu của họ. Khi tạo bot, hãy đảm bảo sử dụng móc mã Lambda với các ý định; điều này sẽ kích hoạt chức năng Lambda để điều phối quy trình làm việc giữa khách hàng, Amazon Lex và LLM.

  1. Thêm ý định đầu tiên của bạn để kích hoạt quy trình làm việc và sử dụng mẫu lời nhắc xác thực ý định để gọi Amazon Bedrock và xác định xem khách hàng đang cố gắng thực hiện điều gì. Thêm một vài câu nói đơn giản để người dùng cuối bắt đầu cuộc trò chuyện.

Bạn không cần sử dụng bất kỳ vị trí nào hoặc lần đọc ban đầu nào trong bất kỳ ý định nào của bot. Trên thực tế, bạn không cần thêm cách nói vào ý định thứ hai hoặc thứ ba. Đó là vì LLM sẽ hướng dẫn Lambda trong suốt quá trình.

  1. Thêm lời nhắc xác nhận. Bạn có thể tùy chỉnh thông báo này trong hàm Lambda sau.

  1. Theo Móc mã, lựa chọn Sử dụng hàm Lambda để khởi tạo và xác thực.

  1. Tạo ý định thứ hai mà không cần nói ra cũng như không có phản hồi ban đầu. Đây là PlaceOrder ý định.

Khi LLM xác định rằng khách hàng đang cố gắng đặt hàng, hàm Lambda sẽ kích hoạt ý định này và xác thực yêu cầu của khách hàng dựa trên menu, đồng thời đảm bảo rằng không thiếu thông tin bắt buộc nào. Hãy nhớ rằng tất cả những điều này đều có trên mẫu lời nhắc, vì vậy bạn có thể điều chỉnh quy trình làm việc này cho phù hợp với mọi trường hợp sử dụng bằng cách thay đổi mẫu lời nhắc.

  1. Không thêm bất kỳ vị trí nào mà hãy thêm lời nhắc xác nhận và từ chối phản hồi.

  1. Chọn Sử dụng hàm Lambda để khởi tạo và xác thực.

  1. Tạo ý định thứ ba có tên ProcessOrder không có cách phát âm mẫu và không có chỗ trống.
  2. Thêm phản hồi ban đầu, lời nhắc xác nhận và phản hồi từ chối.

Sau khi LLM xác thực yêu cầu của khách hàng, hàm Lambda sẽ kích hoạt ý định thứ ba và cuối cùng để xử lý đơn hàng. Ở đây, Lambda sẽ sử dụng mẫu trình tạo đối tượng để tạo cấu trúc dữ liệu JSON của đơn hàng nhằm truy vấn bảng DynamoDB, sau đó sử dụng mẫu tóm tắt đơn hàng để tóm tắt toàn bộ đơn hàng cùng với tổng số tiền để Amazon Lex có thể chuyển cho khách hàng.

  1. Chọn Sử dụng hàm Lambda để khởi tạo và xác thực. Điều này có thể sử dụng bất kỳ hàm Lambda nào để xử lý đơn hàng sau khi khách hàng đưa ra xác nhận cuối cùng.

  1. Sau khi bạn tạo cả ba ý định, hãy đi tới Trình tạo hình ảnh cho ValidateIntent, thêm bước thực hiện mục đích và kết nối đầu ra của xác nhận tích cực với bước đó.
  2. Sau khi bạn thêm ý định truy cập, hãy chỉnh sửa ý định đó và chọn ý định PlaceOrder làm tên ý định.

  1. Tương tự, để sử dụng Trình tạo hình ảnh cho PlaceOrder mục đích và kết nối đầu ra của xác nhận tích cực với ProcessOrder đi đến ý định. Không cần chỉnh sửa đối với ProcessOrder ý định.
  2. Bây giờ, bạn cần tạo hàm Lambda để điều phối Amazon Lex và gọi bảng DynamoDB, như được trình bày chi tiết trong phần sau.

Tạo hàm Lambda để điều phối bot Amazon Lex

Giờ đây, bạn có thể xây dựng hàm Lambda để điều phối quy trình làm việc và bot Amazon Lex. Hoàn thành các bước sau:

  1. Tạo hàm Lambda bằng chính sách thực thi tiêu chuẩn và để Lambda tạo vai trò cho bạn.
  2. Trong cửa sổ mã của hàm, hãy thêm một số hàm tiện ích sẽ trợ giúp: định dạng lời nhắc bằng cách thêm ngữ cảnh lex vào mẫu, gọi API Amazon Bedrock LLM, trích xuất văn bản mong muốn từ phản hồi, v.v. Xem đoạn mã sau:
import json
import re
import boto3
import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

bedrock = boto3.client(service_name='bedrock-runtime')
def CreatingCustomPromptFromLambdaLayer(object_key,replace_items):
   
    folder_path = '/opt/order_processing_agent_prompt_templates/python/'
    try:
        file_path = folder_path + object_key
        with open(file_path, "r") as file1:
            raw_template = file1.read()
            # Modify the template with the custom input prompt
            #template['inputs'][0].insert(1, {"role": "user", "content": '### Input:n' + user_request})
            for key,value in replace_items.items():
                value = json.dumps(json.dumps(value).replace('"','')).replace('"','')
                raw_template = raw_template.replace(key,value)
            modified_prompt = raw_template

            return modified_prompt
    except Exception as e:
        return {
            'statusCode': 500,
            'body': f'An error occurred: {str(e)}'
        }
def CreatingCustomPrompt(object_key,replace_items):
    logger.debug('replace_items is: {}'.format(replace_items))
    #retrieve user request from intent_request
    #we first propmt the model with current order
    
    bucket_name = 'your-bucket-name'
    
    #object_key = 'prompt_template_order_processing.txt'
    try:
        s3 = boto3.client('s3')
        # Retrieve the existing template from S3
        response = s3.get_object(Bucket=bucket_name, Key=object_key)
        raw_template = response['Body'].read().decode('utf-8')
        raw_template = json.loads(raw_template)
        logger.debug('raw template is {}'.format(raw_template))
        #template_json = json.loads(raw_template)
        #logger.debug('template_json is {}'.format(template_json))
        #template = json.dumps(template_json)
        #logger.debug('template is {}'.format(template))

        # Modify the template with the custom input prompt
        #template['inputs'][0].insert(1, {"role": "user", "content": '### Input:n' + user_request})
        for key,value in replace_items.items():
            raw_template = raw_template.replace(key,value)
            logger.debug("Replacing: {} nwith: {}".format(key,value))
        modified_prompt = json.dumps(raw_template)
        logger.debug("Modified template: {}".format(modified_prompt))
        logger.debug("Modified template type is: {}".format(print(type(modified_prompt))))
        
        #modified_template_json = json.loads(modified_prompt)
        #logger.debug("Modified template json: {}".format(modified_template_json))
        
        return modified_prompt
    except Exception as e:
        return {
            'statusCode': 500,
            'body': f'An error occurred: {str(e)}'
        }
    
def validate_intent(intent_request):
    logger.debug('starting validate_intent: {}'.format(intent_request))
    #retrieve user request from intent_request
    user_request = 'Human: ' + intent_request['inputTranscript'].lower()
    #getting current context variable
    current_session_attributes =  intent_request['sessionState']['sessionAttributes']
    if len(current_session_attributes) > 0:
        full_context = current_session_attributes['fullContext'] + 'nn' + user_request
        dialog_context = current_session_attributes['dialogContext'] + 'nn' + user_request
    else:
        full_context = user_request
        dialog_context = user_request
    #Preparing validation prompt by adding context to prompt template
    object_key = 'prompt_template_intent_validator.txt'
    #replace_items = {"REPLACEME":full_context}
    #replace_items = {"REPLACEME":dialog_context}
    replace_items = {"REPLACEME":dialog_context}
    #validation_prompt = CreatingCustomPrompt(object_key,replace_items)
    validation_prompt = CreatingCustomPromptFromLambdaLayer(object_key,replace_items)

    #Prompting model for request validation
    intent_validation_completion = prompt_bedrock(validation_prompt)
    intent_validation_completion = re.sub(r'["]','',intent_validation_completion)

    #extracting response from response completion and removing some special characters
    validation_response = extract_response(intent_validation_completion)
    validation_intent = extract_intent(intent_validation_completion)
    
    

    #business logic depending on intents
    if validation_intent == 'Place Order':
        return validate_request(intent_request)
    elif validation_intent in ['Complain','Speak to Someone']:
        ##adding session attributes to keep current context
        full_context = full_context + 'nn' + intent_validation_completion
        dialog_context = dialog_context + 'nnAssistant: ' + validation_response
        intent_request['sessionState']['sessionAttributes']['fullContext'] = full_context
        intent_request['sessionState']['sessionAttributes']['dialogContext'] = dialog_context
        intent_request['sessionState']['sessionAttributes']['customerIntent'] = validation_intent
        return close(intent_request['sessionState']['sessionAttributes'],intent_request['sessionState']['intent']['name'],'Fulfilled','Close',validation_response)
    if validation_intent == 'Greeting':
        ##adding session attributes to keep current context
        full_context = full_context + 'nn' + intent_validation_completion
        dialog_context = dialog_context + 'nnAssistant: ' + validation_response
        intent_request['sessionState']['sessionAttributes']['fullContext'] = full_context
        intent_request['sessionState']['sessionAttributes']['dialogContext'] = dialog_context
        intent_request['sessionState']['sessionAttributes']['customerIntent'] = validation_intent
        return close(intent_request['sessionState']['sessionAttributes'],intent_request['sessionState']['intent']['name'],'InProgress','ConfirmIntent',validation_response)

def validate_request(intent_request):
    logger.debug('starting validate_request: {}'.format(intent_request))
    #retrieve user request from intent_request
    user_request = 'Human: ' + intent_request['inputTranscript'].lower()
    #getting current context variable
    current_session_attributes =  intent_request['sessionState']['sessionAttributes']
    if len(current_session_attributes) > 0:
        full_context = current_session_attributes['fullContext'] + 'nn' + user_request
        dialog_context = current_session_attributes['dialogContext'] + 'nn' + user_request
    else:
        full_context = user_request
        dialog_context = user_request
   
    #Preparing validation prompt by adding context to prompt template
    object_key = 'prompt_template_request_validator.txt'
    replace_items = {"REPLACEME":dialog_context}
    #validation_prompt = CreatingCustomPrompt(object_key,replace_items)
    validation_prompt = CreatingCustomPromptFromLambdaLayer(object_key,replace_items)

    #Prompting model for request validation
    request_validation_completion = prompt_bedrock(validation_prompt)
    request_validation_completion = re.sub(r'["]','',request_validation_completion)

    #extracting response from response completion and removing some special characters
    validation_response = extract_response(request_validation_completion)

    ##adding session attributes to keep current context
    full_context = full_context + 'nn' + request_validation_completion
    dialog_context = dialog_context + 'nnAssistant: ' + validation_response
    intent_request['sessionState']['sessionAttributes']['fullContext'] = full_context
    intent_request['sessionState']['sessionAttributes']['dialogContext'] = dialog_context
    
    return close(intent_request['sessionState']['sessionAttributes'],'PlaceOrder','InProgress','ConfirmIntent',validation_response)
    
def process_order(intent_request):
    logger.debug('starting process_order: {}'.format(intent_request))

     #retrieve user request from intent_request
    user_request = 'Human: ' + intent_request['inputTranscript'].lower()
    #getting current context variable
    current_session_attributes =  intent_request['sessionState']['sessionAttributes']
    if len(current_session_attributes) > 0:
        full_context = current_session_attributes['fullContext'] + 'nn' + user_request
        dialog_context = current_session_attributes['dialogContext'] + 'nn' + user_request
    else:
        full_context = user_request
        dialog_context = user_request
    #   Preparing object creator prompt by adding context to prompt template
    object_key = 'prompt_template_object_creator.txt'
    replace_items = {"REPLACEME":dialog_context}
    #object_creator_prompt = CreatingCustomPrompt(object_key,replace_items)
    object_creator_prompt = CreatingCustomPromptFromLambdaLayer(object_key,replace_items)
    #Prompting model for object creation
    object_creation_completion = prompt_bedrock(object_creator_prompt)
    #extracting response from response completion
    object_creation_response = extract_response(object_creation_completion)
    inputParams = json.loads(object_creation_response)
    inputParams = json.dumps(json.dumps(inputParams))
    logger.debug('inputParams is: {}'.format(inputParams))
    client = boto3.client('lambda')
    response = client.invoke(FunctionName = 'arn:aws:lambda:us-east-1:<AccountNumber>:function:aws-blog-order-validator',InvocationType = 'RequestResponse',Payload = inputParams)
    responseFromChild = json.load(response['Payload'])
    validationResult = responseFromChild['statusCode']
    if validationResult == 205:
        order_validation_error = responseFromChild['validator_response']
        return close(intent_request['sessionState']['sessionAttributes'],'PlaceOrder','InProgress','ConfirmIntent',order_validation_error)
    #invokes Order Processing lambda to query DynamoDB table and returns order total
    response = client.invoke(FunctionName = 'arn:aws:lambda:us-east-1: <AccountNumber>:function:aws-blog-order-processing',InvocationType = 'RequestResponse',Payload = inputParams)
    responseFromChild = json.load(response['Payload'])
    orderTotal = responseFromChild['body']
    ###Prompting the model to summarize the order along with order total
    object_key = 'prompt_template_order_summary.txt'
    replace_items = {"REPLACEME":dialog_context,"REPLACETOTAL":orderTotal}
    #order_summary_prompt = CreatingCustomPrompt(object_key,replace_items)
    order_summary_prompt = CreatingCustomPromptFromLambdaLayer(object_key,replace_items)
    order_summary_completion = prompt_bedrock(order_summary_prompt)
    #extracting response from response completion
    order_summary_response = extract_response(order_summary_completion)  
    order_summary_response = order_summary_response + '. Shall I finalize processing your order?'
    ##adding session attributes to keep current context
    full_context = full_context + 'nn' + order_summary_completion
    dialog_context = dialog_context + 'nnAssistant: ' + order_summary_response
    intent_request['sessionState']['sessionAttributes']['fullContext'] = full_context
    intent_request['sessionState']['sessionAttributes']['dialogContext'] = dialog_context
    return close(intent_request['sessionState']['sessionAttributes'],'ProcessOrder','InProgress','ConfirmIntent',order_summary_response)
    

""" --- Main handler and Workflow functions --- """

def lambda_handler(event, context):
    """
    Route the incoming request based on intent.
    The JSON body of the request is provided in the event slot.
    """
    logger.debug('event is: {}'.format(event))

    return dispatch(event)

def dispatch(intent_request):
    """
    Called when the user specifies an intent for this bot. If intent is not valid then returns error name
    """
    logger.debug('intent_request is: {}'.format(intent_request))
    intent_name = intent_request['sessionState']['intent']['name']
    confirmation_state = intent_request['sessionState']['intent']['confirmationState']
    # Dispatch to your bot's intent handlers
    if intent_name == 'ValidateIntent' and confirmation_state == 'None':
        return validate_intent(intent_request)
    if intent_name == 'PlaceOrder' and confirmation_state == 'None':
        return validate_request(intent_request)
    elif intent_name == 'PlaceOrder' and confirmation_state == 'Confirmed':
        return process_order(intent_request)
    elif intent_name == 'PlaceOrder' and confirmation_state == 'Denied':
        return close(intent_request['sessionState']['sessionAttributes'],intent_request['sessionState']['intent']['name'],'Fulfilled','Close','Got it. Let me know if I can help you with something else.')
    elif intent_name == 'PlaceOrder' and confirmation_state not in ['Denied','Confirmed','None']:
        return close(intent_request['sessionState']['sessionAttributes'],intent_request['sessionState']['intent']['name'],'Fulfilled','Close','Sorry. I am having trouble completing the request. Let me get someone to help you.')
        logger.debug('exiting intent {} here'.format(intent_request['sessionState']['intent']['name']))
    elif intent_name == 'ProcessOrder' and confirmation_state == 'None':
        return validate_request(intent_request)
    elif intent_name == 'ProcessOrder' and confirmation_state == 'Confirmed':
        return close(intent_request['sessionState']['sessionAttributes'],intent_request['sessionState']['intent']['name'],'Fulfilled','Close','Perfect! Your order has been processed. Please proceed to payment.')
    elif intent_name == 'ProcessOrder' and confirmation_state == 'Denied':
        return close(intent_request['sessionState']['sessionAttributes'],intent_request['sessionState']['intent']['name'],'Fulfilled','Close','Got it. Let me know if I can help you with something else.')
    elif intent_name == 'ProcessOrder' and confirmation_state not in ['Denied','Confirmed','None']:
        return close(intent_request['sessionState']['sessionAttributes'],intent_request['sessionState']['intent']['name'],'Fulfilled','Close','Sorry. I am having trouble completing the request. Let me get someone to help you.')
        logger.debug('exiting intent {} here'.format(intent_request['sessionState']['intent']['name']))
    raise Exception('Intent with name ' + intent_name + ' not supported')
    
def prompt_bedrock(formatted_template):
    logger.debug('prompt bedrock input is:'.format(formatted_template))
    body = json.loads(formatted_template)

    modelId = 'anthropic.claude-v2' # change this to use a different version from the model provider
    accept = 'application/json'
    contentType = 'application/json'

    response = bedrock.invoke_model(body=body, modelId=modelId, accept=accept, contentType=contentType)
    response_body = json.loads(response.get('body').read())
    response_completion = response_body.get('completion')
    logger.debug('response is: {}'.format(response_completion))

    #print_ww(response_body.get('completion'))
    #print(response_body.get('results')[0].get('outputText'))
    return response_completion

#function to extract text between the <Response> and </Response> tags within model completion
def extract_response(response_completion):
    
    if '<Response>' in response_completion:
        customer_response = response_completion.replace('<Response>','||').replace('</Response>','').split('||')[1]
        
        logger.debug('modified response is: {}'.format(response_completion))

        return customer_response
    else:
        
        logger.debug('modified response is: {}'.format(response_completion))

        return response_completion
        
#function to extract text between the <Response> and </Response> tags within model completion
def extract_intent(response_completion):
    if '<intent>' in response_completion:
        customer_intent = response_completion.replace('<intent>','||').replace('</intent>','||').split('||')[1]
        return customer_intent
    else:
        return customer_intent
        
def close(session_attributes, intent, fulfillment_state, action_type, message):
    #This function prepares the response in the appropiate format for Lex V2

    response = {
        "sessionState": {
            "sessionAttributes":session_attributes,
            "dialogAction": {
                "type": action_type
            },
            "intent": {
                "name":intent,
                "state":fulfillment_state
                
            },
            
            },
        "messages":
            [{
                "contentType":"PlainText",
                "content":message,
            }]
            ,
        
    }
    return response

  1. Đính kèm lớp Lambda bạn đã tạo trước đó vào hàm này.
  2. Ngoài ra, hãy đính kèm lớp này vào các mẫu lời nhắc bạn đã tạo.
  3. Trong vai trò thực thi Lambda, hãy đính kèm chính sách để truy cập Amazon Bedrock, được tạo trước đó.

Vai trò thực thi Lambda phải có các quyền sau.

Đính kèm chức năng Orchestration Lambda vào bot Amazon Lex

  1. Sau khi bạn tạo hàm trong phần trước, hãy quay lại bảng điều khiển Amazon Lex và điều hướng đến bot của bạn.
  2. Theo Ngôn ngữ trong ngăn điều hướng, chọn Tiếng Anh.
  3. Trong nguồn, chọn bot xử lý đơn hàng của bạn.
  4. Trong Phiên bản hoặc bí danh của hàm Lambda, chọn $ MỚI NHẤT.
  5. Chọn Lưu.

Tạo các hàm Lambda hỗ trợ

Hoàn thành các bước sau để tạo các hàm Lambda bổ sung:

  1. Tạo hàm Lambda để truy vấn bảng DynamoDB mà bạn đã tạo trước đó:
import json
import boto3
import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# Initialize the DynamoDB client
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('your-table-name')

def calculate_grand_total(input_data):
    # Initialize the total price
    total_price = 0
    
    try:
        # Loop through each item in the input JSON
        for item_id, item_data in input_data.items():
            item_name = item_data['item'].lower()  # Convert item name to lowercase
            item_size = item_data['size'].lower()  # Convert item size to lowercase
            
            # Query the DynamoDB table for the item based on Item and Size
            response = table.get_item(
                Key={'Item': item_name,
                    'Size': item_size}
            )
            
            # Check if the item was found in the table
            if 'Item' in response:
                item = response['Item']
                price = float(item['Price'])
                total_price += price  # Add the item's price to the total
    
        return total_price
    except Exception as e:
        raise Exception('An error occurred: {}'.format(str(e)))

def lambda_handler(event, context):
    try:
       
        # Parse the input JSON from the Lambda event
        input_json = json.loads(event)

        # Calculate the grand total
        grand_total = calculate_grand_total(input_json)
    
        # Return the grand total in the response
        return {'statusCode': 200,'body': json.dumps(grand_total)}
    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps('An error occurred: {}'.format(str(e)))

  1. Điều hướng đến Cấu hình tab trong hàm Lambda và chọn Quyền.
  2. Đính kèm câu lệnh chính sách dựa trên tài nguyên cho phép hàm Lambda xử lý đơn hàng gọi hàm này.

  1. Điều hướng đến vai trò thực thi IAM cho hàm Lambda này và thêm chính sách để truy cập vào bảng DynamoDB.

  1. Tạo một hàm Lambda khác để xác thực xem tất cả các thuộc tính bắt buộc có được chuyển từ khách hàng hay không. Trong ví dụ sau, chúng tôi xác thực xem thuộc tính kích thước có được ghi lại cho một đơn hàng hay không:
import json
import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

def lambda_handler(event, context):
    # Define customer orders from the input event
    customer_orders = json.loads(event)

    # Initialize a list to collect error messages
    order_errors = {}
    missing_size = []
    error_messages = []
    # Iterate through each order in customer_orders
    for order_id, order in customer_orders.items():
        if "size" not in order or order["size"] == "":
            missing_size.append(order['item'])
            order_errors['size'] = missing_size
    if order_errors:
        items_missing_size = order_errors['size']
        error_message = f"could you please provide the size for the following items: {', '.join(items_missing_size)}?"
        error_messages.append(error_message)

    # Prepare the response message
    if error_messages:
        response_message = "n".join(error_messages)
        return {
        'statusCode': 205,
        'validator_response': response_message
            }   
    else:
        response_message = "Order is validated successfully"
        return {
        'statusCode': 200,
        'validator_response': response_message
        }

  1. Điều hướng đến Cấu hình tab trong hàm Lambda và chọn Quyền.
  2. Đính kèm câu lệnh chính sách dựa trên tài nguyên cho phép hàm Lambda xử lý đơn hàng gọi hàm này.

Kiểm tra giải pháp

Bây giờ chúng tôi có thể thử nghiệm giải pháp bằng các đơn hàng mẫu mà khách hàng đặt qua Amazon Lex.

Trong ví dụ đầu tiên của chúng tôi, khách hàng yêu cầu cà phê frappuccino, món này không có trong thực đơn. Mô hình xác thực với sự trợ giúp của mẫu trình xác thực đơn hàng và đề xuất một số đề xuất dựa trên menu. Sau khi khách hàng xác nhận đơn hàng, họ sẽ được thông báo về tổng đơn hàng và tóm tắt đơn hàng. Đơn hàng sẽ được xử lý dựa trên xác nhận cuối cùng của khách hàng.

Trong ví dụ tiếp theo của chúng tôi, khách hàng gọi cà phê cappuccino cỡ lớn và sau đó thay đổi kích cỡ từ lớn thành vừa. Mô hình nắm bắt tất cả những thay đổi cần thiết và yêu cầu khách hàng xác nhận đơn hàng. Mô hình trình bày tổng đơn hàng và tóm tắt đơn hàng, đồng thời xử lý đơn hàng dựa trên xác nhận cuối cùng của khách hàng.

Trong ví dụ cuối cùng của chúng tôi, khách hàng đã đặt hàng nhiều mặt hàng và một số mặt hàng bị thiếu kích thước. Mô hình và hàm Lambda sẽ xác minh xem có tất cả các thuộc tính bắt buộc để xử lý đơn hàng hay không, sau đó yêu cầu khách hàng cung cấp thông tin còn thiếu. Sau khi khách hàng cung cấp thông tin còn thiếu (trong trường hợp này là cỡ cà phê), họ sẽ thấy tổng đơn hàng và tóm tắt đơn hàng. Đơn hàng sẽ được xử lý dựa trên xác nhận cuối cùng của khách hàng.

Hạn chế LLM

Bản chất đầu ra LLM là ngẫu nhiên, điều đó có nghĩa là kết quả từ LLM của chúng tôi có thể khác nhau về định dạng hoặc thậm chí ở dạng nội dung không trung thực (ảo giác). Do đó, các nhà phát triển cần dựa vào logic xử lý lỗi tốt trong toàn bộ mã của họ để xử lý các tình huống này và tránh trải nghiệm người dùng cuối bị suy giảm.

Làm sạch

Nếu không cần giải pháp này nữa, bạn có thể xóa các tài nguyên sau:

  • Các hàm lambda
  • hộp Amazon Lex
  • Bảng DynamoDB
  • Xô S3

Ngoài ra, hãy tắt phiên bản SageMaker Studio nếu ứng dụng này không còn cần thiết nữa.

Đánh giá chi phí

Để biết thông tin về giá của các dịch vụ chính được giải pháp này sử dụng, hãy xem phần sau:

Lưu ý rằng bạn có thể sử dụng Claude v2 mà không cần cung cấp, do đó tổng chi phí vẫn ở mức tối thiểu. Để giảm chi phí hơn nữa, bạn có thể định cấu hình bảng DynamoDB bằng cài đặt theo yêu cầu.

Kết luận

Bài đăng này trình bày cách xây dựng một tác nhân xử lý đơn hàng AI hỗ trợ giọng nói bằng cách sử dụng Amazon Lex, Amazon Bedrock và các dịch vụ AWS khác. Chúng tôi đã chỉ ra cách kỹ thuật nhanh chóng với mô hình AI có khả năng tạo ra mạnh mẽ như Claude có thể cho phép hiểu ngôn ngữ tự nhiên mạnh mẽ và luồng hội thoại để xử lý đơn hàng mà không cần dữ liệu đào tạo mở rộng.

Kiến trúc giải pháp sử dụng các thành phần serverless như Lambda, Amazon S3 và DynamoDB để cho phép triển khai linh hoạt và có thể mở rộng. Việc lưu trữ các mẫu lời nhắc trong Amazon S3 cho phép bạn tùy chỉnh giải pháp cho các trường hợp sử dụng khác nhau.

Các bước tiếp theo có thể bao gồm mở rộng khả năng của đại lý để xử lý nhiều yêu cầu của khách hàng hơn và các trường hợp khó khăn hơn. Các mẫu lời nhắc cung cấp một cách để liên tục cải thiện kỹ năng của tổng đài viên. Các tùy chỉnh bổ sung có thể liên quan đến việc tích hợp dữ liệu đơn hàng với các hệ thống phụ trợ như kho hàng, CRM hoặc POS. Cuối cùng, đại lý có thể được cung cấp trên nhiều điểm tiếp xúc khác nhau của khách hàng như ứng dụng di động, dịch vụ lái xe qua xe, ki-ốt, v.v. bằng cách sử dụng khả năng đa kênh của Amazon Lex.

Để tìm hiểu thêm, hãy tham khảo các tài nguyên liên quan sau:

  • Triển khai và quản lý bot đa kênh:
  • Kỹ thuật nhanh chóng cho Claude và các mô hình khác:
  • Các mẫu kiến ​​trúc serverless dành cho trợ lý AI có thể mở rộng:

Về các tác giả

Moumita Dutta là Kiến trúc sư giải pháp đối tác tại Amazon Web Services. Trong vai trò của mình, cô cộng tác chặt chẽ với các đối tác để phát triển các nội dung có thể mở rộng và tái sử dụng nhằm hợp lý hóa việc triển khai đám mây và nâng cao hiệu quả hoạt động. Cô là thành viên của cộng đồng AI/ML và là chuyên gia về AI sáng tạo tại AWS. Khi rảnh rỗi, cô thích làm vườn và đạp xe.

Fernando Lammoglia là Kiến trúc sư giải pháp đối tác tại Amazon Web Services, hợp tác chặt chẽ với các đối tác AWS trong việc dẫn đầu việc phát triển và áp dụng các giải pháp AI tiên tiến trên khắp các đơn vị kinh doanh. Một nhà lãnh đạo chiến lược có chuyên môn về kiến ​​trúc đám mây, AI tổng quát, học máy và phân tích dữ liệu. Anh ấy chuyên thực hiện các chiến lược tiếp cận thị trường và cung cấp các giải pháp AI có tác động mạnh mẽ phù hợp với mục tiêu của tổ chức. Khi rảnh rỗi, anh ấy thích dành thời gian cho gia đình và đi du lịch các nước khác.

Mitul Patel là Kiến trúc sư giải pháp cấp cao tại Amazon Web Services. Với vai trò là người hỗ trợ công nghệ đám mây, anh làm việc với khách hàng để hiểu mục tiêu và thách thức của họ, đồng thời đưa ra hướng dẫn mang tính quy định để họ đạt được mục tiêu bằng các dịch vụ AWS. Anh ấy là thành viên của cộng đồng AI/ML và là đại sứ Generative AI tại AWS. Khi rảnh rỗi, anh thích đi bộ đường dài và chơi bóng đá.

tại chỗ_img

Tin tức mới nhất

tại chỗ_img