今天這篇我們探討 prompt engineer 相關的知識,不同模型有可能根據提示詞(Prompt)會給不同的結果
(Claude、Llama、Titan) 因為對模型『下指令』,也是開發者的可控範圍之一,
所以這也是一個很重要值得探討的一個項目
舉例:
❌Bad:
請幫我分析這個數據
✅Good :
請分析以下2024年第三季度的銷售數據,重點關注:
1. 各產品線的銷售趋勢
2. 地區間的差異
3. 與去年同期的比較
4. 提供3個具體的改進建議
數據:[具體數據內容]
設定角色可以給予高品質回應,以下以 python 作為不同角色成為參數因子
import boto3
import json
def create_expert_prompt(role, task, context):
prompt = f"""
你是一位經驗豐富的{role},具有10年以上的專業經驗。
任務:{task}
背景資訊:{context}
請以專業角度提供詳細分析和建議,包括:
1. 專業見解
2. 潛在風險
3. 最佳實踐建議
4. 實施步驟
"""
return prompt
# 使用範例
bedrock = boto3.client('bedrock-runtime', region_name='us-east-1')
prompt = create_expert_prompt(
role="AWS解決方案架構師",
task="設計一個高可用性的Web應用架構",
context="電子商務網站,預期日流量10萬人次,需要支持全球用戶"
)
顧名思義,就是根據要求回應給予限制,讓 ai 幫我們回應較為精準且符合格式的回應
def create_few_shot_prompt(examples, new_input):
prompt = "請根據以下範例格式進行回應:\n\n"
for i, example in enumerate(examples, 1):
prompt += f"範例 {i}:\n"
prompt += f"輸入: {example['input']}\n"
prompt += f"輸出: {example['output']}\n\n"
prompt += f"現在請處理以下新的輸入:\n{new_input}"
return prompt
# 實際應用範例
examples = [
{
"input": "客戶抱怨產品品質問題",
"output": "分類:品質問題 | 優先級:高 | 建議部門:品管部"
},
{
"input": "客戶詢問退貨政策",
"output": "分類:政策諮詢 | 優先級:中 | 建議部門:客服部"
}
]
prompt = create_few_shot_prompt(examples, "客戶要求加急處理訂單")
基本上就是要求 ai 要根據哪些思維去思考,
這個思維去思考出來的東西繼續用這樣的結果,去思考下一層面的東西
去誘導 ai 的推理過程
def create_cot_prompt(problem):
return f"""
請逐步分析以下問題:
問題:{problem}
請按照以下步驟思考:
1. 問題分解:將複雜問題分解為子問題
2. 分析每個子問題:逐一分析各個要素
3. 整合思考:將各部分分析結果整合
4. 得出結論:基於前面的分析給出最終答案
請在每個步驟都說明你的思考過程。
"""
# 使用範例
problem = "如何在AWS上設計一個成本效益最佳的機器學習訓練環境?"
prompt = create_cot_prompt(problem)
不同於前面說的 少樣本學習(Few-Shot Learning)
這裡限制的是輸出的格式本身,像是我們會說要以 json
回應,
要以 toml格式
回應 等等
def create_structured_prompt(task, output_format):
return f"""
任務:{task}
輸出要求:
- 格式:{output_format}
- 字數限制:500-800字
- 語言:繁體中文
- 包含具體數據和範例
- 避免使用專業術語,用簡單易懂的語言
請嚴格按照以上要求回應。
"""
# JSON格式輸出範例
json_prompt = create_structured_prompt(
task="分析AWS Bedrock的優勢",
output_format="JSON格式,包含優勢列表、具體說明、使用場景"
)
結構化指令
以下為 claude 標準例子 - 結構化敘述優化
def claude_optimized_prompt(instruction, context="", examples=""):
return f"""
<instruction>
{instruction}
</instruction>
<context>
{context}
</context>
<examples>
{examples}
</examples>
請根據上述指令和背景資訊,提供詳細的回應。
"""
以下為 Llama模型優化 - 對話式響應優化
def llama_optimized_prompt(user_query, system_context=""):
return f"""
System: {system_context}
Human: {user_query}
Assistant: 讓我來幫您解決這個問題。
"""
import boto3
import json
from datetime import datetime
class BedrockPromptOptimizer:
def __init__(self):
self.bedrock = boto3.client('bedrock-runtime', region_name='ap-northeast-1')
def create_customer_service_prompt(self, customer_query, context_info):
prompt = f"""
你是一位專業的客服代表,具有豐富的電商平台服務經驗。
客戶查詢:{customer_query}
客戶背景資訊:
- 會員等級:{context_info.get('membership_level', '一般會員')}
- 歷史訂單數:{context_info.get('order_count', 0)}
- 上次互動時間:{context_info.get('last_interaction', '首次聯繫')}
回應要求:
1. 保持友善和專業的語氣
2. 提供具體的解決方案
3. 如需要額外資訊,主動詢問
4. 結尾提供相關的幫助資源
請以JSON格式回應:
{{
"response": "具體回應內容",
"action_required": "需要採取的行動",
"follow_up": "後續追蹤建議",
"resources": ["相關資源連結"]
}}
"""
return prompt
def invoke_bedrock_with_optimization(self, prompt, model_id="anthropic.claude-3-sonnet-20240229-v1:0"):
body = {
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 1000,
"temperature": 0.3, # 較低溫度確保回應一致性
"top_p": 0.9,
"messages": [
{"role": "user", "content": prompt}
]
}
response = self.bedrock.invoke_model(
modelId=model_id,
body=json.dumps(body)
)
result = json.loads(response['body'].read())
return result['content'][0]['text']
# 使用範例
optimizer = BedrockPromptOptimizer()
context = {
'membership_level': 'VIP會員',
'order_count': 15,
'last_interaction': '2024-10-15'
}
prompt = optimizer.create_customer_service_prompt(
"我的訂單已經延遲3天了,什麼時候能到貨?",
context
)
response = optimizer.invoke_bedrock_with_optimization(prompt)
print(response)
大量相似請求可以批次處理
def batch_process_prompts(prompts, model_id):
results = []
# 將相似的提示組合處理
combined_prompt = "請分別處理以下查詢:\n\n"
for i, prompt in enumerate(prompts, 1):
combined_prompt += f"查詢 {i}: {prompt}\n"
combined_prompt += "\n請以編號對應的方式回應每個查詢。"
# 調用模型
response = invoke_bedrock_model(combined_prompt, model_id)
return response
根據不同角色,或情境給予回應的 template
class PromptTemplateCache:
def __init__(self):
self.templates = {}
def get_template(self, template_name):
if template_name not in self.templates:
self.templates[template_name] = self._load_template(template_name)
return self.templates[template_name]
def _load_template(self, template_name):
# 從檔案或資料庫載入模板
templates = {
'customer_service': """
你是專業的客服代表...
客戶問題:{query}
回應格式:{format}
""",
'technical_support': """
你是技術支援專家...
技術問題:{issue}
系統環境:{environment}
"""
}
return templates.get(template_name, "")
可以參考 : Prompt caching
prompt 的技巧是一般人最容易忽視的事情,很多時候 prompt 下得好,可以少寫不少 code 甚至節約成本或是增加效率等
這是一個不可以忽視的事情,有時候會比多寫幾行 code 有用