7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Strands AgentsでClaudeモデルのプロンプトキャッシュを使う方法

Last updated at Posted at 2026-01-16

Bedrockはプロンプトキャッシュに対応しています。

2025年9月のアップデートでこのプロンプトキャッシュが使いやすくなり、「とりあえずメッセージの最後にキャッシュポイントを追加したらOK」的な感じになりました。

制限事項もあるので詳細はドキュメントを見てね

Simplified Cache Management for Claude Models

で、プロンプトキャッシュをStrands Agentsで使いたいです。

Strands Agentsはエージェントループの動作をいい感じにやってくれるため、内部で複数ターンのメッセージのやり取りが発生します。この複数のターンのそれぞれで「メッセージの最後にキャッシュポイントを追加する」を実現する方法を見つけましたので、シェアします。

Hooksを使う

Strands AgentsはHooksの仕組みがあり、LLMへのリクエスト送信前後に処理を割り込むことが可能です。なので、リクエストの送信前にキャッシュポイントを追加し、リクエスト後にキャッシュポイントを削除することで実現します。

キャッシュポイントは4つまでという上限があるため、キャッシュポイント削除も行う必要があります。

from strands import Agent
from strands.hooks import (
    AfterModelCallEvent,
    BeforeModelCallEvent,
)
from strands.models import BedrockModel

agent = Agent(
    model=BedrockModel(
        model_id="global.anthropic.claude-haiku-4-5-20251001-v1:0",
        region_name="ap-northeast-1",
    ),
)

cache_point_item = {"cachePoint": {"type": "default"}}


# モデル呼び出し前のHook
def before_model_call_event(event: BeforeModelCallEvent):
    event.agent.messages[-1]["content"].append(cache_point_item)


# モデル呼び出し後のHook
def after_model_call_event(event: AfterModelCallEvent):
    event.agent.messages[-1]["content"].remove(cache_point_item)


# hookをagentに追加
agent.hooks.add_callback(BeforeModelCallEvent, before_model_call_event)
agent.hooks.add_callback(AfterModelCallEvent, after_model_call_event)

これでしれっとプロンプトキャッシュを活用できますね。

(Haikuの場合、4,096トークンまではキャッシュされない制限もあるので動作確認の際はご注意を。)

7
1
1

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
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?