# 服務 Part 1:AWS Bedrock 服務及架構 :::success Try out [https://nova.amazon.com/](https://nova.amazon.com/) ::: ## Amazon SageMaker FMs 每季最新上架 :::info [Count Tokens API supported for Anthropic’s Claude models now in Amazon Bedrock](https://hackmd.io/HYi9ZCKKSPWCFbtpXGgHqw) 更新時間: 2025-08-22 [Citations API and PDF support for Claude models now in Amazon Bedrock](https://aws.amazon.com/about-aws/whats-new/2025/06/citations-api-pdf-claude-models-amazon-bedrock/) | [Builder Blog](https://builder.aws.com/content/2yuuUoj0uthPd6M3GR7t2SZ4r8E/claude-pdf-support-on-amazon-bedrock) | [Github](https://github.com/aws-samples/anthropic-on-aws/blob/main/notebooks/claude_pdf_support/claude_pdf_support.ipynb) 更新時間: 2025-06-30 [Amazon Nova Canvas adds virtual try-on and style options for image generation](https://aws.amazon.com/about-aws/whats-new/2025/07/amazon-nova-canvas-virtual-try-on-style-options-image-generation/) 更新時間: 2025-07-11 [Citations API and PDF support for Claude models now in Amazon Bedrock](https://aws.amazon.com/about-aws/whats-new/2025/06/citations-api-pdf-claude-models-amazon-bedrock/) 更新時間: 2025-07-01 [Amazon Nova Premier, our most capable model for complex tasks and teacher for model distillation](https://aws.amazon.com/about-aws/whats-new/2025/04/amazon-nova-premier-complex-tasks-model-distillation/) | [Blog](https://aws.amazon.com/blogs/aws/amazon-nova-premier-our-most-capable-model-for-complex-tasks-and-teacher-for-model-distillation/) 更新時間: 2025-04-30 [Meta’s Llama 4 now available fully managed in Amazon Bedrock](https://aws.amazon.com/about-aws/whats-new/2025/04/metas-llama-4-managed-amazon-bedrock/) | [Blog](https://aws.amazon.com/blogs/aws/llama-4-models-from-meta-now-available-in-amazon-bedrock-serverless/) 更新時間: 2025-04-29 [Writer’s Palmyra X5 and X4 models are now available in Amazon Bedrock](https://aws.amazon.com/about-aws/whats-new/2025/04/writers-palmyra-x5-x4-models-amazon-bedrock/) 更新時間: 2025-04-28 [Amazon Bedrock now offers Pixtral Large 25.02, a multimodal model from Mistral AI](https://aws.amazon.com/about-aws/whats-new/2025/04/amazon-bedrock-pixtral-large-25-02-mistral-ai/) 更新時間: 2025-04-07 [Announcing Amazon Nova Reel 1.1](https://aws.amazon.com/about-aws/whats-new/2025/04/amazon-nova-reel-1-1/) 更新時間: 2025-04-07 [Amazon Nova Canvas now supports fine-tuning](https://aws.amazon.com/about-aws/whats-new/2025/04/amazon-nova-canvas-supports-fine-tuning/) 更新時間: 2025-04-07 [Amazon Nova expands Tool Choice options for Converse API](https://aws.amazon.com/about-aws/whats-new/2025/03/amazon-nova-expands-tool-converse-api/) 更新時間: 2025-03-19 [Meta’s Llama 3.2 models are now available for fine-tuning in Amazon Bedrock](https://aws.amazon.com/about-aws/whats-new/2025/03/metas-llama-3-2-models-fine-tuning-amazon-bedrock/) 更新時間: 2025-03-14 [DeepSeek-R1 is available fully-managed in Amazon Bedrock](https://aws.amazon.com/about-aws/whats-new/2025/03/deepseek-r1-fully-managed-amazon-bedrock/) 更新時間: 2025-03-10 [Announcing latency-optimized inference for Amazon Nova Pro foundation model in Amazon Bedrock](https://aws.amazon.com/about-aws/whats-new/2025/03/latency-optimized-inference-amazon-nova-pro-foundation-model-bedrock/) 更新時間: 2025-03-06 [Anthropic's Claude 3.7 Sonnet is now available in Amazon Bedrock](https://aws.amazon.com/about-aws/whats-new/2025/02/anthropics-claude-3-7-sonnet-amazon-bedrock/) 更新時間: 2025-02-24 [Amazon Bedrock now offers multimodal support for Cohere Embed 3 Multilingual and Embed 3 English](https://aws.amazon.com/about-aws/whats-new/2025/01/amazon-bedrock-multimodal-cohere-embed-3-multilingual-english/) | [Leaderboard](https://huggingface.co/spaces/mteb/leaderboard) 更新時間: 2025-01-24 [Luma AI's Ray2 visual AI model now available in Amazon Bedrock](https://aws.amazon.com/about-aws/whats-new/2025/01/luma-ais-ray2-visual-ai-model-amazon-bedrock/) 更新時間: 2025-01-23 [Llama 3.3 70B now available on AWS via Amazon SageMaker JumpStart](https://aws.amazon.com/about-aws/whats-new/2024/12/llama-3-3-70b-aws-amazon-sagemaker-jumpstart/) 更新時間: 2024-12-26 [Introducing Stable Diffusion 3.5 Large in Amazon Bedrock](https://aws.amazon.com/about-aws/whats-new/2024/12/stable-diffusion-3-5-large-amazon-bedrock/) 更新時間: 2024-12-19 [Meta’s Llama 3.3 70B model now available in Amazon Bedrock](https://aws.amazon.com/about-aws/whats-new/2024/12/metas-llama-3-3-70b-model-amazon-bedrock/) 更新時間: 2024-12-19 ::: ## Amazon Bedrock 服務每季最新消息 :::info [Amazon Bedrock introduces API keys for streamlined development](https://aws.amazon.com/blogs/machine-learning/accelerate-ai-development-with-amazon-bedrock-api-keys/) [Refresh short-term Amazon Bedrock API keys for greater control and security](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-refresh.html) 更新時間: 2025-07-08 🟢 [Amazon Bedrock Data Automation now supports extraction of custom insights from audio](https://aws.amazon.com/about-aws/whats-new/2025/05/amazon-bedrock-data-automation-extraction-custom-insights-audio/) 更新時間: 2025-05-05 [Amazon Bedrock Model Distillation is now generally available](https://aws.amazon.com/about-aws/whats-new/2025/05/amazon-bedrock-model-distillation-generally-available/) | [Blog](https://aws.amazon.com/blogs/machine-learning/amazon-bedrock-model-distillation-boost-function-calling-accuracy-while-reducing-cost-and-latency/) 更新時間: 2025-05-01 [Amazon Bedrock Data Automation now supports modality controls, hyperlinks and larger documents](https://aws.amazon.com/about-aws/whats-new/2025/04/amazon-bedrock-data-automation-modality-controls-hyperlinks-larger-documents/) 更新時間: 2025-04-23 [Prompt Optimization in Amazon Bedrock now generally available](https://aws.amazon.com/about-aws/whats-new/2025/04/prompt-optimization-amazon-bedrock-generally-available/) | [Blog](https://aws.amazon.com/blogs/machine-learning/amazon-bedrock-prompt-optimization-drives-llm-applications-innovation-for-yuewen-group/) 更新時間: 2025-04-23 [Amazon Bedrock Intelligent Prompt Routing is now generally available](https://aws.amazon.com/about-aws/whats-new/2025/04/amazon-bedrock-intelligent-prompt-routing-generally-available/) | [Blog](https://aws.amazon.com/blogs/machine-learning/use-amazon-bedrock-intelligent-prompt-routing-for-cost-and-latency-benefits/) 更新時間: 2025-04-22 [Amazon Bedrock RAG and Model Evaluations now support custom metrics](https://aws.amazon.com/about-aws/whats-new/2025/04/amazon-bedrock-rag-model-evaluations-custom-metrics/) 更新時間: 2025-04-17 [Amazon Bedrock Knowledge Bases now supports hybrid search for Aurora PostgreSQL and MongoDB Atlas vector stores](https://aws.amazon.com/about-aws/whats-new/2025/04/amazon-bedrock-knowledge-bases-hybrid-search-aurora-postgresql-mongo-db-atlas-vector-stores/) 更新時間: 2025-04-10 [PartyRock introduces image playground, powered by Amazon Nova Canvas](https://aws.amazon.com/about-aws/whats-new/2025/04/partyrock-image-playground-amazon-nova-canvas/) 更新時間: 2025-04-09 [Announcing Amazon Nova Sonic, a new speech-to-speech model that brings real-time voice conversations to Amazon Bedrock](https://aws.amazon.com/about-aws/whats-new/2025/04/amazon-nova-sonic-speech-to-speech-conversations-bedrock/) | [Blog](https://aws.amazon.com/blogs/aws/introducing-amazon-nova-sonic-human-like-voice-conversations-for-generative-ai-applications/) 更新時間: 2025-04-08 [Amazon Bedrock Guardrails announces new capabilities to safely build generative AI applications](https://aws.amazon.com/about-aws/whats-new/2025/04/amazon-bedrock-guardrails-safely-build-generative-ai-applications/) | [Blog](Amazon Bedrock Guardrails enhances generative AI application safety with new capabilities) 更新時間: 2025-04-08 [Amazon Bedrock announces general availability of prompt caching](https://aws.amazon.com/about-aws/whats-new/2025/04/amazon-bedrock-general-availability-prompt-caching/) 更新時間: 2025-04-07 [Amazon Bedrock Guardrails announces the general availability of industry-leading image content filters](https://aws.amazon.com/new/?whats-new-content-all.sort-by=item.additionalFields.postDateTime&whats-new-content-all.sort-order=desc&awsf.whats-new-categories=marketing-marchitecture%23artificial-intelligence&awsm.page-whats-new-content-all=3) | [Blog](https://aws.amazon.com/blogs/machine-learning/amazon-bedrock-guardrails-image-content-filters-provide-industry-leading-safeguards-helping-customer-block-up-to-88-of-harmful-multimodal-content-generally-available-today/) 更新時間: 2025-03-29 [Amazon Bedrock Knowledge Bases now supports Amazon OpenSearch Managed Cluster for vector storage](https://aws.amazon.com/about-aws/whats-new/2025/03/amazon-bedrock-knowledge-bases-opensearch-cluster-vector-storage/) 更新時間: 2025-03-27 [Amazon Bedrock Custom Model Import introduces real-time cost transparency](https://aws.amazon.com/about-aws/whats-new/2025/03/amazon-bedrock-custom-model-import-real-time-cost-transparency/) 更新時間: 2025-03-26 [Amazon Bedrock Model Evaluation LLM-as-a-judge is now generally available](https://aws.amazon.com/about-aws/whats-new/2025/03/amazon-bedrock-model-evaluation-llm-as-a-judge/) 更新時間: 2025-03-20 [Amazon Bedrock now supports RAG Evaluation (generally available)](https://aws.amazon.com/about-aws/whats-new/2025/03/amazon-bedrock-rag-evaluation-generally-available/) 更新時間: 2025-03-20 [Amazon Bedrock Guardrails announces policy based enforcement for responsible AI](https://aws.amazon.com/about-aws/whats-new/2025/03/amazon-bedrock-guardrails-policy-based-enforcement-responsible-ai/) 更新時間: 2025-03-18 [Amazon Bedrock now supports multi-agent collaboration](https://aws.amazon.com/about-aws/whats-new/2025/03/amazon-bedrock-multi-agent-collaboration/) 更新時間: 2025-03-10 [Amazon Bedrock Knowledge Bases supports GraphRAG now generally available](https://aws.amazon.com/about-aws/whats-new/2025/03/amazon-bedrock-knowledge-bases-graphrag-generally-available/) 更新時間: 2025-03-07 [Amazon Bedrock Data Automation is now generally available](https://aws.amazon.com/about-aws/whats-new/2025/03/amazon-bedrock-data-automation-generally-available) 更新時間: 2025-03-03 [Amazon Bedrock launches Session Management APIs for GenAI applications (Preview)](https://aws.amazon.com/about-aws/whats-new/2025/02/amazon-bedrock-session-management-apis-genai-applications-preview/) 更新時間: 2025-02-28 [Amazon Bedrock Guardrails announces an increase in service quota limits](https://aws.amazon.com/new/?whats-new-content-all.sort-by=item.additionalFields.postDateTime&whats-new-content-all.sort-order=desc&awsf.whats-new-categories=marketing-marchitecture%23artificial-intelligence&awsm.page-whats-new-content-all=3) 更新時間: 2025-02-25 [Amazon Bedrock Flows announces preview of multi-turn conversation support](https://aws.amazon.com/about-aws/whats-new/2025/01/amazon-bedrock-flows-multi-turn-conversation-support/) | [Blog](https://aws.amazon.com/blogs/machine-learning/introducing-multi-turn-conversation-with-an-agent-node-for-amazon-bedrock-flows-preview/) 更新時間: 2025-01-23 [Amazon Bedrock Agents, Flows, and Knowledge Bases now supports Latency Optimized Models](https://aws.amazon.com/about-aws/whats-new/2024/12/amazon-bedrock-agents-flows-knowledge-optimized-models/) 更新時間: 2024-12-23 [re:Invent 2024 Annoucement](https://hackmd.io/@yuhsintsao/HJ1RRzpQkg) 最後更新時間: 2024-12-06 [Announcing new AWS AI Service Cards to advance responsible generative AI ](https://aws.amazon.com/about-aws/whats-new/2024/12/aws-ai-service-cards-advance-responsible-generative-ai/) 更新時間: 2024-12-04 [Upgraded Claude 3.5 Sonnet from Anthropic (available now), computer use (public beta), and Claude 3.5 Haiku (coming soon) in Amazon Bedrock](https://aws.amazon.com/blogs/aws/upgraded-claude-3-5-sonnet-from-anthropic-available-now-computer-use-public-beta-and-claude-3-5-haiku-coming-soon-in-amazon-bedrock/) 更新時間: 2024-10-22 更多新消息:[請參考官網](https://aws.amazon.com/new/?whats-new-content-all.sort-by=item.additionalFields.postDateTime&whats-new-content-all.sort-order=desc&awsf.whats-new-categories=marketing-marchitecture%23artificial-intelligence) 更多新文章:[請參考官網](https://aws.amazon.com/blogs/?awsf.blog-master-category=category%23generative-ai-2%7Ccategory%23artificial-intelligence&awsf.blog-master-learning-levels=*all&awsf.blog-master-industry=*all&awsf.blog-master-analytics-products=*all&awsf.blog-master-artificial-intelligence=*all&awsf.blog-master-aws-cloud-financial-management=*all&awsf.blog-master-blockchain=*all&awsf.blog-master-business-applications=*all&awsf.blog-master-compute=*all&awsf.blog-master-customer-enablement=*all&awsf.blog-master-customer-engagement=*all&awsf.blog-master-database=*all&awsf.blog-master-developer-tools=*all&awsf.blog-master-devops=*all&awsf.blog-master-end-user-computing=*all&awsf.blog-master-mobile=*all&awsf.blog-master-iot=*all&awsf.blog-master-management-governance=*all&awsf.blog-master-media-services=*all&awsf.blog-master-migration-transfer=*all&awsf.blog-master-migration-solutions=*all&awsf.blog-master-networking-content-delivery=*all&awsf.blog-master-programming-language=*all&awsf.blog-master-sector=*all&awsf.blog-master-security=*all&awsf.blog-master-storage=*all) ::: :::success GitHub: [AWS Bedrock samples](https://github.com/aws-samples/amazon-bedrock-samples) ::: # Amazon Bedrock 服務功能 Deep Dive ## 跨區域推論 Cross-Region Inference :::info AWS blog: [Getting started with cross-region inference in Amazon Bedrock](https://aws.amazon.com/blogs/machine-learning/getting-started-with-cross-region-inference-in-amazon-bedrock/) 更新時間: 2024-08-27 ::: **主要特點和優勢** 關鍵需求是能夠管理各種生成式 AI 工作負載和不同請求形式的突發和尖峰流量模式。跨區域推理的一些主要特點包括: * 利用多個 AWS 區域的容量(累計),使生成式 AI 工作負載能夠隨需求擴展。 * 與現有的亞馬遜 Bedrock API 兼容。 * 無額外的路由或資料傳輸成本,您支付的模型每個token價格與源/主要區域相同。 * 對任何流量突發更具彈性。這意味著用戶可以專注於他們的核心工作負載和為由亞馬遜 Bedrock 支持的應用程式編寫邏輯。 **請注意** * 使用 AWS 網絡骨幹而不是 Internet 或 VPC 對等連接(peering)進行區域間資料傳輸。 * 首先嘗試從您的主要區域服務進行請求,在流量繁重、瓶頸的情況下負載均衡請求,將請求路由到其他區域。 * 您可以通過跨區域推理訪問特定的模型。您將能夠在區域集內的任何地方使用亞馬遜 Bedrock 中可用的模型子集,即使該模型在您的主要區域不可用。 * 您可以在亞馬遜 Bedrock 模型調用 API(InvokeModel 和 Converse API)中使用此功能。 * 您可以選擇直接通過各自的模型標識符使用基礎模型,或通過跨區域推理機制使用模型。通過此功能執行的任何推理都將考慮其所有預配置區域的按需容量,以最大化可用性。 * 當發生重新路由時會產生額外的延遲,在我們的測試中,它增加了雙位數毫秒的延遲。 * 使用特定模型時適用的所有條款,包括任何最終用戶許可協議,在使用跨區域推理時仍然適用。 * 使用此功能時,您的吞吐量可以達到推理配置文件所在區域分配配額的兩倍。吞吐量的增加只適用於通過推理配置文件執行的調用,如果您選擇區域內模型調用請求,則仍適用常規配額。 **次要區域的定義** * 什麼是次要區域?目前您可以選擇美國模型或歐盟模型,每個模型都將包括來自這些地理位置的2-3個預設區域。 * 包括哪些模型?目前我們將提供 Claude 3 系列模型(Haiku、Sonnet、Opus)和 Claude 3.5 Sonnet。 * 我們可以使用 PrivateLink 嗎?是的,您可以利用您的私有鏈接,並確保使用此功能時流量通過您的 VPC 流動。 * 我們也可以將此功能用於預配吞吐量嗎(PT)?目前,此功能不適用於預配吞吐量,只能用於按需推理(on-demand)。 * 工作負載流量何時會被重新路由?跨區域推理首先會嘗試通過主要區域(連接的亞馬遜 Bedrock 端點的區域)服務您的請求。隨著流量模式激增,當亞馬遜 Bedrock 檢測到潛在的延遲時,流量將主動轉移到次要區域並從這些區域提供服務。 * 跨區域推理的日誌會在哪裡?日誌和調用仍將在請求發起的主要區域和帳戶中。亞馬遜 Bedrock 將在日誌上輸出指標,顯示實際服務請求的區域。 eu-west-1(愛爾蘭)的工作負載客戶可能選擇 eu-west-3(巴黎)和 eu-central-1(法蘭克福)作為一對次要區域,或 us-east-1(北弗吉尼亞)的工作負載可能選擇 us-west-2(俄勒岡)作為單一次要區域,反之亦然。這將保持所有推理流量在美國或歐盟內。 ![Screenshot 2024-09-04 at 9.36.15 PM](https://hackmd.io/_uploads/rklbVX1Lh0.png) 操作流程從主要區域的隨需基礎模型的推理請求開始。對主要區域和次要區域列表進行容量評估,按容量順序創建區域容量列表。選擇可用容量最多的區域(在此例中為 eu-central-1,法蘭克福)作為下一個目標。請求使用 AWS 主幹網絡重新路由到法蘭克福,確保所有流量保持在 AWS 網絡內。請求繞過次要區域亞馬遜 Bedrock 服務的標準 API 入口點,直接進入運行時推理服務,響應通過 AWS 主幹返回主要區域,然後按照正常推理請求返回給調用者。如果所選區域的處理因任何原因失敗,則嘗試列表中可用容量最高的下一個區域,在此例中為 eu-west-1(愛爾蘭),然後是 eu-west-3(巴黎),直到嘗試了所有配置的區域。如果次要區域列表中沒有區域可以處理推理請求,則 API 將返回標準的"節流"響應。 **網絡和數據日誌記錄** AWS 到 AWS 的流量,例如區域間(包括邊緣位置和直接連接路徑)的流量,將始終通過 AWS 擁有和操作的主幹路徑。這不僅減少了常見漏洞和 DDoS 攻擊等威脅,還確保所有內部 AWS 到 AWS 流量僅使用可信網絡路徑。這與區域間和區域內路徑加密以及路由策略執行機制相結合,所有這些都使用 AWS 安全設施。這種執行機制的組合有助於確保 AWS 到 AWS 流量永遠不會使用非加密或不受信任的路徑,如互聯網,因此所有跨區域推理請求將始終保持在 AWS 主幹網絡上。 日誌條目將繼續在原始源區域的 Amazon CloudWatch 和 AWS CloudTrail 中記錄,重新路由區域中不會有額外的日誌。為了指示發生了重新路由,AWS CloudTrail 中的相關條目還將包括以下額外數據 - 僅當請求在重新路由區域處理時才添加。 ```xml <requestRoutedToRegion> us-east-1 </requestRoutedToRegion> ``` 在推理請求期間,亞馬遜 Bedrock 不會記錄或以其他方式存儲客戶的任何提示或模型響應。如果跨區域推理將查詢從主要區域重新路由到次要區域進行處理,這仍然是正確的 - 該次要區域不存儲與推理請求相關的任何數據,並且在該次要區域中不存儲 Amazon CloudWatch 或 AWS CloudTrail 日誌。 以下是一個示例策略,允許調用者對 us-east-1 和 us-west-2 區域中的任何模型使用 InvokeModel* API 進行跨區域推理: ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["bedrock:InvokeModel*"], "Resource: [ "arn:aws:bedrock:us-east-1:<account_id>:inference-profile/*", "arn:aws:bedrock:us-east-1::foundation-model/*", "arn:aws:bedrock:us-west-2::foundation-model/*" ] } ] } ``` ```python modelId = 'anthropic.claude-3-5-sonnet-20240620-v1:0' bedrock_runtime.converse( modelId=modelId, system=[{ "text": "You are an AI assistant." }], messages=[{ "role": "user", "content": [{"text": "Tell me about Amazon Bedrock."}] }] ) ``` ```python modelId = 'eu.anthropic.claude-3-5-sonnet-20240620-v1:0' bedrock_runtime.converse( modelId=modelId, system=[{ "text": "You are an AI assistant." }], messages=[{ "role": "user", "content": [{"text": "Tell me about Amazon Bedrock."}] }] ) ``` ```python import boto3 bedrock_client = boto3.client("bedrock", region_name="us-east-1") bedrock_client.list_inference_profiles() ``` ```json { "inferenceProfileSummaries": [ { "inferenceProfileName": "us. Anthropic Claude 3.5 Sonnet", "models": [ { "modelArn": "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-5-sonnet-20240620-v1:0" }, { "modelArn": "arn:aws:bedrock:us-west-2::foundation-model/anthropic.claude-3-5-sonnet-20240620-v1:0" } ], "description": "Routes requests to Anthropic Claude 3.5 Sonnet in us-east-1 and us-west-2", "createdAt": "2024-XX-XXT00:00:00Z", "updatedAt": "2024-XX-XXT00:00:00Z", "inferenceProfileArn": "arn:aws:bedrock:us-east-1:<account_id>:inference-profile/us.anthropic.claude-3-5-sonnet-20240620-v1:0", "inferenceProfileId": "us.anthropic.claude-3-5-sonnet-20240620-v1:0", "status": "ACTIVE", "type": "SYSTEM_DEFINED" }, ... ] } ``` 可以觀察到亞馬遜 Bedrock 中可用的基礎模型和推理配置文件的 ARN 之間的差異: 基礎模型:arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-5-sonnet-20240620-v1:0 推理配置文件:arn:aws:bedrock:us-east-1:<account_id>:inference-profile/us.anthropic.claude-3-5-sonnet-20240620-v1:0 ```python import boto3 primary_region ="<primary-region-name>" #us-east-1, eu-central-1 bedrock_runtime = boto3.client("bedrock-runtime", region_name= primary_region) inferenceProfileId = '<regional-prefix>.anthropic.claude-3-5-sonnet-20240620-v1:0' # Example with Converse API system_prompt = "You are an expert on AWS AI services." input_message = "Tell me about AI service for Foundation Models" response = bedrock_runtime.converse( modelId = inferenceProfileId, system = [{"text": system_prompt}], messages=[{ "role": "user", "content": [{"text": input_message}] }] ) print(response['output']['message']['content']) ``` --- ## 進階 Prompt Engineering :::info AWS blog: [Implementing advanced prompt engineering with Amazon Bedrock]( https://aws.amazon.com/blogs/machine-learning/implementing-advanced-prompt-engineering-with-amazon-bedrock/) 更新時間: 2024-08-30 AWS blog: [Secure RAG applications using prompt engineering on Amazon Bedrock](https://aws.amazon.com/blogs/machine-learning/secure-rag-applications-using-prompt-engineering-on-amazon-bedrock/) 更新時間: 2024-08-26 ::: --- ## Foundation Models 基礎模型 ### 模型評測標準 SWE-bench TAU-bench [OSWorld](https://os-world.github.io/) | | SWE-bench | TAU-bench | OSWorld | | -------- | -------- | -------- | -------- | | Human | Text | Text | 75% | | Sonnet 3.5 | Text | Text | 14.9% | ### Amazon #### Amazon Titan Text Premier :::info 2024-08-26 [Amazon Titan Text Premier](https://aws.amazon.com/blogs/machine-learning/get-the-most-from-amazon-titan-text-premier/) ::: | Model | Availability | Context window | Languages | Functionality | Customized fine-tuning | |-------|--------------|----------------|-----------|---------------|------------------------| | Amazon Titan Text Lite | GA | 4K | English | Code, rich text | Yes | | Amazon Titan Text Express | GA (English) | 8K | Multilingual (100+ languages) | Code, rich text, API orchestration | Yes | | Amazon Titan Text Premier | GA | 32K | English | Enterprise text generation applications, RAG, agents | Yes (preview) | ### Meta #### Meta Llama 3 模型特色: * 採用具有128,256個詞彙量的分詞器,提高了多語言任務的文本編碼效率。 * 80億(8B)參數模型整合了 GQA,以改進對更長文本序列的處理,提升實際應用性能。 * 超過15萬億(15T)個 token 的資料集。 * 超過10M個人工注釋樣本進行了微調。 ### Mistral AI :::info 2024-07-25 [Mistral Large 2](https://aws.amazon.com/blogs/machine-learning/mistral-large-2-is-now-available-in-amazon-bedrock/) ::: ### Anthropic Claude :::success 成功客戶案例 [Mend.io](https://aws.amazon.com/blogs/machine-learning/how-mend-io-unlocked-hidden-patterns-in-cve-data-with-anthropic-claude-on-amazon-bedrock/):Claude以99.9883%的驚人準確率完美應對68,378次挑戰 更新時間: 2024-07-18 ::: :::spoiler Mend.io成功故事 Claude展現出卓越的回答質量和可靠性。在Mend.io進行的大規模評估中,Claude處理了總計68,378個請求,回答成功率高達99.9883%,這意味著Claude能夠提供直接且準確的YES或NO答案。 值得注意的是,在整個評估過程中,Claude沒有出現任何由於自身限制導致的錯誤訊息(failures為0),突顯了其穩定性和效能。 針對高併發需求的場景,可以採取以下策略: * 通過並行化和調整並行度來有效管理API請求和token使用,以確保在配額限制(RPM/TPM)內運作。 * 利用Boto3函式庫的retry機制來處理可能出現的限流問題。 * 對於高throughput的場景,Amazon Bedrock提供了預置吞吐量(Provision Throughput)的選項。 ::: ### Computer Use [Anthropic's Demo code](https://github.com/anthropics/anthropic-quickstarts/blob/main/computer-use-demo/computer_use_demo/loop.py) ```python import base64 import json import boto3 MODEL_ID = "anthropic.claude-3-5-sonnet-20241022-v2:0" IMAGE_NAME = "ubuntu-screenshot.png" bedrock_runtime = boto3.client( "bedrock-runtime", region_name="us-east-1", ) with open(IMAGE_NAME, "rb") as f: image = f.read() image_base64 = base64.b64encode(image).decode("utf-8") prompt = "Find me a hotel in Rome." body = { "anthropic_version": "bedrock-2023-05-31", "max_tokens": 512, "temperature": 0.5, "messages": [ { "role": "user", "content": [ {"type": "text", "text": prompt}, { "type": "image", "source": { "type": "base64", "media_type": "image/jpeg", "data": image_base64, }, }, ], } ], "tools": [ { # new "type": "computer_20241022", # literal / constant "name": "computer", # literal / constant "display_height_px": 1280, # min=1, no max "display_width_px": 800, # min=1, no max "display_number": 0 # min=0, max=N, default=None }, { # new "type": "bash_20241022", # literal / constant "name": "bash", # literal / constant }, { # new "type": "text_editor_20241022", # literal / constant "name": "str_replace_editor", # literal / constant } ], "anthropic_beta": ["computer-use-2024-10-22"], } # Convert the native request to JSON. request = json.dumps(body) try: # Invoke the model with the request. response = bedrock_runtime.invoke_model(modelId=MODEL_ID, body=request) except Exception as e: print(f"ERROR: {e}") exit(1) # Decode the response body. model_response = json.loads(response["body"].read()) print(model_response) ``` ```python! # response { "id": "msg_bdrk_01WjPCKnd2LCvVeiV6wJ4mm3", "type": "message", "role": "assistant", "model": "claude-3-5-sonnet-20241022", "content": [ { "type": "text", "text": "I'll help you search for a hotel in Rome. I see Firefox browser on the desktop, so I'll use that to access a travel website.", }, { "type": "tool_use", "id": "toolu_bdrk_01CgfQ2bmQsPFMaqxXtYuyiJ", "name": "computer", "input": {"action": "mouse_move", "coordinate": [35, 65]}, }, ], "stop_reason": "tool_use", "stop_sequence": None, "usage": {"input_tokens": 3443, "output_tokens": 106}, } ``` ## 調用語言模型的 API ## Converse API ### AWS CLI 和 SDKs ```bash aws bedrock-runtime converse \ --model-id anthropic.claude-3-5-sonnet-20241022-v2:0 \ --messages '[{ "role": "user", "content": [ { "text": "What do you throw out when you want to use it, but take in when you do not want to use it?" } ] }]' \ --query 'output.message.content[*].text' \ --output text ``` ```python! # Python import boto3 MODEL_ID = "anthropic.claude-3-5-sonnet-20241022-v2:0" IMAGE_NAME = "wind-generation.png" bedrock_runtime = boto3.client("bedrock-runtime") with open(IMAGE_NAME, "rb") as f: image = f.read() user_message = "Which are the top countries for wind power generation? Answer only in JSON." messages = [ { "role": "user", "content": [ {"image": {"format": "png", "source": {"bytes": image}}}, {"text": user_message}, ], } ] response = bedrock_runtime.converse( modelId=MODEL_ID, messages=messages, ) response_text = response["output"]["message"]["content"][0]["text"] print(response_text) ``` ### JSON Format [JSON格式生成](https://community.aws/content/2hWA16FSt2bIzKs0Z1fgJBwu589/generating-json-with-the-amazon-bedrock-converse-api) :::spoiler JSON生成範例 ```python tool_list = [ { "toolSpec": { "name": "summarize_email", "description": "Summarize email content.", "inputSchema": { "json": { "type": "object", "properties": { "summary": { "type": "string", "description": "A brief one-line or two-line summary of the email." }, "escalate_complaint": { "type": "boolean", "description": "Indicates if this email is serious enough to be immediately escalated for further review." }, "level_of_concern": { "type": "integer", "description": "Rate the level of concern for the above content on a scale from 1-10", "minimum": 1, "maximum": 10 }, "overall_sentiment": { "type": "string", "description": "The sender's overall sentiment.", "enum": ["Positive", "Neutral", "Negative"] }, "supporting_business_unit": { "type": "string", "description": "The internal business unit that this email should be routed to.", "enum": ["Sales", "Operations", "Customer Service", "Fund Management"] }, "customer_names": { "type": "array", "description": "An array of customer names mentioned in the email.", "items": { "type": "string" } }, "sentiment_towards_employees": { "type": "array", "items": { "type": "object", "properties": { "employee_name": { "type": "string", "description": "The employee's name." }, "sentiment": { "type": "string", "description": "The sender's sentiment towards the employee.", "enum": ["Positive", "Neutral", "Negative"] } } } } }, "required": [ "summary", "escalate_complaint", "overall_sentiment", "supporting_business_unit", "level_of_concern", "customer_names", "sentiment_towards_employees" ] } } } } ] ``` ::: ## Rerank API :::info [Cohere Rerank 3.5 is now available in Amazon Bedrock through Rerank API](https://aws.amazon.com/blogs/machine-learning/cohere-rerank-3-5-is-now-available-in-amazon-bedrock-through-rerank-api/) 更新時間: 2024-12-01 ::: Cohere 的 Rerank 3.5 模型現已通過 Amazon Bedrock 的 Rerank API 提供,可用於 Amazon Bedrock Knowledge Base。 ```python def rerank_text(text_query, text_sources, num_results, model_package_arn): response = bedrock_agent_runtime.rerank( queries=[ { "type": "TEXT", "textQuery": { "text": text_query } } ], sources=text_sources, rerankingConfiguration={ "type": "BEDROCK_RERANKING_MODEL", "bedrockRerankingConfiguration": { "numberOfResults": num_results, "modelConfiguration": { "modelArn": model_package_arn, } } } ) return response['results'] example_query = "What emails have been about returning items?" documents = [ "Hola, llevo una hora intentando acceder a mi cuenta y sigue diciendo que mi contraseña es incorrecta. ¿Puede ayudarme, por favor?", "Hi, I recently purchased a product from your website but I never received a confirmation email. Can you please look into this for me?", "مرحبًا، لدي سؤال حول سياسة إرجاع هذا المنتج. لقد اشتريته قبل بضعة أسابيع وهو معيب", "Good morning, I have been trying to reach your customer support team for the past week but I keep getting a busy signal. Can you please help me?", "Hallo, ich habe eine Frage zu meiner letzten Bestellung. Ich habe den falschen Artikel erhalten und muss ihn zurückschicken.", "Hello, I have been trying to reach your customer support team for the past hour but I keep getting a busy signal. Can you please help me?", "Hi, I have a question about the return policy for this product. I purchased it a few weeks ago and it is defective.", "早上好,关于我最近的订单,我有一个问题。我收到了错误的商品", "Hello, I have a question about the return policy for this product. I purchased it a few weeks ago and it is defective." ] text_sources = [] for text in documents: text_sources.append({ "type": "INLINE", "inlineDocumentSource": { "type": "TEXT", "textDocument": { "text": text, } } }) response = rerank_text(example_query, text_sources, 3, model_package_arn) ``` ```python # 輸出格式 [{'index': 4, 'relevanceScore': 0.1122397780418396} {'index': 8, 'relevanceScore': 0.07777658104896545}, {'index': 2, 'relevanceScore': 0.0770234540104866}] ``` ## Performance Improvement Features :::info [Amazon Bedrock Intelligent Prompt Routing is now available in preview](https://aws.amazon.com/about-aws/whats-new/2024/12/amazon-bedrock-intelligent-prompt-routing-preview/) | [Blog](https://aws.amazon.com/blogs/aws/reduce-costs-and-latency-with-amazon-bedrock-intelligent-prompt-routing-and-prompt-caching-preview/) | [Doc](https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-routing.html) 🚨 English ONLY 更新時間: 2024-12-04 ::: Amazon Bedrock 正在推出智能提示路由功能,該功能提供單一無伺服器端點,能夠在同一模型家族內的不同基礎模型之間高效路由請求。以下是主要特點: 核心功能 * 動態預測每個請求對各模型的回應質量 * 將請求路由到提供最佳質量與成本平衡的模型 * 消除複雜的協調邏輯需求 實施選項 * 預設提示路由器:預先配置的即用型路由系統 * 自定義提示路由器:針對特定需求的自定義路由設置 技術組件 * 後備模型:作為可靠的比較基準 * 回應質量差異:測量模型回應之間的差異 * 路由標準:決定何時從後備模型切換到另一模型 運作方式 * 系統分析傳入請求的內容和背景 * 預測每個指定模型的回應質量 * 選擇提供最佳質量/成本平衡的模型 * 返回回應,並附帶使用模型的相關資訊 考量事項 * 目前**僅針對英文提示**進行優化 * 可能不適用於高度專業化的使用場景 * 預覽期間僅適用於特定的 **Anthropic 和 Meta 模型** ### Prompt Routing (Public Preview) ### Prompt Caching (Public Preview) ### Inference Optimization ## Knowledge Base :::info [Advanced RAG Bedrock Workshop](https://catalog.us-east-1.prod.workshops.aws/workshops/c6b88897-84a7-4885-b9f0-855e2fc61378/en-US/20-optimizing-accuracy/lab1-advanced-chunking-options) ::: :::success 成功客戶案例 [Deltek](https://aws.amazon.com/blogs/machine-learning/how-deltek-uses-amazon-bedrock-for-question-and-answering-on-government-solicitation-documents/):利用RAG技術針對不同時間釋出的多個政府招標文件進行問答 更新時間: 2024-08-09 ::: :::spoiler Deltek成功故事 除了針對匯入PDF資料的IDP流程做了改善,另外主要是針對「多個相關但釋出時間不同的政府招標」文件做了meta data前處理,並引導模型依據文件更新的時間進行排序後再回答問題: * 匯入 Metadata 改善查詢的顆粒度: ```python! index_body = { "embedding_vector": <embedding vector of a text chunk>, "text_chunk": <text chunk>, "document_name": <document name>, "section_name": <document section name>, "release_date": <document release date>, # more metadata can be added } def opensearch_result_to_context(os_res: dict) -> str: """ Convert OpenSearch result to context Args: os_res (dict): Amazon OpenSearch results Returns: context (str): Context to be included in LLM's prompt """ data = os_res["hits"]["hits"] context = [] for item in data: # extract meta data text = item["_source"]["text_chunk"] doc_name = item["_source"]["document_name"] section_name = item["_source"]["section_name"] release_date = item["_source"]["release_date"] context.append( f"<<Context>>: [Document name: {doc_name}, Section name: {section_name}, Release date: {release_date}] {text}" ) context = "\n \n ------ \n \n".join(context) return context ``` * 在初始提示詞中加入思維鏈(CoT)的提示詞內容: ```python! """ Context below includes a few paragraphs from draft RFP and RFI response documents: Context: {context} Question: {question} Think step by step: 1- Find all the paragraphs in the context that are relevant to the question. 2- Sort the paragraphs by release date. <== IMPORTANT!!!!! 3- Use the paragraphs to answer the question. Note: Pay attention to the updated information based on the release dates. """ ``` ::: :::success 成功客戶案例 [Cepsa Química](https://aws.amazon.com/blogs/machine-learning/cepsa-quimica-improves-the-efficiency-and-accuracy-of-product-stewardship-using-amazon-bedrock/):能源巨頭化工部門Cepsa Química利用RAG技術提升合規查詢效率,節省25%的查詢時間 更新時間: 2024-08-02 ::: :::spoiler Cepsa Química成功故事 針對「監管資訊的快速更新」,當頻繁有廢除、修訂和新法規發布,利用檢索增強生成(RAG)方法為LLMs提供動態外部資料,包含非結構化(監管文件和產品規格說明書)和結構化(產品目錄)資料,讓模型以in-context學習的方式回應,而無需重新訓練模型。 客戶對象為產品監管部門,負責管理大量的法規合規文件。他們的職責包括確定哪些法規適用於公司產品組合中的每種特定產品,彙編適用於特定產品的所有相關法規清單,並支持其他內部團隊解答與這些產品和法規相關的問題。內部用戶問題像是「對CMR物質有哪些限制?」、「我需要保存甲苯銷售相關文件多長時間?」或「什麼是REACH表徵比率,如何計算?」,回答這些問題所需的監管內容會隨時間變化,引入新條款並廢除舊條款。 最終解決方案由三個提示詞鏈所組成:(1) 將用戶查詢翻譯成英語 (2) 生成輸入問題的問題形變 (3) 組合生成最終回應。 面對RAG的挑戰,客戶採用以下方法優化解決方案,包括資料「預處理、資料檢索、和答案生成」: * 分塊策略:採用較大的分塊,較大的重疊區域,並額外確保上下文的語意相似度高 * 將問題換句話說(Query variants):將使用者的問題進行語言翻譯及問題重述 * 建立驗證資料集(Benchmarking dataset): * 需要結合不同資料來源的代表性問題 * 設計每個問題的標準答案 * 對資料原文、頁面和行號的引用,指出正確答案的位置 * 制定定性和定量的評測方法:查詢時間、答案準確度、運營效率 ::: ## Knowledge Base: RAG 部署與策略 [CDK 部署](https://aws.amazon.com/blogs/machine-learning/build-an-end-to-end-rag-solution-using-knowledge-bases-for-amazon-bedrock-and-the-aws-cdk/) ## Knowledge Base Advanced Features [KB支援的文檔類型](https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base-ds.html) ### Metadata Filtering :::info (內容主要源自 AWS 部落格) [官方文件](https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base-ds.html#kb-ds-metadata) ::: >[!Caution] >如果檔案未新增 .metadata,則使用下方的程式碼,該檔案一律視為「不符合」過濾條件而被忽略 >如果使用 Amazon OpenSearch Serverless 向量資料庫,目前過濾功能僅支援 faiss 引擎。 >如果使用 Amazon Aurora 向量資料庫,必須在資料匯入前,在資料庫中添加欄位和數值 針對 CSV 檔案,會對每一筆資料 (per row) 的該欄位進行過濾,不需要針對每一筆資料進行檔案拆分。以下方的程式碼為例,KB僅針對 metadata 中 `collectionType = TRAINING` 的結果返回。 ```python! ... retrievalConfiguration={ 'vectorSearchConfiguration': { 'numberOfResults': max_results, 'filter': { 'equals': { 'key': 'collectionType', 'value': 'TRAINING' # 允許 } }, } } ``` :::spoiler 更多 Operator 選擇 | Operator | 控制台 | API filter 名稱 | 支持的屬性數據類型 | 過濾結果 | |----------|---------|-----------------|--------------------------------|------------------| | Equals | = | equals | string, number, boolean | 取屬性「匹配」您提供的數值 | | Not equals | != | notEquals | string, number, boolean | 取屬性「不匹配」您提供的數值 | | Greater than | > | greaterThan | number | 取屬性大於您提供的值 | | Greater than or equals | >= | greaterThanOrEquals | number | 取屬性大於或等於您提供的值 | | Less than | < | lessThan | number | 取屬性小於您提供的值 | | Less than or equals | <= | lessThanOrEquals | number | 取屬性小於或等於您提供的值 | | In | : | in | **string list** | 取屬性「包含」在您提供的列表中 | | Not in | !: | notIn | **string list** | 取屬性「不包含」在您提供的列表中 | | Starts with | ^ | startsWith | string | 屬性以您提供的字符串開頭(僅支持Amazon OpenSearch Serverless向量存儲)| 若採用多個判斷條件: | 操作符 | 控制台 | API 過濾器字段名稱 | 過濾結果 | |-------|-------|-------------------|---------| | And | and | andAll | 結果滿足組中的所有過濾表達式 | | Or | or | orAll | 結果至少滿足組中的一個過濾表達式 | ::: ### Advanced Parsings :::info [AWS 官方網頁](https://docs.aws.amazon.com/bedrock/latest/userguide/kb-advanced-parsing.html) ::: Amazon Bedrock Knowledge Bases 在資料擷取過程中提供了多種解析選項,以處理不同類型的資料內容,以下為解析選項: **Amazon Bedrock 預設解析器:** 僅解析文字檔案中的文字(如 .txt、.md、.html、.doc/.docx、.xls/.xlsx 和 .pdf) 不產生任何使用費用 限制:無法處理圖表、表格或圖像 **多模態資料解析選項:** **Amazon Bedrock Data Automation (BDA):** 全受管服務,無需額外提示即可有效處理多模態資料 費用根據文件頁數或要處理的圖像數量計算 **基礎模型解析:** 使用基礎模型處理多模態資料 允許自定義用於資料擷取的默認提示 費用根據基礎模型處理的輸入和輸出標記數量計算 >[!Caution] >選擇 Amazon Bedrock 資料自動化或基礎模型作為解析器時,所有 .pdf 文件都將使用該方法進行解析,即使僅包含文字,因此選擇解析方法時應考慮: >- 資料是純文字還是包含多模態內容 >- 是否需要自定義解析提示 >- 解析成本(BDA 按頁收費,基礎模型按 token 收費) #### 功能說明 將 PDF 頁面轉為影像格式作為模型輸入,使用 Anthropic Claude 系列模型進行內容分析、擷取、甚至是格式重整。 使用基礎模型(FMs)來解析文件內部的資訊。當您的文件中有複雜的資訊,如合併表格、圖片中的文字等,而這些資訊又至關重要,可以嘗試這種方式爬取資訊。 * 更高的準確性:FMs 可以更好地理解文本的上下文和含義,從而實現更準確的資訊提取和生成。 * 適應性:利用提示詞根據特定領域的資訊進行優化,使其能夠適應不同的行業或使用案例。 * 實體提取:可以根據您的領域和使用案例自定義提取實體名稱。 * 複雜的文檔元素:可以理解並提取以圖形或表格形式表示的資訊。 使用 FMs 解析文檔在文檔複雜、非結構化或包含特定領域術語的情況下特別有用。它可以處理歧義,解釋隱含意義,並使用其理解語義關係的能力來提取相關細節,這對於在 RAG 應用程式中生成準確且相關的回答至關重要。 :::spoiler 預設的 Parser 提示詞 ``` Transcribe the text content from an image page and output in Markdown syntax (not code blocks). Follow these steps: 1. Examine the provided page carefully. 2. Identify all elements present in the page, including headers, body text, footnotes, tables, visulizations, captions, and page numbers, etc. 3. Use markdown syntax to format your output: - Headings: # for main, ## for sections, ### for subsections, etc. - Lists: * or - for bulleted, 1. 2. 3. for numbered - Do not repeat yourself 4. If the element is a visulization - Provide a detailed description in natural language - Do not transcribe text in the visualization after providing the description 5. If the element is a table - Create a markdown table, ensuring every row has the same number of columns - Maintain cell alignment as closely as possible - Do not split a table into multiple tables - If a merged cell spans multiple rows or columns, place the text in the top-left cell and output ' ' for other - Use | for column separators, |-|-| for header row separators - If a cell has multiple items, list them in separate rows - If the table contains sub-headers, separate the sub-headers from the headers in another row 6. If the element is a paragraph - Transcribe each text element precisely as it appears 7. If the element is a header, footer, footnote, page number - Transcribe each text element precisely as it appears Output Example: A bar chart showing annual sales figures, with the y-axis labeled "Sales ($Million)" and the x-axis labeled "Year". The chart has bars for 2018 ($12M), 2019 ($18M), 2020 ($8M), and 2021 ($22M). Figure 3: This chart shows annual sales in millions. The year 2020 was significantly down due to the COVID-19 pandemic. # Annual Report ## Financial Highlights * Revenue: $40M * Profit: $12M * EPS: $1.25 | | Year Ended December 31, | | | | 2021 | 2022 | |-|-|-| | Cash provided by (used in): | | | | Operating activities | $ 46,327 | $ 46,752 | | Investing activities | (58,154) | (37,601) | | Financing activities | 6,291 | 9,718 | Here is the image. ``` ::: ### Advanced Chunking 進階分塊策略 #### 功能說明 進階分塊/分片是分析和從非結構化或半結構化文件中提取有意義的資訊的過程。它涉及將文件分解更小的區塊,如文本、表格、及圖片,並識別這些元素之間的關係。 設計進階分塊/分片策略時,試著先想一下:「什麼是將資訊轉換成FM可以用來完成指定任務的最佳實踐?」而不是「我應該如何分塊我的文檔?」 #### Amazon Bedrock 的知識庫中的文件分塊選項 * **固定分塊** * **無分塊** * **語義分塊**:根據句子的語義含義對其進行分段,有助於確保相關資訊保留在邏輯分塊中。通過保留上下文關係,RAG可以檢索更相關且連貫的結果。 * **階層分塊**:將您的資料分層,基於資料的階層關係進行檢索。 :::spoiler 語義分塊 Semantic chunking 語義分塊通過分析文本之間的關係,將其分割成有意義且完整的片段,相關性取決於嵌入模型計算的語義相似程度。這種方法在檢索過程中保持了文章段落的完整性。 需要配置的參數詳情: * **區塊重疊句數**: * 建議的參數值為1。 * 評估語義相似性時,需同時包含的前後句子數量。如果選擇緩衝大小為1,它將包括前一個句子、目標句子和下一個句子。 * **最大區塊token數**: * 建議的參數值為300。 * 區塊可以包含的最大token數。它可以從最小的20到最大的8,192,這取決於嵌入模型的上下文長度。例如,如果您使用Cohere Embeddings模型,塊的最大大小可以是512。 * **語意相似性閾值**: * 建議的參數值為95,數值介於50到99之間。 * 區塊之間在語義上的相似度。 Amazon Bedrock的知識庫首先根據指定的區塊大小將文檔分塊,並根據「相似度閾值」和「區塊重疊設定」將相似的區塊組合成新的區塊。因此,區塊的大小不一。 儘管這種方法比固定大小分塊需要更大的計算量,但在上下文邊界不明確的文檔中可能會很管用,比如法律文件或技術手冊。 例如,關於詳列各種條款的法律文件,條文之間的上下文邊界可能不太明顯,這種情況下,動態分塊方法可能比具有優勢,因為它可以根據相鄰句子之間的語義相似性自動識別和組合相關內容到連貫的文字區塊中。 ::: :::spoiler 階層分塊 Hierarchical chunking 將資訊組織成階層結構,根據資訊的關係實現更細緻和高效的檢索。將文件組織成層次結構,使您的 RAG 工作流能夠高效地檢索複雜、巢狀的資訊。 所需配置的參數: * **最大 Parent token 數**: * 建議將此參數值設為 1,500。 * 該值範圍可以從 1 到 8,192,**獨立**於嵌入模型的上下文長度,因為母分片不會被嵌入。 * **最大 Child token 數**: * 建議將此參數值設為 300。 * 該值範圍可以從 1 到 8,192,**基於**嵌入模型的上下文長度。 * **重疊的 token 數**: * 建議將此參數值設為最大 Child token 數的 20%。 * 重疊 token 數的百分比。母分片重疊取決於您指定的子分片大小和子分片的百分比重疊。 文檔解析後,第一步是根據最大 Parent/Child token 數進行分塊。然後將這些區塊組織成層次結構,其中 Parent 代表較大的區塊(例如,文檔或章節),Child 代表較小的區塊(例如,段落或句子)。透過階層分塊,保持 Parent/Child 區塊之間的關係。 階層分塊的優點: * **高效檢索**:層次結構允許更快速、更有針對性地檢索相關的資訊;首先對 Child 區塊執行語義搜索,然後在檢索過程中返回 Parent 區塊。將 Parent 區塊替換為 Child 區塊,將可以提供大而全面的上下文。 * **上下文保留**:以層次方式組織語料庫有助於保留區塊之間的上下文關係,這對生成連貫和上下文相關的文本有幫助。 注意:在階層分塊中,我們返回 Parent 區塊,而語義搜索在 Child 區塊,因此您可能會看到返回的搜索結果較少,因為 Parent 區塊可以有多個 Child 區塊。 階層分塊最適合巢狀或層次結構的複雜文檔,如技術手冊、法律文件或具有複雜格式和巢狀表格的學術論文。 ::: :::spoiler 使用 Lambda 函數進行自定義 [官方文件](https://docs.aws.amazon.com/bedrock/latest/userguide/kb-chunking-parsing.html#kb-advanced-parsing) 為了提供更多彈性,Amazon Bedrock 的知識庫現在提供了使用 AWS Lambda 函數定義自定義處理邏輯的能力。使用 Lambda 函數,您可以自定義分塊過程以符合您的 RAG 應用程式的需求。此外,Lambda 也可以用於簡化 metadata 的處理。 您可以編寫一個具有自定義分塊邏輯的 Lambda 函數,或使用您喜歡的開源框架(如 LangChain 和 LLamaIndex)提供的分塊方法。 ::: ### CSV 文件的 Metadata 自定義 [官方文件](https://docs.aws.amazon.com/bedrock/latest/userguide/kb-metadata.html) Amazon Bedrock 的知識庫現在提供了進階的 CSV 文件處理功能,可以分離內容和 metadata。此更新減少了需要進行向量化的文件內容,實現了更有效的數據管理,特別是對於大型 CSV 文件。 這種自定義能力為資料清理、標準化和豐富 metadata 開啟了新的可能性。要使用 metadata 自定義功能,您需要提供 metadata 文件以及 .csv 文件,其名稱與原本的文件來源相同,並帶有 <filename>.csv.metadata.json 的後綴。 :::spoiler metadata 文件內容範例 >[!Caution] 僅能針對 csv 檔案中的一個欄位進行詞句向量化 ``` { "metadataAttributes": { "docSpecificMetadata1": "docSpecificMetadataVal1", "docSpecificMetadata2": "docSpecificMetadataVal2" }, "documentStructureConfiguration": { "type": "RECORD_BASED_STRUCTURE_METADATA", "recordBasedStructureMetadata": { "contentFields": [ { "fieldName": "String" # ONLY ONE COLUMN ALLOWED } ], "metadataFieldsSpecification": { "fieldsToInclude": [ { "fieldName": "String" } ], "fieldsToExclude": [ { "fieldName": "String" } ] } } } } ``` ::: 根據以下步驟來試驗進階的 .csv 文件處理功能: 1. 在相同的 Amazon S3 前綴中上傳 .csv 文件和相應的<filename>.csv.metadata.json 文件。 2. 使用控制台或 Amazon Bedrock SDK 創建知識庫。 3. 使用控制台或 SDK 與您的知識庫對話。 4. 可以使用控制台或 SDK 的檢索 API 和檢索並生成 API 來查詢結構化的 .csv 文件數據。 >[!Note] >:::spoiler 請注意以下事項 >1. CSV中的**每一行**都被視為一個分塊。 >2. CSV文件中發現的空白行會被忽略或跳過。 >3. 對於`documentStructureConfiguration`,每個列的值都被視為字符串值。例如,日期值格式將被視為日期的字符串表示。 >4. Amazon Bedrock知識庫目前支持**一個`content field`**。 >5. 如果沒有提供`fieldsToInclude/fieldsToExclude`,除了`content field`外,所有列都被視為 metadata。 >::: ### 查詢重構 通常在使用 RAG 服務時,由於使用者輸入的問題可能意圖很複雜,背後可能包含許多子問題。針對複雜的問題,問題本身的語句會有語義稀釋的問題(問題的語句過於簡潔,以至於無法透過語意搜尋找到相關的文字區塊),導致檢索到的區塊可能無法提供正確的答案,從而降低 RAG 的準確性。 現在,通過 Amazon Bedrock 的知識庫支持的「查詢重構」功能,我們可以將複雜的使用者輸入拆解為多個子查詢。這些子查詢將分別經過自己的檢索步驟來找到相關的區塊。然後,這些區塊將被匯集在一起進行排序,然後傳遞給 FM 以生成響應。 在創建知識庫後,可以通過進入"測試知識庫配置"並打開"查詢修改"下的"分解查詢"來在控制台中啟用查詢重構。 可以利用 AWS 控制台或是使用 API 時,使用 KnowledgeBaseConfiguration 來啟用查詢重構,如下圖所示: ``` "orchestrationConfiguration": { "queryTransformationConfiguration": { "type": "QUERY_DECOMPOSITION" } ``` :::spoiler 範例 考慮以下針對虛構公司 Octank 的金融文件的複雜查詢,詢問多個不相關的主題: Q:"Octank 公司的建築位於哪裡,舉報人醜聞如何損害公司及其形象?" 我們可以將查詢分解為多個子查詢: Q:Octank 建築位於哪裡? Q:涉及 Octank 的舉報人醜聞是什麼? Q:舉報人醜聞如何影響了 Octank 的聲譽和公眾形象? 現在,我們有了更有針對性的問題,可能有助於從知識庫中檢索到來自文檔更具語義相關性的部分的分塊,而不會出現將多個問題以一個複雜問題來查詢時可能發生的語義不明的情況。 ::: ## Knowledge Base Data Connectors ### Data Source: GraphRAG ### Data Source: Structured Data Retrieval ### Data Source: Custom [AWS Blog: New APIs in Amazon Bedrock to enhance RAG applications, now available](https://aws.amazon.com/blogs/aws/new-apis-in-amazon-bedrock-to-enhance-rag-applications-now-available/) **自定義連接器** - 可通過單一 API 調用直接進行數據的添加、更新或刪除 - 提供四個主要 API: - Add Document API:添加新文件 - Delete Document API:刪除數據 - List Document API:列出符合條件的記錄 - Get Document API:獲取符合條件的文檔信息 ### Data Source: Web Crawler [AWS Blog: Implement web crawling in Knowledge Bases for Amazon Bedrock](https://aws.amazon.com/blogs/machine-learning/implement-web-crawling-in-knowledge-bases-for-amazon-bedrock/) >[!Note] 關於網絡連接器: > * URL 不能需要任何身份驗證,其主機不能是 IP 地址,其協議必須以 http:// 或 https:// 開頭 > * 除非明確排除,否則網絡連接器將獲取爬取頁面中引用的非 HTML 支持文件(如 PDF、文本文件、markdown 文件和 CSV) > * 如果提供了多個seed URL,網絡連接器將爬取符合任何seed URL 的 TPD 和路徑的 URL。 > * 您最多可以有 10 個來源 URL,知識庫將其用作爬取的起點。 #### 設定同步範圍 在設定網絡爬取功能時,您可以選擇不同的「同步類型」。下表顯示給定來源的 URL 的不同同步範圍,爬蟲將爬取的範例路徑(使用 https://example.com 作為說明目的)。 | 同步範圍類型 | 源 URL | 示例爬取的域路徑 | 描述 | |------------|--------|-----------------|------| | 預設 | https://example.com/products/ | https://example.com/products<br>https://example.com/products/product1<br>https://example.com/products/product<br>https://example.com/products/discounts | 與來源 URL 相同的主機和相同的起始路徑 | | 僅Host | https://example.com/sellers/ | https://example.com/<br>https://example.com/products<br>https://example.com/sellers/<br>https://example.com/delivery/ | 與來源 URL 相同的Host | | 子域(Subdomain) | https://example.com/ | https://blog.example.com/<br>https://blog.example.com/posts/post1<br>https://discovery.example.com<br>https://transport.example.com/ | 來源 URL 主域的子域 | 您可以設置爬取速度的最大限制來控制最大爬取率。較高的值將減少同步時間。但是,爬取作業將始終遵守主域的 robots.txt 文件,尊重標準的 robots.txt 指令,如 'Allow'、'Disallow' 和爬取率。 您可以使用包含和排除過濾器進一步細化要爬取的 URL 範圍。這些過濾器是應用於每個 URL 的正則表達式(regex)模式。如果 URL 匹配任何排除過濾器,它將被忽略。相反,如果設置了包含過濾器,爬蟲將只處理匹配至少一個這些過濾器且仍在範圍內的 URL。例如,要排除以 .pdf 結尾的 URL,您可以使用正則表達式 `^.*\.pdf$`。要只包含包含 "products" 一詞的 URL,您可以使用正則表達式 `.*products.*`。 #### 監控 您可以在 Amazon CloudWatch 日誌中追蹤正在進行的網絡爬取的狀態,包含正在訪問的 URL 以及它們是否成功獲取、跳過或失敗。 ![Screenshot 2024-08-17 at 8.53.18 PM](https://hackmd.io/_uploads/SkeEiaGR5C.png) ### Data Source: MuleSoft :::info [MuleSoft](https://aws.amazon.com/blogs/apn/announcing-the-mulesoft-bedrock-connector-for-amazon-generative-ai/) 更新時間:20240-09-03 ::: MuleSoft是一家致力於用API驅動的整合方案來幫助企業實現數位化轉型的創新型軟體公司。 :::spoiler 公司及產品概況 公司概況 * 成立於2006年,總部位於美國加州舊金山 * 2017年在紐交所上市,2018年被Salesforce以65億美元收購 * 目前已有約1000家企業級客戶,包括許多財富500強企業 **主要產品: Anypoint Platform** 這是一個混合整合平台,提供端到端的整合解決方案,主要包括: * API管理:設計、開發、發布、管理和監控API的全生命週期 * 應用、資料和設備整合:通過API連接各個應用、資料源和設備,打通內部部署、行動和雲端 * 應用網路構建:利用API和整合快速構建由應用、資料和設備組成的應用網路 核心理念 * 通過創建API驅動的應用網路來連接企業內外部的各個系統 * 幫助企業打破不同系統和應用間的壁壘,實現無縫整合和資料互通 * 加速企業數位化轉型,實現更高效靈活的業務運營 客戶價值 * 大幅提高開發和交付速度,加快上市時間 * 顯著降低維護工作量和成本 * 實現企業內外部系統的互聯互通,構建客戶360度視圖 * 幫助企業釋放所有資料、應用和設備的潛力,加速創新 ::: ## Prompt Management, Prompt Optimization, and Flows :::info AWS blog: [Improve the performance of your Generative AI applications with Prompt Optimization on Amazon Bedrock](https://aws.amazon.com/blogs/machine-learning/improve-the-performance-of-your-generative-ai-applications-with-prompt-optimization-on-amazon-bedrock/) 更新時間: 2024-11-29 AWS blog: [Streamline generative AI development in Amazon Bedrock with Prompt Management and Prompt Flows (preview)](https://aws.amazon.com/blogs/machine-learning/streamline-generative-ai-development-in-amazon-bedrock-with-prompt-management-and-prompt-flows-preview/) | [AWS Samples](https://github.com/aws-samples/amazon-bedrock-samples/blob/main/introduction-to-bedrock/Getting_started_with_Prompt_Management_Flows.ipynb) 更新時間: 2024-07-10 ::: **提示詞的生命週期** 為生成式AI應用開發有效的提示詞(prompt)是一個迭代的過程,需要仔細的設計、測試和優化。關於提示詞生命週期的重要階段: * 提示詞設計 – 設計能有效地向基礎模型傳達指定的任務的提示詞。提示詞通常包含變量、上下文或其他在推理時提供的外部內容的提示詞模板。 * 測試和評估 – 設計完成後,會針對提示詞或提示模板進行測試,評估輸出的正確性和穩定度。 * 優化 – 基於測試結果,對提示詞進行迭代優化以提高其有效性。這通常涉及調整措辭、添加或刪除上下文,或修改提示詞的結構。 * 版本控制和編目 – 隨著提示詞的開發和優化,維護迭代的版本並整理成目錄。這使團隊能夠追蹤修訂、比較不同版本的有效性,使用經過驗證的提示詞以便重複使用。 * 部署 – 提示詞優化後,可以根據生成式AI應用進行部署。這涉及將提示詞嵌入系統或工作流程中。 * 監控和迭代 – 部署後,團隊持續監控提示詞在實際應用中的有效性,持續進行迭代。 在整個提示詞的生命週期中,提示詞設計和其目錄扮演著關鍵角色。 在更複雜的生成式AI應用中,開發人員經常採用 prompt chaining 或 prompt routing。這些方法需要定義更複雜的邏輯和動態工作流程,通常被稱為 prompt flows。 >[!Note] >* Prompt chaining 使用一個提示詞的輸出作為另一個提示詞的輸入,創建一系列與基礎模型(FMs)的互動,以完成更複雜的任務。例如,客戶服務聊天機器人可以首先使用基礎模型提取與客戶及其問題相關的資訊,然後將資訊作為輸入傳遞給另一個能夠遞交工單的程式。 >* Prompt routing 指的是根據特定條件或輸入的特性,動態地選擇不同的提示詞,從而實現更靈活和上下文感知的AI應用。例如,當用戶和AI銀行助手交談時,若詢問信用卡詳情時,可以使用檢索增強生成(RAG)來找到答案,若詢問帳戶餘額時,則調用函數運行查詢。 ### Prompt Optimization Prompt Optimization 功能讓使用者可以通過單一 API 呼叫或在控制台點擊按鈕來優化提示詞。 主要優點: 節省手動調整提示詞的時間和精力 自動實現各個模型的最佳實踐 可以快速測試不同模型的效果 支援版本控制,可以儲存多個版本的提示詞配置 這項功能的推出主要解決了以下問題: 減少了手動調整提示詞所需的時間(原本可能需要數月的實驗) 避免了不同模型間提示詞效能不一致的問題 簡化了提示詞優化的流程 性能改進顯著: 摘要任務:提升 18% 對話延續:提升 8% 函數調用:提升 22% ### Prompt Management 提示詞管理功能簡化了提示詞的創建、評估、部署和共享過程。此功能幫助開發人員和業務從基礎模型(FMs)獲得最適合其特定任務的回覆。 提示詞管理的主要優勢包括: * 快速提示詞創建和迭代 - 使用Amazon Bedrock控制台內建的提示詞構建器或CreatePrompt API創建您的提示詞。利用動態輸入的placeholder來整合動態資訊以構建您的提示詞模板。 * 無縫測試和部署 - 快速測試單個提示詞,設置變量及其測試值。使用Amazon Bedrock控制台或GetPrompt、ListPrompts和CreatePromptVersion API創建存儲在提示詞庫中的提示詞版本,用於編目和管理。 * 協作提示詞開發 - 在流程或Amazon Bedrock Studio中使用您的提示詞和提示詞模板。提示詞管理使團隊成員能夠在提示詞創建、評估和部署上進行協作,提高開發過程的效率。 :::spoiler 程式碼 ```python! response = bedrock_agent.create_prompt( name = f"MyTestPrompt-{datetime.now().strftime('%Y%m%d-%H%M%S')}", description = "This is my test prompt for the customer service use case", variants = [ { "inferenceConfiguration": { # 參數設定 "text": { "maxTokens": 3000, "temperature": 0, "topP": 0.999, "topK": 250, } }, "modelId": "anthropic.claude-3-haiku-20240307-v1:0", "name": "variant-001", "templateConfiguration": { "text": { #動態輸入 "inputVariables": [ { "name": "input" } ], "text": "You're a customer service agent for the ecommerce company Octank. Answer the following user query in a friendly and direct way: {{input}}" } }, "templateType": "TEXT" } ], defaultVariant = "variant-001" ) response = bedrock_agent.create_prompt_version( promptIdentifier = promptId ) ``` ::: ### Flows **提示詞流程:可視化並加速您的AI工作流程** Amazon Bedrock Flows功能引入了一個視覺化構建器,簡化了複雜生成式AI工作流程的創建。此功能允許您連接多個基礎模型(FMs)、提示詞和其他AWS服務,減少開發時間和工作量。 主要優勢包括: * 直觀的視覺化構建器 - 通過拖放組件來創建流程,將提示詞與其他提示詞、AI服務、知識庫和業務邏輯連接起來。這種視覺化方法有助於消除大量編碼的需求,並提供應用程序結構的全面概覽。此外,您可以使用CreateFlow API以程序化方式創建流程,幫助您自動化流程和開發管道。 * 快速測試和部署 - 直接在Amazon Bedrock控制台上測試您的流程以加快迭代,或使用InvokeFlow API。您可以隨時對流程進行snapshot,以便整合到您的生成式AI應用程式中。您可以在Amazon Bedrock控制台上或使用CreateFlowVersion API創建流程版本。在Amazon Bedrock控制台上或使用CreateFlowAlias API創建別名(alias),可以在不影響您的服務或開發管道的情況下,輕鬆實現rollbacks和不同版本流程之間的A/B測試。 * 管理和模板化 - 使用流程模板加速開發常見的使用場景。您可以在Amazon Bedrock控制台上或使用GetFlow和ListFlows API管理您的流程。 :::spoiler 程式碼 [](https://) ```python! response = bedrock_agent.create_flow( name = f"MyTestFlow-{datetime.now().strftime('%Y%m%d-%H%M%S')}", description = "This is my test flow for the customer service use case", executionRoleArn = flow_role, definition = { "nodes": [ { "name": "StartNode", "type": "Input", "configuration": { "input": {} }, "outputs": [ { "name": "document", "type": "String" } ], }, { "name": "Prompt_1", "type": "Prompt", "configuration": { "prompt": { "sourceConfiguration": { "resource": { "promptArn": promptArn } } } }, "inputs": [ { "expression": "$.data", "name": "input", "type": "String" } ], "outputs": [ { "name": "modelCompletion", "type": "String" } ], }, { "name": "EndNode", "type": "Output", "configuration": { "output": {} }, "inputs": [ { "expression": "$.data", "name": "document", "type": "String" } ], } ], "connections": [ { "name": "Connection_1", "source": "StartNode", "target": "Prompt_1", "type": "Data", "configuration":{ "data": { "sourceOutput": "document", "targetInput": "input" } } }, { "name": "Connection_2", "source": "Prompt_1", "target": "EndNode", "type": "Data", "configuration": { "data": { "sourceOutput": "modelCompletion", "targetInput": "document" } } } ], } ) response = bedrock_agent.prepare_flow( flowIdentifier = flowId ) response = bedrock_agent.create_flow_version( flowIdentifier = flowId ) ``` ```python! response = bedrock_agent_runtime.invoke_flow( flowIdentifier = flowId, flowAliasIdentifier = flowAliasId, inputs = [ { "content": { "document": "Hi, I need help with my order!" }, "nodeName": "StartNode", "nodeOutputName": "document" } ] ) ``` ::: ## Agent 人工智能代理人 :::success HackMD: [Agent Flow 人工智慧工作流程代理](https://hackmd.io/@yuhsintsao/ByRKAvSl0) 所有 Agent 功能和架構請見上方的 HackDM ::: ## Fine-tune 流程總覽 ![Screenshot 2024-09-07 at 4.55.00 PM](https://hackmd.io/_uploads/SyBQH5KnA.png) :::spoiler 資料準備 ![Screenshot 2024-09-07 at 4.55.19 PM](https://hackmd.io/_uploads/B1-VH5Kh0.png) ::: :::spoiler 模型調優 ![Screenshot 2024-09-07 at 4.55.11 PM](https://hackmd.io/_uploads/SkCmHcY2A.png) ::: ## Amazon Bedrock Fine-tune 可以使用 AWS Console 或是 SDK 來進行模型調優。 ### Import Model (Preview) :::info [AWS Blog](https://aws.amazon.com/blogs/aws/import-custom-models-in-amazon-bedrock-preview/) 文章更新時間: 2024-04-23 [官方文件](https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-import-model.html) ::: >[!Note] > 支援的模型:Meta Llama 2, Llama 3, Flan 和 Mistral > 支援的精度:FP32, FP16, 和 BF16 > 部署及調用:On-Demand >[!Caution] > * 您的模型文件的副本儲存在 AWS 操作的部署賬戶中。在刪除自定義模型之前,此副本將一直保留。刪除您賬戶中的文件不會刪除 AWS 操作賬戶中的模型或文件。 > * 如果您是第一次嘗試 import model 的功能,建議先從嘗試執行 [sample](https://github.com/aws-samples/amazon-bedrock-samples/tree/main/custom_models/import_models) 內的範例開始。 > * 請注意:您可能需要設定IAM權限 `bedrock:InvokeModel on resource: <imported model arn>` 使用步驟 [官方連結](https://docs.aws.amazon.com/bedrock/latest/userguide/model-customization-import-model.html): 1. 提交 [quota increase](https://us-west-2.console.aws.amazon.com/servicequotas/home/) 2. 接受的資料格式:Hugging Face format 3. 下載模型並上傳檔案到 s3 bucket :::spoiler 下載模型檔案的範例程式碼 >[!Caution] 請先取得 Hugging Face 模型存取權限 ```python! from huggingface_hub import login from huggingface_hub import snapshot_download access_token_read = None # Specify the repository ID repo_id = "meta-llama/Meta-Llama-3.1-70B" # Download the entire repository snapshot local_dir = snapshot_download(repo_id=repo_id, use_auth_token=access_token_read, local_dir=".") print(f"Repository downloaded to: {local_dir}") ``` ::: --- ### Fine-tune Amazon Titan, Meta Llama, 和 Cohere models :::info [AWS Blog Few-shot prompt engineering and fine-tuning for LLMs in Amazon Bedrock](https://aws.amazon.com/blogs/machine-learning/few-shot-prompt-engineering-and-fine-tuning-for-llms-in-amazon-bedrock/) 文章更新時間: 2024-08-02 [AWS Blog Cohere Command R](https://aws.amazon.com/blogs/machine-learning/amazon-sagemaker-unveils-the-cohere-command-r-fine-tuning-model/) 文章更新時間: 2024-07-17 ::: **訓練/驗證/測試資料集** 資料輸入:JSONL **建議資料量** 第一階段準備「高品質」的訓練資料約莫100筆。 :::spoiler 訓練資料範例 ```json! {"prompt": "<prompt1>", "completion": "<expected generated text>"} {"prompt": "<prompt2>", "completion": "<expected generated text>"} {"prompt": "<prompt3>", "completion": "<expected generated text>"} ``` ::: #### 成本比較 | 方法 | 一次性計價 | 經常性費用 | 推論計價 | |------|------------|----------|----------| | 微調 | 按訓練資料的token數定價 | 每月模型儲存成本 | 自定義模型推論成本(每小時或Provisioned Throughput承諾) | | 提供樣本的提示工程 | 不適用 | 不適用 | 按輸入和輸出token定價 | #### 案例與執行細節說明 :::success [撰寫英文財報:比較few-shot和fine-tune的結果優劣](https://aws.amazon.com/blogs/machine-learning/few-shot-prompt-engineering-and-fine-tuning-for-llms-in-amazon-bedrock/) 更新時間:2024-08-02 ::: :::spoiler 執行細節 解決方法 [方法一]採用in-context進行財報生成:Anthropic Claude 3 Sonnet [方法二]採用fine-tune進行模型調優:Meta Llama 2 70B 提示詞組成 | 部分 | 描述 | 類型 | |------|------|------| | Section A | 整體提示詞,包括角色和分層指示 | 靜態 | | Section B | 財報的具體撰寫任務說明,包括風格、敘述語氣 | 靜態 | | Section C | 過去季度的範例 | 靜態 | | Section D | 需要該季度的財務資料 | 變量 | 訓練及測試資料集格式 ```! { "prompt": "A 部分:整體提示詞... B 部分:撰寫財報講稿的具體規範... D 部分:{time_period}所需要的財務資料:<financial_data>{Section D}</financial_data>。請根據上述提供的資訊,為投資者生成{time_period}的財報。不要編造任何不實內容。", "completion": "{time_period}的財報發布文稿" } ``` 方法結果比較 | 因素 | 比較 | |------|------| | 全面性 | **微調模型**:稿件涵蓋了提示中的大部分關鍵點,但忽略了一些細節。<br><br>**樣本提示工程**:稿件涵蓋了提示中提供的關鍵點。 | | 幻覺 | **微調模型**:兩個例子。<br><br>**樣本提示工程**:一個例子。 | | 寫作風格 | **微調模型**:(1)主要使用客觀專業的口吻,與真實的財報一致,但仍有主觀表達。(2) 語言提供較少變化。例如,它使用"This ** was driven by **"格式10次。(3) 模型生成了一些多餘的句子。例如,"...我們不提供第四季度的具體營業收入。"<br><br>**樣本提示工程**:主要使用客觀專業的口吻,但卻使用許多隱喻。 | | 易用性 | **微調模型**:(1) 與基於相同資料的樣本提示詞工程相比,微調過程通常需要更長時間。(2) 微調需要準備輸入/輸出格式(JSON文件)的訓練資料。(3) 如果新增資料,需要重新進行微調。<br><br>**樣本提示工程**:如果新增資料,使用者只需要在提示詞中添加一個樣本學習或提示詞的範例。總而言之,樣本提示詞工程比微調模型更容易實作。 | ::: :::success [Text-to-SQL的場景中採用QLoRA進行模型調優](https://aws.amazon.com/blogs/machine-learning/import-a-fine-tuned-meta-llama-3-model-for-sql-query-generation-on-amazon-bedrock/) 更新時間:2024-08-01 ::: :::spoiler 執行細節 [參考程式碼](https://github.com/aws-samples/amazon-bedrock-samples/blob/main/custom_models/import_models/llama-3/customized-text-to-sql-model.ipynb) 採用QLoRA進行模型調優:Meta Llama 3 8B 用來進行模型訓練的機種:ml.g5.12xlarge 訓練集:包含 78,577 個上下文,包括問題(以自然語言表達的查詢)和答案(SQL) 成本估算:訓練作業在單個 ml.g5.12xlarge 實例上完成兩個 epoch 大約需要 2.5 小時,訓練成本約為 18 美元 驗證結果:預測分數為 96.65% 配置文件 config.json 將告知 Amazon Bedrock 如何從 safetensors 文件中加載權重。需要注意的一些參數是 model_type(必須是 Amazon Bedrock 當前支持的類型之一)、max_position_embeddings(設置模型可以處理的輸入序列的最大長度)、模型維度(hidden_size、intermediate_size、num_hidden_layers 和 num_attention_heads)以及旋轉位置嵌入(RoPE)參數(描述位置的編碼)。以下是配置範例: ``` { "_name_or_path": "meta-llama/Meta-Llama-3-8B", "architectures": [ "LlamaForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "bos_token_id": 128000, "eos_token_id": 128001, "hidden_act": "silu", "hidden_size": 4096, "initializer_range": 0.02, "intermediate_size": 14336, "max_position_embeddings": 8192, "model_type": "llama", "num_attention_heads": 32, "num_hidden_layers": 32, "num_key_value_heads": 8, "pretraining_tp": 1, "rms_norm_eps": 1e-05, "rope_scaling": null, "rope_theta": 500000.0, "tie_word_embeddings": false, "torch_dtype": "float16", "transformers_version": "4.40.2", "use_cache": true, "vocab_size": 128256 } ``` 評分方式 ``` 您是一位向學生介紹 SQL 的數據科學老師。請考慮以下問題和模式: <question>{question}</question> <schema>{db_schema}</schema> 這是正確答案: <correct_answer>{correct_answer}</correct_answer> 這是學生的答案: <student_answer>{test_answer}<student_answer> 請提供一個從 0 到 100 的數字分數,評估學生的答案與此問題的正確答案的匹配程度。 如果答案本質上表達相同的內容,分數應該很高。 如果缺少某些部分,或包含了不必要的額外部分,分數應該較低。 完全錯誤的答案應得 0 分。請將分數放在 <SCORE> XML 標籤中。 不要考慮您自己對問題的回答,而只根據上面給出的正確答案進行評分。 ``` ::: --- ### Fine-tune Anthropic's Claude (Preview) :::info AWS Blog: [Fine-tune Anthropic’s Claude 3 Haiku in Amazon Bedrock to boost model accuracy and quality](https://aws.amazon.com/blogs/machine-learning/fine-tune-anthropics-claude-3-haiku-in-amazon-bedrock-to-boost-model-accuracy-and-quality/) 文章更新時間: 2024-07-10 ::: 掃 QR code 取得 Data Validator ![Screenshot 2024-09-07 at 3.53.01 PM](https://hackmd.io/_uploads/H12hLtF2R.png =20%x) >[!Note] > 部署及調用:Provisioned Throughput > 場景:Text-to-text **建議場景** 分類 : 例如,當你有10,000個已標記的範例,並希望Anthropic Claude在這項任務上表現出色時。 結構化輸出 : 例如,當你需要Anthropic Claude的回應始終符合給定結構時。 行業知識 : 例如,當你需要教導Anthropic Claude如何回答關於你的公司或行業的問題時。 工具和API : 例如,當你需要教導Anthropic Claude如何熟練使用你的API時。 **訓練/驗證/測試資料集** 資料輸入:JSONL 資料格式:MessageAPI format system:optional messages:required 支援多輪對話 (multi-turn):Yes 最大 token 長度:32,000 tokens (包含system和messages) 最大訓練資料筆數:10,000 (受限於Bedrock服務的配額上限) 最大驗證資料筆數:1,000 (受限於Bedrock服務的配額上限) **建議資料量** 第一階段準備「高品質」的訓練資料約莫50-100筆,根據調優的結果,逐步增加資料量。理論上,資料的品質越高,模型調優的結果,會隨著「資料筆數增加」而變好。 :::spoiler 單筆資料範例 ```json! { "system": "Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.", "messages": [ {"role": "user", "content": "instruction:\n\nSummarize the news article provided below.\n\ninput:\nSupermarket customers in France can add airline tickets to their shopping lists thanks to a unique promotion by a budget airline. ... Based at the airport, new airline launched in 2007 and is a low-cost subsidiary of the airline."}, {"role": "assistant", "content": "New airline has included voucher codes with the branded products ... to pay a booking fee and checked baggage fees ."} ] } ``` ::: :::spoiler 多輪對話情境 ```json! {"system": string, "messages": [{"role": "user", "content": string}, {"role": "assistant", "content": string}, {"role": "user", "content": string}, {"role": "assistant", "content": string}]} ``` ::: :::spoiler 可調優參數 | Name | Description | Type | Default | Value Range | |------|-------------|------|---------|-------------| | epochCount | 整個訓練數據集的最大迭代次數。Epochcount 等同於 epoch。 | integer | 2 | 1-10 | | batchSize | 在更新模型參數之前處理的樣本數量。 | integer | 32 | 4-256 | | learningRateMultiplier | 影響每個批次後模型參數更新學習率的乘數。 | float | 1 | 0.1-2 | | earlyStoppingThreshold | | float | 0.001 | 0-0.1 | | earlyStoppingPatience | | int | 2 | 1-10 | ::: ## Evalutions :::info AWS Blog: [New RAG evaluation and LLM-as-a-judge capabilities in Amazon Bedrock](https://aws.amazon.com/blogs/aws/new-rag-evaluation-and-llm-as-a-judge-capabilities-in-amazon-bedrock/) 更新時間: 2024-12-01 AWS Official: [Evaluator prompts used in a knowledge base evaluation job](https://docs.aws.amazon.com/bedrock/latest/userguide/kb-eval-prompt.html) 關於評測指標的提示詞模板,請參考上方連結 ::: **資料格式** - 存儲在 Amazon S3 中 - 使用 JSON line 格式 - 每個評估工作最多可包含 1000 個提示 - 每個對話最多可有 5 個回合 - 對於使用控制台創建的工作,您必須更新 S3 存儲桶上的跨源資源共享(CORS)配置 ```json { # LLM as judge "prompt": "Bobigny is the capital of", "referenceResponse": "Seine-Saint-Denis", # ground truth response "category": "Capitals" # (optional) scores per category } ``` ```json { # RAG Retrieval ONLY "conversationTurns": [{ "referenceContexts": [{ "content": [{ "text": "" }] }], "prompt": { "content": [{ "text": "This is a prompt" }] } }] } ``` ``` { # RAG Retrieval with Response "conversationTurns": [{ "referenceResponses": [{ "content": [{ "text": "This is a reference context" }] }], ## your prompt to the model "prompt": { "content": [{ "text": "This is a prompt" }] } }] } ``` **RAG 評測指標** **資料抽取 Retrieval ONLY** [指標說明請看這裡](https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base-eval-llm-results.html) - Context relevance - Context coverage (requires ground truth) **資料抽取與答案生成 Retrieval with Response** - Correctness - Completeness - Helpfulness - Logical coherence - Faithfulness - Harmfulness - Stereotyping - Refusal ## Guardrails >[!Caution] > Support English, Spanish, 以及 French > 更新時間: 2024-07-31 :::info AWS Blog: [Use the ApplyGuardrail API with long-context inputs and streaming outputs in Amazon Bedrock](https://aws.amazon.com/blogs/machine-learning/use-the-applyguardrail-api-with-long-context-inputs-and-streaming-outputs-in-amazon-bedrock/) 更新時間: 2024-07-31 ::: ### ApplyGuardrail API #### ApplyGuardrail API 提供了幾個關鍵特性: * 易於使用 - 您可以將 API 整合到應用程序流程的任意位置,以在處理或向使用者提供結果之前驗證內容。例如,在檢索增強生成(RAG)應用中,您可以在執行檢索之前評估用戶輸入。 * 與 Bedrock FM 解耦 - API 與 Bedrock FM 解耦,允許您在不調用 Amazon Bedrock 的 FM 的情況下使用護欄。例如,您現在可以將 API 用於 Amazon SageMaker 上託管的模型。或者,您可以將其用於自託管或來自第三方模型提供商的模型。所需的只是取得輸入或輸出並使用 API 請求評估內容。 範例 API 請求如下: ```json { "source": "INPUT" | "OUTPUT", "content": [{ "text": { "text": "這是一個示例文本片段...", } }] } ``` #### 使用 ApplyGuardrail API 針對串流及長文本的處理 主要挑戰是需要在生成輸出時進行評估,而不是等待整個輸出完成。 這需要一種機制來持續監控串流並能即時使用護欄功能,同時還要考慮生成文本的上下文和連貫性。此外,根據護欄評估結果,須立即判斷是否停止或繼續生成。 * 對流式輸出使用護欄 第一步是將串流分塊批次處理,大約 1,000 個字符為一個分塊,處理成較小的分塊後,可以將每個分塊傳遞給 API 進行評估。如果批次較小,例如 600 個字符,您仍然會被收取整個文本單位(1,000 個字符)的費用。為了有效地使用 API,建議將分塊的批次大小按生成的順序排列,例如 1,000 個字符、2,000 個字符等等。 此外,對於延遲敏感的應用程式,您還可以考慮創建多個buffers和多個護欄,每個護欄具有不同的功能,然後並行使用 ApplyGuardrail API 處理。這樣,您可以最小化護欄評估所需的時間。目前需要額外處理並行。 * 長上下文輸入 ApplyGuardrail API 預設限制為每秒 25 個文本單位(約 25,000 個字符)。如果輸入超過此限制,則需要將其分塊處理以避免遇到限流(throttling)。因此,策略變得相對簡單:如果輸入文本的長度小於 25 個文本單位(25,000 個字符),則可以在單個請求中評估,否則需要將其分解成更小的部分。 #### 最佳實踐和注意事項 * 優化分塊策略 - 分塊大小以最小化 API 調用次數和確保不會丟失上下文為原則。同樣,分塊策略應考慮上下文分割情況,避免關鍵的文本的片段可能會跨越兩個(或更多)分塊。 * 異步處理 - 為 RAG 上下文實施異步處理。這可以幫助將護欄應用過程與主應用程序流程解耦,提高整體性能。對於那些從向量資料庫內頻繁搜尋到的上下文,可以一次性應用 ApplyGuardrail 並將結果存儲在meta data中,避免對相同內容進行冗餘的 API 調用,以顯著提高性能並降低成本。 * 開發全面的測試套件 - 創建一個全面的測試套件,涵蓋廣泛的場景,包括邊緣案例和極端情況,以驗證護欄實施的有效性。 * 實施回退機制 - 可能會出現創建的護欄無法涵蓋所有可能的漏洞並無法捕捉邊緣案例的情況。對於這樣的場景,明智的做法是有一個回退機制,可以將人工審查納入機制,或使用 LLM 二次評估輸入和輸出。 * 定期審核護欄實施 - 不斷完善和調整護欄實施,以及實施日誌記錄和監控機制以捕獲和分析護欄的性能和有效性也是良好的實踐。 :::spoiler Python程式碼 ```python from typing import List, Dict def check_severe_violations(violations: List[Dict]) -> int: """ 當護欄干預時,請求的操作要麼是 BLOCKED,要麼是 NONE。 此方法檢查導致阻止請求的違規次數。 參數: violations (List[Dict]): 違規字典列表,其中每個字典都有一個 'action' 鍵。 返回: int: 嚴重違規的次數('action' 為 'BLOCKED' 的情況)。 """ severe_violations = [violation['action']=='BLOCKED' for violation in violations] return sum(severe_violations) def is_policy_assessement_blocked(assessments: List[Dict]) -> bool: """ 在創建護欄時,您可以指定多種類型的政策。 在評估時,應檢查所有政策是否存在潛在違規。 如果有一個違規阻止了請求,則整個請求都被阻止。 此方法根據給定的評估檢查政策評估是否被阻止。 參數: assessments (list[dict]): 評估字典列表,其中每個字典可能包含 'topicPolicy'、'wordPolicy'、'sensitiveInformationPolicy' 和 'contentPolicy' 鍵。 返回: bool: 如果政策評估被阻止則為 True,否則為 False。 """ blocked = [] for assessment in assessments: if 'topicPolicy' in assessment: blocked.append(check_severe_violations(assessment['topicPolicy']['topics'])) if 'wordPolicy' in assessment: if 'customWords' in assessment['wordPolicy']: blocked.append(check_severe_violations(assessment['wordPolicy']['customWords'])) if 'managedWordLists' in assessment['wordPolicy']: blocked.append(check_severe_violations(assessment['wordPolicy']['managedWordLists'])) if 'sensitiveInformationPolicy' in assessment: if 'piiEntities' in assessment['sensitiveInformationPolicy']: blocked.append(check_severe_violations(assessment['sensitiveInformationPolicy']['piiEntities'])) if 'regexes' in assessment['sensitiveInformationPolicy']: blocked.append(check_severe_violations(assessment['sensitiveInformationPolicy']['regexes'])) if 'contentPolicy' in assessment: blocked.append(check_severe_violations(assessment['contentPolicy']['filters'])) severe_violation_count = sum(blocked) print(f'::Guardrail:: 檢測到 {severe_violation_count} 個嚴重違規') return severe_violation_count>0 def apply_guardrail(text, source, guardrail_id, guardrail_version): response = bedrock_runtime.apply_guardrail( guardrailIdentifier=guardrail_id, guardrailVersion=guardrail_version, source=source, content=[{"text": {"text": text}}] ) if response['action'] == 'GUARDRAIL_INTERVENED': is_blocked = is_policy_assessement_blocked(response['assessments']) alternate_text = ' '.join([output['text'] for output in response['output']]) return is_blocked, alternate_text, response else: # 在沒有護欄干預的情況下返回預設響應 return False, text, response input_message = "列出 3 位知名 CEO 的名字,然後告訴我什麼是銀行以及開立儲蓄帳戶有什麼好處?" model_id = "anthropic.claude-3-haiku-20240307-v1:0" text_unit= 1000 # 字符 response = bedrock_runtime.converse_stream( modelId=model_id, messages=[{ "role": "user", "content": [{"text": input_message}] system=[{"text" : "你是一個協助用戶完成任務的助手。請盡可能詳細地回答。"}], ) stream = response.get('stream') buffer_text = "" if stream: for event in stream: if 'contentBlockDelta' in event: new_text = event['contentBlockDelta']['delta']['text'] if len(buffer_text + new_text) > text_unit: is_blocked, alt_text, guardrail_response = apply_guardrail(buffer_text, "OUTPUT", guardrail_id, guardrail_version) # print(alt_text, end="") if is_blocked: break buffer_text = new_text else: buffer_text += new_text if 'messageStop' in event: # print(f"\n停止原因: {event['messageStop']['stopReason']}") is_blocked, alt_text, guardrail_response = apply_guardrail(buffer_text, "OUTPUT", guardrail_id, guardrail_version) # print(alt_text) ``` ::: # 整合 Amazon Bedrock 及外部工具 [ComfyUI](https://github.com/aws-samples/comfyui-llm-node-for-amazon-bedrock) [LangChain](https://python.langchain.com/v0.2/docs/integrations/chat/bedrock/) [LlamaIndex](https://docs.llamaindex.ai/en/stable/examples/llm/bedrock/) [FlowiseAI](https://docs.flowiseai.com/integrations/langchain/llms/aws-bedrock) [Dify](https://docs.dify.ai/getting-started/readme/model-providers) [Ragas](https://docs.ragas.io/en/latest/howtos/customisations/aws-bedrock.html) [NeMo](https://github.com/kzaamout/bedrock-nemo) [whylabs.ai](https://docs.whylabs.ai/docs/) [LiteLLM](https://docs.litellm.ai/)