使用語言模型產生文字

Amazon Bedrock 入門

Nikhil Rangarajan

Data Scientist

將提示送給語言模型

  • Prompt:你傳給模型的輸入文字
    • 「Explain how AWS Lambda works」

代表提示的圖示。

Amazon Bedrock 入門

將提示送給語言模型

  • Prompt:你傳給模型的輸入文字
    • 「Explain how AWS Lambda works」
  • Completion:模型產生的文字
    • 「AWS Lambda is a serverless compute service that...」

代表提示與完成內容的圖示。

Amazon Bedrock 入門

將提示送給語言模型

  • Prompt:你傳給模型的輸入文字
    • 「Explain how AWS Lambda works」
  • Completion:模型產生的文字
    • 「AWS Lambda is a serverless compute service that...」
  • Response:
    • 產生的文字(completion)
    • 中繼資料(tokens、模型資訊)
    • 狀態資訊

依序代表提示、完成內容與回應的三個圖示。

Amazon Bedrock 入門

應用基礎提示工程技巧

  • 更好結果的技巧:
    • 清楚且具體:寫下詳細精確的說明
    • 指定角色:給模型一個人格以強化脈絡理解
    • 格式指引:加入限制以引導回應
"Explain the benefits of exercise 
in simple terms."
"You are a nutritionist. Explain the 
benefits of a balanced diet."
"List the top 3 benefits of cloud 
computing in bullet points."
Amazon Bedrock 入門

進階文字解析技巧

  • 處理遺漏或非預期的鍵
data = json.loads(response['body'].read())
if 'completion' in data:
    output = data['completion']

else: output = "Key not found"
  • 多層 JSON 解析以瀏覽深層結構
try:
    nova_output = data.decode()["output"]

except (KeyError, IndexError) as e: nova_output = f"Error: {str(e)}"
Amazon Bedrock 入門

回應處理與文字處理

  • Unicode 或編碼問題:處理回應中的特殊字元
    # Ensure proper encoding
    output = data['completion'].encode('utf-8').decode('unicode_escape')
    print(output)
    
  • 處理大型回應:為了可用性切分或截斷輸出
    # Truncate response for display
    output = data['completion'][:500]  # Limit to 500 characters
    print(output)
    
Amazon Bedrock 入門

使用 Bedrock 萃取類別

  • 範例:文字資料分類
  • 使用結構化提示並提供明確類別選項
  • 明確要求只輸出單一類別
  • 有效處理模型回應
  • 結果:精準的文字分類

代表文字分類的圖示

Amazon Bedrock 入門

使用 Bedrock 萃取類別

def categorize_ticket(ticket, categories):
  prompt = f"Categorize into one: {', '.join(categories)}. 
  Ticket: {ticket}"
  response = bedrock.invoke_model(
    modelId='amazon.nova-micro-v1:0',
    body=json.dumps({"messages": [{"role": "user", "content": 
                                   [{"text": prompt}]}]}))

return json.loads(nova_response.get("body").read().decode())["output"]
{"output": {"message": {"role": "assistant","content": [
        {
          "text": "Customer Service"
        }]}, "stop_reason": "stop_sequence"}}
Amazon Bedrock 入門

一起來練習吧!

Amazon Bedrock 入門

Preparing Video For Download...