AgentCore 결제를 위한 프레임워크 통합
AgentCore 결제는 인기 있는 에이전트 프레임워크와 통합되어 자동화된 결제 처리를 제공합니다. 각 프레임워크는 서로 다른 통합 패턴을 사용합니다.
-
Strands Agents - 후크를 사용한 플러그인 기반 통합
-
LangGraph - 도구 호출을 래핑하는 미들웨어 기반 통합
Strands Agents
AgentCore 결제 플러그인은 Strands Agents에 대한 자동 결제 처리를 제공합니다. 에이전트가 HTTP 402 응답을 자동으로 처리할 수 있도록 x402 Payment Required
설치
pip install 'bedrock-agentcore[strands-agents]'
플러그인 구성 및 사용
from strands import Agent from strands_tools import http_request from bedrock_agentcore.payments.integrations.config import AgentCorePaymentsPluginConfig from bedrock_agentcore.payments.integrations.strands.plugin import AgentCorePaymentsPlugin # Configure the plugin config = AgentCorePaymentsPluginConfig( payment_manager_arn="arn:aws:bedrock-agentcore:us-west-2:123456789012:payment-manager/pm-abc123", user_id="test-user-123", payment_instrument_id="payment-instrument-XJU4RSQP9VO0ler", payment_session_id="payment-session-xuzrnUCd7RT725G", region="us-west-2", ) # Create the plugin plugin = AgentCorePaymentsPlugin(config=config) # Create agent with the plugin agent = Agent( system_prompt="You are a helpful assistant that can access paid APIs.", tools=[http_request], plugins=[plugin], ) # Use the agent -- 402 responses are automatically handled agent("access https://drvd12nxpcyd5.cloudfront.net/market-recap")
결제 중단 처리
결제 처리가 실패하면 플러그인이 실패를 저장하고 중단이 발생합니다. 애플리케이션은 다음과 같은 인터럽트를 처리해야 합니다.
result = agent("Access the premium endpoint at https://api.example.com/premium") while result.stop_reason == "interrupt": responses = [] for interrupt in result.interrupts: if interrupt.name.startswith("payment-failure-"): reason = interrupt.reason exception_type = reason.get("exceptionType") if exception_type == "PaymentInstrumentConfigurationRequired": plugin.config.update_payment_instrument_id("payment-instrument-new123") responses.append({ "interruptResponse": { "interruptId": interrupt.id, "response": "Payment instrument configured. Please retry.", } }) elif exception_type == "PaymentSessionConfigurationRequired": plugin.config.update_payment_session_id("payment-session-new456") responses.append({ "interruptResponse": { "interruptId": interrupt.id, "response": "Payment session configured. Please retry.", } }) else: responses.append({ "interruptResponse": { "interruptId": interrupt.id, "response": f"Payment failed: {reason.get('exceptionMessage')}", } }) result = agent(responses)
자동 결제 비활성화
자동 결제 실행 없이 결제 가시성 도구에만 액세스하려면(예: 결제 트랜잭션 전에 인적 또는 사용자 지정 로직을 루프에 유지하려면) 자동 처리를 비활성화합니다.
config = AgentCorePaymentsPluginConfig( payment_manager_arn="arn:aws:bedrock-agentcore:us-east-1:123456789012:payment-manager/pm-abc123", user_id="user-123", region="us-east-1", auto_payment=False, # Disable automatic 402 processing )
네트워크 기본 설정
결제 처리를 위해 선호하는 블록체인 네트워크를 지정할 수 있습니다.
config = AgentCorePaymentsPluginConfig( payment_manager_arn="arn:aws:bedrock-agentcore:us-east-1:123456789012:payment-manager/pm-abc123", user_id="user-123", payment_instrument_id="payment-instrument-xyz789", payment_session_id="payment-session-def456", region="us-east-1", network_preferences_config=["eip155:8453", "base-sepolia", "solana-mainnet"], )
지정하지 않으면 시스템은 낮은 트랜잭션 요금으로 Solana 메인넷 및 기본(이더리움 L2) 우선 순위를 지정하는 기본 기본 기본 설정 순서를 사용합니다.
구성 옵션
다음 표에는 AgentCorePaymentsPluginConfig 파라미터가 나열되어 있습니다.
| 파라미터 | 유형 | 필수 | 설명 |
|---|---|---|---|
|
|
|
예 |
Bedrock AgentCore Payment Manager 리소스의 ARN |
|
|
|
예 |
사용자의 고유 식별자 |
|
|
|
아니요 |
결제 수단 ID입니다. 나중에를 통해 설정할 수 있습니다. |
|
|
|
아니요 |
결제 세션 ID입니다. 나중에를 통해 설정할 수 있습니다. |
|
|
|
아니요 |
AWS 결제 관리자의 리전 |
|
|
|
아니요 |
기본 설정 순서대로 네트워크 CAIP-2 식별자 목록 |
|
|
|
아니요 (기본값: |
402 결제 요구 사항을 자동으로 처리할지 여부 |
|
|
|
아니요 (기본값: |
도구 사용당 최대 인터럽트 재시도 횟수입니다. 인터럽트를 비활성화하려면 0으로 설정합니다. |
|
|
|
아니요 |
API 호출 시 HTTP 헤더를 통해 전파되는 에이전트 이름 |
기본 제공 에이전트 도구
플러그인은 에이전트가 런타임에 결제 정보를 쿼리하는 데 사용할 수 있는 세 가지 도구를 등록합니다.
| 도구 | 설명 |
|---|---|
|
|
특정 결제 수단에 대한 세부 정보 검색 |
|
|
사용자의 모든 결제 수단 나열 |
|
|
결제 세션에 대한 세부 정보 검색(예산, 상태, 만료) |
이러한 도구를 사용하면 에이전트가 대화 중에 결제 방법 및 결제 한도에 대해 정보에 입각한 결정을 내릴 수 있습니다. 자세한 내용과 end-to-end 예제는 Strands Agents
LangGraph
AgentCore 결제 미들웨어는 LangGraph 에이전트를 위한 자동 결제 처리를 제공합니다. 에이전트가 HTTP 402 응답을 자동으로 처리할 수 있도록 x402 Payment Required
설치
pip install 'bedrock-agentcore[langgraph]'
미들웨어 구성 및 사용
from langchain.agents import create_agent from bedrock_agentcore.payments.integrations.langgraph import ( AgentCorePaymentsConfig, AgentCorePaymentsMiddleware, ) config = AgentCorePaymentsConfig( payment_manager_arn="arn:aws:bedrock-agentcore:us-west-2:123456789012:payment-manager/pm-abc123", user_id="test-user-123", payment_instrument_id="payment-instrument-XJU4RSQP9VO0ler", region="us-west-2", auto_session=True, ) payments = AgentCorePaymentsMiddleware(config) agent = create_agent( model="us.anthropic.claude-sonnet-4-20250514-v1:0", tools=[], middleware=[payments], ) result = agent.invoke({"messages": [{"role": "user", "content": "access https://drvd12nxpcyd5.cloudfront.net/market-recap"}]}) print(result)
미들웨어 작동 방식
미들웨어는 도구 호출을 가로채고 6단계로 x402 결제 흐름을 처리합니다.
-
에이전트는 유료 엔드포인트에 대한 HTTP 요청을 생성하는 도구 호출을 수행합니다.
-
엔드포인트는 HTTP 402 결제 필요 및 x402 결제 페이로드로 응답합니다.
-
미들웨어는 402 응답을 가로채고 결제 요구 사항을 추출합니다.
-
미들웨어는 결제 수단 및 세션을
ProcessPayment호출하여 암호화 증명을 생성합니다. -
미들웨어는 결제 증명 헤더가 연결된 상태에서 원래 요청을 재시도합니다.
-
엔드포인트는 증거를 검증하고 요청된 콘텐츠를 에이전트에게 반환합니다.
콜백을 사용한 오류 처리
on_payment_error 콜백을 사용하여 결제 실패를 정상적으로 처리합니다.
from bedrock_agentcore.payments.integrations.langgraph import ( AgentCorePaymentsConfig, AgentCorePaymentsMiddleware, ErrorResolution, ) def handle_payment_error(error, context): """Custom error handler for payment failures.""" if "InsufficientFunds" in str(error): return ErrorResolution.STOP # Stop the agent return ErrorResolution.RETRY # Retry with updated config config = AgentCorePaymentsConfig( payment_manager_arn="arn:aws:bedrock-agentcore:us-west-2:123456789012:payment-manager/pm-abc123", user_id="test-user-123", payment_instrument_id="payment-instrument-XJU4RSQP9VO0ler", region="us-west-2", auto_session=True, on_payment_error=handle_payment_error, )
ErrorResolution 열거형은 다음 옵션을 제공합니다.
| 값 | 동작 |
|---|---|
|
|
현재 구성으로 결제 재시도 |
|
|
처리를 중지하고 오류를 에이전트에 반환합니다. |
|
|
결제를 건너뛰고 유료 콘텐츠 없이 계속하기 |
자동 결제 비활성화
자동 결제 처리를 비활성화하고 명시적 결제 승인을 요구하는 방법:
config = AgentCorePaymentsConfig( payment_manager_arn="arn:aws:bedrock-agentcore:us-west-2:123456789012:payment-manager/pm-abc123", user_id="test-user-123", region="us-west-2", auto_payment=False, # Disable automatic 402 processing )
auto_payment가 인 경우 미들웨어False는 에이전트에 대한 응답을 처리하지 않고 402개의 응답을 표시하므로 결제 전에 사용자 지정 로직 또는 인적 승인을 허용합니다.
결제 도구 허용 목록
자동 결제를 트리거할 수 있는 도구를 제한합니다.
config = AgentCorePaymentsConfig( payment_manager_arn="arn:aws:bedrock-agentcore:us-west-2:123456789012:payment-manager/pm-abc123", user_id="test-user-123", payment_instrument_id="payment-instrument-XJU4RSQP9VO0ler", region="us-west-2", auto_session=True, tool_allowlist=["http_request", "web_fetch", "mcp_call"], )
허용 목록에 있는 도구의 도구 호출만 자동 결제 처리를 트리거합니다. 다른 도구의 도구 호출은 결제 가로채기 없이 전달됩니다.
네트워크 기본 설정
결제 처리를 위해 선호하는 블록체인 네트워크를 지정할 수 있습니다.
config = AgentCorePaymentsConfig( payment_manager_arn="arn:aws:bedrock-agentcore:us-west-2:123456789012:payment-manager/pm-abc123", user_id="test-user-123", payment_instrument_id="payment-instrument-XJU4RSQP9VO0ler", region="us-west-2", auto_session=True, network_preferences_config=["eip155:8453", "base-sepolia", "solana-mainnet"], )
지정하지 않으면 시스템은 낮은 트랜잭션 요금으로 Solana 메인넷 및 기본(이더리움 L2) 우선 순위를 지정하는 기본 기본 기본 설정 순서를 사용합니다.
구성 옵션
다음 표에는 AgentCorePaymentsConfig 파라미터가 나열되어 있습니다.
| 파라미터 | 유형 | 필수 | 설명 |
|---|---|---|---|
|
|
|
예 |
Bedrock AgentCore Payment Manager 리소스의 ARN |
|
|
|
예 |
사용자의 고유 식별자 |
|
|
|
아니요 |
결제 수단 ID |
|
|
|
아니요 |
결제 세션 ID입니다. |
|
|
|
아니요 |
AWS 결제 관리자의 리전 |
|
|
|
아니요 (기본값: |
결제 세션 자동 생성 또는 재사용 |
|
|
|
아니요 (기본값: |
몇 분 안에 자동 생성된 세션의 만료 시간 |
|
|
|
아니요 (기본값: |
자동 생성된 세션의 최대 지출 금액 |
|
|
|
아니요 (기본값: |
자동 생성된 세션 지출 한도의 통화 |
|
|
|
아니요 (기본값: |
402 결제 요구 사항을 자동으로 처리할지 여부 |
|
|
|
아니요 |
기본 설정 순서대로 네트워크 CAIP-2 식별자 목록 |
|
|
|
아니요 |
자동 결제를 트리거할 수 있는 도구 이름 목록입니다. 설정하지 않으면 모든 도구가 결제를 트리거할 수 있습니다. |
|
|
|
아니요 (기본값: |
도구 호출당 최대 결제 재시도 횟수 |
|
|
|
아니요 |
결제 실패 시 호출된 콜백 함수 |
|
|
|
아니요 |
결제 성공 시 호출된 콜백 함수 |
|
|
|
아니요 |
결제 처리가 시작되기 전에 호출된 콜백 함수 |
|
|
|
아니요 |
API 호출 시 HTTP 헤더를 통해 전파되는 에이전트 이름 |
|
|
|
아니요 |
AgentCore 결제 서비스에 대한 사용자 지정 엔드포인트 URL |
기본 제공 에이전트 도구
미들웨어는 에이전트가 런타임에 결제 정보를 쿼리하고 관리하는 데 사용할 수 있는 다섯 가지 도구를 등록합니다.
| 도구 | 설명 |
|---|---|
|
|
특정 결제 수단에 대한 세부 정보 검색 |
|
|
사용자의 모든 결제 수단 나열 |
|
|
결제 세션에 대한 세부 정보 검색(예산, 상태, 만료) |
|
|
결제 수단의 현재 잔액 검색 |
|
|
사용자의 모든 결제 세션 나열 |
동기화와 비동기 비교
LangGraph 미들웨어는 동기식 실행과 비동기식 실행을 모두 지원합니다.
동기식:
result = agent.invoke({"messages": [{"role": "user", "content": "access the paid endpoint"}]})
비동기식:
result = await agent.ainvoke({"messages": [{"role": "user", "content": "access the paid endpoint"}]})
두 모드 모두 동일한 구성 옵션과 결제 처리 동작을 지원합니다. 비동기 프레임워크와 통합하거나 여러 동시 에이전트를 처리할 때 비동기를 사용합니다.