如何使用 AWS Bedrock 模型
在這篇文章中,我們將介紹如何使用 AWS Bedrock 模型來獲取有關特定國家的首都資訊。
所需工具
我們需要使用 Python 程式語言和一些 AWS 的工具來完成這個任務。首先,我們需要安裝 boto3
,這是一個用來與 AWS 服務互動的庫。
設定 AWS 金鑰
在開始之前,我們需要設定 AWS 的存取金鑰和秘密金鑰。這些金鑰可以讓我們安全地使用 AWS 的服務。
撰寫程式碼
接下來,我們將撰寫一個函數,這個函數會根據使用者的輸入來查詢特定國家的首都。
def call_bedrock_model(userPrompt):
brt = boto3.client(
service_name="bedrock-runtime",
region_name=REGION_NAME,
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY
)
county = userPrompt
prompt = f"""告訴我有關 {county} 的首都"""
body = json.dumps({
"inputText": prompt,
"textGenerationConfig": {
"maxTokenCount": 10,
"stopSequences": [],
"temperature": 0.7,
"topP": 0.9
}
})
modelId = 'amazon.titan-text-express-v1'
accept="application/json"
contentType="application/json"
try:
response = brt.invoke_model(body=body, modelId=modelId, accept=accept, contentType=contentType)
response_body = json.loads(response.get('body').read())
print(response_body.get('results')[0]['outputText'])
reponse_text = response_body.get('results')[0]['outputText']
except Exception as e:
print("發生意外事件。", e)
return "內部伺服器錯誤。"
return reponse_text
處理使用者請求
最後,我們需要一個函數來處理使用者的請求,並回傳首都的資訊。
def lambda_handler(event, context):
body = event.get('body', '{}')
body_json = json.loads(body)
userInput = body_json.get('inputText', None)
response = call_bedrock_model("印度")
print(response)
return {
'statusCode': 200,
'body': json.dumps(response)
}
總結
透過這些步驟,我們可以輕鬆地使用 AWS Bedrock 模型來獲取有關不同國家的首都資訊。希望這篇文章能幫助你了解如何使用這些工具!
新聞來源
本文由 AI 台灣 使用 AI 編撰,內容僅供參考,請自行進行事實查核。加入 AI TAIWAN Google News,隨時掌握最新 AI 資訊!