Prompt Chain

Enable AI agents to purchase paid API resources with controls

A Jupyter notebook where an AI agent requests paid API data through application-controlled spending limits and Amazon Bedrock AgentCore Payments.

Works with awsbedrockopenai

79
Spark score
out of 100
Updated 7 days ago
Version 1.0.0

Add to Favorites

Why it matters

Build an AI agent that can autonomously request and pay for external API services while maintaining application-level spending controls, approval workflows, and audit trails through AgentCore Payments infrastructure.

Outcomes

What it gets done

01

Validate merchant payment terms against approved spending policies and budget limits

02

Execute x402 payment protocol with bounded payment proofs from AgentCore Payments

03

Record purchase receipts and maintain audit history for compliance verification

04

Provide agents with controlled tool access to paid resources without exposing credentials

Install

Add it to your toolbox

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/oai-controlledagenticcommerce | bash

Steps

Steps in the chain

01
Setting up the supplier research example
02
Defining supplier requests and spending limits
03
Defining an agent tool for approved purchases
04
Running the x402 payment workflow
05
Verifying the supplier report, receipt, and audit history
06
Checking rejected purchases and fabricated receipts
07
Connecting AgentCore Payments to the AWS testnet
08
Checking testnet readiness before network calls
09
Inspecting the payment instrument and network
10
Running one approved testnet transaction

Overview

Build an AI agent that can pay for APIs using AgentCore Payments

This OpenAI Cookbook notebook walks through a supplier-research example where an AI agent requests a paid API report through an application-owned payment workflow. It covers the x402 402 Payment Required exchange, application-side spending checks, and Amazon Bedrock AgentCore Payments, first as a local simulation and then connected to the AWS testnet. Use it when designing an agent that must request paid third-party data or services but should never hold payment credentials or spending authority itself.

What it does

This notebook demonstrates agentic commerce: an OpenAI Agents SDK agent that needs to pay for a third-party API while the application, not the model, retains authority over payment. Using a supplier-research scenario (a fictional supplier, Northstar Components), the agent requests a paid risk report via an x402_fetch tool. The merchant returns an HTTP 402 Payment Required challenge; the application checks the merchant, purpose, amount, and human approval against its own policy before AgentCore Payments generates a bounded payment proof. Once approved, the application retries the request with the proof, receives the report, and records a receipt and audit trail. The workflow separates four responsibilities: the agent decides a paid tool could help; the application checks merchant, purpose, amount, and approval and records receipts; AgentCore Payments generates a bounded payment proof within an approved session; and the paid API validates the proof and returns content. The notebook first simulates the entire flow locally with a scripted model and a synthetic payment proof, then shows the same flow connected to Amazon Bedrock AgentCore Payments on the AWS Base Sepolia testnet using USDC.

When to use - and when NOT to

Use this when building an agent that needs to consume paid external APIs, such as a paid search or sanctions-screening service, but must not itself hold payment credentials, spending limits, or approval authority - those stay in application code. It also demonstrates rejecting purchases that lack human approval and detecting fabricated receipts, useful when auditability of agent-triggered spending matters. It is not a production payment system: the AWS-connected path requires an operator to explicitly enable five separate gates (RUN_AGENTCORE_E2E, ALLOW_AGENTCORE_SESSION_ADMIN, ALLOW_PAID_INFERENCE, ALLOW_AGENTCORE_TESTNET, APPROVE_AGENTCORE_TESTNET_PURCHASE), and with the default configuration all live payment gates stay disabled, so the testnet readiness check returns NOT_READY and the managed run returns SKIPPED. A separate, narrower gate, ALLOW_AGENTCORE_READ_ONLY, lets the application inspect the configured payment instrument without creating a session - it must report status ACTIVE, the ETHEREUM wallet network, and the exact BASE_SEPOLIA/USDC balance scope, or the check returns NOT_READY; a missing gate returns SKIPPED instead, and none of this exposes a balance, a payment proof, or a transfer.

Inputs and outputs

