在 Alexa 技能開發中,資料儲存至關重要。除了使用會話屬性儲存暫時資料外,更需要持久化儲存方案來管理跨會話的使用者資料。本文將介紹三種儲存方式:技能函式的本地暫存空間、Amazon S3 和 DynamoDB,並說明如何在 Alexa Skills 中實作資料儲存,包含會話屬性和永續性屬性的應用,以及如何使用 Python 和相關 SDK 操作這些服務。同時,我們也會探討 DynamoDBPersistenceAdapter 的使用,以及如何在程式碼中讀取、儲存和初始化永續性屬性。最後,我們將提供程式碼範例,示範如何使用 DynamoDB 儲存持續性屬性並處理語音命令,以及如何使用 S3 儲存檔案和使用 DynamoDB 儲存結構化資料。
SsmlUtils 和 ViewportUtils
Alexa 還提供了 SsmlUtils 和 ViewportUtils 來幫助開發者處理 SSML 字串和檢查 viewport Profile 等。
const ssmlUtils = new SsmlUtils();
const viewportUtils = new ViewportUtils();
圖表翻譯:
flowchart TD
A[使用者語音輸入] --> B[RequestEnvelope]
B --> C[Intent]
C --> D[槽位(Slot)]
D --> E[支援的介面]
E --> F[新會話]
F --> G[Intent 錯誤記錄]
G --> H[SsmlUtils 和 ViewportUtils]
內容解密:
以上程式碼展示瞭如何使用 Alexa 的 Intent 和 RequestEnvelope 來取得使用者的意圖、槽位等資訊,並且如何使用 SsmlUtils 和 ViewportUtils 來處理 SSML 字串和檢查 viewport Profile 等。這些功能是 Alexa 技術開發中的重要組成部分,可以幫助開發者建立更加智慧和互動的應用程式。
使用暫儲存存空間進行資料儲存
在 Alexa Skills 的開發中,瞭解如何儲存和管理使用者資料是非常重要的。雖然我們可以使用會話屬性(session attributes)來儲存暫時資料,但對於更永久的儲存,Amazon 提供了 S3 和 DynamoDB 等選擇。在本章中,我們將探討如何使用這些服務,以及如何在 Alexa Skills 中實作資料儲存。
5.1 簡介
在前面的章節中,我們已經學習瞭如何使用會話屬性來儲存暫時資料。但是,當我們需要儲存更永久的資料時,就需要使用更強大的儲存解決方案。Amazon 的 S3 和 DynamoDB 是兩種常用的選擇,它們提供了高用性和可擴充套件性的儲存方案。
5.2 本地儲存
如果您不想使用 S3 或 DynamoDB,還有一種快速簡單的方式可以進行儲存。每個 Alexa Skills 函式都有 512MB 的暫儲存存空間,可以用來儲存資料。這個儲存空間位於 /tmp 目錄中,但請注意,這種儲存方式只在會話期間有效,一旦會話結束,資料就會丟失。
以下是如何使用本地儲存的範例:
def handle(self, handler_input):
# 開啟檔案並寫入資料
f = open("/tmp/tempfile.txt", "a")
f.write("這是如何建立和儲存檔案")
f.close()
# 開啟檔案並讀取資料
f = open("/tmp/tempfile.txt", "r")
readFile = f.read()
f.close()
speak_output = readFile + " 和這是如何讀取它"
在這個範例中,我們開啟了一個名為 tempfile.txt 的檔案,並寫入了一些資料。然後,我們再次開啟這個檔案,並讀取其中的資料。
5.3 S3 儲存
S3(Simple Storage Service)是一種物件儲存服務,允許您儲存和擷取大量的資料。您可以使用 S3 來儲存 Alexa Skills 的使用者資料、音訊檔案等。
要使用 S3,您需要建立一個 S3 儲存桶,並設定適當的許可權和存取控制。
5.4 DynamoDB 資料函式庫
DynamoDB 是一種完全受管的 NoSQL 資料函式庫服務,允許您儲存和擷取結構化和非結構化的資料。您可以使用 DynamoDB 來儲存 Alexa Skills 的使用者資料、設定等。
要使用 DynamoDB,您需要建立一個 DynamoDB 表,並設定適當的許可權和存取控制。
使用 Alexa 和 Raspberry Pi 開發語音控制 IoT 應用程式
5.3 持續性屬性、DynamoDB 和 S3
在前一章中,我們瞭解瞭如何使用會話屬性(session attributes)儲存暫時資料,但這些資料會在會話結束時丟失。要儲存跨會話的資料,我們需要使用持續性屬性(persistent attributes)。
例如,您可能想要記錄使用者使用您的技能的次數,並在他們達到某個里程碑(例如每 10 次存取)時向他們祝賀。持續性屬性需要一些儲存空間,Alexa-Hosted Skill 提供了 DynamoDB 資料函式庫儲存和 S3(Simple Storage Service)儲存。
使用 DynamoDBPersistenceAdapter
我們將使用 DynamoDBPersistenceAdapter。持續性屬性儲存在 handler_input.attributes_manager 中。
- 讀取持續性屬性:
persistent_attributes = handler_input.attributes_manager.persistent_attributes - 儲存持續性屬性:
handler_input.attributes_manager.session_attributes = persistent_attributes和handler_input.attributes_manager.save_persistent_attributes()
以下是初始化持續性屬性的示例:
persistent_attributes = handler_input.attributes_manager.persistent_attributes
if not persistent_attributes:
# 首次 - 設定屬性,例如:
persistent_attributes['counter'] = 0
persistent_attributes['state'] = 'GO'
注意:您也可以檢查空的持續性屬性使用 if len(persistence_attr) == 0:。
實作持續性屬性的程式碼
以下是實作持續性屬性的程式碼範例:
import os
import boto3
# 建立 DynamoDB 連線
dynamodb = boto3.resource('dynamodb')
# 建立資料表
table_name = 'skill_usage'
table = dynamodb.Table(table_name)
def lambda_handler(event, context):
# 讀取持續性屬性
persistent_attributes = event['session']['attributes']
# 初始化持續性屬性
if not persistent_attributes:
persistent_attributes = {'counter': 0, 'state': 'GO'}
# 儲存持續性屬性
event['session']['attributes'] = persistent_attributes
table.put_item(Item=persistent_attributes)
# 處理語音命令
if event['request']['type'] == 'IntentRequest':
# 處理意圖
intent_name = event['request']['intent']['name']
if intent_name == '使用技能':
# 增加使用次數
persistent_attributes['counter'] += 1
# 儲存持續性屬性
table.put_item(Item=persistent_attributes)
# 回應使用者
speech_output = '您已經使用此技能 {} 次'.format(persistent_attributes['counter'])
return {
'version': '1.0',
'response': {
'outputSpeech': {
'text': speech_output,
'type': 'PlainText'
}
}
}
這個程式碼範例示範瞭如何使用 DynamoDB 儲存持續性屬性和處理語音命令。
使用DynamoDB進行持久化儲存
在這個章節中,我們將學習如何使用DynamoDB進行持久化儲存。首先,我們需要在requirements.txt檔案中新增DynamoDB的介面卡。
ask-sdk-dynamodb-persistence-adapter==1.15.0
接下來,我們需要在lambda_function.py檔案中新增必要的匯入陳述式。
import os
import boto3
from ask_sdk_dynamodb.adapter import DynamoDbAdapter
然後,我們需要初始化DynamoDB的連線。
ddb_region = os.environ.get('DYNAMODB_PERSISTENCE_REGION')
ddb_table_name = os.environ.get('DYNAMODB_PERSISTENCE_TABLE_NAME')
ddb_resource = boto3.resource('dynamodb', region_name=ddb_region)
dynamodb_adapter = DynamoDbAdapter(table_name=ddb_table_name, create_table=False, dynamodb_resource=ddb_resource)
接下來,我們需要使用CustomSkillBuilder來載入DynamoDB的介面卡。
sb = CustomSkillBuilder(persistence_adapter=dynamodb_adapter)
現在,我們可以在LaunchRequestHandler中載入屬性了。
def handle(self, handler_input):
# type: (HandlerInput) -> Response
persistent_attributes = handler_input.attributes_manager.persistent_attributes
session_attributes = handler_input.attributes_manager.session_attributes
if not persistent_attributes:
persistent_attributes['visit_counter'] = 1
session_attributes['number_of_hellos'] = 0
speak_output = "Hi. This is visit number " + str(persistent_attributes['visit_counter']) + ". You haven’t said Hello yet"
persistent_attributes['visit_counter'] = persistent_attributes['visit_counter'] + 1
handler_input.attributes_manager.persistent_attributes = persistent_attributes
handler_input.attributes_manager.save_persistent_attributes()
handler_input.attributes_manager.session_attributes = session_attributes
內容解密:
在這個程式碼中,我們使用DynamoDbAdapter來連線DynamoDB,並使用CustomSkillBuilder來載入DynamoDB的介面卡。然後,我們在LaunchRequestHandler中載入屬性,並更新存取次數和會話屬性。
圖表翻譯:
flowchart TD
A[LaunchRequestHandler] --> B[載入屬性]
B --> C[更新存取次數]
C --> D[更新會話屬性]
D --> E[儲存屬性]
圖表說明:
這個流程圖展示了LaunchRequestHandler的執行流程。首先,載入屬性,然後更新存取次數和會話屬性,最後儲存屬性。
使用 Alexa 和 Raspberry Pi 進行語音控制 IoT 應用開發
在開發語音控制 IoT 應用時,瞭解如何儲存和管理使用者資料非常重要。在本文中,我們將探討如何使用 Amazon S3 和 DynamoDB 來儲存和管理使用者資料。
S3 儲存
Amazon S3 是一個物件儲存服務,允許您儲存和擷取大量的資料。您可以使用 S3 來儲存使用者上傳的檔案,例如圖片或音訊檔案。
import boto3
s3 = boto3.client('s3')
# 上傳檔案到 S3
s3.upload_file('file.txt', 'my-bucket', 'file.txt')
DynamoDB 資料函式庫
Amazon DynamoDB 是一個 NoSQL 資料函式庫服務,允許您儲存和擷取結構化資料。您可以使用 DynamoDB 來儲存使用者資料,例如使用者名稱、電子郵件地址等。
import boto3
dynamodb = boto3.resource('dynamodb')
# 建立一個 DynamoDB 表格
table = dynamodb.create_table(
TableName='users',
KeySchema=[
{'AttributeName': 'id', 'KeyType': 'HASH'}
],
AttributeDefinitions=[
{'AttributeName': 'id', 'AttributeType': 'S'}
],
ProvisionedThroughput={
'ReadCapacityUnits': 1,
'WriteCapacityUnits': 1
}
)
# 插入資料到 DynamoDB 表格
table.put_item(
Item={
'id': '1',
'name': 'John Doe',
'email': 'johndoe@example.com'
}
)
Alexa Skill 的會話屬性
在 Alexa Skill 中,您可以使用會話屬性來儲存使用者資料。會話屬性是指在使用者與 Alexa Skill 互動期間儲存的資料。
def handle(self, handler_input):
# type: (HandlerInput) -> Response
session_attributes = handler_input.attributes_manager.session_attributes
session_attributes['number_of_hellos'] += 1
speak_output = "Hi. This is hello number " + str(session_attributes['number_of_hellos'])
handler_input.attributes_manager.session_attributes = session_attributes
return (
handler_input.response_builder
.speak(speak_output)
.ask("Say hello and I will count them for you")
.response
)
永續性屬性
永續性屬性是指在使用者與 Alexa Skill 互動結束後仍然儲存的資料。您可以使用永續性屬性來儲存使用者資料,例如使用者名稱、電子郵件地址等。
def handle(self, handler_input):
# type: (HandlerInput) -> Response
persistent_attributes = handler_input.attributes_manager.persistent_attributes
persistent_attributes['visit_count'] += 1
speak_output = "You have visited me " + str(persistent_attributes['visit_count']) + " times."
handler_input.attributes_manager.persistent_attributes = persistent_attributes
return (
handler_input.response_builder
.speak(speak_output)
.response
)
刪除永續性屬性
如果您想要刪除永續性屬性,您可以使用 delete_persistent_attributes 方法。
def handle(self, handler_input):
# type: (HandlerInput) -> Response
handler_input.attributes_manager.delete_persistent_attributes()
return (
handler_input.response_builder
.speak("Persistent attributes deleted.")
.response
)
圖表翻譯:
graph LR
A[使用者互動] --> B[會話屬性]
B --> C[永續性屬性]
C --> D[刪除永續性屬性]
D --> E[確認刪除]
在這個圖表中,我們可以看到使用者互動與會話屬性、永續性屬性之間的關係,以及如何刪除永續性屬性。
5.3.2 DynamoDB 資料儲存
在 DynamoDB 中,資料的儲存方式是非常重要的。點選程式碼標籤,然後選擇 DynamoDB。這將會開啟一個新的標籤頁,顯示您的資料函式庫資訊。雖然我們不會涵蓋所有的專案,但您可以透過「探索表格專案」來檢視您的存取次數計數器。您也可以點選編輯框來檢視和編輯專案。另外,點選「JSON 檢視」可以以 JSON 格式檢視資料。
Alexa Skill 開發與資料儲存策略總結
本文深入探討了 Alexa Skill 開發過程中,利用 SsmlUtils、ViewportUtils 以及不同儲存方案管理資料的技巧。從暫儲存存空間 /tmp、S3 到 DynamoDB,各種方案各有其優劣與適用場景。
從技術架構視角來看,/tmp 提供了簡便的會話內資料儲存,但其生命週期受限於會話本身,不適用於持久化資料。S3 適合儲存大量的非結構化資料,例如音訊檔案或圖片,而 DynamoDB 則更擅長處理結構化資料,提供高用性和可擴充套件性,適用於儲存使用者設定、計數器等。選擇哪種方案取決於技能的實際需求,例如資料的結構、存取頻率以及持久化需求等。
然而,單純使用 S3 或 DynamoDB 仍不足以應付所有 Alexa Skill 的資料儲存需求。對於跨會話的資料持久化,永續性屬性(persistent attributes)結合 DynamoDBPersistenceAdapter 提供了更完善的解決方案。透過 handler_input.attributes_manager 介面,開發者可以輕鬆管理和儲存永續性資料,例如使用者存取次數、技能狀態等。此方法有效解決了會話屬性(session attributes)的侷限性,提升了使用者經驗。
目前,DynamoDBPersistenceAdapter 的整合仍存在一些挑戰,例如設定環境變數、資料表結構設計等。開發者需要仔細閱讀官方檔案並參考最佳實務,才能確保資料的正確儲存和讀取。未來,預期會有更簡化的整合方式和更豐富的管理工具出現,降低開發門檻。
對於注重使用者資料管理的 Alexa Skill 開發者,建議優先採用 DynamoDB 結合永續性屬性方案,以兼顧資料的持久化、一致性和可擴充套件性。同時,需持續關注 AWS 提供的最新工具和服務,以最佳化資料儲存策略,提升技能的整體效能和使用者經驗。 玄貓認為,掌握資料儲存策略是開發高品質 Alexa Skill 的關鍵環節,值得開發者投入更多精力深入研究。