Amazon Bedrock의 프롬프트 캐싱은 동일한 컨텍스트를 파운데이션 모델에 반복적으로 전송할 때 입력 토큰 비용을 최대 90퍼센트까지 절감할 수 있습니다(Amazon Bedrock 프롬프트 캐싱 요금 기준). 캐싱이 없다면, 10,000토큰짜리 계약서와 함께 사용자 질문 50개를 보낼 경우, 모델이 이미 처리한 콘텐츠에 대해 500,000개의 입력 토큰이 전액 요금으로 청구됩니다.
이 문제는 프롬프트를 줄이거나, 컨텍스트 윈도를 축소하거나, 애플리케이션 수준의 캐싱을 구현하여 완화할 수 있습니다. 각 옵션에는 트레이드오프가 따릅니다.
- 프롬프트 단축은 토큰 수를 줄이지만 컨텍스트 품질도 떨어뜨릴 수 있습니다.
- 컨텍스트 윈도 축소는 비용을 낮추는 대신, 완전한 정보에 대해 모델이 추론할 수 있는 능력을 희생합니다.
- 응답 캐싱은 동일한 쿼리에는 잘 작동하지만, 같은 컨텍스트에 서로 다른 질문이 짝지어지는 경우에는 아무런 이점을 제공하지 않습니다.
Amazon Bedrock의 프롬프트 캐싱은 이러한 과제를 인프라 수준에서 줄이는 데 도움을 줍니다. 대화 컨텍스트의 일부(시스템 프롬프트, 문서, 도구 정의)를 캐시하면, Amazon Bedrock은 이후 요청에서 해당 토큰을 다시 처리하지 않고 캐시된 토큰을 읽습니다. 이는 모델이나 프롬프트 품질을 변경하지 않고도 캐시 적중 시 첫 토큰까지의 시간(TTFT, time-to-first-token)을 줄이고 캐시된 입력 토큰 비용을 최대 90퍼센트까지 낮출 수 있습니다.
이 글에서는 Amazon Bedrock의 Converse API를 사용해 기본적인 패턴에서 고급 패턴으로 나아가며 여섯 가지 실용적인 프롬프트 캐싱 시나리오를 살펴봅니다.
- 메시지 콘텐츠 캐싱: 여러 질문으로 분석하기 위해 긴 문서를 캐시합니다.
- 시스템 프롬프트 캐싱: 대화 전반에 걸쳐 페르소나 정의와 지침을 캐시합니다.
- 도구 정의 캐싱: 에이전트 워크플로를 위해 도구 스키마를 캐시합니다.
- 혼합 TTL 캐싱: 서로 다른 콘텐츠 계층에 서로 다른 캐시 수명을 할당합니다.
- 테넌트 격리: 멀티테넌트 애플리케이션에서 테넌트별 캐시 분리를 구현합니다.
- LangChain 통합: LangChain 프레임워크와 함께 프롬프트 캐싱을 사용합니다.
프롬프트 캐싱은 어떻게 동작하는가
프롬프트 캐싱은 부분적으로 처리된 입력의 스냅샷을 저장하므로, 동일한 접두사를 가진 이후 요청은 중복 계산을 건너뜁니다. 이 섹션에서는 요청 흐름, 지원 모델, 요금을 다룹니다.
요청에 cachePoint 마커를 포함하면, Amazon Bedrock은 해당 마커 앞의 콘텐츠가 기존 캐시 항목과 일치하는지 평가합니다. 일치하면(캐시 적중) 모델은 해당 토큰을 다시 처리하지 않고 캐시된 상태에서 생성을 시작할 수 있습니다. 일치하는 항목이 없으면(캐시 미스) 모델은 전체 콘텐츠를 처리하고 그 결과를 향후 요청을 위해 캐시에 기록합니다.
다음 다이어그램은 이 흐름을 보여줍니다.
그림 1: 프롬프트 캐싱 요청 흐름으로, 첫 번째 요청은 캐시에 쓰고 두 번째 요청은 캐시에서 읽어 TTFT와 입력 토큰 비용을 줄입니다.
이 흐름을 염두에 두면, 네 가지 핵심 개념이 실제 캐싱 동작을 결정합니다.
- 캐시 범위: 캐시 항목은 개별 AWS 계정과 AWS 리전을 범위로 합니다.
- 토큰 임계값: 각 캐시 체크포인트는 활성화되기 위해 최소 토큰 임계값을 충족해야 합니다. 예를 들어 Anthropic Claude Sonnet 4.5와 Sonnet 4.6은 체크포인트당 최소 1,024토큰이 필요하고, Opus 모델은 최소 4,096토큰이 필요합니다.
- TTL(Time-to-live): 캐시 항목은 요청에 지정된 TTL에 따라 만료됩니다. 기본값은 5분이며, 일부 모델은 최대 1시간까지 지원합니다.
- 모델 독립적 구문: Converse API의
cachePoint구문은 Anthropic Claude와 Amazon Nova를 포함한 지원 모델 패밀리 전반에서 동일합니다.
최신 모델 지원 정보는 Amazon Bedrock 프롬프트 캐싱 설명서를 참조하세요.
요금
프롬프트 캐싱은 표준 입력 및 출력 토큰 외에 두 가지 토큰 범주를 추가로 도입합니다.
| 토큰 유형 | 설명 | 표준 입력 대비 비용 |
|---|---|---|
cacheWriteInputTokens |
캐시에 기록된 토큰(첫 번째 요청) | 표준 입력보다 25% 높음 |
cacheReadInputTokens |
캐시에서 읽은 토큰(이후 요청) | 표준 입력보다 90% 낮음 |
cacheWriteInputTokens (1시간 TTL) |
1시간 TTL로 캐시에 기록된 토큰 | 표준 입력보다 100% 높음(2배) |
컨텍스트가 반복되는 워크로드의 경우, 입력 토큰 비용에서 약 75퍼센트의 절감 효과를 얻습니다. 예를 들어 10,000토큰 문서와 10개의 서로 다른 질문을 보낸다면, 첫 번째 요청에서 캐시 쓰기 비용이 발생합니다. 나머지 아홉 개 요청은 각각 90퍼센트 할인된 비용으로 캐시에서 읽으므로, 해당 문서 컨텍스트에 대한 입력 토큰 비용에서 순절감액은 약 75퍼센트가 됩니다. 이는 이후의 모든 요청이 TTL 윈도 내에 발생한다고 가정한 것입니다. 만료 이후의 요청은 새로운 캐시 쓰기를 유발하여 순절감액을 줄입니다. 자세한 요금 정보는 Amazon Bedrock 요금을 참조하세요.
사전 요구 사항
시나리오를 시작하기 전에 다음 사항을 준비해야 합니다.
- 지원되는 AWS 리전(예:
us-west-2)에서 Amazon Bedrock에 접근할 수 있는 AWS 계정. - 대상 모델에 대한 모델 액세스 활성화. 이 글의 예제는 Anthropic Claude Sonnet 4.5(
global.anthropic.claude-sonnet-4-5-20250929-v1:0)를 사용합니다. 자세한 지침은 모델 액세스 관리를 참조하세요. 최신 모델 및 리전 가용성은 Amazon Bedrock의 AWS 리전별 지원 모델을 참조하세요. 이는 교차 리전 추론 프로파일입니다. 요청이 리전 전반으로 자동 라우팅되므로, 때때로 캐시 쓰기 빈도가 높아질 수 있습니다. - 다음 종속성이 설치된 Python 3.10 이상:
pip install boto3>=1.43.0 langchain-aws>=0.2.12 matplotlib pandas
참고: 시나리오 4(혼합 TTL)에서 사용하는
cachePoint의ttl파라미터에는 Boto3 1.43.0 이상이 필요합니다.
- 기본 프로파일 또는 환경 변수를 통해 구성된 AWS 자격 증명. 설정 지침은 AWS Command Line Interface(AWS CLI) 구성을 참조하세요.
시나리오 1: 메시지 콘텐츠 캐싱
프롬프트 캐싱의 흔한 사용 사례는 반복적으로 질의하는 긴 문서나 참조 콘텐츠를 캐싱하는 것입니다. 예를 들어 검색 증강 생성(RAG) 애플리케이션에서 동일한 문서에 대해 여러 질문을 하거나, 코딩 어시스턴트가 대규모 코드베이스를 참조하는 경우입니다.
이 시나리오에서는 정적 문서와 동적 질문 사이에 cachePoint 마커를 배치합니다. Amazon Bedrock은 첫 번째 호출에서 문서를 캐시하고, 이후 호출에서 이를 재사용할 수 있습니다.
메시지 콘텐츠 캐싱의 동작 방식
정적 콘텐츠 뒤, 동적 질문 앞에 cachePoint 콘텐츠 블록을 배치합니다. Amazon Bedrock은 체크포인트 이전의 모든 내용을 캐시하고 이후 요청에서 재사용합니다.
content = [
{"text": "<정적 문서 콘텐츠>"},
{"cachePoint": {"type": "default"}}, # 위의 모든 내용을 캐시
{"text": "<사용자 질문>"} # 동적, 요청마다 변경됨
]
다음 코드는 이 패턴을 완전하게 동작하는 예제로 구현한 것입니다.
구현
먼저 Amazon Bedrock 런타임 클라이언트를 설정하고 샘플 문서를 정의합니다. 프로덕션 애플리케이션에서 이 문서는 PDF, 지식 베이스 문서, 또는 1,024토큰 임계값을 초과하는 기타 콘텐츠일 수 있습니다.
import boto3
import json
import time
MODEL_ID = "global.anthropic.claude-sonnet-4-5-20250929-v1:0" # 캐시 활성화를 위한 최소 토큰 요구 사항: 1,024토큰
AWS_REGION = "us-west-2"
bedrock = boto3.client("bedrock-runtime", region_name=AWS_REGION)
# Claude Sonnet 4.5에는 1,024토큰 초과가 필요하므로 충분히 큰 문서
DOCUMENT = """
The universe is a vast and mysterious expanse that has captivated human imagination for millennia. From the earliest civilizations who looked up at the night sky and wondered about the nature of the stars, to modern astronomers using sophisticated telescopes and spacecraft to explore distant galaxies, our quest to understand the cosmos continues unabated. This comprehensive overview covers the major components of our universe, from the smallest asteroids to the largest galaxy clusters.
Our solar system, located in the Milky Way galaxy, is home to eight planets, numerous dwarf planets, and countless smaller objects including asteroids, comets, and meteoroids. The Sun, a middle-aged G-type main-sequence star, provides the energy that sustains life on Earth and influences the dynamics of all objects within its gravitational reach.
Mercury, the innermost planet, experiences extreme temperature variations due to its proximity to the Sun and lack of substantial atmosphere. Venus, often called Earth's twin due to its similar size, has a thick atmosphere composed primarily of carbon dioxide, creating a runaway greenhouse effect that makes it the hottest planet in our solar system. Earth, our home, is the only known planet to harbor life, with its unique combination of liquid water, moderate temperatures, and protective magnetic field.
Mars, the Red Planet, has long been a subject of fascination and speculation about the possibility of extraterrestrial life. Its rusty appearance comes from iron oxide prevalent on its surface. The planet features the largest volcano in the solar system, Olympus Mons, and a canyon system, Valles Marineris, that dwarfs the Grand Canyon. Recent Mars missions have discovered evidence of ancient river systems and the presence of water ice beneath the surface.
The asteroid belt, located between Mars and Jupiter, contains millions of rocky objects ranging from small boulders to the dwarf planet Ceres. These remnants from the early solar system provide valuable insights into planetary formation and the conditions that existed billions of years ago. Scientists study these asteroids to understand the building blocks of planets and the early solar system's chemical composition. Some asteroids contain valuable metals and minerals that may one day be mined for space-based industries.
The terrestrial planets share common characteristics: rocky compositions, relatively small sizes compared to gas giants, and solid surfaces. Mercury's heavily cratered surface resembles our Moon, preserving a record of impacts from the early solar system. Venus's dense atmosphere traps heat so effectively that its surface temperature exceeds that of Mercury, despite being farther from the Sun. Earth's plate tectonics continuously reshape its surface, while Mars shows evidence of past geological activity including ancient volcanoes and water-carved channels.
Jupiter, the largest planet, is a gas giant composed primarily of hydrogen and helium. Its Great Red Spot, a persistent anticyclonic storm, has been observed for over 400 years. Jupiter's intense magnetic field and numerous moons, including the four Galilean satellites discovered by Galileo Galilei in 1610, make it a miniature solar system in its own right. Europa, one of these moons, is believed to have a subsurface ocean that could potentially harbor life.
Saturn, famous for its spectacular ring system, is another gas giant with dozens of moons. Titan, its largest moon, has a thick atmosphere and liquid hydrocarbon lakes, making it one of the most intriguing bodies in the solar system for astrobiological research. The Cassini-Huygens mission provided unprecedented details about Saturn and its moons during its 13-year exploration.
Uranus and Neptune, the ice giants, reside in the outer reaches of our solar system. Uranus rotates on its side, likely due to a massive impact early in its history. Neptune, the windiest planet, features storms with wind speeds exceeding 2,000 kilometers per hour. Both planets have ring systems, though less prominent than Saturn's.
Beyond Neptune lies the Kuiper Belt, a region populated by icy bodies including the dwarf planet Pluto. The New Horizons mission's flyby of Pluto in 2015 revealed a geologically active world with nitrogen glaciers and a hazy atmosphere. Even further out is the Oort Cloud, a hypothetical spherical shell of icy objects that may extend halfway to the nearest star.
The outer solar system remains largely unexplored compared to the inner planets. Only Voyager 2 has visited both Uranus and Neptune, conducting brief flybys in the 1980s. Future missions are being planned to study these ice giants in more detail, potentially including orbiters and atmospheric probes. The moons of the outer planets present exciting targets for astrobiology, with Europa, Enceladus, and Titan all showing signs of environments that could support life.
Gas giants and ice giants differ fundamentally in composition. While Jupiter and Saturn are primarily hydrogen and helium, Uranus and Neptune contain significant amounts of water, ammonia, and methane ices. This distinction gives the ice giants their characteristic blue-green colors and different internal structures compared to their larger neighbors.
Exoplanet research has revolutionized our understanding of planetary systems. The Kepler space telescope discovered thousands of planets orbiting other stars, revealing that planets are common throughout our galaxy. Some of these exoplanets reside in the habitable zone of their stars, where liquid water could exist on the surface.
The search for extraterrestrial intelligence, known as SETI, uses radio telescopes to listen for signals from advanced civilizations. While no definitive signals have been detected, the Drake Equation provides a framework for estimating the number of communicating civilizations in our galaxy.
Black holes, regions of spacetime where gravity is so strong that nothing can escape, represent some of the most extreme objects in the universe. Stellar black holes form from the collapse of massive stars, while supermassive black holes, containing millions to billions of solar masses, reside at the centers of most galaxies including our own.
The James Webb Space Telescope, launched in 2021, observes in infrared to study the earliest galaxies and probe planetary atmospheres for signs of life. Understanding the universe requires collaboration across disciplines including physics, chemistry, biology, and engineering.
Stellar evolution describes how stars change over their lifetimes. Stars form in molecular clouds when gravity causes dense regions to collapse. Nuclear fusion in the core converts hydrogen to helium, releasing enormous amounts of energy. When stars exhaust their nuclear fuel, their fate depends on their mass: smaller stars become white dwarfs, medium stars may become neutron stars, and the most massive stars explode as supernovae, potentially leaving behind black holes.
Galaxies, containing billions of stars, come in various shapes including spiral, elliptical, and irregular. The Milky Way is a barred spiral galaxy approximately 100,000 light-years in diameter. Galaxies often cluster together, forming groups and superclusters connected by cosmic filaments of dark matter and gas. The observable universe contains approximately two trillion galaxies, each harboring hundreds of billions of stars.
The cosmic microwave background radiation, discovered in 1965, provides a snapshot of the universe approximately 380,000 years after the Big Bang. Detailed measurements of this radiation have confirmed the Big Bang theory and revealed information about the early universe's composition and geometry. Dark matter and dark energy together comprise about 95% of the universe's total mass-energy content.
Space exploration has achieved remarkable milestones since the launch of Sputnik in 1957. Human spaceflight began with Yuri Gagarin's orbit in 1961 and culminated in the Apollo Moon landings. The International Space Station has hosted continuous human presence in space since 2000. Future missions aim to return humans to the Moon through the Artemis program and eventually send astronauts to Mars. Private space companies have transformed the industry, developing reusable rockets that have dramatically reduced launch costs.
The study of astrobiology examines the origin, evolution, and distribution of life in the universe. Scientists search for biosignatures in planetary atmospheres and analyze extremophiles on Earth to understand the limits of life. The discovery of organic molecules on Mars and in the plumes of Enceladus fuels speculation about the possibility of life elsewhere in our solar system. Modern telescopes have detected exoplanets using multiple methods including transit photometry, radial velocity measurements, and direct imaging.
Gravitational wave astronomy represents one of the newest frontiers in space science. The LIGO and Virgo detectors have observed mergers of black holes and neutron stars, confirming predictions from Einstein's general theory of relativity. These observations have opened an entirely new window on the universe, allowing scientists to study phenomena that are invisible to traditional electromagnetic telescopes. The future space-based LISA mission promises to detect gravitational waves from even more exotic sources, including the mergers of supermassive black holes at the centers of galaxies.
"""
다음으로 캐싱 함수를 정의합니다. 핵심 요소는 정적 문서와 동적 질문 사이에 배치된 cachePoint 블록입니다.
def converse_with_cache(document, question):
"""프롬프트 캐싱을 활성화한 상태로 문서에 질의합니다."""
content = [
{"text": document},
{"cachePoint": {"type": "default"}},
{"text": question}
]
response = bedrock.converse(
modelId=MODEL_ID,
messages=[{"role": "user", "content": content}],
inferenceConfig={"maxTokens": 512}
)
return response["usage"]
캐싱 동작을 관찰하기 위해 두 개의 요청을 실행합니다. 최초 호출이 캐시를 채우고, 다른 질문을 담은 이후 호출이 이를 재사용합니다.
# 요청 1: 캐시 쓰기 (이 콘텐츠를 처음 보는 경우)
usage1 = converse_with_cache(DOCUMENT, "What are the key points?")
print("요청 1 (캐시 쓰기 예상):")
print(json.dumps(usage1, indent=2))
time.sleep(1)
# 요청 2: 캐시 읽기 (동일한 문서, 다른 질문)
usage2 = converse_with_cache(DOCUMENT, "Summarize the conclusions.")
print("
요청 2 (캐시 읽기 예상):")
print(json.dumps(usage2, indent=2))
캐시 지표 읽기
응답의 usage 객체에는 두 개의 캐시 전용 필드가 포함됩니다.
| 필드 | 설명 |
|---|---|
cacheWriteInputTokens |
캐시에 기록된 토큰(첫 번째 요청에서 나타남) |
cacheReadInputTokens |
캐시에서 읽은 토큰(이후 요청에서 나타남) |
Anthropic Claude Sonnet 4.5와 1,024토큰을 초과하는 문서로 테스트한 결과, 최초 응답은 캐시 쓰기를 보여줍니다.
{
"inputTokens": 28,
"outputTokens": 253,
"cacheWriteInputTokens": 1898,
"cacheReadInputTokens": 0
}
동일한 문서 접두사로 수행한 이후 요청은 캐시 읽기를 만들어냅니다.
{
"inputTokens": 28,
"outputTokens": 294,
"cacheWriteInputTokens": 0,
"cacheReadInputTokens": 1898
}
cacheReadInputTokens가 이제 캐시에서 읽은 1,898토큰을 반영한다는 점에 주목하세요. 문서 접두사 전체가 다시 처리되지 않고 재사용되었습니다. 표준 입력으로 처리된 것은 28토큰(질문 자체)뿐입니다. 이 캐시된 토큰은 할인된 캐시 읽기 요율(표준 입력보다 90퍼센트 낮음)로 청구됩니다.
간소화된 캐시 관리
Amazon Bedrock의 Claude 모델은 _간소화된 캐시 관리_를 지원합니다. cachePoint를 하나만 배치하면, Amazon Bedrock이 해당 마커 이전의 최대 약 20개 콘텐츠 블록에 대해 자동으로 캐시 적중을 확인합니다. 대화의 앞부분에 대한 캐시 적중을 얻기 위해 여러 캐시 체크포인트를 수동으로 배치할 필요가 없습니다.
더 세밀한 제어가 필요하면 각 콘텐츠 섹션 뒤에 여러 cachePoint 마커를 배치할 수 있습니다.
content = [
{"text": SECTION_1},
{"cachePoint": {"type": "default"}},
{"text": SECTION_2},
{"cachePoint": {"type": "default"}},
{"text": SECTION_3},
{"cachePoint": {"type": "default"}},
{"text": QUESTION}
]
이 접근 방식은 부분 캐시 적중을 지원합니다. 앞의 두 섹션만 이전 요청과 일치하면, 모델은 해당 섹션에 대한 캐시를 재사용하고 나머지 콘텐츠를 처리합니다.
스트리밍 변형
동일한 캐싱 구문이 converse_stream에서도 동작합니다. 핵심 차이는 캐시 지표가 즉각적인 응답이 아니라 스트림 끝의 metadata 이벤트로 도착한다는 점입니다.
def converse_stream_with_cache(document, question):
content = [
{"text": document},
{"cachePoint": {"type": "default"}},
{"text": question}
]
response = bedrock.converse_stream(
modelId=MODEL_ID,
messages=[{"role": "user", "content": content}],
inferenceConfig={"maxTokens": 512}
)
text = ""
usage = {}
for event in response["stream"]:
if "contentBlockDelta" in event:
text += event["contentBlockDelta"]["delta"].get("text", "")
elif "metadata" in event:
usage = event["metadata"].get("usage", {})
return usage, text
TTFT 벤치마크
지연 시간 개선을 정량화하기 위해 캐싱 사용 여부에 따라 TTFT를 측정할 수 있습니다.
def measure_ttft(document, question, use_cache=True, iterations=5):
"""ConverseStream을 사용해 TTFT를 측정합니다."""
ttfts = []
for i in range(iterations):
if use_cache:
content = [
{"text": document},
{"cachePoint": {"type": "default"}},
{"text": question}
]
else:
content = [{"text": document + "
" + question}]
start = time.time()
response = bedrock.converse_stream(
modelId=MODEL_ID,
messages=[{"role": "user", "content": content}],
inferenceConfig={"maxTokens": 512}
)
for event in response["stream"]:
if "contentBlockDelta" in event:
ttft = time.time() - start
ttfts.append(ttft)
for _ in response["stream"]:
pass
break
time.sleep(0.5)
return ttfts
프롬프트 캐싱은 TTFT를 줄일 수 있으며, 캐시된 접두사 크기가 커질수록 이점이 커집니다. 상대적으로 작은 문서(약 2,000~5,000토큰)의 경우 적은 반복 횟수에서는 개선 효과가 통계적으로 유의미하지 않을 수 있습니다. 정확한 개선 정도는 문서 크기, 모델, 현재 부하에 따라 달라집니다. 큰 캐시 접두사(10,000토큰 초과)의 경우 TTFT 감소가 더 뚜렷해집니다.
시나리오 2: 시스템 프롬프트 캐싱
많은 애플리케이션은 모델의 페르소나, 가이드라인, 도메인 전문성을 정의하는 상세한 시스템 프롬프트를 사용합니다. 이러한 시스템 프롬프트는 수천 토큰에 이를 수 있으며 사용자 상호작용 전반에 걸쳐 일정하게 유지됩니다. 시스템 프롬프트 캐싱을 사용하면 전체 처리 비용을 한 번만 지불하고, 이후 모든 메시지에서 캐시된 시스템 프롬프트를 재사용합니다. 캐시 포인트는 사용자 메시지와 분리된 system 파라미터 내부에 위치합니다.
구성
Converse API의 system 파라미터는 콘텐츠 블록 배열을 받습니다. 시스템 텍스트 뒤에 cachePoint를 배치합니다.
system = [
{"text": "<상세한 시스템 프롬프트>"},
{"cachePoint": {"type": "default"}}
]
다음 예제는 상세한 페르소나 프롬프트를 담은 전체 요청에서 이를 보여줍니다.
구현
다음 예제는 포괄적인 시스템 프롬프트, 즉 상세한 응답 가이드라인을 갖춘 우주 과학 전문가 어드바이저(Expert Space Science Advisor) 페르소나를 정의합니다. 이 프롬프트는 캐싱에 필요한 2,048토큰 임계값을 초과합니다.
SYSTEM_PROMPT = """You are an Expert Space Science Advisor, a highly knowledgeable AI assistant specializing in astronomy, astrophysics, planetary science, and space exploration. Your role is to provide accurate, comprehensive, and engaging information about many aspects of space science.
## Core Expertise Areas
### Planetary Science
You possess deep knowledge of planetary formation, composition, atmospheres, and geology across our solar system and beyond. This includes understanding the inner rocky planets (Mercury, Venus, Earth, and Mars), gas giants (Jupiter and Saturn), ice giants (Uranus and Neptune), dwarf planets such as Pluto and Ceres, and the countless smaller bodies that inhabit our solar system.
You understand the processes that shape planetary worlds: volcanism, tectonics, atmospheric erosion, meteorite impacts, cryovolcanism, and planetary differentiation. You can explain how planetary magnetic fields arise and protect atmospheres, how seasons change on different worlds, and how water and other volatiles behave under varying planetary conditions.
Your expertise extends to moons and satellite systems. You know the fascinating moons of the solar system: Jupiter's volcanic Io, Europa with its subsurface ocean, Saturn's Titan with its methane lakes, Enceladus with its water geysers, Neptune's Triton with its frozen nitrogen, and our own Moon with its unique formation history. You understand how tidal forces shape these worlds and how they may harbor habitable environments.
### Astrophysics and Cosmology
Your expertise extends to the fundamental physics governing the universe. You understand stellar evolution from star-forming nebulae to supernovae and black holes. You can explain the life cycle of stars, from long-lived red dwarfs to short-lived blue giants, and how stellar mass determines a star's fate.
You comprehend the structure and evolution of galaxies, including our Milky Way. You know the different types of galaxies (spirals, ellipticals, and irregulars) and how they form, interact, and evolve over billions of years. You understand the role of supermassive black holes at galactic centers and how they influence galactic evolution.
Your knowledge encompasses modern cosmology: the Big Bang theory, the expansion of the universe, the cosmic microwave background radiation, dark energy, dark matter, and the large-scale structure of the cosmos. You can discuss the ultimate fate of the universe, the nature of spacetime, and the fundamental principles governing physical reality.
### Space Exploration
You are well-versed in the history and future of human and robotic space exploration. You know the milestones of the space age: the launch of Sputnik, Yuri Gagarin as the first human in space, the Apollo program and Moon landings, the Skylab, Mir, and ISS space stations, the space shuttle programs, and the pioneering robotic missions.
You understand current and past robotic missions: the Voyager probes exploring interstellar space, Cassini-Huygens at Saturn, New Horizons at Pluto, the Mars rovers Spirit, Opportunity, Curiosity, and Perseverance, ESA missions like Rosetta, Chinese lunar missions, and the Parker Solar Probe and Solar Orbiter.
You are familiar with space technology: propulsion systems (chemical, ionic, nuclear), space navigation, life support systems, radiation protection, deep-space communications, space telescopes, and scientific instruments. You understand the unique engineering challenges of spaceflight: vacuum, radiation, microgravity, extreme temperatures, and long-term reliability.
You follow current developments in commercial space exploration: SpaceX and its Starship system, Blue Origin and New Glenn, NASA's Artemis plans to return to the Moon, the lunar Gateway space station, planned missions to Mars, and the growing role of private companies in space exploration.
### Astrobiology and the Search for Life
You have specialized knowledge about the conditions necessary for life, habitable zones around stars, and the search for life in the universe. You understand the fundamental requirements for life as we know it: liquid water, energy sources, basic elements (CHNOPS), and stable environments.
You know the potentially habitable environments in the solar system: Europa's subsurface ocean, Enceladus's seas, Titan's lakes, ancient wet Mars, and possibly even Venus's upper atmosphere. You understand how extremophiles on Earth inform our search for life elsewhere.
### Astronomical Observation
You have knowledge of astronomical observation techniques, from ground-based telescopes to space observatories. You understand different wavelengths of light: radio, infrared, visible, ultraviolet, X-ray, and gamma rays, and what each reveals about the cosmos.
You know major observatories: the Hubble Space Telescope, the James Webb Space Telescope, the Chandra X-ray Observatory, ESO's VLT telescopes, the Keck observatories, the Atacama Large Millimeter Array (ALMA), and gravitational wave observatories like LIGO and Virgo.
## Response Guidelines
### Scientific Accuracy
Always prioritize scientific accuracy in your responses. Base your explanations on our current scientific understanding. When there is uncertainty or scientific debate, acknowledge this explicitly and present different perspectives. Clearly distinguish between established facts, well-supported theories, speculative hypotheses, and science fiction.
### Clarity and Accessibility
Adapt your explanations to the apparent knowledge level of the questioner. For basic questions, provide clear, accessible explanations using analogies when appropriate. For advanced questions, you may use more technical terminology freely, but always define specialized terms the first time you use them.
Use analogies and comparisons to make abstract concepts more concrete. For example, compare planetary sizes to familiar objects, cosmic distances to terrestrial journeys, or geological timescales to human historical events.
### Context and Perspective
Always provide appropriate context for your answers. Explain not just what we know, but how we know it: the missions, observations, and experiments that provided the evidence. When relevant, mention the history of discoveries and how our understanding has evolved.
## Communication Style
Maintain a professional but accessible tone. Be patient and encouraging with all questions, regardless of sophistication level. Avoid unnecessary jargon, but do not oversimplify complex concepts in ways that may be misleading.
Structure long responses clearly with sections and subheadings when appropriate. Use numbered or bulleted lists to organize complex information. Begin with a direct answer to the question, then provide additional details and context.
When appropriate, suggest additional resources or related areas of interest the user may want to explore. Encourage curiosity and continued learning about our fascinating universe.
"""
캐싱 함수는 system 파라미터에 cachePoint를 배치하여 사용자 메시지를 분리된 상태로 유지합니다.
def converse_system_cached(question):
response = bedrock.converse(
modelId=MODEL_ID,
system=[
{"text": SYSTEM_PROMPT},
{"cachePoint": {"type": "default"}}
],
messages=[{"role": "user", "content": [{"text": question}]}],
inferenceConfig={"maxTokens": 512}
)
return response["usage"], response["output"]["message"]["content"][0]["text"]
# 요청 1: 캐시 쓰기
usage1, _ = converse_system_cached("What are the most promising locations for finding microbial life?")
print("요청 1 (캐시 쓰기 예상):")
print(json.dumps(usage1, indent=2))
time.sleep(1)
# 요청 2: 다른 질문, 동일한 시스템 프롬프트 (캐시 읽기)
usage2, _ = converse_system_cached("How do gravitational waves help us study the universe?")
print("
요청 2 (캐시 읽기 예상, 다른 사용자 질문):")
print(json.dumps(usage2, indent=2))
요청마다 사용자 메시지는 바뀌지만 시스템 프롬프트는 동일하게 유지됩니다. Amazon Bedrock은 사용자가 무엇을 묻든 관계없이 시스템 프롬프트 접두사를 캐시하고 재사용하도록 설계되었습니다.
시스템 프롬프트 캐싱을 사용해야 하는 경우
시스템 프롬프트 캐싱은 다음과 같은 경우에 이상적입니다.
- 상세한 역할 설명과 행동 지침을 갖춘 페르소나 기반 어시스턴트.
- 턴 전반에 걸쳐 일정하게 유지되는 방대한 지침을 가진 에이전트 워크플로.
- 복잡한 회사 정책과 응답 프로토콜을 가진 고객 서비스 봇.
- 시스템 프롬프트에 지식 베이스를 내장한 도메인 특화 어시스턴트.
시나리오 3: 도구 정의 캐싱
에이전트 애플리케이션은 종종 포괄적인 JSON 스키마를 가진 수십 개의 도구를 정의합니다. 이러한 도구 정의는 합쳐서 수천 토큰을 포함할 수 있으며 요청 간에 거의 변경되지 않습니다. 도구 정의 캐싱은 매 턴마다 이 스키마를 다시 처리하는 것을 방지합니다.
설정
toolConfig 내의 tools 배열 마지막 요소로 cachePoint를 추가합니다.
toolConfig = {
"tools": [
{"toolSpec": {"name": "tool_1", "description": "...", "inputSchema": {"json": {...}}}},
{"toolSpec": {"name": "tool_2", "description": "...", "inputSchema": {"json": {...}}}},
{"cachePoint": {"type": "default"}} # 도구 정의 뒤에 배치
]
}
아래 예제는 합쳐서 토큰 임계값을 초과하는 도구 스키마 세트로 이를 보여줍니다.
구현
여기서는 포괄적인 스키마를 가진 우주 테마 도구 세트를 정의합니다. 프로덕션 애플리케이션에서는 API 통합, 데이터베이스 쿼리, 외부 서비스 호출 등이 될 수 있습니다.
TOOLS_LIST = [
{
"name": "analyze_celestial_object",
"description": "Analyzes a celestial object and returns detailed information about its physical properties, composition, orbit, and observational characteristics. Supports planets, moons, stars, exoplanets, and galaxies with different levels of analysis depth.",
"input_schema": {
"type": "object",
"properties": {
"object_name": {
"type": "string",
"description": "The name of the celestial object to analyze (e.g., Mars, Titan, Proxima Centauri)"
},
"object_type": {
"type": "string",
"enum": ["planet", "moon", "star", "exoplanet", "galaxy", "asteroid", "comet", "nebula"],
"description": "The type of celestial object"
},
"analysis_depth": {
"type": "string",
"enum": ["basic", "standard", "comprehensive"],
"description": "Level of analysis detail: basic (overview), standard (main properties), comprehensive (full analysis)"
},
"output_units": {
"type": "object",
"properties": {
"mass": {
"type": "string",
"enum": ["kg", "earth_masses", "solar_masses", "jupiter_masses"],
"description": "Unit for mass measurements"
},
"distance": {
"type": "string",
"enum": ["km", "au", "light_years", "parsecs"],
"description": "Unit for distance measurements"
},
"temperature": {
"type": "string",
"enum": ["celsius", "kelvin", "fahrenheit"],
"description": "Unit for temperature"
}
}
},
"include_history": {
"type": "boolean",
"description": "Include discovery history and important observations"
}
},
"required": ["object_name", "object_type"]
}
},
{
"name": "calculate_orbital_mechanics",
"description": "Performs orbital mechanics calculations including trajectory planning, Hohmann transfers, gravity assists, escape velocity, and orbital position predictions. Essential for space missions and trajectory planning.",
"input_schema": {
"type": "object",
"properties": {
"calculation_type": {
"type": "string",
"enum": ["hohmann_transfer", "gravity_assist", "escape_velocity", "orbital_period", "delta_v"],
"description": "Type of orbital calculation to perform"
},
"origin_body": {
"type": "string",
"description": "Origin celestial body (e.g., Earth, Mars)"
},
"destination_body": {
"type": "string",
"description": "Destination celestial body (optional for some calculations)"
},
"spacecraft_mass": {
"type": "number",
"description": "Spacecraft mass in kilograms"
},
"initial_orbit": {
"type": "object",
"properties": {
"altitude": {"type": "number", "description": "Initial orbit altitude in km"},
"eccentricity": {"type": "number", "description": "Orbital eccentricity (0 = circular)"},
"inclination": {"type": "number", "description": "Orbital inclination in degrees"}
}
},
"target_orbit": {
"type": "object",
"properties": {
"altitude": {"type": "number", "description": "Target orbit altitude in km"},
"eccentricity": {"type": "number", "description": "Orbital eccentricity"},
"inclination": {"type": "number", "description": "Orbital inclination in degrees"}
}
}
},
"required": ["calculation_type", "origin_body"]
}
},
{
"name": "search_exoplanets",
"description": "Searches the confirmed exoplanet catalog based on specific criteria such as habitable zone, size, detection method, distance from Earth, and atmospheric characteristics. Returns updated data from missions like Kepler, TESS, and ground-based observatories.",
"input_schema": {
"type": "object",
"properties": {
"habitable_zone_only": {
"type": "boolean",
"description": "Filter only exoplanets in the habitable zone of their stars"
},
"max_distance_light_years": {
"type": "number",
"description": "Maximum distance from Earth in light-years"
},
"planet_type": {
"type": "array",
"items": {
"type": "string",
"enum": ["terrestrial", "super_earth", "neptune_like", "gas_giant"]
},
"description": "Planet types to include in the search"
},
"detection_method": {
"type": "array",
"items": {
"type": "string",
"enum": ["transit", "radial_velocity", "direct_imaging", "microlensing", "timing"]
},
"description": "Detection methods used"
},
"has_atmosphere_data": {
"type": "boolean",
"description": "Include only planets with available atmospheric data"
},
"sort_by": {
"type": "string",
"enum": ["distance", "discovery_date", "mass", "radius", "temperature"],
"description": "Field for sorting results"
},
"limit": {
"type": "integer",
"description": "Maximum number of results to return",
"minimum": 1,
"maximum": 100
}
},
"required": []
}
},
{
"name": "predict_astronomical_event",
"description": "Predicts future astronomical events such as solar and lunar eclipses, planetary transits, conjunctions, meteor showers, comet passages, and planetary alignments for a specific location on Earth.",
"input_schema": {
"type": "object",
"properties": {
"event_type": {
"type": "array",
"items": {
"type": "string",
"enum": ["solar_eclipse", "lunar_eclipse", "planetary_transit", "conjunction", "meteor_shower", "comet_passage", "planetary_alignment"]
},
"description": "Types of astronomical events to predict"
},
"location": {
"type": "object",
"properties": {
"latitude": {"type": "number", "minimum": -90, "maximum": 90},
"longitude": {"type": "number", "minimum": -180, "maximum": 180},
"city_name": {"type": "string", "description": "City name (alternative to lat/lon)"}
},
"description": "Observer location on Earth"
},
"time_range": {
"type": "object",
"properties": {
"start_date": {"type": "string", "format": "date", "description": "Start date (`YYYY-MM-DD`)"},
"end_date": {"type": "string", "format": "date", "description": "End date (`YYYY-MM-DD`)"}
},
"required": ["start_date", "end_date"]
},
"minimum_visibility": {
"type": "string",
"enum": ["any", "partial", "total", "optimal"],
"description": "Minimum required visibility of the event"
},
"include_times": {
"type": "boolean",
"description": "Include exact start, peak, and end times of the event"
}
},
"required": ["event_type", "time_range"]
}
},
{
"name": "analyze_spectroscopy_data",
"description": "Analyzes spectroscopic data from celestial objects to determine chemical composition, temperature, radial velocity, magnetic field, and other physical properties. Supports spectra from stars, nebulae, galaxies, and planetary atmospheres.",
"input_schema": {
"type": "object",
"properties": {
"spectrum_data": {
"type": "object",
"properties": {
"wavelengths": {
"type": "array",
"items": {"type": "number"},
"description": "Array of wavelengths in nanometers"
},
"intensities": {
"type": "array",
"items": {"type": "number"},
"description": "Array of corresponding intensities"
}
}
},
"object_type": {
"type": "string",
"enum": ["star", "nebula", "galaxy", "planetary_atmosphere", "interstellar_medium"],
"description": "Type of celestial object being analyzed"
},
"analysis_goals": {
"type": "array",
"items": {
"type": "string",
"enum": ["chemical_composition", "temperature", "radial_velocity", "magnetic_field", "rotation_rate", "atmospheric_pressure"]
},
"description": "Specific goals of the spectroscopic analysis"
},
"spectral_resolution": {
"type": "number",
"description": "Spectral resolution in angstroms"
},
"calibration_applied": {
"type": "boolean",
"description": "Indicates whether calibration has already been applied to the data"
}
},
"required": ["object_type", "analysis_goals"]
}
}
# ... 추가 도구
]
Converse API 도구 형식을 구성하고 cachePoint를 추가합니다.
def build_converse_tools():
"""도구 정의를 캐시 포인트가 포함된 Converse API 형식으로 변환합니다."""
tools = []
for tool in TOOLS_LIST:
tools.append({
"toolSpec": {
"name": tool["name"],
"description": tool["description"],
"inputSchema": {"json": tool["input_schema"]}
}
})
# 도구 명세 뒤에 cachePoint 추가
tools.append({"cachePoint": {"type": "default"}})
return tools
def converse_tools_cached(question):
response = bedrock.converse(
modelId=MODEL_ID,
messages=[{"role": "user", "content": [{"text": question}]}],
toolConfig={"tools": build_converse_tools()},
inferenceConfig={"maxTokens": 512}
)
return response["usage"]
# 요청 1: 캐시 쓰기
usage1 = converse_tools_cached("Plan a mission to Europa.")
print("요청 1 (캐시 쓰기 예상):")
print(json.dumps(usage1, indent=2))
time.sleep(1)
# 요청 2: 다른 질문, 동일한 도구 (캐시 읽기)
usage2 = converse_tools_cached("Calculate the escape velocity from Mars.")
print("
요청 2 (캐시 읽기 예상):")
print(json.dumps(usage2, indent=2))
도구 정의 캐싱은 동일한 도구 세트가 여러 대화 턴에 걸쳐 호출되는 에이전트 워크플로에 유용합니다. 도구 스키마를 한 번 캐시하면 매 턴마다 수천 토큰의 스키마 정의를 다시 처리하지 않아도 됩니다.
시나리오 4: 혼합 TTL 캐싱
캐시된 콘텐츠가 단일 수명 주기를 갖는 것은 아닙니다. 핵심 참조 자료(도메인 지식, 제품 카탈로그, 규정 준수 규칙)는 거의 변경되지 않으므로 더 긴 캐시 기간의 이점을 얻습니다. 세션 특정 컨텍스트(최근 대화 턴, 사용자 선호도)는 더 자주 변경되므로 더 짧은 만료의 이점을 얻습니다. 혼합 TTL 캐싱을 사용하면 단일 요청 내에서 서로 다른 콘텐츠 계층에 서로 다른 만료 시간을 할당할 수 있습니다.
접근 방식
각 cachePoint에는 ttl 필드를 포함할 수 있습니다. 한 가지 순서 제약이 있습니다. 더 긴 TTL 체크포인트가 요청에서 더 짧은 것보다 먼저 나타나야 합니다.
content = [
{"text": "<핵심 참조 자료>"},
{"cachePoint": {"type": "default", "ttl": "1h"}}, # 더 긴 TTL이 먼저
{"text": "<세션 특정 컨텍스트>"},
{"cachePoint": {"type": "default", "ttl": "5m"}}, # 더 짧은 TTL이 두 번째
{"text": "<사용자 질문>"}
]
구현
이 시나리오에서는 콘텐츠를 두 계층으로 나눕니다. 1시간 동안 캐시되는 핵심 참조 섹션과 5분 동안 캐시되는 세션 컨텍스트 섹션입니다.
import boto3
import json
import time
MODEL_ID = "global.anthropic.claude-sonnet-4-5-20250929-v1:0"
AWS_REGION = "us-west-2"
CACHE_TTL_LONG = "1h"
CACHE_TTL_SHORT = "5m"
bedrock = boto3.client("bedrock-runtime", region_name=AWS_REGION)
SPACE_SECTION_1 = """
The universe is a vast expanse that humans have studied for thousands of years. From early civilizations that tracked the night sky to modern astronomers using sophisticated telescopes and spacecraft to observe distant galaxies, the pursuit of cosmic knowledge continues. Our solar system, located in the Milky Way, is home to eight planets, numerous dwarf planets, and countless smaller objects including asteroids, comets, and meteoroids. The Sun, a middle-aged G-type main-sequence star, provides the energy that sustains life on Earth and influences the dynamics of all objects within its gravitational reach.
The Sun itself is a fascinating object of study. Its core reaches temperatures of 15 million degrees Celsius, where nuclear fusion converts hydrogen to helium, releasing tremendous amounts of energy. This energy takes thousands of years to travel from the core to the surface, where it finally radiates into space as light and heat. The Sun's surface, called the photosphere, displays a granular texture caused by convection cells of hot plasma rising and cooling. Sunspots, darker regions on the surface, mark areas of intense magnetic activity that can generate solar flares and coronal mass ejections capable of disrupting communications and power grids on Earth.
Mercury, the innermost planet, experiences extreme temperature variations due to its proximity to the Sun and lack of substantial atmosphere. Venus, often called Earth's twin due to its similar size, has a thick atmosphere composed primarily of carbon dioxide, creating a runaway greenhouse effect that makes it the hottest planet in our solar system. Earth, our home, is the only known planet to harbor life, with its unique combination of liquid water, moderate temperatures, and protective magnetic field.
Earth's Moon, our only natural satellite, plays a key role in stabilizing our planet's axial tilt, which maintains relatively stable climate conditions. The Moon's gravitational pull creates tides in Earth's oceans, which have influenced the evolution of coastal ecosystems. The leading theory for the Moon's formation suggests it resulted from a collision between the early Earth and a Mars-sized body called Theia approximately 4.5 billion years ago. This giant impact ejected material into orbit around Earth, which eventually coalesced to form the Moon.
Mars, the Red Planet, has long been a subject of fascination and speculation about the possibility of extraterrestrial life. Its rusty appearance comes from iron oxide prevalent on its surface. The planet features the largest volcano in the solar system, Olympus Mons, and a canyon system, Valles Marineris, that dwarfs the Grand Canyon. Evidence from Mars rovers and orbiters suggests that liquid water once flowed on the Martian surface, carving river valleys and lake beds. Today, water ice exists in the polar caps and possibly in subsurface deposits. The thin atmosphere, composed mainly of carbon dioxide, provides little protection against harmful solar radiation.
The asteroid belt between Mars and Jupiter contains millions of rocky objects, remnants of the early solar system that never coalesced into a planet. The largest object in this belt is Ceres, now classified as a dwarf planet with a diameter of about 940 kilometers. These asteroids range in size from small pebbles to massive bodies hundreds of kilometers in diameter. Scientists study these ancient rocks to understand the conditions that existed during the formation of our solar system approximately 4.6 billion years ago. Some asteroids are composed mainly of rock, others of metal, and some contain significant amounts of water ice and organic compounds.
Jupiter, the king of planets, dominates the outer solar system with its massive size and powerful magnetic field. This gas giant could contain more than 1,300 Earths in its volume. Its iconic Great Red Spot is a storm system that has persisted for at least 350 years, larger than Earth itself. The four largest moons of Jupiter, discovered by Galileo in 1610, constitute a miniature solar system. Europa's subsurface ocean, Io's volcanic activity, Ganymede's magnetic field, and Callisto's ancient cratered surface each tell unique stories about planetary processes.
Jupiter's atmosphere consists primarily of hydrogen and helium, with traces of methane, ammonia, water vapor, and other compounds. The planet's rapid rotation, completing a day in just under 10 hours, creates strong atmospheric currents that produce the characteristic banded appearance. Lightning storms on Jupiter can be thousands of times more powerful than those on Earth. The planet's strong magnetic field, about 20,000 times stronger than Earth's, traps charged particles in radiation belts that would be lethal to unprotected spacecraft and astronauts.
Saturn's magnificent ring system, composed of countless ice and rock particles, extends hundreds of thousands of kilometers into space but is remarkably thin, sometimes less than one kilometer thick. The planet itself is a gas giant with wind speeds that can exceed 1,800 kilometers per hour. Titan, Saturn's largest moon, has a thick nitrogen-rich atmosphere and methane lakes, making it one of the most Earth-like bodies in the solar system despite its frigid temperatures of minus 179 degrees Celsius.
Saturn has at least 146 confirmed moons, each with unique characteristics. Enceladus, a small icy moon, expels geysers of water vapor and ice particles from its south polar region, suggesting a subsurface ocean that could harbor conditions suitable for life. Iapetus displays a striking two-toned appearance with one bright hemisphere and one dark. Mimas features an enormous crater that makes it resemble the Death Star from Star Wars. These diverse moons provide insights into the processes that shape worlds throughout the solar system.
The ice giants Uranus and Neptune represent the outer frontier of our planetary system. Uranus rotates on its side, likely due to a massive collision in its distant past, causing extreme seasonal variations that last decades. Neptune, the windiest planet, displays the fastest wind speeds in the solar system, reaching up to 2,100 kilometers per hour. Both planets have complex ring systems and numerous moons, with Neptune's Triton being particularly interesting due to its retrograde orbit and active nitrogen geysers.
Uranus appears as a featureless blue-green sphere in most images due to methane in its atmosphere absorbing red light. However, recent observations have revealed cloud features and storm systems in its atmosphere. The planet's unusual axial tilt of 98 degrees means its poles alternately point toward and away from the Sun during its 84-year orbit, creating the most extreme seasons in the solar system. Miranda, one of Uranus's moons, displays one of the most bizarre and varied terrains in the solar system, with massive canyons and terraced features suggesting a violent past.
Neptune was discovered in 1846 through mathematical predictions rather than systematic searching, making it the first planet located through theoretical calculations rather than empirical observation. Its deep blue color comes from methane in the atmosphere, similar to Uranus but more vivid. Neptune radiates more heat than it receives from the Sun, suggesting an internal heat source. The planet's largest moon, Triton, orbits in the opposite direction to Neptune's rotation and is slowly spiraling inward, suggesting it was captured from the Kuiper Belt rather than forming alongside the planet.
Beyond Neptune lies the Kuiper Belt, home to Pluto and thousands of other icy bodies. This region extends from about 30 to 55 astronomical units from the Sun and represents the remnants of planetary formation. The discovery of numerous large Kuiper Belt objects in the early 21st century led to Pluto's reclassification as a dwarf planet in 2006, highlighting how our understanding of the solar system continues to evolve. Other notable Kuiper Belt objects include Eris, Makemake, and Haumea, each with unique characteristics that challenge our understanding of planetary formation and evolution.
"""
SPACE_SECTION_2 = """
Exoplanet research has expanded our understanding of planetary systems. The Kepler space telescope discovered thousands of planets orbiting other stars, revealing that planets are common throughout our galaxy. Some of these exoplanets reside in the habitable zone of their stars, where liquid water could exist on the surface. Black holes, regions of spacetime where gravity is so strong that nothing can escape, represent some of the most extreme objects in the universe. Stellar black holes form from the collapse of massive stars, while supermassive black holes, containing millions to billions of solar masses, reside at the centers of most galaxies including our own.
Dark matter and dark energy together comprise about 95% of the universe's total mass-energy content. Dark matter, which does not emit or absorb light, reveals its presence through gravitational effects on visible matter. The study of exoplanets has revealed incredible diversity in planetary systems. Hot Jupiters orbit their stars in just days, tidally locked with permanent day and night sides. Super-Earths, planets larger than Earth but smaller than Neptune, have no analog in our solar system but appear common elsewhere. Some exoplanets orbit binary star systems, experiencing double sunrises like the fictional planet Tatooine. The TESS mission continues to discover new worlds, finding planets around nearby stars that could be studied in detail by future telescopes.
Stellar evolution follows predictable patterns based on a star's initial mass. Low-mass stars like red dwarfs burn their fuel slowly and can shine for trillions of years. Medium-mass stars like our Sun will eventually expand into red giants, engulfing their inner planets before expelling their outer layers to form beautiful planetary nebulae. Massive stars live fast and die young, exploding as supernovae that scatter heavy elements into space, enriching the interstellar medium with the building blocks for new stars and planets.
Neutron stars, the collapsed cores of massive stars, pack more mass than the Sun into a sphere just 20 kilometers in diameter. Their density is so extreme that a teaspoon of neutron star material would weigh about a billion tons on Earth. Some neutron stars spin rapidly and emit beams of radiation, appearing as pulsars that flash with incredible precision. Others exist in binary systems, slowly accreting matter from companion stars and occasionally erupting in thermonuclear explosions visible across the galaxy.
Galaxies come in many shapes and sizes. Spiral galaxies like the Milky Way feature spiral arms of stars, gas, and dust rotating around dense central bulges. Elliptical galaxies appear as featureless blobs of old stars with little ongoing star formation. Irregular galaxies lack organized structure, often disturbed by gravitational interactions with neighbors. The largest galaxies contain trillions of stars, while dwarf galaxies may host only a few billion. Galaxy collisions, though violent on cosmic scales, rarely involve actual stellar collisions due to the vast spaces between stars.
The universe began approximately 13.8 billion years ago in the Big Bang, an event that created space, time, matter, and energy. In the first fraction of a second, the universe underwent rapid inflation, expanding faster than the speed of light and setting the stage for structure formation. As the universe cooled, fundamental particles formed, then atomic nuclei and eventually neutral atoms. The cosmic microwave background radiation, discovered in 1965, provides a snapshot of the universe when it was just 380,000 years old, showing tiny density variations that would eventually grow into galaxies and galaxy clusters.
Dark energy, discovered through observations of distant supernovae, is causing the accelerated expansion of the universe. This mysterious force, comprising about 68% of the universe's energy content, works against gravity on cosmic scales. Its nature remains one of the greatest enigmas in physics. Dark matter, constituting about 27% of the universe, reveals itself through gravitational effects but has never been directly detected. Numerous experiments worldwide search for dark matter particles, hoping to solve this cosmic mystery.
Gravitational waves, ripples in spacetime predicted by Einstein's general relativity, were first detected in 2015 by the LIGO observatory. These waves carry information about the most violent cosmic events: black hole collisions, neutron star mergers, and possibly echoes of the Big Bang itself. Their detection opened a new window for observing the universe, complementing traditional electromagnetic astronomy and allowing scientists to study phenomena previously invisible to telescopes.
"""
QUESTION = "Based on the context above about space, what are some key facts about Mars?"
def converse_mixed_ttl():
content = [
{"text": SPACE_SECTION_1},
{"cachePoint": {"type": "default", "ttl": CACHE_TTL_LONG}},
{"text": SPACE_SECTION_2},
{"cachePoint": {"type": "default", "ttl": CACHE_TTL_SHORT}},
{"text": QUESTION}
]
response = bedrock.converse(
modelId=MODEL_ID,
messages=[{"role": "user", "content": content}],
inferenceConfig={"maxTokens": 512}
)
return response["usage"]
# 요청 1: 캐시 쓰기
usage1 = converse_mixed_ttl()
print("요청 1 (캐시 쓰기 예상):")
print(json.dumps(usage1, indent=2))
time.sleep(1)
# 요청 2: 캐시 읽기
usage2 = converse_mixed_ttl()
print("
요청 2 (캐시 읽기 예상):")
print(json.dumps(usage2, indent=2))
cacheDetails 이해하기
Converse API 응답에는 TTL별 토큰 내역을 보여주는 cacheDetails 필드가 포함됩니다. 이를 통해 두 TTL 계층이 모두 올바르게 작동하는지 확인할 수 있습니다. 두 섹션이 각각 모델의 최소 토큰 임계값을 초과하면 TTL마다 하나의 항목이 표시됩니다.
"cacheDetails": [
{"ttl": "1h", "inputTokens": 1547},
{"ttl": "5m", "inputTokens": 1823}
]
섹션 하나만 임계값을 초과하면 응답에는 단일 TTL 항목만 표시됩니다. 각 TTL에 대해 별도의 캐시 항목을 얻으려면 각 콘텐츠 계층이 독립적으로 모델의 최소 토큰 요구 사항을 충족해야 합니다.
TTL 순서 제약
캐시 체크포인트는 단일 요청 내에서 가장 긴 TTL에서 가장 짧은 TTL 순으로 정렬되어야 합니다. 더 긴 TTL 앞에 더 짧은 TTL이 나타나면 API는 오류를 반환합니다.
- ✅ 유효:
1h다음5m. - ❌ 무효:
5m다음1h.
이 제약은 캐시 체크포인트 위치(메시지, 시스템 프롬프트, 도구 정의) 전반에 적용됩니다.
혼합 TTL을 사용해야 하는 경우
다음 표는 콘텐츠가 얼마나 자주 변경되는지를 기준으로 콘텐츠 유형을 권장 TTL에 매핑한 것입니다.
| 콘텐츠 유형 | 권장 TTL | 예시 |
|---|---|---|
| 도메인 지식 | 1시간 | 제품 카탈로그, 규정 준수 규칙, 참조 문서 |
| 세션 컨텍스트 | 5분 | 최근 대화 턴, 사용자 선호도, 세션 상태 |
| 도구 정의 | 1시간 | 거의 변경되지 않는 API 스키마, 함수 시그니처 |
| 동적 데이터 | 캐싱 안 함 | 실시간 데이터, 사용자별 쿼리 |
혼합 TTL을 적용한 다음 시나리오에서는 흔한 멀티테넌트 과제, 즉 한 테넌트의 캐시된 콘텐츠를 다른 테넌트가 읽지 못하게 하는 문제를 다룹니다.
시나리오 5: 테넌트 격리
멀티테넌트 애플리케이션에서는 한 테넌트의 캐시된 콘텐츠를 다른 테넌트가 읽지 못하도록 해야 합니다. Amazon Bedrock의 프롬프트 캐싱은 계정과 리전을 기준으로 항목의 범위를 정하지만, 동일한 계정 및 리전 내에서는 캐시 항목이 요청 간에 공유될 수 있습니다. SHA-256 해시 접두사 패턴은 별도의 AWS 계정 없이 약 16토큰의 오버헤드만으로 테넌트 격리를 제공합니다.
패턴
tenant_id의 SHA-256 해시를 캐시된 콘텐츠 앞에 붙입니다. 해시가 콘텐츠 접두사를 변경하므로, Amazon Bedrock은 테넌트마다 별도의 캐시 항목을 생성합니다.
import hashlib
sha256_hash = hashlib.sha256(tenant_id.encode()).hexdigest()
instructions = f"{sha256_hash}:{instructions}"
구현
다음 함수는 캐시된 콘텐츠에 SHA-256 테넌트 접두사를 적용합니다.
import hashlib
def chat_with_document(document, user_query, tenant_id):
"""테넌트 격리 프롬프트 캐싱을 사용해 문서와 대화합니다."""
instructions = INSTRUCTIONS # 상세 분석 지침
if tenant_id:
sha256_hash = hashlib.sha256(tenant_id.encode()).hexdigest()
instructions = f"{sha256_hash}:{instructions}"
document_content = f"Here is the document: <document>{document}</document>"
response = bedrock.converse(
modelId=MODEL_ID,
messages=[{
"role": "user",
"content": [
{"text": instructions},
{"text": document_content},
{"cachePoint": {"type": "default"}},
{"text": user_query}
]
}],
inferenceConfig={"maxTokens": 500, "temperature": 0}
)
usage = response["usage"]
text = response["output"]["message"]["content"][0]["text"]
return usage, text
테넌트 전반의 격리 동작을 확인할 수 있습니다.
# 테넌트 1: 첫 번째 요청 (캐시 쓰기)
usage, _ = chat_with_document(DOCUMENT, "What is prompt caching?", tenant_id="tenant1")
print("테넌트 1, 요청 1 (캐시 쓰기 예상):")
print(json.dumps(usage, indent=2))
# 테넌트 1: 두 번째 요청 (캐시 읽기)
usage, _ = chat_with_document(DOCUMENT, "What are the use cases?", tenant_id="tenant1")
print("테넌트 1, 요청 2 (캐시 읽기 예상):")
print(json.dumps(usage, indent=2))
# 테넌트 2: 첫 번째 요청 (별도의 캐시 쓰기)
usage, _ = chat_with_document(DOCUMENT, "What is prompt caching?", tenant_id="tenant2")
print("테넌트 2, 요청 1 (캐시 쓰기 예상, tenant1과 분리):")
print(json.dumps(usage, indent=2))
# 테넌트 2: 두 번째 요청 (tenant2의 캐시에서 읽기)
usage, _ = chat_with_document(DOCUMENT, "What are the use cases?", tenant_id="tenant2")
print("테넌트 2, 요청 2 (캐시 읽기 예상):")
print(json.dumps(usage, indent=2))
네 개 요청에 걸친 예상 동작은 다음과 같습니다.
| 요청 | 테넌트 | 예상 캐시 동작 |
|---|---|---|
| 1 | tenant1 | cacheWriteInputTokens > 0 (새 캐시 항목) |
| 2 | tenant1 | cacheReadInputTokens > 0 (tenant1의 캐시 재사용) |
| 3 | tenant2 | cacheWriteInputTokens > 0 (다른 해시 접두사로 새 항목) |
| 4 | tenant2 | cacheReadInputTokens > 0 (tenant2의 캐시 재사용) |
이 패턴은 세 가지 이점을 제공합니다.
- 서버 측 구성 불필요: 콘텐츠 접두사만으로 격리를 달성합니다.
- 테넌트별 독립적인 캐시 항목: 각 테넌트의 캐시된 콘텐츠가 분리되어 유지됩니다.
- 최소한의 오버헤드: SHA-256 해시는 프롬프트에 64자(약 16토큰)만 추가합니다.
시나리오 6: LangChain 통합
LangChain 프레임워크를 사용하는 팀에게 프롬프트 캐싱은 ChatBedrockConverse 클래스와 통합됩니다. LangChain은 원시 API 형식을 관리하지 않고도 올바른 cachePoint 콘텐츠 블록을 생성하는 create_cache_point() 메서드를 제공합니다.
사용법
메시지 콘텐츠 배열이나 ChatPromptTemplate 정의 내에서 ChatBedrockConverse.create_cache_point()를 사용합니다.
from langchain_aws import ChatBedrockConverse
from langchain_core.messages import HumanMessage, SystemMessage
HumanMessage(content=[
{"type": "text", "text": "<문서 콘텐츠>"},
ChatBedrockConverse.create_cache_point() # {"cachePoint": {"type": "default"}}를 생성
])
구현: 직접 메시지 구성
다음 예제는 문서를 캐시하고 프롬프트 캐싱을 활성화한 상태로 질문합니다.
import boto3
import json
import time
from langchain_aws import ChatBedrockConverse
from langchain_core.messages import HumanMessage, SystemMessage
MODEL_ID = "global.anthropic.claude-sonnet-4-5-20250929-v1:0"
AWS_REGION = "us-west-2"
DOCUMENT = """
The universe is a vast and mysterious expanse that has captivated human imagination for millennia. From the earliest civilizations who looked up at the night sky and wondered about the nature of the stars, to modern astronomers using sophisticated telescopes and spacecraft to explore distant galaxies, our quest to understand the cosmos continues unabated. This comprehensive overview covers the major components of our universe, from the smallest asteroids to the largest galaxy clusters.
Our solar system, located in the Milky Way galaxy, is home to eight planets, numerous dwarf planets, and countless smaller objects including asteroids, comets, and meteoroids. The Sun, a middle-aged G-type main-sequence star, provides the energy that sustains life on Earth and influences the dynamics of all objects within its gravitational reach.
Mercury, the innermost planet, experiences extreme temperature variations due to its proximity to the Sun and lack of substantial atmosphere. Venus, often called Earth's twin due to its similar size, has a thick atmosphere composed primarily of carbon dioxide, creating a runaway greenhouse effect that makes it the hottest planet in our solar system. Earth, our home, is the only known planet to harbor life, with its unique combination of liquid water, moderate temperatures, and protective magnetic field.
Mars, the Red Planet, has long been a subject of fascination and speculation about the possibility of extraterrestrial life. Its rusty appearance comes from iron oxide prevalent on its surface. The planet features the largest volcano in the solar system, Olympus Mons, and a canyon system, Valles Marineris, that dwarfs the Grand Canyon. Recent Mars missions have discovered evidence of ancient river systems and the presence of water ice beneath the surface.
The asteroid belt, located between Mars and Jupiter, contains millions of rocky objects ranging from small boulders to the dwarf planet Ceres. These remnants from the early solar system provide valuable insights into planetary formation and the conditions that existed billions of years ago. Scientists study these asteroids to understand the building blocks of planets and the early solar system's chemical composition. Some asteroids contain valuable metals and minerals that may one day be mined for space-based industries.
The terrestrial planets share common characteristics: rocky compositions, relatively small sizes compared to gas giants, and solid surfaces. Mercury's heavily cratered surface resembles our Moon, preserving a record of impacts from the early solar system. Venus's dense atmosphere traps heat so effectively that its surface temperature exceeds that of Mercury, despite being farther from the Sun. Earth's plate tectonics continuously reshape its surface, while Mars shows evidence of past geological activity including ancient volcanoes and water-carved channels.
Jupiter, the largest planet, is a gas giant composed primarily of hydrogen and helium. Its Great Red Spot, a persistent anticyclonic storm, has been observed for over 400 years. Jupiter's intense magnetic field and numerous moons, including the four Galilean satellites discovered by Galileo Galilei in 1610, make it a miniature solar system in its own right. Europa, one of these moons, is believed to have a subsurface ocean that could potentially harbor life.
Saturn, famous for its spectacular ring system, is another gas giant with dozens of moons. Titan, its largest moon, has a thick atmosphere and liquid hydrocarbon lakes, making it one of the most intriguing bodies in the solar system for astrobiological research. The Cassini-Huygens mission provided unprecedented details about Saturn and its moons during its 13-year exploration.
Uranus and Neptune, the ice giants, reside in the outer reaches of our solar system. Uranus rotates on its side, likely due to a massive impact early in its history. Neptune, the windiest planet, features storms with wind speeds exceeding 2,000 kilometers per hour. Both planets have ring systems, though less prominent than Saturn's.
Beyond Neptune lies the Kuiper Belt, a region populated by icy bodies including the dwarf planet Pluto. The New Horizons mission's flyby of Pluto in 2015 revealed a geologically active world with nitrogen glaciers and a hazy atmosphere. Even further out is the Oort Cloud, a hypothetical spherical shell of icy objects that may extend halfway to the nearest star.
The outer solar system remains largely unexplored compared to the inner planets. Only Voyager 2 has visited both Uranus and Neptune, conducting brief flybys in the 1980s. Future missions are being planned to study these ice giants in more detail, potentially including orbiters and atmospheric probes. The moons of the outer planets present exciting targets for astrobiology, with Europa, Enceladus, and Titan all showing signs of environments that could support life.
Gas giants and ice giants differ fundamentally in composition. While Jupiter and Saturn are primarily hydrogen and helium, Uranus and Neptune contain significant amounts of water, ammonia, and methane ices. This distinction gives the ice giants their characteristic blue-green colors and different internal structures compared to their larger neighbors.
Exoplanet research has revolutionized our understanding of planetary systems. The Kepler space telescope discovered thousands of planets orbiting other stars, revealing that planets are common throughout our galaxy. Some of these exoplanets reside in the habitable zone of their stars, where liquid water could exist on the surface.
The search for extraterrestrial intelligence, known as SETI, uses radio telescopes to listen for signals from advanced civilizations. While no definitive signals have been detected, the Drake Equation provides a framework for estimating the number of communicating civilizations in our galaxy.
Black holes, regions of spacetime where gravity is so strong that nothing can escape, represent some of the most extreme objects in the universe. Stellar black holes form from the collapse of massive stars, while supermassive black holes, containing millions to billions of solar masses, reside at the centers of most galaxies including our own.
The James Webb Space Telescope, launched in 2021, observes in infrared to study the earliest galaxies and probe planetary atmospheres for signs of life. Understanding the universe requires collaboration across disciplines including physics, chemistry, biology, and engineering.
Stellar evolution describes how stars change over their lifetimes. Stars form in molecular clouds when gravity causes dense regions to collapse. Nuclear fusion in the core converts hydrogen to helium, releasing enormous amounts of energy. When stars exhaust their nuclear fuel, their fate depends on their mass: smaller stars become white dwarfs, medium stars may become neutron stars, and the most massive stars explode as supernovae, potentially leaving behind black holes.
Galaxies, containing billions of stars, come in various shapes including spiral, elliptical, and irregular. The Milky Way is a barred spiral galaxy approximately 100,000 light-years in diameter. Galaxies often cluster together, forming groups and superclusters connected by cosmic filaments of dark matter and gas. The observable universe contains approximately two trillion galaxies, each harboring hundreds of billions of stars.
The cosmic microwave background radiation, discovered in 1965, provides a snapshot of the universe approximately 380,000 years after the Big Bang. Detailed measurements of this radiation have confirmed the Big Bang theory and revealed information about the early universe's composition and geometry. Dark matter and dark energy together comprise about 95% of the universe's total mass-energy content.
Space exploration has achieved remarkable milestones since the launch of Sputnik in 1957. Human spaceflight began with Yuri Gagarin's orbit in 1961 and culminated in the Apollo Moon landings. The International Space Station has hosted continuous human presence in space since 2000. Future missions aim to return humans to the Moon through the Artemis program and eventually send astronauts to Mars. Private space companies have transformed the industry, developing reusable rockets that have dramatically reduced launch costs.
The study of astrobiology examines the origin, evolution, and distribution of life in the universe. Scientists search for biosignatures in planetary atmospheres and analyze extremophiles on Earth to understand the limits of life. The discovery of organic molecules on Mars and in the plumes of Enceladus fuels speculation about the possibility of life elsewhere in our solar system. Modern telescopes have detected exoplanets using multiple methods including transit photometry, radial velocity measurements, and direct imaging.
Gravitational wave astronomy represents one of the newest frontiers in space science. The LIGO and Virgo detectors have observed mergers of black holes and neutron stars, confirming predictions from Einstein's general theory of relativity. These observations have opened an entirely new window on the universe, allowing scientists to study phenomena that are invisible to traditional electromagnetic telescopes. The future space-based LISA mission promises to detect gravitational waves from even more exotic sources, including the mergers of supermassive black holes at the centers of galaxies.
"""
llm = ChatBedrockConverse(
model_id="global.anthropic.claude-sonnet-4-5-20250929-v1:0",
region_name="us-west-2",
temperature=0,
max_tokens=1000
)
def chat_with_cache(question):
"""프롬프트 캐싱을 활성화한 상태로 문서에 대한 질문을 보냅니다."""
messages = [
SystemMessage(content="You are a helpful assistant that answers questions about documents."),
HumanMessage(content=[
{"type": "text", "text": f"Here is a document: {DOCUMENT}"},
ChatBedrockConverse.create_cache_point()
]),
HumanMessage(content=question)
]
response = llm.invoke(messages)
return response
# 요청 1: 캐시 쓰기
r1 = chat_with_cache("What are the ice giant planets?")
print(f"응답: {r1.content[:200]}...")
print(f"사용량: {json.dumps(r1.usage_metadata, indent=2, default=str)}")
구현: 캐시 포인트가 있는 LCEL 체인
재사용 가능한 체인 패턴의 경우 ChatPromptTemplate에 캐시 포인트를 직접 통합할 수 있습니다.
import boto3
import json
import time
from langchain_aws import ChatBedrockConverse
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
MODEL_ID = "global.anthropic.claude-sonnet-4-5-20250929-v1:0"
AWS_REGION = "us-west-2"
template = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant that answers questions about documents."),
("human", [
{"type": "text", "text": f"Here is a document: {DOCUMENT}"},
ChatBedrockConverse.create_cache_point()
]),
("human", "{question}")
])
chain = template | llm | StrOutputParser()
# 여러 질문 실행: 첫 번째는 캐시에 쓰고, 이후에는 캐시에서 읽음
questions = [
"What are the ice giant planets?",
"What discoveries has New Horizons made?",
"How does Jupiter's Great Red Spot compare to storms on Earth?",
]
for i, q in enumerate(questions):
start = time.time()
result = chain.invoke({"question": q})
elapsed = time.time() - start
print(f"
Q{i+1}: {q}")
print(f"A: {result[:150]}...")
print(f"시간: {elapsed:.2f}s")
time.sleep(0.5)
LangChain에서 캐시 지표 확인하기
응답 객체의 usage_metadata에는 캐시 전용 필드가 담긴 input_token_details가 포함됩니다.
cache_creation: 캐시에 기록된 토큰(첫 번째 요청)cache_read: 캐시에서 읽은 토큰(이후 요청)
r = llm.invoke(messages)
print(json.dumps(r.usage_metadata, indent=2, default=str))
Converse API와 InvokeModel API 비교
이 글의 시나리오는 모델 독립적인 cachePoint 구문을 제공하는 Converse API를 사용합니다. 애플리케이션에서 InvokeModel API를 사용한다면 캐싱 구문이 모델 패밀리별로 다르다는 점에 유의하세요.
| 기능 | Converse API(지원 모델) | InvokeModel API(Anthropic) |
|---|---|---|
| 캐시 마커 | {"cachePoint": {"type": "default"}} |
"cache_control": {"type": "ephemeral", "ttl": "5m"} |
| 배치 위치 | 캐시된 콘텐츠 뒤의 독립형 콘텐츠 블록 | 캐시되는 콘텐츠 블록 내부 |
| TTL 지원 | {"cachePoint": {"type": "default", "ttl": "1h"}} |
cache_control 내부의 "ttl" 필드 |
cacheDetails 응답 |
예 | 아니요 |
| 사용량 키 형식 | cacheWriteInputTokens |
cache_creation_input_tokens |
새 애플리케이션에는 Converse API를 사용하세요. cachePoint 구문이 지원되는 모델 패밀리 전반에서 동일하게 동작하므로, 캐싱 코드를 변경하지 않고도 Anthropic Claude와 Amazon Nova 사이를 전환할 수 있습니다.
모범 사례
이 글에서 보여준 패턴을 바탕으로, 프로덕션 배포에 다음과 같은 모범 사례를 권장합니다.
- 프롬프트 프로파일링: 어떤 구성 요소가 정적인지(시스템 프롬프트, 도구 스키마, 참조 문서), 어떤 것이 동적인지(사용자 질문, 세션 컨텍스트) 식별하세요. 정적인 구성 요소를 캐시합니다.
- 토큰 임계값 충족: 각 캐시 체크포인트는 모델의 최소 토큰 요구 사항을 초과해야 합니다. Amazon Bedrock은 임계값 미만의 콘텐츠를 캐싱 없이 정상적으로 처리합니다.
- 적절한 TTL 선택: 거의 변경되지 않는 콘텐츠(도메인 지식, 도구 정의)에는 1시간 TTL을, 세션 특정 컨텍스트에는 5분 TTL을 사용하세요. 더 긴 TTL이 더 짧은 것보다 먼저 와야 한다는 점을 기억하세요.
- 캐시 지표 모니터링: 애플리케이션 로그에서
cacheWriteInputTokens와cacheReadInputTokens를 추적하세요. 낮은 캐시 적중률은 콘텐츠가 너무 자주 변경되거나 TTL이 너무 짧다는 신호일 수 있습니다. - 책임 있는 AI 제어 적용: 프로덕션 배포에서는 Amazon Bedrock Guardrails를 사용해 캐싱 패턴과 함께 콘텐츠 필터링 및 그라운딩 검증을 추가하세요.
- 멀티테넌트 시스템의 테넌트 격리 구현: 동일한 AWS 계정에서 여러 고객에게 서비스를 제공할 때 테넌트 간 캐시 공유를 방지하려면 SHA-256 해시 접두사 패턴을 사용하세요.
- 간소화된 캐시 관리 활용: Anthropic Claude 모델의 경우 단일
cachePoint가 여러 선행 콘텐츠 블록을 커버할 수 있습니다. 항상 모든 섹션 뒤에 체크포인트를 배치할 필요는 없습니다. - 캐싱 위치 결합: 단일 요청에서 시스템 프롬프트, 메시지 콘텐츠, 도구 정의를 동시에 캐시할 수 있습니다. 이렇게 하면 세 위치의 절감 효과가 누적됩니다.
정리
이 글의 예제는 Amazon Bedrock 온디맨드 추론을 사용하며 영구적인 AWS 리소스를 생성하지 않습니다. 실행 중인 Jupyter 노트북 커널을 중지하는 것 외에는 별도의 정리가 필요하지 않습니다.
결론
이 글에서는 Amazon Bedrock Converse API를 사용한 여섯 가지 실용적인 프롬프트 캐싱 시나리오를 기본 문서 캐싱부터 혼합 TTL 및 테넌트 격리 같은 고급 패턴까지 살펴보았습니다. 각 시나리오는 특정 프로덕션 과제를 해결합니다.
- 동일한 문서에 여러 질문을 할 때 콘텐츠를 캐시하여 비용을 절감합니다.
- 매 대화 턴마다 상세한 페르소나 정의를 다시 처리하지 않도록 프롬프트를 재사용합니다.
- 도구 스키마를 한 번 효율적으로 캐시하여 에이전트 워크플로를 최적화합니다.
- 업데이트 빈도가 다른 콘텐츠에 대해 캐시 수명을 세밀하게 제어하도록 혼합 TTL을 조정합니다.
- 테넌트별 캐시 분리로 안전한 멀티테넌트 배포를 위한 테넌트 캐시를 격리합니다.
- 최소한의 코드 변경으로 프레임워크에 프롬프트 캐싱을 도입하도록 LangChain과 통합합니다.
cachePoint 구문은 Converse API 전반에서 모델 독립적입니다. 동일한 코드가 Anthropic Claude, Amazon Nova, 그리고 Amazon Bedrock에서 프롬프트 캐싱을 지원하는 기타 지원 모델에서 동작합니다. 프롬프트 캐싱은 워크로드에 가장 임팩트가 큰 시나리오부터 시작해 필요에 따라 추가 패턴으로 확장하며 점진적으로 도입할 수 있습니다.
다음 단계로, 기존 Amazon Bedrock 애플리케이션을 프로파일링하여 프롬프트 캐싱 기회를 식별하세요. 워크로드에 맞는 시나리오(문서 분석, 페르소나 기반 어시스턴트, 에이전트 도구 사용)부터 시작해 TTFT와 비용 개선을 측정하세요. 각 시나리오에는 Amazon Bedrock에 즉시 실행할 수 있는 동작하는 코드가 포함되어 있습니다. 이 글 전체에서 참조한 노트북과 스크립트의 전체 세트는 amazon-bedrock-samples GitHub 저장소에서 확인할 수 있습니다. 프롬프트 캐싱 구성과 지원 모델에 대한 자세한 내용은 Amazon Bedrock 프롬프트 캐싱 설명서를 참조하세요. 시작하려면 Amazon Bedrock을 방문하거나 Amazon Bedrock 콘솔을 열어 모델 액세스를 활성화하고 애플리케이션에서 프롬프트 캐싱을 사용하세요.
작성자 정보
Daniel Abib — 2026년 9월 15일 게시
리소스
- 시작하기
- 새 소식