Inputs are supplied by application code, not the model: the approved merchant, permitted research purpose, maximum price per purchase, total run budget, and an ApprovalGrant tied to a request ID, resource URL, and expiry. The model only supplies a resource URL and business purpose when calling x402_fetch; before a purchase starts, the tool consumes a one-use capability so the model cannot issue more than one economic request per agent run. Outputs are an AgentPurchaseEvidence object containing only the report and receipt fields the model needs - wallet material, payment proof headers, and the full audit trail stay outside model context. The application separately records a receipt and audit history covering the resource request, authorization, payment proof creation, merchant retry, and returned content, and can hash the original HTTP response bytes for later verification. A second check changes the receipt identifier in an otherwise valid supplier summary to confirm the output validator rejects the mismatch. The managed result also records whether merchant acceptance and payment-proof creation completed, but reports settlement_verified=false, since independent blockchain settlement and transaction finality require separate evidence the notebook does not provide.

Integrations

Built on the OpenAI Agents SDK, with an alternative walkthrough using the Responses API directly - exposing x402_fetch as a function and accepting a function_call_output after the application handles the purchase. Payment infrastructure is Amazon Bedrock AgentCore Payments for bounded payment sessions, using the x402 HTTP 402 Payment Required protocol. The connected testnet path runs against an approved x402 merchant on Base Sepolia using USDC, and requires Python 3.11 through 3.13 and uv. Optional CloudWatch log delivery can supply sanitized session-lifecycle evidence, such as session creation, payment processing, and session deletion, for a reviewed live run, though it does not independently establish payment amount or blockchain settlement finality.

Who it's for

Developers building agentic systems that need to consume paid third-party APIs under strict, auditable spending controls - for example procurement, supplier-research, or data-enrichment agents - and who want a reference for separating agent, application, and payment-provider responsibilities before connecting to a real payment network.

Source README

Build an AI agent that can pay for APIs using AgentCore Payments

AI agents often need information from external services to complete a task. A procurement agent might check a supplier against a sanctions database, retrieve a current risk report, or use a paid search API. When those services charge for each request, the application needs clear rules for which purchases the agent can request and who approves the spending.

Agentic commerce describes workflows in which an agent can request a paid resource while application code retains authority over payment. Amazon Bedrock AgentCore Payments provides infrastructure for bounded payment sessions, and the OpenAI Agents SDK lets a model request an application-defined tool. The application checks the merchant, purpose, amount, and approval before a payment can occur.

This notebook explains that workflow through a supplier research example. It covers the AgentCore Payments flow, the x402 payment exchange, application-owned spending controls, and receipt verification. The same payment controls are first illustrated with a local simulation and then connected to AgentCore Payments on the AWS testnet.

Why agents need access to paid services

Consider a procurement agent reviewing a fictional supplier named Northstar Components. The agent has basic supplier information, but it needs a current risk report from a paid API before it can summarize potential concerns for a human reviewer.

The application approves that data provider, defines a supplier research purpose, and sets a maximum price for the report. It also records the human approval associated with the request. When the model decides that the report is useful, it requests the x402_fetch tool with the supplier report URL and the approved purpose.

The merchant returns an HTTP 402 Payment Required challenge describing its payment terms. The application checks those terms against the approved merchant, amount, network, expiry, and budget. If the request passes, the application obtains a bounded payment proof, retrieves the report, and records a receipt and audit history. The agent then prepares its answer from the report and receipt evidence returned by the tool.

Architecture and payment authority

The system separates four responsibilities:

  1. The AI agent identifies when a paid service could help complete the user's request and calls the application-defined tool.
  2. The application checks the merchant, purchase purpose, amount, approval, and spending limit before recording the receipt and audit history.
  3. AgentCore Payments generates a payment proof within the limits of an approved payment session.
  4. The paid API checks the payment proof and returns the requested content.

The local example simulates the AgentCore Payments step. The connected AWS workflow uses AgentCore Payments to generate the bounded proof.

The application is the boundary between the model and the payment infrastructure. The model receives the resource URL and research purpose, while approval records, spending limits, payment credentials, and audit state remain outside its control.

The application controls approval and spending, while AgentCore Payments provides a bounded payment session for the connected AWS workflow.

