1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Amazon Bedrock Prompt Caching とは

Last updated at Posted at 2024-12-22

2024/12 現在 プレビュー

内容

AWS re:Invent 2024 で発表があった Amazon Bedrock Prompt Caching をシンプルに纏めます。

頻繁に使用されるコンテキストをプロンプトにキャッシュできる。
キャッシュされたコンテキストは、アクセスするたびに最大 5 分間使用可能。
コストを最大 90% 削減し、レイテンシーを最大 85% 削減。

利用可能なモデル

  • Claude 3 Haiku, Claude 3.5 Sonnet v2
  • Nova Micro/Lite/Pro(バージニアのみ)

対応リージョン

  • バージニア
  • オレゴン

実装方法

cachePoint ブロックを追加してあげれば良いようです。

SDK での実装

実装は、AWS ブログのものを利用させていただいてます。

import json
import boto3

MODEL_ID = "us.anthropic.claude-3-5-sonnet-20241022-v2:0"

AWS_REGION = "us-west-2"

bedrock_runtime = boto3.client(
    "bedrock-runtime",
    region_name=AWS_REGION,
)

DOCS = [
    "bedrock-or-sagemaker.pdf",
    "generative-ai-on-aws-how-to-choose.pdf",
    "machine-learning-on-aws-how-to-choose.pdf",
]

messages = []


def converse(new_message, docs=[], cache=False):

    if len(messages) == 0 or messages[-1]["role"] != "user":
        messages.append({"role": "user", "content": []})

    for doc in docs:
        print(f"Adding document: {doc}")
        name, format = doc.rsplit('.', maxsplit=1)
        with open(doc, "rb") as f:
            bytes = f.read()
        messages[-1]["content"].append({
            "document": {
                "name": name,
                "format": format,
                "source": {"bytes": bytes},
            }
        })

    messages[-1]["content"].append({"text": new_message})

    if cache:
        messages[-1]["content"].append({"cachePoint": {"type": "default"}})

    response = bedrock_runtime.converse(
        modelId=MODEL_ID,
        messages=messages,
    )

    output_message = response["output"]["message"]
    response_text = output_message["content"][0]["text"]

    print("Response text:")
    print(response_text)

    print("Usage:")
    print(json.dumps(response["usage"], indent=2))

    messages.append(output_message)


converse("AWS Trainium と AWS Inferentia を 20 文字以内で比較する。", docs=DOCS, cache=True)
converse("Amazon Textract と Amazon Transcribe を 20 字以内で比較する。")
converse("Amazon Q BusinessとAmazon Q Developerを20字以内で比較する。")
botocore.exceptions.ParamValidationError: Parameter validation failed:
Unknown parameter in messages[0].content[4]: "cachePoint", must be one of: text, image, document, video, toolUse, toolResult, guardContent

 
やはり、プレビュー中でリクエストしないとダメそうですね。

GA されたまたやってみて更新したいと思います。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?