1. Setting up the supplier research example

The example requires Python 3.11 through 3.13 and uv. Follow the repository-root Jupyter command in README.md so the notebook can load its package and display the architecture diagrams.

The first part uses a scripted model, a simulated merchant, and a synthetic payment proof. This setup lets you inspect the same request, approval, receipt, and audit sequence without configuring AWS credentials or transferring funds. The final section shows where a real Amazon Bedrock model and AgentCore Payments testnet resources enter the workflow.

The following cell locates the example package and makes its application, merchant, and policy modules available to the notebook.

2. Defining supplier requests and spending limits

The application needs to establish its payment rules before the model can request a tool. In this example, the supplier report costs 0.25 synthetic USDC. The application also defines the approved merchant, the permitted research purpose, a maximum amount for this purchase, and the total budget available to the agent run.

ApprovalGrant ties the purchase to a particular request ID and resource URL. Its expiry limits how long that authorization remains valid. The model never supplies or changes these values; they are provided by application code when the tool is created.

3. Defining an agent tool for approved purchases

The x402_fetch function is the only payment-related tool available to the agent. The model can provide a resource URL and a business purpose, but the application supplies the request ID, idempotency key, spending policy, and approval grant.

Before starting a purchase, the tool consumes a one-use capability. That check prevents a model from issuing multiple economic requests during the same agent run. application.purchase then validates the merchant and payment challenge before producing a receipt.

AgentPurchaseEvidence returns only the report and receipt fields the model needs to prepare its answer. Wallet material, payment proof headers, and the complete application audit trail are kept out of the model context.

4. Running the x402 payment workflow

x402 uses the HTTP 402 Payment Required response to communicate the terms of a paid request. When the application first requests the supplier report, the merchant returns a challenge with the amount, asset, network, recipient, and expiry.

The application checks those terms against its approved policy. If the merchant, price, request purpose, and human approval are valid, AgentCore Payments creates one bounded proof in the connected AWS workflow. The local example uses a synthetic proof to demonstrate the same sequence. The application retries the request with the proof, and the merchant returns the supplier report with HTTP 200.

The merchant's 402 response supplies payment terms. Application approval occurs before a payment proof is requested.

Runner.run executes the Agents SDK loop. The scripted model requests x402_fetch on its first turn and prepares a typed supplier summary after the tool returns. The application checks that summary against the purchase it actually recorded.

Using the Responses API directly

The OpenAI Agents SDK coordinates the tool loop in the previous example, but the payment workflow does not require that orchestration layer. The Responses API can expose x402_fetch as a function, return the model's proposed arguments, and accept a function_call_output after the application handles the purchase.

The application still checks the merchant, purpose, approval, and spending limit before making a payment. AgentCore Payments remains responsible for generating the bounded proof in the connected AWS workflow. The example below uses the same simulated merchant and payment processor as the local walkthrough.

This alternative calls a real Bedrock-hosted GPT-5.6 Sol model, so it runs only when ALLOW_PAID_INFERENCE=1 and valid AWS credentials are configured. It does not enable a live payment or transfer funds.

5. Verifying the supplier report, receipt, and audit history

The model returns a structured supplier summary, but a valid schema only establishes that the response has the expected shape. The application still needs to check whether the reported receipt, amount, currency, and supplier details match the completed tool request.

The first cell compares the agent's proposed result with the application-owned receipt. The second cell shows the audit sequence from the initial resource request through authorization, payment proof creation, the merchant retry, and returned content.

6. Checking rejected purchases and fabricated receipts

A useful payment example should show what happens when its controls reject a request. The first check submits another supplier report request without the required human approval. The application can inspect the merchant's challenge, but it must reject the purchase before creating another payment proof or charge.

The existing synthetic charge count should remain unchanged after the request is denied.

The second check changes the receipt identifier in an otherwise valid supplier summary. The output validator compares that response with the purchase observed by the application and rejects the mismatch.

These two checks cover separate boundaries: authorization before payment and evidence verification after the model responds.

7. Connecting AgentCore Payments to the AWS testnet

The connected supplier research workflow uses a Bedrock-hosted OpenAI model, AgentCore Payments, and an approved x402 merchant on Base Sepolia. The application keeps the same merchant policy, spending approval, request identity, and receipt checks demonstrated in the local simulation. AgentCore Payments creates a short-lived session with its own maximum spending limit.

The local simulation and AWS testnet workflow share the same application controls. AgentCore Payments provides bounded payment sessions in the connected environment.

Before enabling the AWS path, an operator provisions the payment manager, connector, instrument, and exact-wallet signing permission outside the notebook. Model inference, session administration, and payment execution use separate responsibilities. README.md describes the setup, supported configuration, below-budget denial check, and cleanup procedure.

AgentCore Runtime is not used by this notebook. The notebook process remains the application runtime, and all live payment gates are disabled unless an operator explicitly enables them.

Checking testnet readiness before network calls

The readiness check inspects local configuration without contacting AWS, the model, the merchant, or the wallet. It confirms that the required payment opt-ins are present, AWS roles are separated, the session budget is finite, and no payment session is recorded in the local state file.

The check also rejects proxy settings that are incompatible with the merchant connection's DNS and TLS protections. With the default configuration, the expected result is NOT_READY because live payment gates are disabled.

Inspecting the payment instrument and network

When ALLOW_AGENTCORE_READ_ONLY=1 is explicitly enabled, the application can inspect the configured payment instrument without creating a payment session. The instrument must be ACTIVE, use the ETHEREUM wallet network, and report the exact BASE_SEPOLIA and USDC balance scope.

A missing gate returns SKIPPED. A network or asset mismatch returns NOT_READY. These checks do not expose a balance amount, generate a payment proof, contact the merchant, or transfer value.

Running one approved testnet transaction

An operator can enable the managed testnet run only after checking the approved merchant, recipient, asset, amount, wallet, and short-lived session configuration. The workflow requires all five explicit gates: RUN_AGENTCORE_E2E, ALLOW_AGENTCORE_SESSION_ADMIN, ALLOW_PAID_INFERENCE, ALLOW_AGENTCORE_TESTNET, and APPROVE_AGENTCORE_TESTNET_PURCHASE.

The combined execution path checks those gates again before starting model inference or payment activity. It creates one bounded session, sends the agent's request through the application policy, requests an AgentCore payment proof, and retries the approved merchant once.

Session creation is serialized. If local session persistence fails, the application attempts compensating cleanup. A successful or failed managed run also attempts to delete the session in finally. If cleanup fails, the operator must follow the recovery procedure in README.md before starting another run.

With the default notebook configuration, the cell returns SKIPPED and performs no live operation.

Interpreting payment and settlement evidence

The managed result records whether the model completed its tool call, AgentCore Payments produced the payment proof, the merchant returned HTTP 200, and the temporary session was deleted. The application hashes the original HTTP response bytes and keeps provider credentials, payment headers, and internal identifiers out of the report.

Merchant acceptance establishes that the paid request completed. Independent settlement and transaction finality require separate evidence. The example therefore reports settlement_verified=false.

Optional CloudWatch lifecycle evidence

This public notebook does not include a CloudWatch screenshot. For a reviewed live run, configure AgentCore Payments log delivery before the run and use CloudWatch only as sanitized lifecycle evidence. Do not share account IDs, request IDs, wallet data, payment identifiers, or proof headers.

Lifecycle events can help confirm session creation, payment processing, and session deletion. They do not independently establish the payment amount, blockchain settlement, transaction finality, or production readiness.

Applying the payment workflow to other services

The same structure can support other paid data sources, including premium search, sanctions screening, market data, or supplier verification. Each integration should define its approved merchants, permitted purposes, maximum amount, approval requirements, and session duration before the agent can request a purchase.

The model chooses when a paid tool might help complete the user's task. Application code determines whether that request is authorized, records the resulting transaction evidence, and checks the model's final response against the actual tool result. AgentCore Payments provides an additional spending boundary when the workflow is connected to an approved AWS testnet session.

References

FAQ

Common questions

Discussion

Questions & comments · 0

Sign In Sign in to leave a comment.