Documentation
Getting started
Welcome to the Last Price platform documentation. This guide explains pricing, integrations, and workspace workflows. Use the API reference for the current endpoint contracts.
Base URL & authentication
Use this base URL for API requests. Secured operations accept the credentials listed in the API reference, commonly a JWT bearer token or an API key passed via the x-api-key header.
# Base URL
https://api.last-price.ai
# Example authenticated request
curl https://api.last-price.ai/api/me \
-H "Authorization: Bearer YOUR_JWT_TOKEN"GET /api/me also returns plan: your workspace's plan, its daily compute limit, whether it runs built-in functions only, and which billing settings it can change.
Ways to access the API
Building an agent? Read /llms.txt first. It is the current word on getting a key with no human, keyless calls, pay per call, limits and error fields, and this guide does not repeat it. Machine-readable versions: the OpenAPI contract, the agent manifest, the MCP manifest and the changelog feed.
Everything is labelled with the same feature tags as the release notes. Each section of this guide shows its tags, and each one opens the release notes filtered to that feature (/changelog?feature=webhooks). Each product page under Features lists its recent changes, and every tag in the OpenAPI contract carries x-feature (an operation about something narrower has its own), so an agent can match an operation to the notes about it.
Explanations for people and agents
Agents reading the website: every page carries its explanations in full. People see the first line of each, with More to open it; agents (signed in with AgentID, a driven browser, or a link with ?explain=all) see all of them. Either way the whole text is in the page, so select-all and copy get every word. The line at the top of the dashboard or the end of a page says who the page thinks is looking and switches explanations for every page at once; a signed-in account remembers the choice. Only how much explanation shows changes. Prices, data and limits are the same for everyone.
Choose one way to start. These options and limits come from this deployment's current discovery document.
Open the API reference for request bodies and response schemasLoading current access options...
Platform overview
Last Price is a pricing optimization and A/B testing platform that helps businesses find the price that maximizes revenue.
| Component | What it does |
|---|---|
| Elo | A/B testing engine - deterministic variant assignment via SHA-256 hashing |
| Jale | AI pricing optimizer: learns price sensitivity from your sales, simulates revenue, recommends prices |
| PCN | Pricing Compute Network - function registry, inference routing, metering |
| Price router | Multi-vendor pricing facade - one API in front of all built-in and custom pricing models |
| Rosetta | Schema translation - map any price data format to canonical schemas with AI-assisted adapters |
| Commerce control plane | End-to-end pipeline - connectors, observations, policies, approvals, execution |
| Oja | Admin dashboard - manage experiments, functions, usage, marketplace |
| Snippet | Embeddable JavaScript widget - zero-dependency, drop into any website |
| API | REST API - full programmatic control over every feature |
| Marketplace | Publish and consume community pricing functions with revenue sharing |
| Scraper | Competitive pricing data collection from any website |
Quick start
- Set Up Your Workspace
For this experiment workflow, sign up and create an API key in Settings, API keys. If you started with a sandbox, use its claim link to move into a full workspace first. Discover your tenant_id with GET /api/me using that key, then use it in the experiment URL below. Keep the key on your server and send it in x-api-key. If using OAuth, send the access token in Authorization: Bearer instead.
Create a workspace - Create Your First Experiment
curl -X POST https://api.last-price.ai/api/tenants/YOUR_TENANT_ID/experiments \ -H "Authorization: Bearer lp_<hex>" \ -H "Content-Type: application/json" \ -d '{ "name": "Homepage Pricing Test", "key": "homepage_price_test", "variants": [ { "name": "control", "price": 29.99, "weight": 50 }, { "name": "experiment", "price": 39.99, "weight": 50 } ] }' - Choose an Integration Method
Method Best for Effort Shopify, WordPress, any HTML site 5 minutes Next.js, React apps 15 minutes Any backend or frontend 30 minutes
Platform integrations
Step-by-step integration guides for Shopify, SaaS apps, e-commerce platforms, marketplaces, and digital products.
Shopify store integration
Integrate Last Price to A/B test product prices, subscription tiers, and promotional offers in your Shopify store.
Option A: Embed Snippet (No Coding)
Go to Shopify Admin → Online Store → Themes → Edit Code → theme.liquid. Add before the closing </body> tag:
<!-- Last Price A/B Testing -->
<script src="https://last-price.ai/lastprice.js"></script>
<script>
LastPrice.configure({
apiBase: 'https://api.last-price.ai',
embedToken: 'lpe_YOUR_EMBED_TOKEN',
tenantId: 'YOUR_TENANT_ID',
experimentId: 'YOUR_EXPERIMENT_KEY',
debug: false
});
</script>Add a pricing container to your product template:
<div id="lastprice-pricing"></div>
<script>
LastPrice.showPricing('#lastprice-pricing', {
customRenderer: function(pricing) {
// Escaped because this string is assigned to innerHTML and the value
// comes from the variant's metadata, which can carry markup.
var price = String(pricing.price)
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return '<div class="product-price">' +
'<span class="money">' + price + '</span></div>';
}
});
// Record the conversion from Shopify's own Add to Cart form.
// onConvert is not used here: the SDK attaches it to a button with id
// lp-convert-btn, which the default renderer emits and a custom one like
// the above does not. Give your rendered button that id if you would
// rather use onConvert.
document.addEventListener('submit', function (event) {
var action = event.target && event.target.action;
if (action && action.indexOf('/cart/add') !== -1) {
// Record what this visitor was shown. A variant's metadata can
// override the price, so leaving revenue out would store the
// variant's own figure and disagree with the page.
var shown = LastPrice.getVariant();
LastPrice.convert(shown && typeof shown.price === 'number'
? { revenue: shown.price }
: {});
}
});
</script>Option B: Headless / Custom Storefront
Note: @lastprice/client is a hypothetical SDK package name shown for illustration. Use the REST API directly.
This example runs on your server, so it sends your secret API key. Do not move these calls into the browser as they are: a page has no credential here, and the cross-origin preflight does not allow the header this uses. For a browser component, configure the snippet with an embed token instead and register the page origin on it.
import { cookies } from 'next/headers';
const API_BASE = 'https://api.last-price.ai';
const TENANT_ID = 'YOUR_TENANT_ID';
export default async function ProductPage({ product }) {
// A Server Component has no localStorage, so the participant id comes from
// a cookie. It has to already exist: minting one here would mint a new one
// on every render, and assignment is stable per participant, so the visitor
// would move between variants as they browsed. Set it once at the edge (see
// the middleware below) and read it everywhere else.
const userId = (await cookies()).get('lp_uid')?.value;
if (!userId) return null; // middleware sets it on the first request
// Get the A/B tested price via the pricing endpoint
// Server side, so the secret key is safe here. Never ship this to a browser.
const resp = await fetch(
`${API_BASE}/api/experiments/product_price_test/pricing?userId=${userId}&tenantId=${TENANT_ID}`,
{ headers: { 'x-api-key': process.env.LASTPRICE_API_KEY } }
);
const { pricing } = await resp.json();
return (
<div>
<h1>{product.title}</h1>
<p className="price">${pricing.price}</p>
<AddToCart userId={userId} revenue={pricing.price} />
</div>
);
}The participant id is minted once, at the edge, so every later render reads the same one and the visitor stays in one variant:
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
if (request.cookies.get('lp_uid')) return NextResponse.next();
const response = NextResponse.next();
response.cookies.set('lp_uid', crypto.randomUUID(), {
maxAge: 60 * 60 * 24 * 365,
sameSite: 'lax',
path: '/'
});
return response;
}The button is a client component, because a click handler cannot be passed out of a Server Component. It posts to a route on your own domain, which holds the key:
'use client';
// app/product/add-to-cart.jsx
export function AddToCart({ userId, revenue }) {
return (
<button
onClick={async () => {
// Your own route, which holds the secret key. Posting straight to the
// API from a page would carry no credential the API accepts.
await fetch('/api/record-conversion', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId, revenue })
});
}}
>
Add to Cart
</button>
);
}Shopify Use Cases
| Use case | Experiment setup |
|---|---|
| Product price testing | Variant A: $49.99 vs Variant B: $54.99 |
| Subscription tier pricing | Variant A: $9/mo vs Variant B: $12/mo |
| Bundle pricing | Variant A: $79 bundle vs Variant B: $89 bundle |
| Discount depth testing | Variant A: 10% off vs Variant B: 20% off |
| Free shipping threshold | Variant A: free at $50 vs Variant B: free at $75 |
| Psychological pricing | Variant A: $49.99 vs Variant B: $50.00 |
SaaS / subscription integration
Test pricing tiers, plans, and subscription models in React/Next.js apps.
Note: @lastprice/react is a hypothetical SDK package name shown for illustration. Use the REST API directly.
"use client";
import { useState, useEffect } from 'react';
const API_BASE = 'https://api.last-price.ai';
const EMBED_TOKEN = 'lpe_YOUR_EMBED_TOKEN';
export default function PricingPage() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const userId = localStorage.getItem('lp_uid') || crypto.randomUUID();
localStorage.setItem('lp_uid', userId);
fetch(`${API_BASE}/api/experiments/saas_pricing_test/pricing?userId=${userId}`, {
headers: { 'x-embed-token': EMBED_TOKEN }
})
.then(r => r.json()).then(setData).finally(() => setLoading(false));
}, []);
if (loading || !data) return <PricingSkeleton />;
return (
<PricingCard
name={data.variant === 'control' ? 'Starter' : 'Growth'}
price={data.pricing.price}
features={data.pricing.features || []}
onSubscribe={async () => {
await fetch(`${API_BASE}/api/experiments/saas_pricing_test/convert`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-embed-token': EMBED_TOKEN
},
body: JSON.stringify({
userId: localStorage.getItem('lp_uid'),
revenue: data.pricing.price
})
});
window.location.href = `/api/checkout?plan=${data.variant}&price=${data.pricing.price}`;
}}
/>
);
}Use Jale for AI price recommendations learned from your market data:
curl -X POST https://api.last-price.ai/api/compute/price \
-H "Content-Type: application/json" \
-H "x-api-key: YOUR_API_KEY" \
-d '{
"function_name": "lastprice/jale-optimizer",
"input": {
"current_price": 29,
"product_type": "saas_subscription",
"market_data": {
"competitor_prices": [19, 25, 39, 49],
"current_conversion_rate": 0.03
}
}
}'E-commerce platform integration
Server-side price assignment for e-commerce platforms (recommended for SEO and consistency).
// pages/api/product-price.ts (Next.js API route)
// Uses the REST API directly
export default async function handler(req, res) {
const { userId, productId } = req.query;
const resp = await fetch(
`${process.env.LASTPRICE_API_URL}/api/experiments/product_${productId}_price/pricing?userId=${userId}`,
{
headers: {
'x-api-key': process.env.LASTPRICE_API_KEY
}
}
);
const data = await resp.json();
res.json({
productId,
price: data.pricing.price,
variant: data.variant,
experimentId: data.experimentId
});
}Track conversions after a successful payment:
// After successful payment - track conversion via REST API
async function onPaymentSuccess(order) {
await fetch(`${process.env.LASTPRICE_API_URL}/api/experiments/${order.experimentKey}/convert`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': process.env.LASTPRICE_API_KEY
},
body: JSON.stringify({
userId: order.userId,
revenue: order.totalAmount
})
});
}Marketplace integration
For platforms connecting buyers and sellers - test commission rates, platform fees, and pricing models.
// Test different commission rates using the REST API from your server
const API_BASE = 'https://api.last-price.ai';
const HEADERS = {
'x-api-key': process.env.LASTPRICE_API_KEY
};
const resp = await fetch(
`${API_BASE}/api/experiments/commission_rate_test/pricing?userId=${sellerId}`,
{ headers: HEADERS }
);
const { variant, pricing } = await resp.json();
const commissionRate = variant === 'control' ? 0.10 : 0.15;
const platformFee = transactionAmount * commissionRate;
// Track when a transaction completes
await fetch(`${API_BASE}/api/experiments/commission_rate_test/convert`, {
method: 'POST',
headers: {
...HEADERS,
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: sellerId, revenue: platformFee })
});Digital products integration
For courses, ebooks, templates, and downloadable content.
// Test course pricing ($199 control vs $299 premium positioning)
const API_BASE = 'https://api.last-price.ai';
const HEADERS = {
'x-api-key': process.env.LASTPRICE_API_KEY
};
const resp = await fetch(
`${API_BASE}/api/experiments/course_pricing_test/pricing?userId=${userId}`,
{ headers: HEADERS }
);
const { pricing } = await resp.json();
const coursePrice = pricing.price;
// Track enrollment as conversion
await fetch(`${API_BASE}/api/experiments/course_pricing_test/convert`, {
method: 'POST',
headers: {
...HEADERS,
'Content-Type': 'application/json'
},
body: JSON.stringify({
userId, revenue: coursePrice
})
});Salesforce
Connect Salesforce on Settings, Integrations. An owner or admin signs in to Salesforce from the modal (the OAuth 2.0 web server flow with PKCE, and a one-time state checked on the way back), at login.salesforce.com unless the deployment names another login host. Tokens are encrypted at rest and refreshed when Salesforce asks; they are never shown.
- Pull: each Account becomes a customer, matched first to one whose email is at the Account's website domain, then by a contact's email, and created otherwise. Contacts with an email become that customer's contacts. Opportunities are linked to the customer.
- Push: each order of a linked customer goes back as an Opportunity, with the order total as its amount and the customer's invoiced and paid totals in its description. A later sync updates it only when something changed.
- Every sync is idempotent (records are linked once) and written to the sync log on the modal's Settings tab with its counts. Syncs run every hour and on Sync now; one runs at a time per workspace. Disconnect revokes the token at Salesforce and forgets it.
Reading needs integrations:read, syncing integrations:write. Agents use the MCP tools list_integrations and sync_salesforce. For help, write to support@last-price.ai.
Running your own deployment? It offers Salesforce when it has a Salesforce connected app (with the OAuth scopes api and refresh_token, and its callback URL set to /api/integrations/salesforce/callback on your app's address) and these settings: SALESFORCE_CLIENT_ID and SALESFORCE_CLIENT_SECRET, the connected app's consumer key and secret, and optionally SALESFORCE_LOGIN_HOST, where people sign in (login.salesforce.com by default; test.salesforce.com for sandbox orgs, or a My Domain host). ENCRYPTION_KEY seals the tokens.
# Connection, linked records and the sync log
curl https://api.last-price.ai/api/integrations/salesforce \
-H "x-api-key: YOUR_API_KEY"
# Sync now: pull, push or both (the default)
curl -X POST https://api.last-price.ai/api/integrations/salesforce/sync \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"direction": "both"}'Datadog
Send Last Price telemetry to your own Datadog account. On Settings, Integrations, add a named key pair (an API key and an application key from your Datadog organization) and pick its Datadog site (US1, US3, US5, EU1, AP1, AP2, UK1, US1-FED or US2-FED). Last Price checks the keys with Datadog before saving them, encrypts them at rest, and only ever shows the last four characters of the API key. Everything is sent with your keys, so there is nothing to set up on the Last Price side.
- Metrics: pricing calls, cached calls, average compute time, usage cost, order count and total, invoiced and paid revenue, tagged with the currency, under
lastprice.*. - Events: each price change (learned pricing and competitive price proposals) as a Datadog event.
- Logs: a summary of each delivery and each price change, with source
last-price, so you can search and alert on them in Log Explorer. - Sent every hour, and on Send now, for the time since the last delivery. A delivery Datadog refuses is sent again next time.
Agents check keys with the MCP tool test_datadog_keys. Reading needs integrations:read, everything else integrations:write.
# Check keys without saving them
curl -X POST https://api.last-price.ai/api/integrations/datadog/validate \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"api_key": "DD_API_KEY", "app_key": "DD_APP_KEY", "site": "eu1"}'
# Save a key pair (checked first)
curl -X POST https://api.last-price.ai/api/integrations/datadog/keys \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name": "production", "site": "eu1", "api_key": "DD_API_KEY", "app_key": "DD_APP_KEY"}'Embed snippet (no-code)
The fastest way to add Last Price to any website. No build tools needed, just a drop-in JavaScript widget.
The snippet authenticates with an embed token, created on the Embed Snippet page. It is publishable, so it is safe in your page source: it reaches the pricing lookup, the conversion beacon and (when storefront outcome reporting is on) the outcome report only, and it is rate limited per client address (visitors sharing an address share a budget). Calls from a browser work only from the sites you register on it, which is what stops someone copying the token onto their own page. That is a browser check, not proof of where a request came from: a script outside a browser can claim any site. Anything that has to be trustworthy, revenue reporting included, belongs on your server with your secret API key, which stays there, where nobody viewing a page can read it. A page on another origin cannot send one at all, because the cross-origin preflight does not allow the header that carries it, though that follows from crossing an origin rather than from anything protecting a key you have published.
Basic setup
<div id="pricing-container"></div>
<script src="https://last-price.ai/lastprice.js"></script>
<script>
LastPrice.configure({
apiBase: 'https://api.last-price.ai',
embedToken: 'lpe_YOUR_EMBED_TOKEN',
tenantId: 'YOUR_TENANT_ID',
experimentId: 'YOUR_EXPERIMENT_KEY'
});
LastPrice.showPricing('#pricing-container');
</script>Auto-initialize via data attributes
<div id="pricing-container"></div>
<script
src="https://last-price.ai/lastprice.js"
data-api-base="https://api.last-price.ai"
data-embed-token="lpe_YOUR_EMBED_TOKEN"
data-tenant-id="YOUR_TENANT_ID"
data-experiment-id="YOUR_EXPERIMENT_KEY"
data-container="#pricing-container"
data-auto-load
></script>Custom rendering
LastPrice.showPricing('#pricing-container', {
customRenderer: function(pricing) {
// The plan name and the features come from the variant's metadata and
// end up in innerHTML, so escape them the way the default card does.
var esc = function(value) {
return String(value)
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/"/g, '"').replace(/'/g, ''');
};
return '<div class="my-pricing-card">' +
'<h2>' + esc(pricing.plan) + '</h2>' +
'<p class="price">$' + esc(pricing.price) + '/mo</p>' +
'<button id="lp-convert-btn">Subscribe Now</button>' +
'</div>';
},
onConvert: async function(pricing) {
await LastPrice.convert({ revenue: pricing.price });
window.location.href = '/checkout?price=' + pricing.price;
}
});Snippet API reference
| Method | Description |
|---|---|
| LastPrice.configure(options) | Set API base URL, embed token, tenant ID, experiment key |
| LastPrice.showPricing(selector, options?) | Fetch variant and render pricing card |
| LastPrice.convert(options?) | Record a conversion event with optional revenue |
| LastPrice.getUserId() | Get the current user's persistent ID (cookie-based) |
| LastPrice.getVariant() | Get the current variant assignment |
API client (code-level)
Full programmatic control over Last Price features using TypeScript, React hooks, REST, or Python.
The server samples below carry your secret API key in the x-api-key header. Without it the API answers 401. They show the header once and then leave it out for brevity; add it to each request. The React sample is the exception and is browser code: it calls a route on its own origin, which is the proxy pattern, so the key stays on the server behind it. Calling the API from a page directly is a different thing again: only the pricing lookup, the conversion beacon and the outcome report answer a cross-origin call at all, and only with a publishable embed token, which is what the snippet above does. A secret key cannot be used from another origin and must never be put in page source.
TypeScript / JavaScript client
Note: @lastprice/client is a hypothetical SDK package name shown for illustration. In this repo, use the REST API directly.
const API_BASE = 'https://api.last-price.ai';
const TENANT_ID = 'YOUR_TENANT_ID';
// Server side only: this key must never reach a browser.
const HEADERS = { 'x-api-key': process.env.LASTPRICE_API_KEY };
// 1. Get pricing (assigns a variant automatically)
const pricingResp = await fetch(
`${API_BASE}/api/experiments/pricing_experiment_1/pricing?userId=user_123&tenantId=${TENANT_ID}`,
{ headers: HEADERS }
);
const { variant, pricing } = await pricingResp.json();
console.log(variant); // "control" or "experiment"
console.log(pricing.price); // 29.99 or 39.99
// 2. Track a conversion
await fetch(`${API_BASE}/api/experiments/pricing_experiment_1/convert`, {
method: 'POST',
headers: { ...HEADERS, 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: 'user_123',
tenantId: TENANT_ID,
revenue: 29.99
})
});React hooks
Note: @lastprice/react is a hypothetical SDK package name shown for illustration. Use the REST API with fetch in a custom hook, as below.
import { useState, useEffect } from 'react';
// Browser code using a publishable embed token. The secret API key must never
// reach a browser.
const API_BASE = 'https://api.last-price.ai';
const EMBED_TOKEN = 'lpe_YOUR_EMBED_TOKEN';
function usePricing(experimentKey) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const userId = localStorage.getItem('lp_uid') || crypto.randomUUID();
localStorage.setItem('lp_uid', userId);
fetch(`${API_BASE}/api/experiments/${experimentKey}/pricing?userId=${userId}`, {
headers: { 'x-embed-token': EMBED_TOKEN }
})
.then(r => r.json()).then(setData).finally(() => setLoading(false));
}, [experimentKey]);
return { ...data, loading };
}
function PricingPage() {
const { variant, pricing, loading } = usePricing('my_experiment');
if (loading) return <div>Loading prices...</div>;
return (
<div>
<h2>Plan: {pricing?.plan}</h2>
<p>Price: ${pricing?.price}/month</p>
</div>
);
}REST API (any language)
# Assign a variant. The tenant comes from your API key.
curl "https://api.last-price.ai/api/experiments/EXPERIMENT_KEY/pricing?userId=USER_ID" \
-H "x-api-key: YOUR_API_KEY"
# Track a conversion. Send 0 for one that earned nothing; omit revenue to
# record the assigned variant's list price instead.
curl -X POST https://api.last-price.ai/api/experiments/EXPERIMENT_KEY/convert \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"userId": "USER_ID", "revenue": 29.99}'
# Get experiment results
curl https://api.last-price.ai/api/experiments/EXPERIMENT_KEY/results \
-H "x-api-key: YOUR_API_KEY"Python client
import os
import requests
class LastPriceClient:
# Server side. api_key never reaches a browser.
def __init__(self, base_url, tenant_id, api_key):
self.base_url = base_url
self.tenant_id = tenant_id
self.headers = {"x-api-key": api_key}
def get_pricing(self, user_id, experiment_key):
"""Assign a variant and get pricing via the pricing endpoint."""
resp = requests.get(
f"{self.base_url}/api/experiments/{experiment_key}/pricing",
params={"userId": user_id, "tenantId": self.tenant_id},
headers=self.headers
)
resp.raise_for_status()
return resp.json()
def track_conversion(self, user_id, experiment_key, revenue=None):
"""Record a conversion.
Pass revenue=0 for a conversion that earned nothing; it is recorded as
zero. Leaving it out is what asks for the variant's list price, so the
key is omitted rather than sent as null, which the API rejects.
"""
body = {"userId": user_id, "tenantId": self.tenant_id}
if revenue is not None:
body["revenue"] = revenue
resp = requests.post(
f"{self.base_url}/api/experiments/{experiment_key}/convert",
json=body,
headers={**self.headers, "Content-Type": "application/json"}
)
resp.raise_for_status()
return resp.json()
def get_results(self, experiment_key):
"""Get experiment results."""
resp = requests.get(
f"{self.base_url}/api/experiments/{experiment_key}/results",
params={"tenantId": self.tenant_id},
headers=self.headers
)
resp.raise_for_status()
return resp.json()
# Usage
lp = LastPriceClient("https://api.last-price.ai", "YOUR_TENANT_ID", os.environ["LASTPRICE_API_KEY"])
result = lp.get_pricing("user_123", "pricing_test")
print(f"Variant: {result['variant']}, Price: ${result['pricing']['price']}")
results = lp.get_results("pricing_test")
print(f"Control conversion rate: {results['control']['conversionRate']}")Pricing Compute Network (PCN)
The Pricing Compute Network lets you register modular pricing functions, invoke them with rich context, and route requests across multiple strategies - all through a single API.
Pricing functions
The Functions table loads up to 100 functions at a time. Use Previous and Next to reach every page. The status filter searches all accessible functions and starts at the first matching page.
A pricing function encapsulates a single pricing strategy. You can register five types of functions:
- rule_based: Deterministic rules (e.g., margin tables, tiered pricing)
- ml_model: Your own machine-learning model, hosted by Last Price (trained on your sales or uploaded as ONNX; see Hosted Models) or run on GPUs at the inference provider your workspace connects
- llm_prompt: Your prompt template, run on the LLM provider your workspace connects
- external_api: Delegates to your own REST endpoint
- composite: Chains or aggregates multiple functions
- namestring, required
- Unique name: lowercase letters, digits, hyphens, underscores and slashes, such as acme/margin-pricer
- display_namestring, required
- Name shown in the dashboard and the marketplace
- execution_typeenum, required
- One of: rule_based, ml_model, llm_prompt, external_api, composite
- descriptionstring
- Short description of the function's purpose
- endpoint_urlstring
- For external_api: the public HTTPS URL Last Price POSTs each request to. Private and internal addresses are refused.
- auth_configobject
- Credential sent to your endpoint: { "type": "bearer", "token": "..." } or { "type": "api_key", "header": "...", "key": "..." }. Stored encrypted and never returned.
- inference_configobject
- For llm_prompt and ml_model: the provider and model it runs on
- input_schemaobject
- JSON Schema of the context your function reads
- output_schemaobject
- JSON Schema of what it returns
- cost_per_unitnumber
- Your cost per call (default: 0)
- cost_multipliernumber
- Scales the metering cost per invocation (default: 1). Use higher values for premium or expensive models.
- tagsstring[]
- Up to 20 tags
- is_publicboolean
- Whether to list it on the marketplace (default: false)
A function starts as draft. Activate it before you test it or route to it. To write the endpoint itself, start from a recipe in the Pricing Function Cookbook.
# Register a new pricing function
curl -X POST https://api.last-price.ai/api/functions \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"name": "acme/margin-pricer",
"display_name": "Margin pricer",
"description": "Applies a margin by product category",
"execution_type": "external_api",
"endpoint_url": "https://pricing.example.com/margin",
"cost_multiplier": 1,
"tags": [
"margin"
]
}'
# Activate it, using the id the register call returned
curl -X PATCH https://api.last-price.ai/api/functions/FUNCTION_ID \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{"status": "active"}'# List your pricing functions
curl https://api.last-price.ai/api/functions \
-H "Authorization: Bearer lp_<hex>"
# Test a function with sample input (your own function can be tested while it is still a draft)
curl -X POST https://api.last-price.ai/api/functions/FUNCTION_ID/test \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"context": {
"product_id": "prod_001",
"product_type": "saas",
"current_price": 99,
"currency": "USD"
}
}'Function rules
A rule_based function prices by the rule it declares in rule: where the price starts, then the steps applied to it in order. Its input_schema is made from the rule, so what a buyer reads is what a call must send, and a call missing an input is refused naming it. A rule_based function needs a rule before it can be active (409rule_required), and one without a rule is never picked by routing. This is switching on workspace by workspace; until then a rule_based function runs the default optimizer.
- base:
{"from":"current_price"},{"from":"unit_cost"}(metadata.unit_cost),{"from":"competitor_prices","pick":"min"}(metadata.competitor_prices, by min, avg or max) or{"from":"field","field":"metadata.list_price"}. - adjust_pct { pct }: move by a percentage, +5 up or -12 down.
- margin { target_margin_pct }: the price that earns that margin on price, from a cost base.
- scale { field, sensitivity, min_factor?, max_factor? }: multiply by 1 + (value minus 1) times sensitivity, for an index around 1 such as demand.
- tiers { field, tiers: [{ min, pct } or { min, price }] }: the highest tier the field reaches applies, such as a volume break.
- floor and ceiling { value } or { field }: hold the price at or above, or at or below. They hold through every later step.
- ending { cents }: the nearest price ending in those cents (99 for x.99), never past a floor or ceiling. round { step }: the nearest multiple.
- The explanation lists each step and the price after it. Changing the rule, the endpoint, the schemas or the cost raises the function's
version. MCP:create_functionandupdate_functiontakerule.
# Match the cheapest competitor less 2%, never below cost plus 20%, ending in .99
curl -X POST https://api.last-price.ai/api/functions \
-H "Authorization: Bearer YOUR_TOKEN" -H "Content-Type: application/json" \
-d '{"name": "acme/competitive-match", "display_name": "Competitive match", "execution_type": "rule_based",
"rule": {"base": {"from": "competitor_prices", "pick": "min"},
"steps": [{"op": "adjust_pct", "pct": -2},
{"op": "floor", "field": "metadata.unit_cost"},
{"op": "ending", "cents": 99}]}}'A self-registered sandbox can draft, edit and test its own rule_based functions without a person: they stay drafts, with no endpoint or credential, until the workspace is claimed. A person holding a workspace:claim key can then claim it with"target": "new_workspace" so it becomes their own separate workspace, ready to activate and list. This is switching on workspace by workspace.
Hosted models
In the app: Compute, Hosted models
Last Price can host your pricing model and run it on every call. Train one on your own sales, or upload one you trained anywhere, and every version is kept so you can promote and roll back without touching your code. Where hosted models are off for a workspace, every route below answers 404 not_released; ML models can also run on GPUs at a provider you connect.
- Train: a demand model learns, from your quotes with an outcome (reported, or inferred from what buyers did next), how segment, region, product and buyer type change both the chance of a sale and its price sensitivity (gradient-boosted trees). A fifth of the quotes is held out to score it against one curve for everyone;
metrics.improvement_pctsays how much better it did. It needs at least 60 outcomes. - Upload: an ONNX file up to 4 MiB from scikit-learn, XGBoost or LightGBM (skl2onnx, onnxmltools) or a small PyTorch or Keras network. Supported operators: tree ensembles, linear regressors, scalers, Gemm and MatMul, the common activations, Concat and reshapes. It is checked before it is stored. Larger models run on a provider you connect.
- Inputs: the spec maps request fields to the model's columns:
current_price,unit_cost,unit_cost_ratio,customer_segment,geo,product_id,product_type,buyer_type,channel,currencyor anymetadata.<key>, each a number or a category with its vocabulary. - Kinds: a
demandmodel outputs the chance of a sale at the current price and its slope, and the optimizer picks the profit-optimal price, never below unit cost. Apricemodel outputs the price, or a ratio of the current price. - Versions: one is live.
promotemakes another live androllbackreturns to the one before. Withauto_retraina new candidate is trained nightly, and withauto_promoteit goes live only when it beats the live one on held-out quotes. Download any version as ONNX to run it elsewhere. - Use it: register an
ml_modelfunction with"inference_config": {"provider": "last-price", "model": "MODEL_ID"}. Requests must includecontext.current_price. Workspace guardrails and the fallback chain apply as for any function. - Buyer-aware pricing: with buyer-aware pricing on, the demand model you promoted last also prices learned and optimizer quotes as its
hostedmodel, in shadow or live, inside the exploration band. - Reading needs
pcn:function:read, changes needpcn:function:publish, and trying a version needspcn:function:test. Agents use the MCP toolslist_hosted_models,create_hosted_model,train_hosted_model,upload_hosted_model_version,promote_hosted_model_version,rollback_hosted_modelandpredict_with_hosted_model.
# Create a demand model that retrains nightly
curl -X POST https://api.last-price.ai/api/hosted-models \
-H "Authorization: Bearer lp_<hex>" -H "Content-Type: application/json" \
-d '{"name": "demand-by-segment", "kind": "demand", "auto_retrain": true, "auto_promote": true}'
# Train it on your outcomes now, and make it live if it beats the live version
curl -X POST https://api.last-price.ai/api/hosted-models/MODEL_ID/train \
-H "Authorization: Bearer lp_<hex>" -H "Content-Type: application/json" \
-d '{"promote": "if_better"}'
# Or upload a scikit-learn model exported with skl2onnx
curl -X POST https://api.last-price.ai/api/hosted-models/MODEL_ID/versions \
-H "Authorization: Bearer lp_<hex>" -H "Content-Type: application/json" \
-d '{"artifact_base64": "'"$(base64 -w0 model.onnx)"'", "spec": {"kind": "price", "output": "ratio", "inputs": [{"source": "unit_cost_ratio", "type": "number"}]}}'Test a function (MCP)
An agent can run the same test over MCP with test_function. Give it the function id and, optionally, a sample context, constraints and options. It needs pcn:function:test, works on your own drafts, changes nothing and is not metered, and only the owner can test a function that runs on a model provider. A sandbox key is refused until a person claims the workspace.
Batch, price tests and the demand curve (MCP)
Four more calls an agent could only make over REST are MCP tools. All of them need a credential of a claimed workspace, except the demand curve, which a sandbox key may read.
compute_prices_batch: up to 100 price requests in one call, drawn together from your balance, all or nothing. Send anidempotency_keyto retry safely; a repeat re-runs only the items that did not price. Needsprice:compute:batch.check_variant_significance: the trials and conversions of two to ten price variants in, each one's chance of being best, expected loss and credible interval out, with a verdict of winner, equivalent or continue. Needsprice:computeand is billed as one call.allocate_variant_traffic: the same input, and each variant's share of the next traffic by Thompson sampling, with a floor so none is starved. Needsprice:computeand is billed as one call.get_learned_elasticity_curve: how buyers react to price, as binned outcomes, the fitted acceptance line with its band and the estimate over time, for the workspace or one product. Owners and admins; needspcn:routing:read.
# Is the raise winning yet, and where should the next traffic go?
check_variant_significance { "variants": [ { "id": "control", "trials": 1000, "conversions": 50 }, { "id": "raise", "trials": 1000, "conversions": 70 } ] }
allocate_variant_traffic { "variants": [ { "id": "control", "trials": 1000, "conversions": 50 }, { "id": "raise", "trials": 1000, "conversions": 70 } ], "min_weight": 0.1 }Built-in functions
The platform ships with 18 pre-registered functions ready to use out of the box: Jale (pricing intelligence), Elo (A/B testing) and Rosetta (data translation). Each one's cost multiplier is listed below, and every call to it is billed at that multiplier.
| Function | Description | Multiplier |
|---|---|---|
| lastprice/jale-optimizer | Statistical price optimizer | 2× |
| lastprice/cost-plus | Price from a declared unit cost and target margin, or from a supplied price band, for callers with no existing price to price against. Refuses rather than inventing a price when given no basis. | 1× |
| lastprice/competitive-price | Evaluate a caller-supplied competitor offer against a stated match or undercut goal and a cost, margin or minimum-price floor. Requests missing inputs rather than inventing them. | 1× |
| lastprice/stopping-rule | Whether one more round of negotiation is worth its cost (see Optimal Stopping Rule below) | 1× |
| lastprice/jale-elasticity | Price elasticity calculator | 1× |
| lastprice/jale-advanced | Advanced recommendations with alternatives | 5× |
| lastprice/elo-ab-test | A/B test variant assignment by stable hash | 1× |
| lastprice/jale-psychological | Psychological pricing (.99 endings) | 1× |
| lastprice/rosetta-translate | Translate price schemas across platforms | 3× |
| lastprice/rosetta-normalize | Normalize price fields to canonical schema | 2× |
| lastprice/rosetta-validate | Validate schema against canonical contracts | 1× |
| lastprice/rosetta-suggest | AI-assisted schema mapping suggestions | 2× |
| lastprice/rosetta-freeze | Freeze a finalized schema adapter | 1× |
| lastprice/rosetta-ingest | Autonomous merchant onboarding via schema inference | 3× |
| lastprice/elo-significance | Bayesian significance test (POST /api/compute/significance) | 1× |
| lastprice/elo-allocator | Thompson-sampling traffic allocation (POST /api/compute/allocation) | 2× |
| lastprice/jale-bundle | Bundle pricing optimizer | 3× |
| lastprice/jale-tier-optimizer | Tiered pricing structure optimizer | 3× |
The cost_multiplier scales the base compute cost for each invocation. A 5× multiplier means each call costs 5 times the base rate. When a fallback function handles a request, the multiplier of the executed function is used, not the originally requested one.
Optimal stopping rule
lastprice/stopping-rule answers one question in a negotiation: is one more round worth what it costs? It fits a geometric decay to how much the offer improved each round, compares the expected gain from the next round with that round's cost, and says stop or continue. The "last price" is the offer on the table when continuing stops paying, so the answer is a best offer so far and a reason to stop, not a claim that the number is final.
Call it with POST /api/price-router and function_name, or with POST /api/compute/price and its function_id from GET /api/functions/catalog. Inputs go in context.metadata; no current_price is needed. It is billed at 1x like any call.
Try your own numbers. The picture is worked out again by the same rules.
- rolestring, required
- seller or buyer. A seller gains when offers rise, a buyer when they fall.
- historyarray
- Offers so far as { round, offer }, at most 200. Two or more are needed unless next_round.estimated_improvement is sent.
- best_offernumber
- The offer on the table now. Defaults to the latest offer in history.
- reservationnumber
- Your walk-away price: a seller's floor or a buyer's ceiling. A stop past it says walk_away.
- roundinteger
- Rounds played so far. Defaults to the last round in history.
- horizoninteger
- Your total round limit.
- counterparty_horizoninteger
- Your estimate of the other side's total round limit.
- budget_remainingnumber
- Money you have left for rounds, in the cost's currency.
- opponent_patiencenumber
- 0 to 1. A more patient counterparty concedes less, which lowers the expected gain (times one minus half the patience).
- disclosurestring
- What the other side knows about your limit: uncertain (default), hidden (gain times 0.8) or known (gain times 0.5, the deadline effect).
- fairness_modeboolean
- Default false. When true, your rounds are capped at the other side's smaller horizon, so the deeper pocket cannot simply outlast the other.
- value_modelobject
- { type: "linear", marginal_value_per_unit } converts a price improvement into value (default 1).
- next_roundobject
- { function_id, estimated_cost, estimated_improvement, input_units, output_units }. Without estimated_cost, the cost is metered: the metering formula for the function the next round would run (this one when none is named).
curl -X POST https://api.last-price.ai/api/price-router \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"function_name": "lastprice/stopping-rule",
"context": {
"currency": "USD",
"metadata": {
"role": "seller",
"best_offer": 29.99,
"reservation": 24,
"history": [
{ "round": 1, "offer": 39.99 },
{ "round": 2, "offer": 34.99 },
{ "round": 3, "offer": 29.99 }
],
"next_round": { "estimated_cost": 0.0023 }
}
}
}'
# Part of the response
{
"computed_price": 29.99,
"stopping": {
"stop": true,
"action": "accept",
"best_so_far": 29.99,
"ev_next_round": 0,
"cost_next_round": 0.0023,
"cost_source": "caller",
"crossing": { "expected_rounds_remaining": 0, "expected_final_price": 29.99, "confidence": 0.7, "bounded_by": "value" },
"driver": "buyer_economics",
"budget_driven": false,
"reason": "counterparty_not_conceding",
"explanation": "The last round did not improve the price for the seller, so the buyer is not conceding ... Stop and take 29.99."
}
}driver always says whose economics forced the stop. When the other side stops conceding, or its concessions shrink below the cost of a round, it is theirs. When your round limit or budget runs out first, it is yours and budget_driven is true, and the explanation says the stop was forced by your budget, not by the price. When both horizons are known, budget_asymmetry shows who can afford to hold out longer.
computed_price is the best offer, held to your constraints and workspace guardrails like every price; stopping.best_so_far is the offer exactly as sent. Use reservation, not min_price, for your walk-away. Missing or contradictory inputs answer 400 naming each field. value_model takes type linear with marginal_value_per_unit.
Compute price
When computing through /api/compute/conversation, a payment challenge names that conversation endpoint. Retry it with the continuation and the payment. The direct compute endpoint keeps its own payment resource.
Submit a single pricing request with full context. The platform selects the appropriate function based on your active routing policy and returns the computed price.
customer_segment and geo must be non-identifying: a segment label and a country or region, never an email, phone number, IP address, coordinates or street address, and nothing that stands in for age, sex, race or religion. A value that looks identifying is dropped from the logged quote (the price is still computed from what you sent). buyer_type is optional and must be agent or person; any other value is rejected with a 400.buyer_agent is an optional short label naming the buying agent (at most 100 characters, otherwise a 400). It is recorded on the logged quote only where agent identity is on for your workspace (off by default), never sent to the pricing function, and never verified. A buying agent that calls the UCP routes itself can prove who it is instead, with an AgentID token (see Universal Commerce Protocol below); a verified agent outranks a declared label.
The fields go inside context. Add function_id to run one function, and options to get the explanation and confidence back.
Prices come back in whole cents, never below a floor or above a ceiling. In a currency with no minor unit, such as JPY or KRW, prices can come back in whole units instead (1429, not 1428.57), within the same limits and with the explanation saying so. That rounding is off by default for a workspace.
Try your own numbers. The picture is worked out again by the same rules.
Pricing a job from what it costs you? You can send the same flat fields the MCPcompute_price tool takes, with no context wrapper:unit_cost, target_margin_pct, current_price,currency (USD when left out), min_price and max_price. Each is read where the full body keeps it, and the answer lists what was moved or assumed inread_as, so you can send the full body next time. A request with no current price, no cost and no band is refused once, with missing_pricing_inputs naming all three.
# First call with a fresh key: price a job that cost you $0.5154
curl -X POST https://api.last-price.ai/api/compute/price \
-H "x-api-key: YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{"unit_cost": 0.5154}'
# Response (trimmed): cost-plus at the default 30% margin
{ "computed_price": 0.74, "read_as": ["unit_cost as context.metadata.unit_cost", "context.currency assumed USD"] }No rival price in hand? Rolling out: put the job in context.metadata.market_query(what it is and its unit, such as "logo design for a startup") and Last Price reads what other sellers charge from public web pages before pricing. The answer carries market_prices: the low, median and high price in your currency, and each page a price came from. With competitive_actionand no competitor_price, the lowest market price is used to undercut and the median to match (market_reference: low, median or high chooses). With nothing else to price from, the median is used as a fallback current price, marked current_price_fallback. Prices are read from page text, not checked as the same job, so look at the pages before relying on one. If the market cannot be read, the call is refused with a code saying why, never priced as if there were no market. To see the range alone, the MCP tool find_market_prices sells one lookup for 0.02 USDC.
# Undercut the market by 5%, never below cost plus 30% (rolling out)
curl -X POST https://api.last-price.ai/api/compute/price \
-H "x-api-key: YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{"context": {"currency": "USD", "metadata": {"market_query": "logo design for a startup", "competitive_action": "undercut", "undercut_pct": 5, "unit_cost": 60, "target_margin_pct": 30}}}'
# Response (trimmed)
{ "computed_price": 142.5, "function_name": "lastprice/competitive-price",
"market_prices": { "low": 150, "median": 150, "high": 325, "count": 3, "used_as": "competitor_price", "used_as_competitor_price": "low",
"observations": [{ "url": "https://…", "price": 150, "per": null, "snippet": "…$150 per project…" }] } }- currencystring, required
- ISO 4217 currency code, three letters
- product_idstring
- Your product identifier
- product_typeenum
- One of: saas, ecommerce, marketplace, digital, api, custom (default: custom)
- current_pricenumber
- Current listed price. Functions that price relative to it refuse a request without it.
- customer_segmentstring
- Segment label (e.g., enterprise, smb). Must be non-identifying.
- geostring
- Country or region code (e.g., US, EU, APAC). Never an address, coordinates or IP.
- buyer_type"agent" | "person" | null
- Who the price is for: an AI agent or a person. Recorded with the quote. A workspace's own pricing function receives it in the context. Built-in pricing uses it only to pick agent buyers' own learned estimate, where that is rolled out (see Learned pricing).
- buyer_agentstring | null
- The buying agent, as a short non-identifying label (e.g., chatgpt or agent.example.com). Recorded lower-cased with the quote while agent identity is on for your workspace (off by default); it implies buyer_type agent when that is not sent. Never sent to the pricing function, so it does not change the price.
- buyer_ceilingnumber | null
- The most the buyer says it will pay, in the request currency: a buying agent's budget, spend limit or offer cap. Never sent to the pricing function, so it cannot set the price. The model layer reads it as evidence about the buyer at the trust that buyer kind's past declarations have earned, and checks it against what the buyer then does. Echoed in price_object.evidence.declared_ceiling.
- timestampstring
- ISO 8601 time the price is for
- metadataobject
- Arbitrary key-value pairs for custom context. Your own function receives them as sent.
# Compute a single price
curl -X POST https://api.last-price.ai/api/compute/price \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"context": {
"product_id": "prod_001",
"product_type": "saas",
"current_price": 99,
"currency": "USD",
"customer_segment": "enterprise",
"geo": "US"
},
"options": {
"include_explanation": true,
"include_confidence": true
}
}'
# Response (trimmed)
{
"request_id": "51db5c0f-25e7-48b5-ad8f-d59440778828",
"function_id": "1bf2353a-bea8-438e-8bab-848913776661",
"function_name": "lastprice/jale-optimizer",
"computed_price": 90.99,
"currency": "USD",
"confidence": 0.5,
"explanation": "Profit-maximising price of $90.99 from $99, using an elasticity of -1.2 assumed because metadata.elasticity was not supplied and no unit cost (send metadata.unit_cost to price for profit rather than revenue). Price range allowed: $49.50-$198.00.",
"product_type": "saas",
"metering": {
"input_units": 105,
"output_units": 81,
"compute_duration_ms": 2,
"cost": 0.00348
}
}Limits: a body over 64 KB, or context.metadata over 8 KB, answers 413 before it runs, since metadata is metered as input. Prices above 1,000,000,000,000, a min_price above max_price and a currency that is not an ISO code (or USDC) answer 400.
Product prices
POST /api/public/product-prices (MCP toolfind_product_prices) looks a physical product up bybarcode (8 to 14 digits) or name. Several price sources answer at once: what sellers ask today (listed, low, median and high with each offer), a year of price history (history), a 30-day outlook from two trained forecast models (forecast), and, when you send aprice and a side (buying or selling), averdict with its reasons.
sources says which sources answered, found nothing, or were skipped. When no source finds a price the call is refused with no_product_prices and nothing is charged. One lookup costs 0.05 USDC with x402. Pictures are never read or stored.
Retrying a compute call
A compute call is charged when it succeeds. If a request times out you cannot tell whether it ran, and sending it again without a key is a new call that is charged again. Send an Idempotency-Key header (8 to 255 visible characters, one new value per call you intend to make) and repeat the request with the same key and body to make the retry safe.
- The first request with a key runs, is metered and charged once, and its answer is kept for 24 hours.
- A repeat with the same key and body returns that answer with
Idempotent-Replay: true. It is not computed, metered or charged again. - The same key with a different body answers 409
idempotency_conflict. - A repeat that arrives while the first is still running answers 409 with a
Retry-Afterheader. Wait that long and send it again. - A call that failed is not kept, so retrying it with the same key runs it again, and a failed call is not charged.
- A repeat that is answered from the stored copy is not charged against a free plan's daily calls or a workspace's prepaid balance, and is not refused for a balance too low to cover a new call. It still counts toward rate limits. The same holds for a repeat that finds the first request still running, which is answered 409 and takes nothing.
- The header is optional. Requests without it behave exactly as before.
# Retry-safe compute call: repeat this exact request after a timeout
curl -X POST https://api.last-price.ai/api/compute/price \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: 6f1d2c9e-5b0a-4c53-9d7e-1a2b3c4d5e6f" \
-d '{"context": {"product_id": "prod_001", "currency": "USD", "current_price": 99.00}}'The Last Price MCP server and the agent tools take an optional idempotency_key argument on compute_price: pass the same value when you retry.
POST /api/compute/batch takes the same header. The key covers the whole batch, which is drawn from the balance all or nothing: the first request computes and draws once, and a repeat with the same body returns the stored answer and draws nothing. There is no key per item. A batch whose items partly failed still answers 200 with those items as errors. Repeat it with the same key and body and only those items run again, drawing and metering for them alone; the answer comes back with the first one's priced items kept and the failed ones replaced, and the Idempotent-Resumed header says how many ran. Items that priced are never charged twice. Once all have priced, a repeat is a plain replay.
Retry only a 5xx or a 429. A 4xx means the request itself has to change, and itscode says what: missing_incumbent_price needs acontext.current_price above zero, conflicting_pricing_inputsmeans two inputs contradict each other or an amount is too large to count in cents,validation_failed names a value that is not in the expected format (an id that is not a UUID, say), and conflict (409) means a record with the same unique value, such as an invoice number, already exists. provider_not_connected (409) means the function runs on an inference provider the workspace has not connected yet. Sending the same request again gets the same answer.
Quote expiry
A computed price can say how long it stays good to quote or charge. Where quote expiry is on for your workspace, every priced answer carriesvalid_until, an RFC 3339 time in UTC, andvalid_for_seconds, the window it was worked out from. Quote or charge the price only before valid_until, and compute it again after.
- The window is 15 minutes unless the function that priced it sets its own.
- A function owner sets
quote_valid_seconds(30 to 86400) when registering the function or withPATCH /api/functions/{id}; null returns to the default. Over MCP it is an argument ofcreate_functionandupdate_function. - Single, batch (on each item), router, chain and pay-per-call answers all carry it. When the answer also carries a
signed_quote, the quote expires at the same time. - Pass
quote_valid_untiltoPOST /api/price-router/verify(orverify_price) with the price you are about to act on. If that time has passed the answer saysquote_expired: trueand how many seconds ago; the verdict itself carries its ownvalid_until. - Reporting a price as accepted after its quote expired still records the outcome, and the answer says
quote_expired: true. - Where quote expiry is off, none of these fields appear and nothing else changes.
quote_valid_seconds, from 30 seconds to a day. A signed quote expires at the same time.Try your own numbers. The picture is worked out again by the same rules.
{
"computed_price": 44.99,
"currency": "USD",
"valid_until": "2026-10-06T08:15:00.000Z",
"valid_for_seconds": 900
}Price check links
Every priced answer carries receipt.check_url, a link to a page that confirms the price was computed on Last Price, when, and until when it holds. Send it with a price you quote. The buyer, or the buyer's agent, opens it with no account and no key. The page says the seller chose the pricing function, so it shows where the number came from, not that Last Price vouches for it, and it offers the buyer an independent check of the price.
- Single, batch (on each item), router, chain and pay-per-call answers all carry it, sandbox keys included.
- The link is signed. Change one character and the page answers 404 and says it is not genuine.
- The page names no workspace, pricing function or input, and it does not commit you to sell at the price.
- Agents read it as JSON with
?format=json(or anAccept: application/jsonheader), or as plain text with?format=text. - For a proof the buyer checks offline, against a published key, use a
signed_quotewhere your workspace has one.
{
"computed_price": 42.5,
"currency": "USD",
"receipt": {
"id": "9b1f3c2e-5d4a-4e8f-9a61-2c7b0d4e8f13",
"check_url": "https://last-price.ai/q/eyJ2IjoxLCJwIjo0Mi41...."
}
}Outcome terms
A price charged per outcome needs an exit condition: by when the outcome must happen, and what is owed if it does not. Without one, a job can stay “in progress” and keep being billed. Where outcome terms are on for your workspace, the answer for an outcome price carries an outcome_terms block that states them.
- A price counts as an outcome price when its
context.metadatasaysunit: "outcome", names a topology such asoutcome-basedorpay-on-success(intopology,pricing_modelorbilling_model), or carriesoutcome_terms. - State the terms in
context.metadata.outcome_terms:success_definition(what the buyer must see),resolve_by(an ISO 8601 duration such asP30DorPT48H, or an RFC 3339 time, one minute to one year away),on_timeout(no_charge,partialwithtimeout_share, orfull) andevidence(what proves it). Over MCP, pass them as theoutcome_termsargument ofcompute_priceorverify_price. - The answer gives the deadline as a time (
resolves_at) and the amount owed on timeout (owed_on_timeout). - Nothing is filled in for you. A term you left out is listed in
missing, with a default you could adopt insuggested, andcompleteis false untilsuccess_definition,resolve_byandon_timeoutare all stated. A term that cannot be read is listed inproblemswith the reason. POST /api/price-router/verify(andverify_price) adds the same block, so an outcome price with no deadline is reported as incomplete inoutcome_terms.noterather than judged on the number alone. The verdict itself does not change.- Single, batch (on each item), router, chain, pay-per-call and demo answers all carry it. Where outcome terms are off, nothing is added and nothing else changes.
Try your own numbers. The picture is worked out again by the same rules.
{
"computed_price": 40,
"currency": "USD",
"outcome_terms": {
"success_definition": "Ticket closed and the customer confirms.",
"resolve_by": "P7D",
"resolve_by_kind": "duration",
"resolves_at": "2026-10-26T08:00:00.000Z",
"on_timeout": "partial",
"timeout_share": 0.3,
"owed_on_timeout": 12,
"evidence": ["buyer_confirmation"],
"complete": true,
"missing": [],
"problems": [],
"suggested": {},
"note": null
}
}Request tracing
Compute responses can include a trace with ordered steps, handoffs, and total_ms. Steps describe cache lookup, routing, execution, fallback, constraints, and metering, with a status and duration_ms for each step. A cache hit has cache and meter steps only. Keep the response request_id when investigating a result. See the ComputeTrace schema in the API reference for the complete response contract.
Floor and ceilingChanged the price0 ms
Applied the minimum and maximum price.
Open a step to read what it did. The Commerce page draws the same view for every price you try.
The steps that can move the price (buyer_model, forge, explore, channel and constrain) carry price_before and price_after, rounded to the cent, so you can say which step changed a quote and by how much without reading detail.
Batch compute
Process up to 100 pricing requests in a single API call. Each item in the batch is evaluated independently and may route to different functions.
An item that does not pass validation is answered at its position as an error object with code: "validation_failed", its index and the failing fields, and the other items still run, as an item that fails to price does. Only a body that is not a list of 1 to 100 requests fails the whole call. This is switching on workspace by workspace; until then a schema error in any item answers 400 for the batch.
With outcome pricing on and the batch paid from your prepaid balance, each priced item carries its own outcome_window: report an item as rejected within 7 days and 70% of its price comes back. Items that failed were given back and have none.POST /api/price-router responses carry one too.
- requestsarray, required
- Array of pricing request objects (max 100)
- fail_fastboolean
- Abort the entire batch on the first failure (default: false)
- max_concurrencynumber
- Maximum number of parallel requests (default: 10)
# Batch compute prices (up to 100 items)
curl -X POST https://api.last-price.ai/api/compute/batch \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"requests": [
{
"product_id": "prod_001",
"product_type": "SaaS",
"current_price": 99.00,
"currency": "USD"
},
{
"product_id": "prod_002",
"product_type": "Hardware",
"current_price": 450.00,
"currency": "EUR",
"geo": "EU"
}
],
"fail_fast": false,
"max_concurrency": 10
}'
# Response
{
"results": [
{
"request_id": "req_001",
"product_id": "prod_001",
"computed_price": 128.70,
"currency": "USD",
"function_id": "fn_abc123"
},
{
"request_id": "req_002",
"product_id": "prod_002",
"computed_price": 531.00,
"currency": "EUR",
"function_id": "fn_def456"
}
],
"summary": {
"total": 2,
"succeeded": 2,
"failed": 0,
"total_cost": 0.0046,
"total_duration_ms": 120
}
}Routing policies
Routing policies control how the platform selects a pricing function for each request. You can configure strategy, weights, cost/latency constraints, and fallback chains.
For weighted routing in the dashboard, choose a function by name and set its relative weight. Use Previous functions and Next functions to reach more choices. Setting the same function again updates its weight; zero excludes it, and at least one weight must be positive. The JSON editor remains available. API and MCP requests still use function IDs as weight keys; obtain them from the function list rather than substituting names.
Automatic strategies only choose functions that can run: they skip a model function whose owner has not connected its provider, a model function with no provider, an external function with no endpoint, and a composite. Naming such a function with function_id still runs it, and the answer says what to set up.
max_latency_ms 100. Limits narrow the field before the strategy chooses; naming a function with function_id skips both.Try your own numbers. The picture is worked out again by the same rules.
cheapest
Select the function with the lowest compute cost
fastest
Select the function with the lowest latency
round_robin
Cycle through functions evenly
weighted
Distribute traffic by configured weights
policy
Rule-based selection from conditions
explicit
Caller specifies the function_id directly
default
Use the tenant's default function
- namestring, required
- Policy name, up to 255 characters
- strategyenum, required
- Routing strategy (see above)
- is_defaultboolean
- Make this the workspace default. Only the default policy is consulted when a request states no routing_preference
- fallback_function_idstring
- Single fallback function ID. Send null to clear it
- configobject
- Everything below lives inside this object, not at the top level
- config.weightsobject
- Function ID to weight mapping (for weighted strategy). Keys must be function IDs and at least one weight must be above zero
- config.rulesarray
- Array of condition → function rules (for policy strategy). Each rule needs a non-empty field, a supported operator, and a function_id
- config.max_latency_msnumber
- Maximum acceptable latency in ms. Applied when this policy's strategy selects a function
- config.max_cost_per_unitnumber
- Maximum base cost per compute unit, compared before the function's cost_multiplier. Applied when this policy's strategy selects a function
- config.fallback_chainarray
- Ordered list of fallback function IDs, used when the strategy yields nothing available
- config.learned_routingobject
- { "enabled": true } lets the router learn which function serves this policy best (see Learned Routing below)
How routing picks a function
- Only functions that can price are candidates: not an experiment assigner such as
lastprice/elo-ab-test, not a function whose provider is not connected, not an external function with no endpoint, not a composite, and not a rule_based function with no rule. Ties are broken by name, so the same request picks the same function every time. explicitneeds afunction_id(400validation_failedwithout one).weightedneeds a default policy with weights (400weighted_policy_required), and when no weighted function can serve, 400no_weighted_function_availablerather than an unweighted pick.- A policy that names a function routing can never pick (one that does not exist, that this workspace cannot reach, or that does not compute a price) is refused when saved, naming the field.
- The trace's route step and
routing.policyname the policy that decided. A function that is a draft or retired answers 409function_not_active; a provider that is not connected answers 409 with its setup code. - Saving a default policy replaces the previous default, and the response names it in
replaced_default. Every save answersapplies_within_seconds: how soon the next call uses it. - Skipping functions with nothing to run on applies to every workspace now. Leaving out experiment assigners and rule_based functions with no rule, breaking ties by name, strict weighted routing, the policy checks at save and the trace naming the policy are switching on workspace by workspace.
# Create a weighted routing policy with fallback
curl -X POST https://api.last-price.ai/api/routing-policies \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"name": "weighted-with-fallback",
"strategy": "weighted",
"is_default": true,
"config": {
"weights": {
"3f1a7c88-0b2e-4d51-9a63-1c4e7b905d12": 0.7,
"9d2b4e60-7a13-4c8f-b5e2-6f0a83c71d44": 0.3
},
"max_latency_ms": 200,
"fallback_chain": [
"c7e4a1f2-8d35-4b90-a6c1-2e58f3b74a09",
"5b8f0d33-6c21-4a7e-9f84-0d1c6e29b537"
]
}
}'Routing policies over MCP
Your agent can manage routing policies from its MCP session with five tools: list_routing_policies, get_routing_policy, create_routing_policy, update_routing_policy and delete_routing_policy. They call the same routes as above, with the same checks: a weighted policy needs a weight above zero, and the strategy must still work with the config a change leaves behind. Reading needs routing read scope; saving and deleting need routing write scope. Making a policy the default replaces the current one.
Routing one call
A policy sets how your workspace routes. One call can narrow it further under constraints, or with the routing argument of the compute_price MCP tool. The limits apply to every strategy, to your policy's rules and to its fallback chain. If they leave no function able to answer, the call is refused with a 404 naming the limit that ruled the rest out, before anything runs or is charged. A pinned function_id the same call rules out is refused rather than run. Being switched on workspace by workspace; until then these fields are accepted and ignored.
- constraints.only_functionsuuid[]
- Only these functions may answer
- constraints.excluded_functionsuuid[]
- These may not answer, not even as a fallback
- constraints.preferred_functionsuuid[]
- Tried first, in this order, among the functions allowed that can answer; if one fails, the next is tried before your fallback chain
- constraints.max_cost_per_unitnumber
- The most you will pay per metered unit: the function's rate times its multiplier
- constraints.max_latency_msinteger
- Skip functions slower than this on average (new, unmeasured ones are kept), and stop waiting for an external function after it
- constraints.allow_fallbacksboolean
- false: fail the call when the chosen function fails, rather than trying your fallback chain
# Price with anything but one function, for at most 0.002 per unit
curl -X POST https://api.last-price.ai/api/compute/price \
-H "x-api-key: YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"routing_preference": "fastest",
"context": { "currency": "USD", "metadata": { "unit_cost": 0.47 } },
"constraints": {
"excluded_functions": ["c7e4a1f2-8d35-4b90-a6c1-2e58f3b74a09"],
"max_cost_per_unit": 0.002,
"allow_fallbacks": false
}
}'Circuit breaker
Each pricing function has an automatic circuit breaker that prevents cascading failures. When a function fails repeatedly, the circuit opens and requests are routed to the fallback chain instead. The hourly endpoint health probe of external functions counts toward it as well (see Review and Health).
config.circuit_breaker. A failing function stops taking traffic until trial requests show it has recovered.Try your own numbers. The picture is worked out again by the same rules.
Closed
Normal operation - requests flow through to the function
Open
Function is unhealthy - requests are immediately rejected or rerouted to fallbacks
Half-open
Recovery mode - a limited number of trial requests are allowed to test if the function has recovered
- failure_thresholdnumber
- Consecutive failures before opening the circuit (default: 5)
- recovery_timeout_msnumber
- Milliseconds to wait before transitioning from open → half-open (default: 30000)
- half_open_max_callsnumber
- Trial requests allowed in half-open state (default: 3)
# Create a routing policy with circuit breaker config
curl -X POST https://api.last-price.ai/api/routing-policies \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"name": "explicit-with-breaker",
"strategy": "explicit",
"config": {
"fallback_chain": ["c7e4a1f2-8d35-4b90-a6c1-2e58f3b74a09"],
"circuit_breaker": {
"failure_threshold": 3,
"recovery_timeout_ms": 60000,
"half_open_max_calls": 2
}
}
}'Learned routing
A policy whose strategy is cheapest, fastest, round_robin or weighted can learn which of the functions it chooses among serves your workspace best. Every routed call is already logged with the function chosen and how it went; learned routing scores each function on whether it answered, how fast, and its billed rate, and routes by Thompson sampling: mostly to the best scorer, sometimes to one it knows less about, so a function that improves is noticed.
- It only chooses among the functions your policy already allows: reachable, active, circuit closed, able to serve the request, within your cost and latency ceilings, and with a weight above zero under
weighted. - Until it has seen 30 routed calls across those functions in the last 14 days, your strategy decides, exactly as before.
- A call that a fallback had to answer counts against the function chosen; a call refused for missing inputs does not.
- Turn it on per policy with
"config": { "learned_routing": { "enabled": true } }, or the switch in the Edit Policy dialog. - See what it has learned with
GET /api/routing-policies/{id}/learnedor the MCP toolget_learned_routing: calls, success rate, latency, expected reward and the share of calls each function would get now.
Where learned routing is off for a workspace, the setting is saved and the router ignores it, and the estimates route answers with released: false. Questions: support@last-price.ai.
# What learned routing has learned for a policy
curl https://api.last-price.ai/api/routing-policies/POLICY_ID/learned \
-H "Authorization: Bearer lp_<hex>"
# Response (trimmed)
{
"released": true,
"enabled": true,
"learning": true,
"reason": null,
"fallback_strategy": "cheapest",
"total_calls": 412,
"min_calls": 30,
"arms": [
{ "name": "acme/margin-guard", "calls": 301, "success_rate": 0.98, "latency_ms": 120, "expected_reward": 0.79, "route_share": 0.93 },
{ "name": "acme/fast-quote", "calls": 111, "success_rate": 0.81, "latency_ms": 60, "expected_reward": 0.68, "route_share": 0.07 }
]
}Learned routing for requests
A compute call does not need a saved policy to learn. When it names its own strategy as routing_preference (cheapest, fastest, round_robin or weighted), add "learned_routing": true and the router learns which of the functions that strategy chooses from serves your workspace best, the same way a policy does. It works on POST /api/compute/price, every item of POST /api/compute/batch, POST /api/price-router, pay-per-call requests, and the MCP tool compute_price.
- It only chooses among the functions the strategy would: reachable, active, circuit closed and able to serve the request; under
weighted, the functions your default policy weights above zero (every one when none is weighted). As with any request strategy, no policy ceiling applies. - Until it has seen 30 routed calls across those functions in the last 14 days, the strategy you named decides, exactly as without the flag. A request and a policy learn from the same routed calls, so either one gathers data for both.
- It is ignored for
default,policyandexplicit, and with afunction_id; a default policy that turned learning on still learns for those calls. - When it chose, the trace's
routestep sayslearned. - Once it is on for your workspace, pay-per-call calls teach it too: a settled call counts like any other, a call that failed counts against the function chosen, and so does one that could not be sold because the function metered above the price, metered an unusable cost, or ran too long to settle. A payment that simply did not settle says nothing about the function and is not counted.
- See what it has learned for a strategy with
GET /api/routing/learned?strategy=cheapest, the MCP toolget_learned_routingwithstrategy, or "Learned routing for requests" on the Routing Policies page.
Like policy learning, this is being switched on workspace by workspace. Until it is on for yours, learned_routing is accepted and ignored, and the estimates route answers with released: false. Questions: support@last-price.ai.
# Let the router learn within the cheapest strategy for this call
curl -X POST https://api.last-price.ai/api/compute/price \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"routing_preference": "cheapest",
"learned_routing": true,
"context": { "product_id": "prod_001", "current_price": 49.99, "currency": "USD" }
}'
# What it has learned for calls like this one
curl "https://api.last-price.ai/api/routing/learned?strategy=cheapest" \
-H "Authorization: Bearer lp_<hex>"
# Response (trimmed)
{
"scope": "request",
"strategy": "cheapest",
"released": true,
"learning": false,
"reason": "collecting",
"total_calls": 12,
"min_calls": 30,
"arms": [
{ "name": "acme/margin-guard", "calls": 9, "success_rate": 0.91, "latency_ms": 120, "route_share": 0 },
{ "name": "acme/fast-quote", "calls": 3, "success_rate": 0.6, "latency_ms": 60, "route_share": 0 }
]
}The last tick
A wall of 24 panels at /last-tick, each recomputing one price every few seconds with a different pricing function: cost-plus, the optimizer's profit optimum, a competitor undercut with a floor, the metering formula, an A/B split, Thompson sampling, a second-price auction and more. It is a preview and is not open to everyone yet.
- Every market is simulated: seeded demand, costs and bidders, several taken from the scenarios Last Price uses to test its own pricing. No workspace or customer data is read and no API call is made.
- A price depends only on the panel and the tick (one tick is 2.5 seconds of UTC time), so every visitor sees the same wall at the same moment.
- Panels refresh on their own rhythms. Every 90 to 180 seconds the whole wall refreshes at once for a moment, then the rhythms drift apart again. No panel ever settles for good.
- Tap a panel to see its function, the market behind it and what it read on this tick. Pause holds the wall where it is.
To price your own products with these functions, see Built-in Functions and Compute Price.
Pricing function cookbook
Small pricing functions, each about ten lines of plain JavaScript, that you run on your own endpoint and register as external_api functions. Copy one, change the numbers, and it answers compute calls like any built-in. Every recipe and request on this page is run by our test suite, so what you copy works.
Last Price POSTs { context, constraints, options } to your endpoint: the same context a compute call sends, including metadata as you sent it. Answer with { computed_price, confidence, explanation }: a positive price, a confidence from 0 to 1, and one sentence. An error status or a missing price counts as a failed call, so your fallback chain answers instead.
Walkthrough
- Run a recipe. Save the cost plus recipe as
cost-plus.mjsand this server next to it asserve.mjs, then runnode serve.mjs cost-plus. It needs Node 18 or later and nothing else.// Serve one recipe as an external_api pricing function: node serve.mjs cost-plus (PORT defaults to 8787). // Set FUNCTION_TOKEN to require the bearer token you register in auth_config. import { createServer } from 'node:http'; const name = process.argv[2] ?? 'cost-plus'; const { default: price } = await import(`./${name}.mjs`); const token = process.env.FUNCTION_TOKEN; createServer(async (req, res) => { let body = ''; for await (const chunk of req) body += chunk; let status = 200; let result; if (req.method !== 'POST') [status, result] = [405, { error: 'POST a JSON body' }]; else if (token && req.headers.authorization !== `Bearer ${token}`) [status, result] = [401, { error: 'bad token' }]; else { try { result = price(JSON.parse(body || '{}')); } catch (error) { [status, result] = [422, { error: error.message }]; } } res.writeHead(status, { 'Content-Type': 'application/json' }).end(JSON.stringify(result)); }).listen(Number(process.env.PORT ?? 8787), () => console.log(`${name} is listening`)); - Put it on a public HTTPS URL. Any host that runs Node works. Private and internal addresses are refused. To require a token, set
FUNCTION_TOKENon the server and register the same token as"auth_config": { "type": "bearer", "token": "..." }. It is stored encrypted and never returned. - Register and activate it.
curl -X POST https://api.last-price.ai/api/functions \ -H "Authorization: Bearer lp_<hex>" \ -H "Content-Type: application/json" \ -d '{ "name": "acme/cost-plus", "display_name": "Cost plus", "description": "Unit cost plus a margin, from the Last Price cookbook", "execution_type": "external_api", "endpoint_url": "https://pricing.example.com/cost-plus", "tags": [ "cookbook" ] }' # Use the id the register call returned curl -X PATCH https://api.last-price.ai/api/functions/FUNCTION_ID \ -H "Authorization: Bearer lp_<hex>" \ -H "Content-Type: application/json" \ -d '{"status":"active"}' - Compute a price with it.
curl -X POST https://api.last-price.ai/api/compute/price \ -H "Authorization: Bearer lp_<hex>" \ -H "Content-Type: application/json" \ -d '{ "function_id": "FUNCTION_ID", "context": { "currency": "USD", "metadata": { "unit_cost": 40, "margin_pct": 35 } }, "options": { "include_explanation": true, "include_confidence": true } }' # Response (trimmed) { "function_name": "acme/cost-plus", "computed_price": 54, "currency": "USD", "confidence": 0.9, "explanation": "Unit cost 40.00 plus a 35% margin" }
Recipes
Each recipe reads its inputs from the compute call, mostly from context.metadata, and refuses a call that is missing one rather than guessing. Serve any of them with node serve.mjs RECIPE_NAME.
Cost plus
Charge what it costs you plus a margin. The usual first price when there is no market data yet.
Reads: metadata.unit_cost (required), metadata.margin_pct (default 30), constraints.min_price
// cost-plus.mjs
// Cost plus: the unit cost plus a margin. Send metadata.unit_cost and, optionally, metadata.margin_pct (default 30).
export default function price({ context, constraints = {} }) {
const cost = Number(context.metadata?.unit_cost);
if (!(cost > 0)) throw new Error('metadata.unit_cost must be a positive number');
const margin = Number(context.metadata?.margin_pct ?? 30);
const p = Math.max(cost * (1 + margin / 100), constraints.min_price ?? 0);
return {
computed_price: Math.round(p * 100) / 100,
confidence: 0.9,
explanation: `Unit cost ${cost.toFixed(2)} plus a ${margin}% margin`,
};
}
# Try it: send this to POST /api/compute/price with your function_id
{
"context": {
"currency": "USD",
"metadata": {
"unit_cost": 40,
"margin_pct": 35
}
}
}
# Your function answers
{
"computed_price": 54,
"confidence": 0.9,
"explanation": "Unit cost 40.00 plus a 35% margin"
}Competitor match with a floor
Match the cheapest competitor, but never sell below cost plus a minimum margin.
Reads: metadata.unit_cost and metadata.competitor_prices (required), metadata.min_margin_pct (default 10), constraints.min_price
// competitor-match.mjs
// Competitor match with a floor: match the lowest competitor, but never go below cost plus a minimum margin.
export default function price({ context, constraints = {} }) {
const cost = Number(context.metadata?.unit_cost);
const rivals = (context.metadata?.competitor_prices ?? []).map(Number).filter((p) => p > 0);
if (!(cost > 0) || rivals.length === 0) throw new Error('send metadata.unit_cost and metadata.competitor_prices');
const floor = Math.max(cost * (1 + Number(context.metadata?.min_margin_pct ?? 10) / 100), constraints.min_price ?? 0);
const lowest = Math.min(...rivals);
const p = Math.max(lowest, floor);
return {
computed_price: Math.round(p * 100) / 100,
confidence: p === lowest ? 0.85 : 0.7,
explanation: p === lowest ? `Matched the lowest competitor at ${lowest.toFixed(2)}` : `Held at the floor ${floor.toFixed(2)}; the lowest competitor is ${lowest.toFixed(2)}`,
};
}
# Try it: send this to POST /api/compute/price with your function_id
{
"context": {
"currency": "USD",
"metadata": {
"unit_cost": 45,
"competitor_prices": [
49.5,
52,
47.25
]
}
}
}
# Your function answers
{
"computed_price": 49.5,
"confidence": 0.7,
"explanation": "Held at the floor 49.50; the lowest competitor is 47.25"
}Time decay
Mark a listing down a little every day it does not sell, down to a floor. Good for seasonal stock and event tickets.
Reads: current_price (the list price) and metadata.listed_at (required), metadata.decay_pct_per_day (default 2), metadata.floor_pct (default 50), timestamp
// time-decay.mjs
// Time decay: take a set percent off the list price for every full day since metadata.listed_at, down to a floor.
export default function price({ context }) {
const listed = Date.parse(context.metadata?.listed_at);
const now = context.timestamp ? Date.parse(context.timestamp) : Date.now();
if (!(context.current_price > 0) || Number.isNaN(listed)) throw new Error('send current_price and metadata.listed_at');
const days = Math.max(0, Math.floor((now - listed) / 86_400_000));
const decay = (1 - Number(context.metadata?.decay_pct_per_day ?? 2) / 100) ** days;
const factor = Math.max(decay, Number(context.metadata?.floor_pct ?? 50) / 100);
return {
computed_price: Math.round(context.current_price * factor * 100) / 100,
confidence: 0.8,
explanation: `Listed ${days} days ago, so ${(factor * 100).toFixed(1)}% of the list price`,
};
}
# Try it: send this to POST /api/compute/price with your function_id
{
"context": {
"currency": "USD",
"current_price": 120,
"timestamp": "2026-10-11T09:00:00Z",
"metadata": {
"listed_at": "2026-10-01T09:00:00Z"
}
}
}
# Your function answers
{
"computed_price": 98.05,
"confidence": 0.8,
"explanation": "Listed 10 days ago, so 81.7% of the list price"
}Inventory aware
Raise the price as stock runs low and lower it when there is too much, within a limit you set.
Reads: current_price, metadata.stock and metadata.target_stock (required), metadata.max_move_pct (default 20)
// inventory-aware.mjs
// Inventory aware: raise the price as stock runs low, lower it when there is too much, by at most metadata.max_move_pct.
export default function price({ context }) {
const stock = Number(context.metadata?.stock);
const target = Number(context.metadata?.target_stock);
if (!(context.current_price > 0) || !(stock >= 0) || !(target > 0)) throw new Error('send current_price, metadata.stock and metadata.target_stock');
const maxMove = Number(context.metadata?.max_move_pct ?? 20) / 100;
const move = Math.max(-maxMove, Math.min(maxMove, (1 - stock / target) * maxMove));
return {
computed_price: Math.round(context.current_price * (1 + move) * 100) / 100,
confidence: 0.75,
explanation: `${stock} in stock against a target of ${target}: ${move >= 0 ? '+' : ''}${(move * 100).toFixed(1)}%`,
};
}
# Try it: send this to POST /api/compute/price with your function_id
{
"context": {
"currency": "USD",
"current_price": 80,
"metadata": {
"stock": 5,
"target_stock": 50
}
}
}
# Your function answers
{
"computed_price": 94.4,
"confidence": 0.75,
"explanation": "5 in stock against a target of 50: +18.0%"
}Same price for agent buyers
An AI agent buying for someone never pays more than a person would: no agent surcharge.
Reads: current_price (required), buyer_type, metadata.person_price
// fair-agent-price.mjs
// Same price for agent buyers: an AI agent never pays more than a person would. No agent surcharge.
export default function price({ context }) {
const listed = Number(context.current_price);
if (!(listed > 0)) throw new Error('send current_price');
const personPrice = Number(context.metadata?.person_price ?? listed);
const isAgent = context.buyer_type === 'agent';
const p = isAgent ? Math.min(listed, personPrice) : listed;
return {
computed_price: Math.round(p * 100) / 100,
confidence: 0.95,
explanation: p < listed ? `Agent pays the person price ${p.toFixed(2)}, not ${listed.toFixed(2)}` : 'Same price for agents and people',
};
}
# Try it: send this to POST /api/compute/price with your function_id
{
"context": {
"currency": "USD",
"current_price": 59,
"buyer_type": "agent",
"metadata": {
"person_price": 49
}
}
}
# Your function answers
{
"computed_price": 49,
"confidence": 0.95,
"explanation": "Agent pays the person price 49.00, not 59.00"
}Round to a charm price
Turn any computed price into the nearest price ending in .99, never below your floor.
Reads: current_price or metadata.raw_price (required), metadata.ending (default 0.99), constraints.min_price
// charm-round.mjs
// Round to charm: the nearest price ending in .99 (or metadata.ending), never below constraints.min_price.
export default function price({ context, constraints = {} }) {
const raw = Number(context.metadata?.raw_price ?? context.current_price);
if (!(raw > 0)) throw new Error('send current_price or metadata.raw_price');
const ending = Number(context.metadata?.ending ?? 0.99);
const min = constraints.min_price ?? 0;
let p = Math.max(ending, Math.round(raw - ending) + ending);
if (p < min) p = Math.ceil(min - ending) + ending;
return {
computed_price: Math.round(p * 100) / 100,
confidence: 0.9,
explanation: `Rounded ${raw.toFixed(2)} to the charm price ${p.toFixed(2)}`,
};
}
# Try it: send this to POST /api/compute/price with your function_id
{
"context": {
"currency": "USD",
"current_price": 41.2
}
}
# Your function answers
{
"computed_price": 40.99,
"confidence": 0.9,
"explanation": "Rounded 41.20 to the charm price 40.99"
}Bundle
Price a bundle as the sum of its items less a bundle discount, never below your floor.
Reads: metadata.items as [{ price, quantity }] (required), metadata.bundle_discount_pct (default 15), constraints.min_price
// bundle.mjs
// Bundle: add up the items, then take a bundle discount, never going below constraints.min_price.
export default function price({ context, constraints = {} }) {
const items = context.metadata?.items ?? [];
const total = items.reduce((sum, item) => sum + Number(item.price) * Number(item.quantity ?? 1), 0);
if (!(total > 0)) throw new Error('send metadata.items as [{ "price": 10, "quantity": 1 }]');
const discount = Number(context.metadata?.bundle_discount_pct ?? 15);
const p = Math.max(total * (1 - discount / 100), constraints.min_price ?? 0);
return {
computed_price: Math.round(p * 100) / 100,
confidence: 0.85,
explanation: `${items.length} item${items.length === 1 ? '' : 's'} worth ${total.toFixed(2)} with a ${discount}% bundle discount`,
};
}
# Try it: send this to POST /api/compute/price with your function_id
{
"context": {
"currency": "USD",
"metadata": {
"items": [
{
"price": 30
},
{
"price": 20,
"quantity": 2
}
],
"bundle_discount_pct": 15
}
}
}
# Your function answers
{
"computed_price": 59.5,
"confidence": 0.85,
"explanation": "2 items worth 70.00 with a 15% bundle discount"
}Tested docs
This page is checked on every change we make. Each recipe is run on the request shown and must give the answer shown, and the walkthrough goes through the real register, activate and compute steps. The examples under Pricing Functions and Compute Price are sent to the API the same way. If a change would break an example, the change fails before the docs do. Spot something that does not work? Write to support@last-price.ai.
Price router
Price Router is the multi-vendor pricing facade - a single API endpoint in front of the entire catalog of built-in and tenant-owned pricing models. Think of it as the "OpenRouter for price computation": you submit a pricing request and the router selects the best function based on your routing policy, handles metering, and returns the result.
The route mirrors POST /api/compute/price but is the canonical product-named entrypoint for external clients, OpenAPI tooling, and AI-agent tool runtimes. The GET returns a public capability descriptor - no auth needed - so AI agents can introspect the network at planning time.
Overview
The Price Router dashboard at /price-router shows all available routing strategies, the built-in function catalog, and a live test console. It links out to the Routing policies, Compute, and Functions pages so you don't lose context.
| Strategy | Description |
|---|---|
| cheapest | Pick the lowest-cost function that can handle the request |
| fastest | Pick the function with the lowest median latency |
| round_robin | Distribute requests evenly across eligible functions |
| weighted | Send traffic proportional to per-function weights |
| explicit | Use the specified function_id. A missing, unreachable, or inactive id fails immediately; the fallback chain applies only if the chosen function fails while running |
| default | Use the tenant's active routing policy |
Route a request
Submit a pricing request to the router. The request body is identical to POST /api/compute/price.
Naming a function, by id or by name, reaches built-in functions, functions your workspace owns, and functions with a public marketplace listing. Anything else is answered exactly as a function that does not exist, so the response never reveals whether another workspace holds it. The same rule applies to the single compute endpoint and to every item of a batch.
POST /api/price-router
Authorization: Bearer lp_<hex>
Content-Type: application/json
{
"function_id": "00000000-0000-0000-0000-000000000001", // optional UUID - omit to let routing_preference pick
"routing_preference": "explicit", // cheapest | fastest | round_robin | weighted | policy | default
"learned_routing": false, // optional: true learns within cheapest | fastest | round_robin | weighted
"context": {
"product_id": "prod_001",
"product_type": "ecommerce",
"current_price": 99.00,
"currency": "USD",
"customer_segment": "enterprise"
},
"options": {
"include_explanation": true,
"include_confidence": true
}
}
// Response
{
"request_id": "req_...",
"function_id": "00000000-0000-0000-0000-000000000001",
"function_name": "lastprice/jale-optimizer",
"computed_price": 109.00,
"currency": "USD",
"confidence": 0.87,
"explanation": "Elasticity-adjusted recommendation based on 3-month cohort data",
"alternatives": [],
"metering": { "input_units": 1, "output_units": 1, "compute_duration_ms": 42, "cost": 0.005 },
"metadata": { "model_version": "1", "routing_reason": "explicit", "cached": false }
}Pricing chains
A pricing chain runs several functions in order in one request. Each stage's price becomes the next stage's current price, and the metadata you give a stage stays in the context for every later stage. A typical chain prices from cost, holds the result at or under a competitor, then rounds to a charm ending. Where pricing chains are off for a workspace, the endpoint answers 501 with the code pricing_chains_not_enabled.
- Stages. A function stage runs one built-in or workspace function, named by function_id or function_name, with its own constraints. A clamp stage runs no function: it holds the running price to min_price, max_price, or max_over_competitor_pct (a cap that many percent above the context's competitor_price). Up to 10 stages. LLM and vision stages let a model adjust or annotate the price (see Model stages below); until they are on for your workspace they are refused with 422 stage_kind_unavailable.
- Guardrails at the end. Stages run without your workspace guardrails. They apply once, to the chain's final price, measured from the current price you sent, together with the top-level constraints. A 10% maximum change holds the whole chain within 10%, not each stage.
- Metering. Each function stage that returns a price is one metered compute call with its own usage event, costing exactly what the same request costs on its own. A stage answered by its fallback is one call at the fallback's cost. Skipped stages, clamp stages and the guardrail step are free. The response's metering.cost is the sum, and the top-level receipt is the usage event that carries the final price.
- Failures. A failing function stage tries its fallback_function_name (or fallback_function_id) once. If that also fails, on_error skip (the default) passes the previous price through and marks the stage skipped; on_error fail stops the chain with 502. A missing input, such as a competitive stage with no competitor_price, always stops the chain with a 400 naming the stage. A chain that stops charges nothing.
Try your own numbers. The picture is worked out again by the same rules.
Any credential with the price:compute scope can run a chain, including an agent's API key. Send it in x-api-key:
curl -X POST https://api.last-price.ai/api/price-router/chain \
-H "x-api-key: $LASTPRICE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"pipeline": {
"stages": [
{ "label": "cost-plus", "function_name": "lastprice/cost-plus",
"metadata": { "unit_cost": 10, "target_margin_pct": 30 } },
{ "label": "competitor clamp", "kind": "clamp", "max_over_competitor_pct": 0,
"metadata": { "competitor_price": 13.2 } },
{ "label": "charm", "function_name": "lastprice/jale-psychological" }
]
},
"context": { "product_id": "SKU-1", "currency": "USD" },
"options": { "include_explanation": true }
}'// Response (abridged; costs depend on request size)
{
"computed_price": 12.99,
"currency": "USD",
"confidence": 0.75, // the lowest stage confidence
"stages": [
{ "index": 0, "kind": "function", "label": "cost-plus", "status": "ok",
"price_in": null, "price_out": 14.29, "metered": true,
"metering": { "cost": 0.001175 }, "receipt": { "id": "..." } },
{ "index": 1, "kind": "clamp", "label": "competitor clamp", "status": "ok",
"price_in": 14.29, "price_out": 13.2, "metered": false, "metering": null },
{ "index": 2, "kind": "function", "label": "charm", "status": "ok",
"price_in": 13.2, "price_out": 12.99, "metered": true,
"metering": { "cost": 0.00138 }, "receipt": { "id": "..." } }
],
"guardrails": { "source": "default_cost_floor", "price_before": 12.99, "price_after": 12.99, "notes": [] },
"metering": { "stages_metered": 2, "cost": 0.002555 },
"receipt": { "id": "..." }
}A stage with a fallback, and a chain that must not answer if that stage fails:
{
"pipeline": {
"stages": [
{ "function_name": "acme/demand-model",
"fallback_function_name": "lastprice/jale-optimizer",
"on_error": "fail",
"metadata": { "elasticity": -1.8 } },
{ "function_name": "lastprice/jale-psychological" }
]
},
"context": { "product_id": "SKU-2", "current_price": 49, "currency": "USD" },
"constraints": { "max_price": 59 }
}Any function your workspace can call can be a stage, so a decision function such as a stopping rule can run after the quote that feeds it once it is registered.
Model stages: llm and vision
An llm stage gives a language model your prompt and the chain's running price, and the model either adjusts the price or leaves it and annotates it. A vision stage does the same while looking at a product image. Where model stages are off for a workspace, a chain that names one answers 422 with the code stage_kind_unavailable. A model stage needs a price to work on, so it comes after a function stage or you send current_price.
- Fields. prompt (up to 2,000 characters; it may use {{price}}, {{currency}}, {{product_type}}, {{customer_segment}}, {{geo}}, {{channel}} and {{metadata.<key>}}), mode (adjust, the default, or annotate), max_change_pct (how far an adjust may move the price, default 15, at most 50), timeout_ms (default 10000, from 1000 to 30000) and on_error (skip, the default, or fail). A vision stage also takes image_url (or uses the context's metadata.image_url) and needs image_consent: true.
- Strict answers. The model answers in a fixed shape: action (adjust or annotate), price (null for annotate), confidence from 0 to 1, a short reason and up to five tags. An answer with any other field, a price moved further than max_change_pct, or an adjust from an annotate stage is refused, and the stage is skipped (invalid_model_output) or stops the chain with on_error fail. A model that does not answer within timeout_ms is skipped with stage_timeout, and a model error with model_failed. Every stage that answered returns its annotation, and the guardrails still apply to the chain's final price.
- Metering. Each model stage that answers is one metered model call, recorded as an LLM usage event with its own tokens and cost; the cost is in the stage's metering and in the chain's total. The call runs on your workspace's connected model key when you have one. A model stage is not a pricing function call, so it draws nothing from a prepaid balance. A skipped stage costs nothing.
- Privacy. The model sees only the running price, currency, product type, segment, region, channel and short metadata values under keys that do not name a person: emails, phone numbers, names, addresses, ids and locations are left out, and a placeholder for one reads [withheld]. Prompts, images and answers are never logged.
- Images. image_url must be a public https address. Private, internal, loopback and cloud metadata addresses are refused with 400 unsafe_image_url, as are hosts that resolve to one; a vision stage with no image stops with 400 missing_image_url.
- No face or emotion analysis. image_consent: true confirms you may send the image to a third-party model. Vision stages look at the product, its packaging and its condition, never at people: a prompt that asks about faces, expressions, emotions or personal characteristics is refused with 422 vision_policy_refused, the model is told to ignore people, and an answer that describes them is refused.
{
"pipeline": {
"stages": [
{ "function_name": "lastprice/cost-plus", "metadata": { "unit_cost": 10 } },
{ "kind": "llm", "label": "launch nudge", "max_change_pct": 10,
"prompt": "This {{product_type}} launches next week in {{geo}}. Adjust for launch demand." },
{ "kind": "vision", "label": "condition", "mode": "annotate", "image_consent": true,
"image_url": "https://cdn.example.com/sku-1.jpg",
"prompt": "Describe the item's condition and packaging." }
]
},
"context": { "product_type": "ecommerce", "geo": "US", "currency": "USD" }
}
// Each model stage in the response carries its annotation:
{ "index": 1, "kind": "llm", "status": "ok", "price_in": 14.29, "price_out": 15.49,
"metered": true, "metering": { "input_units": 412, "output_units": 38, "cost": 0.000113 },
"annotation": { "action": "adjust", "price": 15.49, "confidence": 0.7,
"reason": "Launch week demand supports a small premium.", "tags": ["launch"] } }From an agent: the run_pricing_chain MCP tool runs a chain with the same stages.
Reference pipelines without a key
POST /api/public/pipelines runs one of the seven reference pipelines on the pricing-chain engine, with no API key. It is what the pipeline page at /price-check/pipeline uses. Each pipeline becomes a chain of real stages: built-in pricing functions, a market clamp from the shared price pool, and model stages, so every number in the answer was computed. When runs are off, the endpoint answers 501 with the code pipeline_execution_unavailable, and GET /api/public/pipelines still lists the pipelines with the stages each would run.
- What to send. pipeline (fast_path by default), and either context.current_price (today's price) or context.unit_cost (what one unit costs you, with an optional target_margin_pct). Optional: product.name (looks the product up in the pool), product.product_type, product.description (read by the reasoning stage), product.image_url with image_consent: true (read by the vision stage), context.competitor_price and context.currency. The body is at most 4 KB.
- What each pipeline runs. fast_path prices, then rounds to a charm ending. reason_first adds a reasoning stage on the description; vision_first and direct_multimodal add a vision stage on the image. retrieval_augmented holds the price within 5% of the market median from the pool (or your competitor_price). fan_out_maximalist runs all of them. cascade runs the fast path and escalates to the reasoning chain when its confidence is under 0.8.
- What did not run. A stage that cannot run, such as a vision stage with no image, a model stage while model stages are off for keyless runs, or market retrieval with fewer than three recent pool prices, is listed under not_run with a reason_code, and the rest of the pipeline still prices.
- Limits. 10 runs per hour per IP address, reported in the X-Demo-Limit, X-Demo-Remaining and X-Demo-Reset headers; past it, 429 with Retry-After. Runs use the public demo workspace and built-in functions only. Market retrieval reports a median and a count, never the pool's rows. To run your own functions, use a pricing chain with an API key.
curl -X POST https://api.last-price.ai/api/public/pipelines \
-H "Content-Type: application/json" \
-d '{
"pipeline": "retrieval_augmented",
"product": { "name": "Pro plan", "vertical": "saas" },
"context": { "current_price": 49, "currency": "USD" }
}'// Response (abridged)
{
"pipeline": "retrieval_augmented",
"engine": "pricing-chain",
"computed_price": 46.99,
"currency": "USD",
"stages": [
{ "label": "Optimize current price", "status": "ok", "price_in": 49, "price_out": 48.1 },
{ "label": "Hold near the market", "kind": "clamp", "status": "ok", "price_in": 48.1, "price_out": 46.2 },
{ "label": "Charm rounding", "status": "ok", "price_in": 46.2, "price_out": 46.99 }
],
"not_run": [],
"market": { "matches": 7, "median": 44, "currency": "USD", "window_days": 90, "used_as_competitor_price": true },
"metering": { "cost": 0.0026, "stages_metered": 2, "model_calls": 0 }
}The price check page
last-price.ai/price-check/pipeline is the same run as a form: pick a pipeline, enter today's price or your cost, optionally a name, description and image, and it shows the price with every stage that ran, every stage that did not and why, and the market median when the pool has one. It appears in the site navigation once runs are switched on. Agents can do the same with the run_reference_pipeline MCP tool, and list_pricing_pipelines shows the pipelines.
Ask by link
Some assistants (Perplexity, ChatGPT search, Gemini) can open a web page but cannot send a request with a body, so they cannot call the API. They can open last-price.ai/ask?item=…&price=…¤cy=…&where=… instead, and read the answer: whether the price is fair, too high or too low, judged by the same verifier as POST /api/price-router/verify against what sellers ask for the item on public web pages, with each page listed. No key, no account and no model call.
- The link.
item(orq) is required.pricetakes 5852, 5,852.33 or 5 852,33 €.currencydefaults to USD, or comes from a symbol in the price.whereis a country or city,sideis buying (the default) or selling, andlist_price(ormsrp) adds how the price compares with the maker's list price. - The answer. A page by default; add
format=textfor plain text orformat=json(or sendAccept: application/json) for the verdict, the band it was judged against and the market pages. Withoutpriceit gives the market range. With no market prices found, the verdict is unknown and the page says why. - Limits. An answer is reused for 15 minutes for the same item and currency. A new market search counts against 20 an hour from one address and 300 a day in all; past either the page still answers, without market prices.
Price from a photo
Send what you captured of one item (photos or screenshots, a PDF such as an invoice, a link to a listing, a description or a product code) to POST /api/price-router/pipelines and get a price for it. This is what Get price in the mobile app calls, and what Price an item on the Price Router Pipelines tab calls on the web. Where it is off for a workspace, the endpoint answers 501 with the code pipeline_execution_unavailable.
- Understand. One model call reads every attachment together and names the item, its brand, model and condition, any price it can read (a tag, a listing, an invoice line), and a low, typical and high value. The answer must match a strict schema or the request fails with 502 and nothing is charged.
- Price. The typical value, rounded to the currency, is
computed_price. Low and high come back as the quick sale and top of range alternatives. When the item cannot be recognized there is no price:computed_priceis null,confidenceis 0, andexplanationandvaluation.would_helpsay what would fix it. - Your price. A
current_priceyou send is the price you have in mind. It is compared with the estimate (valuation.target_gap) and never used as the price. - Selling or buying. Send
commercial.sideasselling(the default) orbuying. The value is the same either way; the range is labelled for your side (quick sale and top of range when selling, opening offer and most to pay when buying), the comparison with your price reads the right way round, and the side comes back asvaluation.side. - Ready to post. With a price,
valuation.write_upcarries a listing (title and description, no price in the text) when selling, or a message to the seller with the opening offer filled in when buying. The amount in a message is always written by our code, never by the model. - Share link. With a price,
share_urlis a link to a page on last-price.ai showing the price as a card, with a preview image chat apps show before it is opened. The price is signed into the link, so a changed link opens nothing. Anyone with the link can see the card without signing in; the mobile app opens it with the item ready to price again. - Photos of several things. Send
commercial.photosasgroupwith two or more photos that may show different things. The attachments are numbered for the model, and when they show more than one thing,valuation.photo_groupslists them by thing (0-based attachment indexes, one list per thing). The price is for the first list's thing; price each other list with its own call. Left out, every attachment is read as the same item. The mobile app sends it for every check with two or more photos, so nobody has to say whether the photos show one thing or several. - Who it is for.
commercial.intent(selling,buyingorboth) says what the person uses the app for, as they answered when they first opened it. It is recorded with the check and never changes the price. - On the web, with no key. The price check at
last-price.ai/price-checkruns the same pricing for anyone, with no account, throughPOST /api/public/price-check: up to 4 photos, PDFs, links or descriptions, selling or buying, a currency and the price you hope to get or are being asked. It answers like this endpoint, withouttenant_id, and allows 6 checks an hour from one address. Photos are shrunk in the browser before they are sent and are not stored. - Barcodes. A
skuattachment holds a product code, such as an EAN or UPC, and is read alongside everything else in the bundle. - Links. A link's page is read through a fetch that only reaches public addresses, follows no redirects and keeps the first megabyte of HTML. A page that cannot be read is priced from its address alone, counted in
valuation.pages_unread. - Signals.
bundle.signalscarries what the person allows from their phone and the moment: battery and charging, Wi-Fi or mobile data, the exact location with the store or place they are in, the local time, the device and its settings, how each photo was taken and this visit. Your account's own price history is read here, never sent. Withworldallowed, the public holidays near the date, the shopping moment (Black Friday, the January sales) and recent news about the item and the place are read too. Only the groups listed inconsent.facetsare read. Each signal becomes a band such aspower.battery=loworlocation.in_store=yes, the bands are weighed together up to three at a time, and the price moves inside its own range by at most half the gap to the low or high end. The model can also name things no signal covered (a shelf tag, a sale sticker), kept as candidate labels. Send what an item really sold for toPOST /api/price-router/checks/{id}/outcome: every signal and combination learns a weight from those sales, and the learned side counts for more as sales pile up.valuation.signalssays which signals and combinations moved it, and by how much. The phone app sends them from the groups switched on under Account, Advanced, Price inputs. - Photo and PDF links. A photo, screenshot or PDF can be sent as a public http or https link to the file instead of base64. It is downloaded through the same public-address-only fetch, then checked like an attached file (type, 5 MB). A link that cannot be downloaded, or that serves something other than a JPEG, PNG, GIF, WebP or PDF, is refused with 422
artifact_unreadableand nothing is charged. - Limits. Up to 12 attachments. Photos are JPEG, PNG, GIF or WebP and documents are PDF, 5 MB each. Audio is refused with 422
unsupported_artifact. Each call has 30 seconds. - Cost. Runs on your workspace's own Anthropic key when one is set in Settings, otherwise ours. Each call is one LLM usage event (
llm.capture-pricing), not a pricing function call, so it draws nothing from a prepaid balance.
Try your own numbers. The picture is worked out again by the same rules.
curl -X POST https://api.last-price.ai/api/price-router/pipelines \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"bundle": {
"artifacts": [
{ "id": "a1", "type": "text", "content": "Sony WH-1000XM4 headphones, used, with case" },
{ "id": "a2", "type": "url", "content": "https://example.com/listing/123" }
],
"commercial": { "currency": "USD", "catalog_state": { "current_price": 150 } }
}
}'
// The answer (shortened):
{ "computed_price": 145, "currency": "USD", "confidence": 0.7,
"explanation": "Used noise cancelling headphones in good condition, with the case.",
"alternatives": [ { "price": 110, "label": "quick sale" }, { "price": 175, "label": "top of range" } ],
"valuation": { "item": { "name": "Sony WH-1000XM4 headphones", "condition": "good" },
"range": { "low": 110, "high": 175 }, "target_price": 150, "target_gap": -5,
"would_help": ["a photo of the serial label"] },
"simulated": false }Your price history. Where history is kept on your account, every price is saved, whichever way it was asked: the mobile app, the API, or ChatGPT or Claude through MCP. Only the answer is kept, never what you sent. Each price carries its check_id. GET /api/price-router/checks lists your workspace's checks, newest first, with limit, before (the last page's next_before) and q (words in the item's name), and GET /api/price-router/checks/{id} returns one with its whole answer. The mobile app's History reads the same list. DELETE /api/price-router/checks/{id} removes one for good, everywhere it shows; the app's Remove does this.
Price from a photo (MCP)
Agents get the same pricing as the mobile app through the price_from_capture MCP tool. It takes what the agent has about one item in artifacts, the price it has in mind in current_price, the currency and the side (selling or buying), calls POST /api/price-router/pipelines, and returns the whole answer: the price, the range labelled for its side, the item and its condition, and valuation.write_up, a listing to post or a message to the seller with the opening offer filled in.
- Attachments. Each entry has a
type(imageorscreenshotfor a photo,documentfor a PDF,urlfor a product page,textfor a description,skufor a barcode) and itscontent. A photo or PDF is base64 with itsmime_type, or a public link to the file. - Big photos. The hosted MCP endpoint takes requests up to 64 KB, which fits a small photo but not a full camera shot. Send a link to the photo and it is downloaded on our side, or, from an agent with a terminal, upload the file itself in one command (below) and get the same answer. File links allow up to 5 MB per file; a direct multipart upload allows 4 MB for the whole request, including its framing.
- Chat attachments. A host that supports file references can pass an attachment in
photoorfile, with itsdownload_url. The tool advertises these parameters withopenai/fileParams. Where the host does not pass file references, send a public file link or describe the item intext. - Signals. Optional
signalsuses the same consent contract asbundle.signalsabove. Only groups inconsent.facetsare read, where signal pricing is available. It never gathers the person's device or location on its own. The response keepsvaluation.signalsunchanged. For multipart, sendsignalsas JSON text. - Who can call it. A credential with
price:computeon a claimed workspace. It is in the LangChain, AI SDK and Agents SDK packages too, aspriceFromCaptureon the client. - Price history. Where history is kept on your account,
list_price_checkslists every price the workspace got, newest first, from the mobile app, the API or a chat app, withqto find an item by name andbeforefor older pages.get_price_checktakes acheck_idand returns that price's whole answer again, listing or offer included. So an assistant can answer "what did I price last week?" or pick up a price the person got on their phone. Both only read, and arelistPriceChecksandgetPriceCheckon the client. - Real sold prices. Where market evidence is on for your workspace, the item is also looked up online once it is named: what it sold for and what it is listed at. With at least 3 pages showing a price, the price is the middle of the sold prices (or of the listings, short of sold ones) and the range their lowest and highest.
valuation.market_evidenceshows it all: the search, how many sold and listed prices were found, their low, median and high, each page with its price, thebasis(sold,listingormodel) and the estimate from what was sent. With fewer pages, or when the search fails, the price stays that estimate andmarket_evidencesays why. The same answer comes back in price history. - Report a problem. When the person says a price is off or names the wrong item,
report_problemsends it to the team with areason(price_wrong,wrong_item,broken,ideaorother), theirnote, and for a price itscheck_id,computed_priceand theexpected_price. It is the same report as the app's, callsPOST /api/problem-reports(see Report a Problem), changes no price, and takes up to 20 an hour. On the client it isreportProblem. - What it is so far. While the person is still describing an item,
describe_item_so_fartakes the words so far intextand returns a sheet (likely name, brand, model, category, a headline, details andcertainty) with up to 6 freely licensed pictures from Openverse and Wikimedia Commons, each with its creator and license to credit.settledturns true at 0.75 certainty, the moment to confirm the item and callprice_from_capture. It never gives a price. On a cache miss it runs a model call recorded as model usage and refreshes the cached answer. Repeats can reuse the same answer for ten minutes on that server instance. It callsPOST /api/price-router/identify(see Live Sheet). On the client it isdescribeItemSoFar.
price_from_capture {
"artifacts": [
{ "type": "image", "content": "https://example.com/photos/headphones.jpg" },
{ "type": "text", "content": "Sony WH-1000XM4, used, with case" }
],
"current_price": 120,
"side": "buying"
}
// The same from a terminal, with the photo on disk:
curl -X POST https://api.last-price.ai/api/price-router/pipelines \
-H "x-api-key: YOUR_KEY" \
-F photo=@headphones.jpg -F text="Sony WH-1000XM4, used, with case" \
-F current_price=120 -F side=buying
// The answer (shortened):
{ "computed_price": 145, "currency": "USD", "confidence": 0.7,
"alternatives": [ { "price": 110, "label": "opening offer" }, { "price": 175, "label": "most to pay" } ],
"share_url": "https://last-price.ai/p/...",
"valuation": { "side": "buying", "range": { "low": 110, "high": 175 },
"write_up": { "kind": "offer", "title": "Sony WH-1000XM4 headphones",
"body": "Hi, are these still available? Would you take $110?", "price": 110 } } }Live sheet
While you type or talk about an item in the mobile app, a sheet fills in above the box: what it sounds like, a line on what it is, what you said about it, and pictures of it. The pictures swap as your words change and settle into one large picture once it is sure. When you tap the arrow, a sure sheet's name goes with the price check. The sheet never gives a price.
- What you send. The
textso far (3 to 2,000 characters; it may stop mid-word) and optionally theside,sellingorbuying. - What you get. A
sheetwithname,brand,model,category,headline,description, up to fourdetailsand acertaintyfrom 0 to 1;settledfrom 0.75; and up to sixpicturesfrom Openverse or Wikimedia Commons, each with its creator, licence and source page, from certainty 0.4. - Cost. One small, fast model call, recorded as model usage with your workspace's own Anthropic key when you have one. The same words asked again get the last answer without a second call.
curl -X POST https://api.last-price.ai/api/price-router/identify \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{ "text": "sony noise cancelling headphones, the xm4, used about a year", "side": "selling" }'
// 200
{ "sheet": { "name": "Sony WH-1000XM4 headphones", "brand": "Sony", "model": "WH-1000XM4",
"category": "Headphones", "headline": "Wireless noise cancelling over-ear headphones",
"description": "Used about a year.", "details": ["Used about a year"],
"certainty": 0.92, "image_query": "Sony WH-1000XM4 headphones" },
"settled": true,
"pictures": [{ "url": "https://…", "thumbnail": "https://…", "creator": "…",
"license": "CC BY 2.0", "source_url": "https://…", "provider": "openverse" }] }Live tags
Open Live tags in the mobile app and point the camera at things: a price tag floats over each item it sees and moves with it as you move the phone. Everything it tags is saved as you go, with a photo of each item and when it was seen, under Saved tags; there is nothing to press. Press record to keep a clip as well; it plays back with its tags. All of it is kept on the phone and on your account (the tags, a photo of each item and recorded clips with their sound), so it shows on any phone you sign in on; deleting a session, or the account, removes it from both. Tap a tag for the full price of that item, which is saved to History.
- What you send. One small
frame(a JPEG about 768 pixels wide, base64, at most 1.5 MB) about once a second, with optionally theside, thecurrencyand the tags showing now asprevious, so the same item keeps its name. - What you get. Up to twelve
tags, the background included, each with itsboxon the frame (fractions of the width and height), a shortname, a roughlow,typicalandhighprice and the one-linelabelto show. People, faces and pets are never tagged, and the frame itself is not kept. - Pace. A person's token spends that person's own rate budget, not the workspace's. More than 90 frames a minute from one person, 7,200 an hour from one workspace or 20,000 a day from one workspace gets 429
too_many_frames; wait forRetry-After. - Cost. One small, fast vision call per frame, recorded as model usage with your workspace's own Anthropic key when you have one. A tag's price is a quick read; the full price is a normal price check.
curl -X POST https://api.last-price.ai/api/price-router/tag \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{ "frame": "<base64 JPEG>", "side": "selling", "currency": "USD" }'
// 200
{ "tags": [{ "name": "Sony WH-1000XM4 headphones", "box": { "x": 0.24, "y": 0.36, "w": 0.52, "h": 0.26 },
"low": 120, "typical": 145, "high": 170, "currency": "USD", "certainty": 0.86, "label": "$145" }],
"currency": "USD", "side": "selling",
"range_labels": { "low": "quick sale", "high": "top of range" } }Report a problem
When a price looks wrong, the wrong thing was priced, or something did not work, tell us. In the mobile app, the flag under a price opens What's wrong? with the item and its price filled in, and Report a problem in the account menu covers anything else. Every report reaches the Last Price team by email and is read by a person.
- What you send. A
reason(price_wrong,wrong_item,broken,ideaorother), an optionalnoteof up to 2,000 characters, and for a price, itscheck_id,computed_price,currencyand what you think it is worth inexpected_price. - Where it comes from. The report records whether it came from the app, the website, the API or an AI assistant, from the credential that sent it.
- Limits. 20 reports an hour per workspace; more are refused with 429
too_many_reports.
curl -X POST https://api.last-price.ai/api/problem-reports \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{ "reason": "price_wrong", "check_id": "CHECK_ID", "computed_price": 145,
"currency": "USD", "expected_price": 190, "note": "This one has the case and both cables." }'
// 201
{ "data": { "id": "…", "created_at": "2026-10-22T16:40:00Z" } }Reference pipelines (MCP)
The list_pricing_pipelines MCP tool reads GET /api/price-router/pipelines: each reference pipeline with its name, purpose, topology, latency and cost ceilings, the consent it needs and the trust zones it may run in, and the stage catalogue with each stage's layer and tags. It is public, so it needs no credential and a keyless agent can call it.
To run one without a key, use run_reference_pipeline (see Reference Pipelines Without a Key); until runs are switched on it answers 501 with the code pipeline_execution_unavailable rather than a simulated price. POST /api/price-router/pipelines prices one item from photos, files, links and text, also through price_from_capture (see Price from a photo above). To price from numbers, use compute_price, or run_pricing_chain for a chain you define.
list_pricing_pipelines {}Capability descriptor
The public GET /api/price-router returns a static capability document: platform version, all available providers, routing strategies, and the full built-in function catalog. No auth required: suitable for AI-agent tool manifests and external documentation tooling.
GET /api/price-router
// Response (public, cached 5 minutes)
// model_count values are computed dynamically at runtime from the built-in registry
{
"version": "1.0.0",
"providers": [
{ "id": "jale", "display_name": "Jale", "model_count": 6,
"description": "Elasticity-driven price optimization, bundle pricing, tier optimization, and psychological-pricing models." },
{ "id": "elo", "display_name": "Elo", "model_count": 3,
"description": "Pricing experimentation: a stable two-arm price split for a single call, a Bayesian significance test (POST /api/compute/significance) and Thompson-sampling traffic allocation (POST /api/compute/allocation). Tracked experiments are the Experiments API." },
{ "id": "rosetta", "display_name": "Rosetta", "model_count": 6,
"description": "Schema mapping and contract translation between merchant catalogs / vendor APIs and the canonical pricing core." }
],
"strategies": [
{ "id": "explicit", "description": "Use the function_id supplied in the request. The id must name a built-in function, one this tenant owns, or one with a public marketplace listing; anything else is refused exactly as a function that does not exist. Fails fast if the function is missing, unreachable, or inactive." },
{ "id": "cheapest", "description": "Pick the active function with the lowest cost_per_unit × cost_multiplier, the rate each call is billed at. As a stored policy strategy it selects only from functions inside that policy config.max_cost_per_unit and config.max_latency_ms, and defers to the policy fallback_chain when none qualify; as a request routing_preference it overrides the policy and neither ceiling applies." },
{ "id": "fastest", "description": "Pick the active function with the lowest avg_latency_ms. As a stored policy strategy it selects only from functions inside that policy config.max_cost_per_unit and config.max_latency_ms, and defers to the policy fallback_chain when none qualify; as a request routing_preference it overrides the policy and neither ceiling applies." },
{ "id": "round_robin", "description": "Distribute requests evenly across active functions in the catalog. As a stored policy strategy it selects only from functions inside that policy config.max_cost_per_unit and config.max_latency_ms, and defers to the policy fallback_chain when none qualify; as a request routing_preference it overrides the policy and neither ceiling applies." },
{ "id": "weighted", "description": "Pick a function by weighted random draw using config.weights (function_id → weight) from the tenant default policy. Overrides the strategy that policy declares. With no policy in reach, or no usable weight in it, the draw is an even one over the available functions; a stored weighted policy in that position defers to its fallback chain instead." },
{ "id": "policy", "description": "Use the tenant default routing policy: config.rules in order, first match wins, then the strategy that policy declares, then its fallback_chain, then its fallback_function_id, then the default selection." },
{ "id": "default", "description": "Use the tenant default routing policy if set: a matching rule first, then the strategy that policy declares, then its fallback_chain, then its fallback_function_id. With no policy, or when none of those yield a function, prefer a built-in function, then the cheapest." }
],
"builtins": [ /* all built-in function descriptors: count reflects current registry */ ],
"metering": {
"cost_per_unit": 0.005,
"input_factor": 0.001,
"output_factor": 0.003,
"formula": "(input_units * cost_per_unit * input_factor + output_units * cost_per_unit * output_factor) * cost_multiplier"
}
}Verify a price
The keyless compute and verification demos have separate budgets of 30 attempts per IP per hour, including invalid requests. Their countdown survives app restarts. A full budget returns 429 with Retry-After. If the budget cannot be checked, a retryable 503 names demo_limit_unavailable and asks you to retry after five seconds; it does not invent a remaining balance.
POST /api/price-router/verify (or the keyless demo at POST /api/public/price-router/verify, and the verify_price MCP tool) judges a proposed price against its context and answers fair, too_high, too_low or unknown, with the band it was judged against, the reference price, and every piece of evidence behind it.
independent_evidence says whether the verdict was corroborated by something other than you. Your own constraints never count. The network reference counts when you send context.current_price, or when the function that answered gives the same reference whatever price stands in for the incumbent. With no incumbent the proposed price stands in, so the reference is recomputed with a stand-in below and above the proposal, and only an unchanged reference and band count as independent. A unit cost on its own is not enough: under default routing an optimizer that prices relative to the incumbent may answer, and its reference follows the proposal. For an independent reference without an incumbent, send metadata.unit_cost with routing_preference: "explicit" and the function_id of lastprice/cost-plus. A reference that leans on the proposal is reported with independent_of_proposal: false and counts at half its weight.
A unit_cost of 0 (work made on a free model, say) sets a floor, not a price. Cost-plus then prices from your constraints.min_price and constraints.max_price, and without them it refuses and names them rather than quoting 0. Verify with a cost of 0 and no current_price counts only the floor: any price at or above 0 is fair at confidence 0.25, and the reasons say the verdict means only that the price covers its cost. Send a band, a current price or a comparable price for a judgement above the floor.
Offers and counter-offers
Let a buyer, or the agent shopping for them, name a price for one of your products. Every offer gets one of three answers, accept, counter or reject, with the price and the reason in plain words. The answer comes from your own terms: your list price (or your workspace's own computed price for the product, if that is lower), a floor you set, and your price guardrails. Your floor is never shown and never breached.
Buyers need no Last Price account and no key: they read your terms and make offers on public routes. You manage everything with a dashboard session or an API key, so your own agent can run it. Nothing is negotiable until you switch offers on for the workspace and for each product, in Settings, Offers.
Open products to offers
Add each product with its list price (public) and floor price (private, at most the list price), plus a unit cost if you want the minimum margin and never below cost guardrails to apply. Then switch offers on for the workspace. Your handle is the public name buyers use; one is generated if you do not choose it.
curl -X PUT https://api.last-price.ai/api/negotiation/products \
-H "x-api-key: $LASTPRICE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"product_id":"broadband-100","title":"Broadband 100","enabled":true,"list_price":45,"floor_price":36,"currency":"USD"}'
curl -X PUT https://api.last-price.ai/api/negotiation/settings \
-H "x-api-key: $LASTPRICE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"enabled":true,"handle":"acme-broadband","max_rounds":3}'Try an offer before buyers do with POST /api/negotiation/preview: it returns the answer a buyer would get plus the floor, what set it and the asking price, and records nothing. List your negotiations with GET /api/negotiation/negotiations and charge an accepted negotiation's agreed_price at checkout.
Your own agent can do all of this over MCP, with the same scopes: get_offer_settings, set_offer_settings, set_offer_product, remove_offer_product, list_negotiations and preview_offer.
How an offer is answered
The rules are deterministic: the same terms, round and offer always get the same answer.
- At or above the asking price (or your last counter): accepted at the asking price. A buyer is never charged more than asked.
- Below the share of the list price you set (half, by default): rejected without a counter. The buyer may try again while offers are left.
- Otherwise you counter. Each counter gives up a share of the room left to your floor (35% by default) and never reaches it.
- On the last offer: accepted at the offer if it clears your floor, otherwise rejected and closed.
- The floor is the highest of your floor price, the minimum margin over unit cost, never below cost, and the most a price may move from the list price.
- A counter stands for the time you set (60 minutes by default), then lapses.
Try your own numbers. The picture is worked out again by the same rules.
Each price you put to a buyer is recorded as a usage event with a quote, and the buyer's reply as its outcome (accepted, or rejected when they offer lower or let it lapse), so the answers are labels your demand estimate can learn from. Negotiating is not billed. Because the public routes take anyone, they are rate limited per address (60 reads and 20 offers a minute), each negotiation is bound to a token only its buyer holds, and you cap new negotiations per day. A buyer who negotiates many times could still narrow down your floor, so set a floor you are content to sell at.
Make an offer (buyers and agents)
No key needed. Read the terms, send an offer, and keep the buyer_token from the first answer: send it as the x-negotiation-token header to continue, read the negotiation or accept a counter. An unknown handle and a seller with offers off both answer 404 not_negotiable.
GET /api/negotiation/public/{handle} terms
POST /api/negotiation/public/{handle}/offers offer
GET /api/negotiation/public/{handle}/offers/{negotiation_id} state (token)
POST /api/negotiation/public/{handle}/offers/{negotiation_id}/accept accept (token)A buyer's agent on MCP needs no key for any of this: get_offer_terms, make_offer, get_negotiation and accept_counter. The first make_offer returns the buyer_token once; pass it with the negotiation_id to continue. accept_counter commits the buyer to the standing counter, so call it only when you mean to buy.
Worked example: an agent negotiates a household bill
A household asks its assistant agent to get the broadband bill down, the way bill negotiation services haggle a subscription or utility on someone's behalf. The provider has opened its 45 USD plan to offers with a floor of 36 USD and three offers per negotiation. The agent has no Last Price account.
1. Read the terms.
curl https://api.last-price.ai/api/negotiation/public/acme-broadband
{
"handle": "acme-broadband",
"negotiable": true,
"products": [
{ "product_id": "broadband-100", "title": "Broadband 100", "list_price": 45,
"currency": "USD", "max_rounds": 3, "min_offer": 22.5 }
],
"counter_valid_minutes": 60,
"decisions": ["accept", "counter", "reject"]
}2. Open low. The provider counters.
curl -X POST https://api.last-price.ai/api/negotiation/public/acme-broadband/offers \
-H "Content-Type: application/json" \
-d '{"product_id":"broadband-100","offered_price":30,"buyer_ref":"household-42"}'
{
"decision": "counter",
"code": "counter",
"counter_price": 41.85,
"agreed_price": null,
"round": 1,
"rounds_remaining": 2,
"reason": "Countered at 41.85 USD. Accept it, or make another offer (2 offers left).",
"negotiation_id": "8f0c2d4e-3b1a-4c55-9d7e-2a6b1f0e9c31",
"buyer_token": "lpn_<48 hex characters, shown once>",
"expires_at": "2026-10-05T10:00:00.000Z"
}3. Offer again with the token. The provider concedes further and says the next offer is the last.
curl -X POST https://api.last-price.ai/api/negotiation/public/acme-broadband/offers \
-H "Content-Type: application/json" \
-H "x-negotiation-token: $BUYER_TOKEN" \
-d '{"product_id":"broadband-100","offered_price":37,"negotiation_id":"8f0c2d4e-3b1a-4c55-9d7e-2a6b1f0e9c31"}'
{
"decision": "counter",
"counter_price": 39.8,
"rounds_remaining": 1,
"next_offer_is_final": true,
"reason": "Countered at 39.80 USD. Accept it, or make another offer (your next offer is your last)."
}4. The agent checks with the household, which is happy at 39.80 USD (down from 45), and accepts.
curl -X POST https://api.last-price.ai/api/negotiation/public/acme-broadband/offers/8f0c2d4e-3b1a-4c55-9d7e-2a6b1f0e9c31/accept \
-H "x-negotiation-token: $BUYER_TOKEN"
{
"decision": "accept",
"code": "counter_accepted",
"agreed_price": 39.8,
"currency": "USD",
"reason": "Accepted at 39.80 USD: you took the seller's counter.",
"negotiation": { "status": "accepted", "agreed_price": 39.8, "rounds_used": 2 }
}The provider sees the accepted negotiation in Settings, Offers and through GET /api/negotiation/negotiations, and bills 39.80 USD. Had the agent offered 35 USD on its last turn, below the floor, the answer would have been a reject that closes the negotiation, with no price below 36 USD ever offered.
Rosetta - schema translation
Rosetta solves the hardest integration problem in pricing: every platform uses a different schema. Shopify calls it list_price, Amazon calls it selling_price, your ERP calls it unit_cost.
Rosetta maps any source schema to a canonical schema using AI-assisted planning with hard contracts: the plan is compiled into a vendor contract, validated structurally, and optionally frozen into a sealed adapter that never drifts. Every built-in Rosetta function is also callable as a PCN function (prefix lastprice/rosetta-*) for agent-driven workflows.
| API route | Dashboard tab | Purpose |
|---|---|---|
| POST /api/rosetta/translate | Translate | Full pipeline: plan → compile → validate in one call |
| POST /api/rosetta/plan | Mapping Studio | AI-assisted field mapping suggestions from sample data |
| POST /api/rosetta/normalize | - | Normalize a vendor response to canonical schema |
| POST /api/rosetta/freeze | Frozen Adapters | Promote a plan to a sealed, versioned adapter |
| GET/POST /api/rosetta/review | Review Queue | Human review of low-confidence mapping proposals |
| POST /api/rosetta/ingest | Onboard | Autonomous merchant onboarding - infer schema from sample |
| GET /api/rosetta/canonical-schemas | Canonical Schemas | List all built-in canonical price schemas |
Overview
The pipeline has three stages:
- Plan - the heuristic/AI mapper proposes field mappings with per-field confidence scores.
- Compile - the plan is turned into a vendor contract (a validated, executable mapping).
- Validate - the compiled contract is structurally verified against the canonical schema.
Low-confidence mappings are queued for human review. High-confidence adapters can be frozen into immutable, versioned artifacts that the Commerce Control Plane uses at execution time.
Try your own numbers. The picture is worked out again by the same rules.
Translate
The translate endpoint runs the full plan → compile → validate pipeline in a single call and returns both the mapping plan and the compiled canonical record.
POST /api/rosetta/translate
Authorization: Bearer lp_<hex>
Content-Type: application/json
{
"source_schema": {
"id": "merchant.product.v1",
"fields": [
{ "path": "sku", "type": "string" },
{ "path": "list_price", "type": "number" },
{ "path": "currency", "type": "string" }
]
},
"source_record": { "sku": "BLUE-001", "list_price": 29.99, "currency": "USD" },
"canonical_schema": "offer",
"vendor_contract": {
"id": "lastprice.price.v1",
"fields": [
{ "path": "sku", "type": "string", "required": true },
{ "path": "current_price", "type": "number", "required": true },
{ "path": "currency", "type": "string", "required": false }
]
}
}
// Response
{
"ready": true,
"plan": {
"source_schema_id": "merchant.product.v1",
"target_schema_id": "lastprice.price.v1",
"confidence": 0.95,
"tier": "schema-guided",
"notes": [],
"mappings": [
{ "source": "list_price", "target": "current_price", "confidence": 0.97, "origin": "heuristic" },
{ "source": "sku", "target": "sku", "confidence": 0.99, "origin": "heuristic" }
]
},
"payload": { "sku": "BLUE-001", "current_price": 29.99, "currency": "USD" },
"skipped": [],
"validation": { "valid": true, "issues": [] },
"review_queued": null
}Mapping studio (plan)
The Mapping Studio lets you draft a mapping from sample data without running the full pipeline. Useful for iterating on schemas before committing. Also agent-callable as lastprice/rosetta-suggest.
POST /api/rosetta/plan
{
"source_schema": {
"id": "my.schema.v1",
"fields": [
{ "path": "list_price", "type": "number" },
{ "path": "currency", "type": "string" }
]
},
"canonical_schema": "offer"
}
// Response
{
"plan": {
"source_schema_id": "my.schema.v1",
"target_schema_id": "offer",
"confidence": 0.88,
"tier": "schema-guided",
"notes": [],
"mappings": [
{ "source": "list_price", "target": "current_price", "confidence": 0.92, "origin": "heuristic" },
{ "source": "currency", "target": "currency", "confidence": 0.99, "origin": "heuristic" }
]
},
"review_queued": null
}Normalize
Normalize takes a raw vendor API response (after execution) and maps it back to the canonical schema. Use this when you receive a price update confirmation from a connector and need to store it in a standard format.
POST /api/rosetta/normalize
{
"plan": {
"sourceSchemaId": "shopify.price.v1",
"targetSchemaId": "offer",
"confidence": 0.95,
"tier": "schema-guided",
"mappings": [
{ "source": "new_list_price", "target": "current_price", "confidence": 0.96, "origin": "heuristic" },
{ "source": "sku", "target": "sku", "confidence": 0.99, "origin": "heuristic" }
]
},
"vendor_response": { "new_list_price": 34.99, "sku": "BLUE-001" }
}
// Response
{
"canonical": { "current_price": 34.99, "sku": "BLUE-001" },
"missing": [],
"lossy": [],
"passthrough": {}
}Freeze adapter
Freezing promotes a mapping plan to an immutable, versioned adapter. Frozen adapters are used by the Commerce Control Plane at execution time and can be referenced by ID across runs.
POST /api/rosetta/freeze
{
"plan": {
"sourceSchemaId": "shopify.price.v1",
"targetSchemaId": "offer",
"confidence": 0.97,
"tier": "schema-guided",
"mappings": [
{ "source": "list_price", "target": "current_price", "confidence": 0.97, "origin": "heuristic" },
{ "source": "sku", "target": "sku", "confidence": 0.99, "origin": "heuristic" }
]
}
}
// Response
{
"adapter": {
"sourceSchemaId": "shopify.price.v1",
"targetSchemaId": "offer",
"mappings": [
{ "source": "list_price", "target": "current_price", "confidence": 0.97, "origin": "frozen" },
{ "source": "sku", "target": "sku", "confidence": 0.99, "origin": "frozen" }
],
"frozenAt": 1747400000000,
"fingerprint": "a1b2c3d4e5f6"
}
}Review queue
Mappings with low confidence (or those flagged by the validator) are placed in the review queue for human resolution. Reviewers approve or reject each item; approved items can then be frozen.
An agent or API key that queued an item cannot approve or reject it: that answers 403. A person, or a different agent or key, decides. Items queued before this rule have no recorded queuer and stay open to anyone.
# List pending review items
GET /api/rosetta/review
# Approve an item
POST /api/rosetta/review
{ "id": "rev_abc", "action": "approve" }
# Reject an item
POST /api/rosetta/review
{ "id": "rev_abc", "action": "reject", "reason": "wrong field mapped" }MCP tools
An agent can run the whole mapping loop. list_canonical_schemas and get_rosetta_health are public and need no credential; every other tool needs a Last Price credential of a claimed workspace and refuses a sandbox key.
list_canonical_schemas: the canonical schemas a source can be mapped onto (product, offer, observation, match, action) with each one's id and fields. Public.get_rosetta_health: whether the translator is up, and which schemas it serves. Public.list_rosetta_review: the mappings held back for approval, with their status. Passstatusaspending,approvedorrejectedto filter.plan_rosetta_mapping: map asource_schemaonto acanonical_schema(a built-in id or a whole schema). A plan below the confidence bar is queued for review.translate_with_rosetta: plan, compile and validate onesource_recordagainst avendor_contractin one call. Also queues a low-confidence plan for review.normalize_with_rosetta: a vendor response into the canonical shape, using aplan. Read only.freeze_rosetta_adapter: pin aplaninto an adapter so it maps the same way every time. Returns the adapter and stores nothing.ingest_with_rosetta: one-call onboarding for apayloadandcanonical_target. A new shape provisions and stores an adapter, and may queue a review.decide_rosetta_review: approve or reject one held mapping byid. A decision is final, and it sends the review-resolved webhook. An agent or key that queued the item cannot decide it; that answers 403.list_rosetta_adapters: the workspace's adapters, newest first, bystatus,canonical_targetormerchant_id. Part of checks and adapters.revoke_rosetta_adapter: revoke one adapter byadapter_id; the next payload of that shape plans a new mapping. Part of checks and adapters.
list_canonical_schemas { }
plan_rosetta_mapping { "source_schema": { "id": "shop", "fields": [{ "path": "title", "type": "string" }] }, "canonical_schema": "offer" }
list_rosetta_review { "status": "pending" }
decide_rosetta_review { "id": "rev_abc", "action": "approve" }Onboard (ingest)
The Onboard tab provides autonomous merchant onboarding: you paste a sample payload and Rosetta infers the schema, plans the mapping, and proposes a frozen adapter - all in one call. Also callable as the PCN function lastprice/rosetta-ingest for agent-driven onboarding workflows.
POST /api/rosetta/ingest
{
"canonical_target": "offer",
"payload": {
"product_id": "P001",
"sale_price": 49.99,
"currency_code": "USD",
"stock": 12
},
"merchant_id": "merchant_abc"
}
// Response - auto-provisioned (confidence ≥ 0.9, adapter frozen immediately)
{
"status": "auto_provisioned",
"adapter_id": "ada_...",
"fingerprint": "f1a2b3c4",
"canonical_record": { "current_price": 49.99, "currency": "USD" },
"ready": true,
"confidence": 0.94,
"plan": {
"tier": "schema-guided",
"notes": [],
"mappings": [
{ "source": "sale_price", "target": "current_price", "confidence": 0.95, "origin": "heuristic" },
{ "source": "currency_code", "target": "currency", "confidence": 0.98, "origin": "heuristic" }
]
}
}
// status values: "stable" | "auto_provisioned" | "provisional" | "needs_review" | "drift_detected"Checks and adapters
Rosetta never hands back a record as ready unless it is. These checks are off by default.
- Confidence counts the required fields a mapping leaves out. A mapping that misses one is never frozen: it is queued for review, and
unmapped_requirednames what is missing. - A record that fails validation answers
invalid_recordwithready: falseand anext_step, neverstable. Prices must be zero or more and currencies an ISO 4217 code such asUSD. A field sent in a form the mapping cannot use, such as"12,50", is reportedinvalid_typerather than missing. - Each
merchant_idgets its own adapters. A merchant's first payload is never drift, and going back to an older payload shape brings back the adapter it had. - Approving a review queued by ingest freezes it as the adapter, so the same payload answers from it. List adapters with
GET /api/rosetta/adaptersand revoke one withDELETE /api/rosetta/adapters/{id}. From MCP, the same two calls arelist_rosetta_adaptersandrevoke_rosetta_adapter. - Ingest takes JSON only (415 otherwise), up to 256 KB (413), reads the first 25 samples and says so in
inference.samples_truncated, and refuses an empty payload or a key sent twice. - Translate checks the record against the canonical schema as well as your vendor contract, and
missinglists required fields it lacks. Normalize reads a response in either the plan's source or target field names and says which inkey_space.
POST /api/rosetta/ingest
{ "canonical_target": "offer", "merchant_id": "shop-1",
"payload": { "sku": "A-100", "channel": "web", "price": -3, "currency": "ZZZ" } }
// Response
{
"status": "invalid_record",
"ready": false,
"canonical_record": null,
"validation": { "valid": false, "issues": [
{ "path": "price", "code": "invalid_value", "message": "field "price" must be zero or more, got -3" },
{ "path": "currency", "code": "invalid_value", "message": "field "currency" must be an ISO 4217 currency code such as USD, got "ZZZ"" }
] },
"missing": [],
"next_step": "Correct the fields listed in validation.issues and send the record again."
}
GET /api/rosetta/adapters?status=active
DELETE /api/rosetta/adapters/{id}Marketplace
The Last Price Marketplace allows you to discover, publish, and monetize pricing functions. Publish your own functions to earn revenue when other tenants use them.
Browse listings
Previous and Next browse up to 100 catalogue listings at a time. Search applies to the whole visible catalogue's function names, descriptions and tags. The exact-tag field can use any tag, including tags outside its first 100 suggestions. Changing a filter starts at the first matching page.
The public API accepts search (up to 200 characters) and one exact tag. Both filters apply before limit, offset and pagination.total.available_tags contains up to 100 suggestions from the whole visible catalogue, and available_tags_total reports the full distinct-tag count. Hidden listings contribute no tags. Search and tag are public-scope filters; supplying them with scope=owned is a 400.
Discover publicly available pricing functions from other providers. Browsing needs no API key: it is rate limited per IP address, and only public listings of active functions appear. Your own listings, private ones included, are ?scope=owned, which needs a key.
# Browse public marketplace listings (no key needed)
curl "https://api.last-price.ai/api/marketplace/listings?search=pricing&tag=retail&limit=20&offset=0"
# Your own listings need a key
curl "https://api.last-price.ai/api/marketplace/listings?scope=owned" \
-H "x-api-key: YOUR_API_KEY"
# Response (public scope)
{
"listings": [
{
"function": {
"id": "8b1c...",
"name": "acme/saas-pricer",
"display_name": "Dynamic SaaS Pricer",
"execution_type": "ml_model",
"cost_per_unit": 0.002,
"is_builtin": false
},
"listing": { "id": "4f2e...", "is_public": true, "commission_rate": 0.15 },
"stats": {
"total_invocations": 124500,
"distinct_consumers": 38,
"usage_status": "published",
"avg_latency_ms": 38,
"avg_confidence": 0.85
}
}
],
"available_tags": ["pricing", "retail"],
"available_tags_total": 2,
"pagination": { "limit": 20, "offset": 0, "total": 47 }
}Elo index leaderboard
The Elo index ranks public marketplace functions by an Index Score from 0 to 100. It needs no API key and is rate limited per IP address. The score combines adoption (distinct consumers), confidence, reported outcomes, speed and cost efficiency. A component with no data behind it is left out and the others are reweighted, so a missing number never counts as a zero.
- Outcome is scored from what consumers report after a quote with
PATCH /api/usage/events/EVENT_ID/outcome: the share of quotes accepted and the average quality score. It is published once at least 20 outcomes have been reported by at least 3 distinct consumers, rounded to 0.05; until then the entry readsinsufficient_data. Cheap prices are accepted more often, so outcome is one component among several, not the ranking. - Time windows: add
?window=7d,30d,90dorall(the default). Usage, confidence and outcomes then count only calls made in the window, under the same privacy floors. Latency and cost describe the function, so they are the same in every window. - Head-to-head ratings come from experiments whose variants name a pricing function in
metadata.function_id: revenue per visitor decides each pair, and a Bradley-Terry fit turns the results into an Elo-scale rating (1500 is an average opponent). Ratings are published only from experiments run by at least 3 workspaces.head_to_head_enabledsays whether the index includes them. - Ranking: functions with enough distinct consumers to publish usage are ranked strictly by score. The rest follow, unranked, with
rankandindex_scorenull andunranked_reasonbelow_thresholdorusage_unavailable, so a function nobody uses never sits above one that is measured. Speed is scored from the latency its consumers saw, on a fixed scale (100 ms or less scores 100, 5 seconds or more scores 0), not from its owner's tests. The board is cached for 15 seconds, so a listing taken down leaves it within about 30 seconds. This ranking is switching on for everyone at once.
# The last 30 days of the Elo Index (no key needed)
curl "https://api.last-price.ai/api/public/leaderboard?window=30d"
# Response (abridged)
{
"method_version": 4,
"window": "30d",
"window_start": "2026-09-04T12:00:00.000Z",
"head_to_head_enabled": false,
"min_distinct_consumers": 3,
"min_reported_outcomes": 20,
"overall": [
{
"rank": 1,
"function_name": "Dynamic SaaS Pricer",
"index_score": 78.4,
"components": { "adoption": 100, "confidence": 85, "outcome": 70,
"speed": 62, "cost_efficiency": 55, "head_to_head": null },
"stats": {
"outcomes": { "status": "published", "reported_outcomes": 64,
"acceptance_rate": 0.6, "avg_quality_score": 0.8 },
"head_to_head": { "status": "disabled", "rating": null,
"matches": 0, "opponents": 0 }
}
}
]
}To have an experiment count toward head-to-head, set metadata.function_id on each variant to the function that priced it. Questions: support@last-price.ai.
Agent feed and reels
An agent does not scroll; it asks. Send what you are trying to do as task and the feed answers with a short, ranked list of offers you can call: marketplace pricing functions and paid x402 services, each with how to call it (call), its price per call, where that price sits against what paid x402 services list (price_vs_market), and why it is in the list. MCP tool discover_offers.
Earned places and explore places. A ranked place is earned on measured results (the Elo index) and relevance to the task. About a fifth of places, never the top two, go to new offers that have not been measured yet and are marked explore, so a new function gets a fair first look and climbs only if it performs. Nobody pays for a place. When you call an offer, send itsfeed_ref as the x-lp-feed-ref header; it changes daily and says which feed sent the call, not who you are.
curl "https://api.last-price.ai/api/public/agent-feed?task=price+a+subscription+plan&limit=3"
# Response (one item shown)
{
"items": [
{
"rank": 1,
"slot": "ranked",
"why": "Elo Index 72 from 6 distinct consumers (measured); it matches 100% of the task's words.",
"kind": "listing",
"title": "Jale optimizer",
"price_per_call": 0.002,
"price_vs_market": { "position": "inside", "band": { "category": "all", "p10": 0.001, "median": 0.003, "p90": 0.01, "n": 40 } },
"call": { "via": "mcp", "tool": "compute_price", "arguments": { "function_id": "..." } },
"feed_ref": "fr_3kP0aZ9xQm2LbV7w"
}
],
"follow": "Send an item's feed_ref as the x-lp-feed-ref header when you call it."
}Reels are the agent-readable alternative to a demo video. A reel is a short recipe for a real task (price a SaaS seat, check a vendor quote, find an offer for a task). Reading one with get_reel or GET /api/public/reels/{id} runs its keyless calls live and returns the transcript: each step's tool, arguments, status, time and answer, and the outcome in one line. When a signing key is configured, signature.jws signs the SHA-256 of the transcript; check it with the key at/.well-known/quote-keys.json. list_reels lists them. The calls spend your own demo allowance.
Where the feed is off, both answer 404 not_released.
Publish functions
The Listings tab shows 100 listings per page, one panel each, with the steps to live (asked to publish, automated review, Last Price review, live), why a listing is not live yet and its latest activity. A live listing stays folded to one line until you open it. Use Previous and Next to manage older listings. The publish form also pages through your registered functions; a selection stays selected when you change pages.
List your pricing functions on the marketplace and set a commission rate. A public listing lets other workspaces route to your function; before it turns public, the function passes an automated review (see Review and Health). Last Price staff then approve the listing: until they do, it is not in the catalogue, the marketplace or the leaderboard, and other workspaces cannot call the function. You can still call and test it.
A listing from a workspace other than Last Price also waits for a person at Last Price to approve it before it shows in the catalogue or other workspaces can call it. Its approval_status reads pending_review, approved or rejected. A function must be active to list (409 function_not_active), and a listing whose name or description asks buyers to pay outside Last Price, such as a wallet address, web address or email address, is refused (422 listing_text_not_allowed): payment always runs through Last Price. Listings from other workspaces show a Third party badge. Staff approval is always required, and approval_status is on every listing you read; the checks at publish are switching on workspace by workspace.
While a listing waits, it is already in the staff review queue: there is nothing to send, and its Notifications item and the Listings tab say “Waiting for review”. Until it is approved, another workspace that looks up its function with GET /api/functions/:id or prices with it gets 404 Function not found, the same answer as for a function that does not exist.
A new listing can also carry listing_description, your own words about it (up to 2048 characters), and pricing_info, a JSON object describing how it is priced (up to 4000 characters as JSON). Both are optional, are stored on the listing and come back on your own reads (the 201 and ?scope=owned); the public catalogue does not publish them. Any other type, or a longer value, is refused with 400.
# Publish a function to the marketplace
curl -X POST https://api.last-price.ai/api/marketplace/listings \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"function_id": "3f6c1a52-8d0e-4b7a-9c21-5e4f0a7b2d10",
"is_public": true,
"commission_rate": 0.10,
"listing_description": "Prices SaaS seats from usage and churn risk.",
"pricing_info": { "model": "per_call" }
}'Review and health
A function other workspaces can route to has to work for strangers, so a listing is reviewed when it turns public: when you create it with is_public: true, or switch a private listing to public. Your own functions are never gated: your workspace routes to them whether or not they are listed. A public listing from your workspace goes live for others once Last Price staff approve it (approved_at on the listing).
- manifestcheck, required
- The function is active, its name and display name are set, both schemas are JSON objects, and an external function has an HTTPS endpoint the network may call.
- sample_callcheck, required
- One call with current price 29.99 and unit cost 12 returns a finite price and a confidence between 0 and 1.
- price_boundscheck, required
- That price is between 0.1 and 10 times the current price, which catches an answer in cents or a constant.
- latencycheck, required
- The call answers within 3000 ms.
When a check fails, the listing stays private and the request answers 422 with code: review_failed, the reasons in error, and the whole report in review. The report is also stored on the listing, so the Edit Listing dialog on the Marketplace page shows each check and why. Fix the function, then turn the listing public again, or run the review on its own first. There is no manual approval step: the automated checks are the whole review.
# Run the review now (a dry run: it never publishes)
curl -X POST https://api.last-price.ai/api/functions/FUNCTION_ID/review \
-H "x-api-key: YOUR_API_KEY"
# Read the latest stored review
curl https://api.last-price.ai/api/functions/FUNCTION_ID/review \
-H "x-api-key: YOUR_API_KEY"Every hour, the endpoint of each active external function is probed with the same sample request. Each probe records whether the endpoint answered with a usable price, how long it took, and the error when it did not, and it counts toward the function's circuit breaker like any other call. History is kept for 30 days. You can probe on demand too. Both routes are owner only, and take an API key with pcn:function:read to read and pcn:function:test to run.
# Probe the endpoint now
curl -X POST https://api.last-price.ai/api/functions/FUNCTION_ID/health \
-H "x-api-key: YOUR_API_KEY"
# Read the 20 most recent probes
curl https://api.last-price.ai/api/functions/FUNCTION_ID/health \
-H "x-api-key: YOUR_API_KEY"Earnings
In the dashboard, Previous and Next browse up to 100 matching ledger entries per page. A status filter applies to all entries and resets the page. Summary amounts cover the displayed page and selected status.
Track revenue earned from your published marketplace functions: one ledger entry per function and billing period. Filter by payout_status and page with limit (1 to 100) and offset; keep paging while offset + limit is less than pagination.total. A billing period's start and end are calendar days at 00:00 UTC, and both days are included.
Every priced call to a function you list adds your share to the current month's pending earnings, however it arrives: a single compute call, each priced item of a batch, a pay-per-call request or an MCP tool call. A batch item that fails earns nothing. At the end of the month the pending amount is settled from that month's recorded usage.
# View marketplace earnings: one ledger entry per function and billing period
curl https://api.last-price.ai/api/marketplace/earnings \
-H "Authorization: Bearer lp_<hex>" \
-G \
-d "payout_status=pending" \
-d "limit=50" \
-d "offset=0"
# Response: pagination.total counts every matching entry, not just this page
{
"earnings": [
{
"id": "8d0f6c1e-2b7a-4c55-9e1f-3a6b2d4c8e90",
"function_id": "b2c4e6f8-1a3b-4c5d-8e9f-0a1b2c3d4e5f",
"owner_tenant_id": "your-workspace-id",
"billing_period_start": "2026-09-01T00:00:00.000Z",
"billing_period_end": "2026-09-30T00:00:00.000Z",
"total_invocations": 1240,
"total_revenue": 124,
"platform_commission": 24.8,
"owner_earnings": 99.2,
"payout_status": "pending",
"stripe_payout_id": null,
"created_at": "2026-10-01T00:05:00.000Z",
"updated_at": "2026-10-01T00:05:00.000Z"
}
],
"pagination": { "limit": 50, "offset": 0, "total": 1 }
}Payouts
The dashboard payout ledger uses Previous and Next to show up to 100 entries per page. The amount summaries and latest paid entry update describe the current page. Payout runs remain below the ledger.
Your payout ledger: one entry per published function and billing period, with what it earned and its payout status (pending, processing, paid or failed). Entries are paid through payout runs, below, requested by hand or on a payout schedule.
# List your payout ledger
curl https://api.last-price.ai/api/marketplace/payouts \
-H "x-api-key: YOUR_API_KEY"
# Response
{
"payouts": [
{
"id": "6f1c2a1e-4c1b-4d0e-9a51-3f2f6b1c0a11",
"function_id": "0b6e1c4a-2f3d-4e5a-8b9c-1d2e3f4a5b6c",
"billing_period_start": "2026-09-01",
"billing_period_end": "2026-09-30",
"total_invocations": 500,
"total_revenue": 150.00,
"platform_commission": 30.00,
"owner_earnings": 120.00,
"payout_status": "pending",
"stripe_payout_id": null
}
],
"total": 1
}Payout schedule
A payout schedule requests a payout run for you on a set day, so nobody has to remember: every week on a weekday (run_day 1 for Monday to 7 for Sunday) or every month on a day from 1 to 28 (so every month has it), in UTC. It is part of payout runs and is on wherever they are.
- What a run day requests: every unpaid ledger entry whose billing period ended before that day, looking back a year. Entries already paid, or in a run still open, are left out, so nothing is paid twice.
- Who approves: the request is made in the name of whoever saved the schedule, so, like any request, someone else approves it before anything is paid. Saving a schedule that is on needs a person behind it: a signed-in user, or a key or agent a person created.
- One request at a time: if the previous request is still waiting for approval, the run day requests nothing new and says so (
previous_request_waiting); approve or reject it and the next run day covers everything still unpaid. - Retries (
auto_retry, on by default): transfers waiting for a retry are re-sent each hour with the same idempotency keys, without anyone pressing Retry.
The schedule answers its next run day (next_run_on), the period that day will request (next_period) and what the last run day did (last_outcome: requested, nothing_to_pay, open_run_exists or previous_request_waiting). Scheduled runs carry requested_via: "schedule" and send the same webhooks and emails as one requested by hand. Reading needs billing:read, saving billing:write.
# Request a payout on the 1st of every month
curl -X PUT https://api.last-price.ai/api/marketplace/payouts/schedule \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"enabled": true, "cadence": "monthly", "run_day": 1, "auto_retry": true}'
# Read it: next run day, the period it requests, the last outcome
curl https://api.last-price.ai/api/marketplace/payouts/schedule \
-H "x-api-key: YOUR_API_KEY"
# Turn it off
curl -X PUT https://api.last-price.ai/api/marketplace/payouts/schedule \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"enabled": false, "cadence": "monthly", "run_day": 1}'Storefronts and your own domain
A storefront is your own front door for agents. It lists a selection of your public pricing functions and products open to offers at <subdomain>.store.last-price.ai (and/s/<subdomain> on last-price.ai), with its own page, an A2A agent card at/.well-known/agent-card.json, an /llms.txt, an MCP manifest at/.well-known/mcp.json and an MCP endpoint at /mcp whose tools (list_offers, get_offer, compute_price,make_offer) see only that selection. Listing needs no key; computing a price takes a Last Price key or a per-call x402 payment, the same as on the main API.
Several storefronts, each distinct. Run one per product line or audience: narrow each by function tags (offer_tags), by products open to offers (product_ids) or by the kinds it shows. Two storefronts that list exactly the same offers are refused (duplicate_selection): each is a real storefront, not a copy under another name. Every page and agent card says it is powered by Last Price and links back.
Your own domain (white label). Add a domain your company owns, such as agents.yourcompany.com, and put two records at your DNS provider: a TXT record_lastprice.agents.yourcompany.com holding lastprice-verify=…, which proves the domain is yours, and the CNAME (or A record for a bare domain) that routes it. Then press Check now, or callverify_storefront_domain. Only verified domains are served, and a verified domain also gets aserver.json for the MCP registry under your own namespace. Last Price and hosting domains cannot be added.
Get a new domain. Where it is switched on, search for a name in Settings, Storefronts (or search_storefront_domains), get a price that holds for 15 minutes (quote_storefront_domain), and the workspace owner can buy it from the dashboard: it is registered in your company's name, paid from your Last Price balance, attached to the storefront and set up with no DNS work. Its DNS records are yours to manage there too (email, subdomains), apart from the ones the storefront needs, and the transfer code moves it to another registrar whenever you like. Buying always needs the owner in the dashboard: no API key or agent can buy a domain.
Manage them in Settings, Storefronts, through /api/storefronts (scopesworkspace:settings:read and workspace:settings:write) or with the MCP toolslist_storefronts, create_storefront, update_storefront,delete_storefront, add_storefront_domain,verify_storefront_domain and remove_storefront_domain. Nothing is public until you publish. Rolling out: while storefronts are off for your workspace, the API answersnot_released.
# Create a storefront for one product line
curl -X POST https://api.last-price.ai/api/storefronts \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"display_name": "Acme SaaS pricing", "subdomain": "acme-saas", "offer_tags": ["saas"], "published": true}'
# Serve it on your own domain: answers the DNS records to add
curl -X POST https://api.last-price.ai/api/storefronts/STOREFRONT_ID/domains \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"domain": "agents.acme.com"}'
# After adding the records, check them
curl -X POST https://api.last-price.ai/api/storefronts/STOREFRONT_ID/domains/DOMAIN_ID/verify \
-H "x-api-key: YOUR_API_KEY"Usage & billing
Monitor your platform consumption, view granular event logs, and manage Stripe-based billing - all from a single set of endpoints.
Usage summary
Retrieve an aggregated summary of total requests, compute time, and costs for a given period.
- start_datestring (ISO 8601), required
- Start of the period
- end_datestring (ISO 8601), required
- End of the period
- granularityenum
- daily, weekly, or monthly (default: daily)
# Get usage summary
curl https://api.last-price.ai/api/usage \
-H "Authorization: Bearer lp_<hex>" \
-G \
-d "start_date=2024-12-01" \
-d "end_date=2024-12-31" \
-d "granularity=daily"
# Response
{
"total_requests": 48210,
"total_compute_ms": 1932840,
"total_cost": 142.38,
"currency": "USD",
"period": { "start": "2024-12-01", "end": "2024-12-31" }
}A call is charged when it is paid per call, by a day pass or from your prepaid balance. The cost of other calls shows as unbilled_cost (not charged, never invoiced) with billable_cost at 0, and their receipts say none.
Usage events
Page with limit and offset, or page and per_page (page starts at 1). The page size is capped at 100. Narrow dates with start_date and end_date. Cursor and since are unsupported and return 400 invalid_query with supported alternatives instead of silently returning an unfiltered page.
Access the per-request granular event log. Each event contains the function invoked, latency, cost, input context, and computed result.
# List usage events (paginated)
curl https://api.last-price.ai/api/usage/events \
-H "Authorization: Bearer lp_<hex>" \
-G \
-d "start_date=2024-12-01" \
-d "page=1" \
-d "per_page=50"
# Response
{
"events": [
{
"id": "evt_001",
"created_at": "2024-12-15T10:32:01Z",
"function_id": "fn_abc123",
"product_type": "saas",
"compute_duration_ms": 38,
"cost": 0.003,
"outcome": null
}
],
"pagination": { "limit": 50, "offset": 0, "count": 1 }
}Usage breakdown
View a function-level breakdown of usage. Identify which pricing functions consume the most resources and generate the most traffic.
# Get function-level usage breakdown
curl https://api.last-price.ai/api/usage/breakdown \
-H "Authorization: Bearer lp_<hex>" \
-G \
-d "start_date=2024-12-01" \
-d "end_date=2024-12-31"
# Response
{
"breakdown": [
{
"function_id": "fn_abc123",
"function_name": "margin-lookup-v2",
"requests": 32140,
"avg_latency_ms": 35,
"total_cost": 96.42
},
{
"function_id": "fn_def456",
"function_name": "geo-pricer",
"requests": 16070,
"avg_latency_ms": 62,
"total_cost": 45.96
}
]
}AI usage
Usage of the AI-backed features (agent generation, task estimation). Reported separately from pricing functions, and split by which key paid for each call: calls served with your own provider key are not billed by Last Price, so platform_key_cost is the billable amount.
A date-only range is normalised before it is queried, so the echoed period comes back as UTC instants and the end covers the whole final day. Fractional seconds are accepted to microsecond precision and preserved exactly.
# Get AI feature usage for the current month
curl https://api.last-price.ai/api/usage/llm \
-H "Authorization: Bearer lp_<hex>" \
-G \
-d "start_date=2024-12-01" \
-d "end_date=2024-12-31"
# Response
{
"tenant_id": "3f2b1c88-5d4e-4a91-9c2f-7b6a0d1e8f42",
"period": {
"start": "2024-12-01T00:00:00.000000Z",
"end": "2024-12-31T23:59:59.999999Z"
},
"usage": {
"total_calls": 128,
"total_input_tokens": 98400,
"total_output_tokens": 24100,
"total_compute_ms": 184000,
"total_cost": 3.87,
"tenant_key_calls": 90,
"platform_key_calls": 38,
"platform_key_cost": 1.12,
"by_operation": [
{
"operation": "llm.agent-generation",
"calls": 74,
"input_tokens": 61200,
"output_tokens": 15300,
"compute_duration_ms": 110400,
"cost": 2.41
},
{
"operation": "llm.task-estimation",
"calls": 54,
"input_tokens": 37200,
"output_tokens": 8800,
"compute_duration_ms": 73600,
"cost": 1.46
}
]
}
}Usage signals
Record custom signals for analytics and observability. Signals can track conversion rates, A/B test outcomes, or any custom metric you define.
# Record a custom usage signal
curl -X POST https://api.last-price.ai/api/usage/signals \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"eventType": "price_accepted",
"properties": {
"product_id": "prod_001",
"computed_price": 128.70,
"customer_segment": "enterprise"
}
}'Instrumentation setup
The Event tracking and Cost tracing pages walk you from nothing to a first recorded signal or cost. Pick your framework and language, edit the signal or cost templates, and run the one click setup: it creates (or reuses) the agent and the customer your templates name, and mints an API key with only the price:compute scope. The key is shown once. The page then writes the code for your stack with the real agent id in it, and checks every few seconds until the first record arrives.
The same steps are on the API, with kind set to events or costs: GET and PUT /api/instrumentation/setup/{kind} read and save the choice and the templates (send {"reset": true} to go back to the defaults), POST /api/instrumentation/setup/{kind}/provision runs the setup (an owner or admin, signed in or with a person's JWT: never an API key or an agent's token, since it mints one), and GET /api/instrumentation/setup/{kind}/verify says whether a record has arrived since. Running the setup again mints a new key and names the one it replaced; tick Also revoke the current key (or send {"revoke_previous": true}) and the old one is revoked in the same step. Over MCP, get_instrumentation_setup, save_instrumentation_setup and verify_instrumentation_setup do the same, but provisioning stays in the app and the API because it creates a key. While the setup is not released for your workspace these routes answer 404 with not_released.
# Run the one click setup for usage signals
curl -X POST https://api.last-price.ai/api/instrumentation/setup/events/provision \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
# Then check for the first signal
curl https://api.last-price.ai/api/instrumentation/setup/events/verify \
-H "Authorization: Bearer YOUR_TOKEN"Stripe integration
Last Price integrates natively with Stripe for metered billing, invoicing, and marketplace payouts. Usage is automatically reported to Stripe and reflected on your monthly invoice.
Metered billing
Usage automatically synced to Stripe meter events
Invoicing
Monthly invoices generated and sent via Stripe
Marketplace payouts
Earnings paid out via Stripe Connect
Payment methods
Cards, ACH, and wire supported through Stripe
Connect with Stripe
An owner or admin connects the workspace's own Stripe account from the Monetization page. Last Price keeps only the account id, never a token. A workspace has one Stripe account: if it already opened one on the Get paid page, invoices use that one and it is managed there. After that, POST /api/invoices/{invoiceId}/stripe issues an invoice on that account: Stripe hosts the payment page, send: true also emails it, a calculated tax becomes its own line, and Stripe's invoice.paid event marks the invoice paid here. Retrying is safe: every Stripe call carries an idempotency key from the invoice id.
Agents read the connection with get_stripe_connection and issue an invoice withissue_invoice_with_stripe. Connecting itself needs a person in a browser. It runs in Stripe test mode.
Automated setup
The Monetization page's Automated tab, POST /api/monetization/scaffold and the MCP toolgenerate_monetization_code write the integration code for your app: a small client that records signals, prices calls, creates customers and bills them through Stripe, and an example of where each call goes. Pick Next.js, Express or FastAPI; your agent id is filled in and the API key is read from the environment. The answer is the files plus one patch you add with git apply last-price.patch. The patch itself writes nothing to your repository.
To skip the patch, install the Last Price GitHub App from the Automated tab (a workspace owner or admin, on your GitHub account or organization, choosing the repositories it may use). Then enter a repository and Open pull request: Last Price commits the same files to a new branch (last-price/billing-setup unless you name another) and opens a pull request against your default branch, or POST /api/monetization/scaffold/pull-request does the same withrepository set to owner/name. An existing .env.example keeps its lines and gets ours at the end. Nothing is merged for you, an existing branch is never moved, and no GitHub token is stored. Disconnecting stops Last Price opening pull requests; uninstall the App on GitHub to remove its access. Agents use get_github_app_connection and open_monetization_pull_request.
Tax on invoices and orders
With tax turned on in Settings, Tax, Last Price calculates tax on every new or repriced invoice and order from the registrations saved there. The amount you send is the subtotal; the row keepssubtotal_amount, tax_amount and a tax_breakdown per jurisdiction, and its total becomes subtotal plus tax. US sales tax applies only in states with an active nexus, at the state rate (county and city rates are not included; set your own rate on a registration to override). EU VAT under OSS charges the customer's country rate to consumers and reverse charges businesses that give a VAT number. Other VAT and GST registrations charge that country's standard rate.
Pass taxDestination (country and state) and customerTaxId on the request, or keep them on the customer's metadata; taxExempt: true skips tax. Preview a calculation without saving with POST /api/tax/calculate or the MCP tool calculate_tax.
Credit bundles
A credit bundle is something you sell: a name, a code, a price, how often it bills, how many credits it gives (or unlimited) and how many roll over. Create one on Credits, New credit bundle, and choose Activate now to put it on sale or Save as inactive to finish it later. /api/credit-bundle-planslists, creates and edits them; archiving keeps the history. Granting a bundle to a customer adds its credits to their balance and, by default, a draft invoice for its price.
Granting a monthly, quarterly or annual bundle also starts a subscription for that customer. Each hour Last Price renews every subscription whose period has ended: unused credits up to the bundle's rollover amount carry into the new period (all of them when rollover is unlimited, none when it is 0), the rest expire, the customer gets a new grant of the bundle's credits plus what rolled over, and a draft invoice is written when the original grant asked for one. A customer holds at most one active subscription per bundle. Cancel one with POST /api/credit-bundle-subscriptions/{subscriptionId}/cancel or Cancel renewal on the Credits page; the customer keeps the credits of the period they are in. List a bundle's subscriptions with GET /api/credit-bundle-plans/{planId}/subscriptions. A bundle that is deactivated, archived or made unlimited stops renewing, and its subscriptions are cancelled at their next renewal.
Agents use list_credit_bundle_plans, create_credit_bundle_plan,update_credit_bundle_plan, grant_credit_bundle_plan, list_credit_bundle_subscriptions and cancel_credit_bundle_subscription.
Handover: Build a business for someone
Handover is for building a business for someone else: a driver, a stall, a barber, anyone you meet. Ask what business they would like to own, record the conversation once they say yes, and the page builds as they talk. When they have checked it, it goes live on its own Last Price workspace and you hand it over with a QR code, a claim link that makes them the owner, and a WhatsApp message. You keep running it for them: the first 90 days are free, then a small monthly fee. Open Handover in the dashboard to start.
Handover uses only the public API, the way any partner would. Going live opens the business a workspace with your partner key (POST /api/partner/workspaces, one of the partner's daily allowance), lists its items, and opens items the owner is happy to haggle on to offers under the business's own handle, with a floor at 85% of the price that buyers never see. The business's key and claim link are stored encrypted and are never returned. Trades that need a licence (food, alcohol, health, driving people, money) stay a draft until you confirm the owner holds it or will get it before selling.
The monthly fee after the free months is set per market and priced through Last Price itself: at handover the market's base fee goes to POST /api/compute/price as product handover-monthly-fee in the business's country, and the answer is the fee. Change it per business afterwards with monthly_fee on PATCH /api/handover/businesses/{id}.
curl -X POST https://api.last-price.ai/api/handover/businesses -H "x-api-key: $LAST_PRICE_API_KEY" \
-H "content-type: application/json" -d '{
"brief": {
"owner_name": "Ade Okafor",
"owner_whatsapp": "+2348012345678",
"what_it_sells": "Airport runs and school drop offs around Ikeja",
"area": "Ikeja, Lagos",
"country": "NG",
"currency": "NGN",
"offerings": [{ "name": "Airport run", "price": 15000, "unit": "per trip", "negotiable": true }]
},
"consent": { "asked_at": "2026-10-22T18:00:00.000Z", "words": "Yes, you can record." }
}'
curl -X POST https://api.last-price.ai/api/handover/businesses/$BUSINESS_ID/publish -H "x-api-key: $LAST_PRICE_API_KEY"
curl https://api.last-price.ai/api/handover/businesses/$BUSINESS_ID/pack -H "x-api-key: $LAST_PRICE_API_KEY"Each live business has a public page at /b/{slug} for people, and the same business as data for agents at GET /api/handover/public/{slug}: its items and prices, where to make offers, and where to order. An order (POST /api/handover/public/{slug}/orders) is recorded on the business's own workspace at the page's prices, or at a price agreed in an offer (checked with the buyer's own negotiation token), and answers a WhatsApp link that sends it to the owner.
curl -X POST https://api.last-price.ai/api/handover/public/ade-rides/orders -H "content-type: application/json" \
-d '{ "name": "Funke", "items": [{ "id": "airport-run-1", "quantity": 1 }], "when": "Saturday 6am" }'
{
"reference": "#6b1e0c2a",
"total": 15000,
"currency": "NGN",
"whatsapp_url": "https://wa.me/2348012345678?text=Hello%20Ade%20Rides..."
}Agents can run Handover over MCP, in the same steps: fill_handover_sheet while you talk,create_handover_business with the brief and the person's yes,update_handover_business as you check the page with them,publish_handover_business, then get_handover_pack for the QR code, claim link and message. list_handover_businesses and get_handover_business read what you built. Buyers' agents need no key: get_handover_page reads a live business,make_offer haggles on its open items, and order_from_handover_business orders, with any agreed offer.
Answers you may see: licences_unconfirmed (confirm the licence first), not_configured (the deployment has no partner key), partner_allowance_spent (today's new businesses are used up), offer_not_agreed (an order named an offer that was not accepted) and rate_limited (10 orders a minute per address).
Get paid into your own Stripe
A workspace can take card payments for its orders into its own Stripe account. Stripe collects the owner's identity and bank details on its own pages, buyers pay through a Stripe Checkout link, and Stripe pays the balance out to the owner's bank. Last Price never holds the money and adds no fee per sale. Open Get Paid in the dashboard to start.
Setup is started by a person who owns or runs the workspace, signed in. An API key cannot start it, so whoever set the business up for its owner can see sales but can never set or change where the money goes. POST /api/payouts/connect answers a one-time Stripe link to open in the browser, and GET /api/payouts/account shows how far setup has got.
curl https://api.last-price.ai/api/payouts/account -H "x-api-key: $LAST_PRICE_API_KEY"
{
"account": {
"stripe_account_id": "acct_1Q2w3E4r5T6y7U8i",
"method": "express",
"details_submitted": true,
"charges_enabled": true,
"payouts_enabled": true,
"livemode": false,
"ready": true
},
"refreshed": true,
"readiness": { "ready": true, "mode": "test" }
}Once card payments are on, make a payment link for an order and send it on WhatsApp, SMS or email. Calling it again returns the same open link until it is close to expiry or the order total changes. When the buyer pays, the order is marked paid and completed.
curl -X POST https://api.last-price.ai/api/orders/$ORDER_ID/payment-link -H "x-api-key: $LAST_PRICE_API_KEY"
{
"payment": {
"checkout_session_id": "cs_test_a1B2c3",
"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3",
"status": "open",
"amount": 1250050,
"currency": "NGN",
"livemode": false,
"expires_at": "2026-10-23T12:00:00.000Z"
}
}Answers you may see: no_account or account_not_ready (finish setup first), order_closed (a cancelled or already paid order), bad_amount (the order has no total to charge) and person_required (setup was tried with an API key). Amounts are in the currency's smallest unit, the way Stripe counts them.
Authentication & security
AgentID sign-in requests the agent identity and its owner's name and verified email. The owner may need to approve sharing. Existing accounts can share these details on their next AgentID sign-in; refreshing a session does not add them. Staff can see recorded ownership and related agents on the user detail page. A shared owner ID does not merge accounts or grant workspace access. Ownership is recorded at sign-in and is not a live guarantee.
If you are calling the API from your own code, you have two credentials: API keys (long-lived, ideal for server-to-server) and JWT Bearer tokens (short-lived, minted for agents from an agent-bound key). Every secured endpoint takes one of these. The credential exchanges are the exception, since they carry their own credential: /api/oauth/token takes client credentials, and native apps call /api/auth/native-token with their Supabase access token to get a Last Price JWT. Two other credentials exist but are not for API callers: webhook receivers authenticate the sender by signature rather than by key, such as x-paid-signature on /api/webhooks/paid, and the dashboard authenticates with its own session cookie, which is what the settings pages use. Where shared sign-in is switched on, that one cookie covers every last-price.ai address, so the website and app.last-price.ai always show the same signed-in person. Explore all endpoints interactively in the API reference.
JWT tokens
This section covers the agent JWT. Native apps get a JWT too, from the Supabase exchange at /api/auth/native-token described above, which carries the signed-in user rather than an agent. Exchange an agent-bound API key for a one-hour token with the OAuth 2.0 client credentials grant, then send it in the Authorization header as a Bearer token. The client_id is the key prefix and the client_secret is the full key. Plain tenant keys are not exchanged: they authenticate directly as x-api-key.
Native sign-in tokens are bound to the verified provider session. After it ends, native requests are refused with 401. Legacy unbound native tokens need a fresh sign-in and exchange. An exchange or REST response with reason: session_binding_required explains this requirement. If the native session check is temporarily unavailable, the answer is 503 service_unavailable withRetry-After: 5. The browser reports a failed sign-out and stays on the page so you can retry; it does not claim the provider signed you out. Signing in again through AgentID can return to the same account.
# Exchange an agent-bound key for a JWT
curl -X POST https://api.last-price.ai/api/oauth/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials" \
-d "client_id=lp_a3f9e2b1" \
-d "client_secret=lp_a3f9e2b1c4d5e6f7..."
# Response
{
"access_token": "eyJhbGciOiJSUzI1NiIs...",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "price:compute commerce:catalog:read",
"agent_id": "550e8400-e29b-41d4-a716-446655440000"
}
# Use the token
curl https://api.last-price.ai/api/functions \
-H "Authorization: Bearer eyJhbGciOiJSUzI1NiIs..."API keys
In Settings, leave the ordinary secret-key expiration blank for no expiration, or choose a valid future date within 3,650 days. Invalid or past dates are refused before creating a key. This does not change the non-expiring agent keys made by Get started.
For server-to-server integrations, use long-lived API keys. Keys are prefixed with lp_ and stored as SHA-256 hashes; the plaintext is returned only once at creation. Optionally restrict a key to specific scopes (e.g., price:compute, billing:read, or a wildcard such as commerce:*) for least-privilege access. Rosetta, price experiments (with their embed tokens) and webhooks each have a read and a write scope (rosetta:read, rosetta:write, experiments:read, experiments:write, webhooks:read and webhooks:write); your own marketplace listings use pcn:function:read and pcn:function:publish, and disputes and costs use billing:read and billing:write. Any other name is refused with a 400 that lists the valid scopes, which /.well-known/agents.json also publishes. Keys created earlier with the old read, write or admin labels keep their billing and commerce access. Manage keys via Settings → API Keys in the dashboard, or directly via the API.
# Create a key with scopes (requires JWT)
curl -X POST https://api.last-price.ai/api/api-keys \
-H "Authorization: Bearer <JWT>" \
-H "Content-Type: application/json" \
-d '{"name": "Production server", "scopes": ["price:compute", "pcn:function:read"]}'
# Response (key shown only once, save it now)
{
"api_key": {
"id": "550e8400-...",
"name": "Production server",
"key": "lp_a3f9e2b1c4d5e6f7...",
"key_prefix": "lp_a3f9e2",
"scopes": ["price:compute", "pcn:function:read"],
"created_at": "2025-01-01T00:00:00Z",
"expires_at": null
}
}
# Use the key in subsequent requests
curl https://api.last-price.ai/api/functions \
-H "x-api-key: lp_a3f9e2b1c4d5e6f7..."
# List all active keys
curl https://api.last-price.ai/api/api-keys \
-H "Authorization: Bearer <JWT>"
# Revoke a key
curl -X DELETE https://api.last-price.ai/api/api-keys/<keyId> \
-H "Authorization: Bearer <JWT>"Which scope each route needs: GET /api/openapi?view=scopes lists every operation with what a credential needs to call it (a scope, one of several, any credential, a dashboard session, or none) and every scope with what it is for. A key whose only scopes are workspace:claim, team:admin or launches:read acts from the key itself and carries no workspace data, so it cannot read usage; the commerce audit trail needs audit:read, like the workspace audit log.
The API keys page marks each key Active, Expired (past its expiry date, so refused) or Revoked, with the date, and filters by them; revoked keys stay listed for 90 days. Revoking asks you to confirm the key by name and the row turns Revoked straight away. The list answers with a status per key, and ?include_revoked=true adds the revoked ones. A key can only carry the scopes your role holds (see Team Roles).
Rotate an API key
POST /api/api-keys/rotate with the current key in x-api-key replaces that key. Save api_key.key from the 201 response immediately: it is shown once, and the old key stops working, along with any token exchanged from it at POST /api/oauth/token. Only you get the new key, so if someone else gave you this key, ask them before rotating it. If the answer is 400 confirmation_required, nothing changed: send the request again with the body {"confirm": true} to go ahead. The replacement preserves scopes, agent binding, name, and expiry. Rotation does not extend a sandbox key's lifetime or increase its permissions. Sandbox rotation limits still apply. Use Settings, API keys to manage keys with a browser session. A key that has finished its work can end itself with DELETE /api/me/key (the MCP tool revoke_my_key); GET /api/me returns its key_id. A key with no scopes ticked has full access except team:admin and workspace:claim, which are only ever granted by name.
Sessions and security log
Profile, Sessions lists each device signed in to your account: browser, system, approximate location, a masked address, how it signed in and when it was last active. Sign out ends that device's sign-in at once, and Sign out everywhere else ends every sign-in but the one you are using. The mobile app's token names its sign-in, so each native request checks that the provider session still exists, independently of the optional log. Profile, Security shows your account's security log: sign-ins, sign-outs, devices signed out, password changes, email change requests and confirmed email changes, and API keys you created, revoked or rotated (a rotation done with the key itself is logged for the person who created it). Both lists are your own account, not a workspace, so they answer a browser session or a person's sign-in token from POST /api/auth/native-token, never an API key. Signing a device out needs the browser session, because it has to know which sign-in is yours.
The log pages newest first: pass the next_cursor of one answer as before for the next. MCP clients with LASTPRICE_JWT set can call list_account_sessions and list_security_events. Recorded sessions are being rolled out; until they reach your account the sessions list is empty and the log answers 404.
# Devices signed in to your account
curl https://api.last-price.ai/api/user/sessions \
-H "Authorization: Bearer <JWT>"
# Your security log, 20 at a time
curl "https://api.last-price.ai/api/user/security-events?limit=20" \
-H "Authorization: Bearer <JWT>"Sign in from an MCP client
Add https://api.last-price.ai/api/mcp to Claude as a custom connector, or to any MCP client that supports OAuth. Pricing, the catalog, the marketplace and offers work before anyone signs in. The first call to a tool that needs an account asks the person to sign in to Last Price, choose a workspace, and allow either everything they can do there or read only. The client then acts as that person, with their role.
Access tokens last one hour and work only through the MCP server; refresh tokens rotate on every use. Disconnect an app in Profile, Sessions, Connected apps, or from the app itself with the MCP toolslist_connected_apps anddisconnect_connected_app; a read-only connection can disconnect only itself. API keys keep working at/api/mcp/rpc. Client details are at/.well-known/oauth-protected-resource/api/mcp.
Your account in the mobile app
Account and security, in the app's account menu, has what Profile has on the website. Changes made in one show in the other, because both use the same account.
- Sign-in and security. Change your email (a link goes to both addresses), change your password or set your first one, see the ways you sign in and remove one while another remains, turn two-factor on with any authenticator app or turn it off, and sign out on every other device.
- Signing in. Sign in with Apple on an iPhone. With two-factor on, the app asks for the 6-digit code before anything else opens, as the website does.
- Notifications. The inbox has your workspace's notifications, and opening it marks them read. Owners and admins choose each alert email and whether it comes right away or in the daily summary at 8:00 in their time zone.
- Profile. Your name, photo, time zone and product news emails.
- Balance. What is left and each line that added to or drew from it. You can see it in the app; you can't buy credit there.
- Connected apps. The AI assistants you signed in to with Last Price, each with Disconnect.
- Delete account. Type DELETE to confirm. It deletes the account everywhere, and the phone stops getting notifications.
The app reports what was used, never anything you typed, with POST /api/mobile/events, which takes only the app's own listed events.
Legacy authentication
The x-tenant-id header is rejected on all secured endpoints. Use Authorization: Bearer <JWT> or x-api-key: lp_... instead.
# Rejected: x-tenant-id no longer accepted on secured endpoints
curl https://api.last-price.ai/api/customers \
-H "x-tenant-id: 00000000-0000-0000-0000-000000000001"
# → 401 Unauthorized
# Use a JWT bearer token
curl https://api.last-price.ai/api/customers \
-H "Authorization: Bearer eyJhbGciOiJSUzI1NiIs..."
# Or use an API key (lp_ prefix)
curl https://api.last-price.ai/api/customers \
-H "x-api-key: lp_a3f9e2b1c4d5e6f7..."Rate limiting
All API endpoints are rate-limited per tenant using a sliding window algorithm. When you exceed the limit, the API returns a 429 Too Many Requests response.
- X-RateLimit-Limitheader
- Maximum requests allowed in the window
- X-RateLimit-Remainingheader
- Remaining requests in the current window
- X-RateLimit-Resetheader
- Unix timestamp when the window resets
- Retry-Afterheader
- Seconds to wait before retrying (on 429)
MCP tool calls sent without a key have a separate hourly budget per address, where it is on: each tools/call costs 1 and a call that fails costs 6, out of 120. Past it the MCP endpoint answers 429 with a JSON-RPC error whose data.retry_after says when to try again. Calls with an API key are never counted against it, and POST /api/agents/register gives an agent a key with no human needed.
Self-registration has a daily budget per address. Several agents on one machine can share one key, so an agent that registered before should reuse its saved key rather than register again: keep it in LASTPRICE_API_KEY (or ~/.config/lastprice/api_key) and look there before registering. Where it is on, once a person claims one workspace registered from an address, that address may register 25 agents a day instead of 5, and every address also counts toward a budget for its network. A refused registration answers 429 rate_limited with a reason and next steps: reuse the saved key, ask a person to claim a workspace or create a key, or use the keyless demo. Keep asking for the price; do not estimate it yourself.
# Rate limit headers in every response
HTTP/1.1 200 OK
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 742
X-RateLimit-Reset: 1704067200
# When rate limited
HTTP/1.1 429 Too Many Requests
Retry-After: 30
{
"error": "rate_limit_exceeded",
"message": "Too many requests. Retry after 30 seconds."
}Webhooks
Receive real-time event notifications via webhooks. Every webhook delivery includes an HMAC-SHA256 signature in the x-lastprice-signature header, the event type in x-webhook-event, and a Unix timestamp in x-lastprice-timestamp. The older x-paid-signature and x-paid-timestamp headers are still sent with the same values, so receivers built against them keep working.
# Register a webhook endpoint (an owner or admin of the workspace)
curl -X POST https://api.last-price.ai/api/webhooks \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"url": "https://your-app.com/webhooks/last-price",
"events": ["balance.low", "platform.changelog", "rosetta.adapter.review_required"]
}'
# The response carries the signing secret (whsec_...). Send a test event with
# POST /api/webhooks/{webhookId}/ping.
# Verify the signature in your handler: HMAC-SHA256 of the raw body, hex encoded
import hmac, hashlib
def verify_signature(payload: bytes, signature: str, secret: str) -> bool:
expected = hmac.new(
secret.encode(), payload, hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, signature)The signature covers the raw request body and nothing else: the timestamp header is not part of the signed string. To refuse a replayed delivery, check that x-lastprice-timestamp is within five minutes of your clock, and keep the id of each event you have handled. An API key listing endpoints sees each secret masked; to get a usable one, callPOST /api/webhooks/{webhookId}/rotate-secret, which makes a new secret and returns it once. Deliveries are signed with the new secret from then on.
To act without opening the dashboard, subscribe to approval.requested, sent when a call is held for approval (with the action and a link to approve it), and dispute.opened, sent when a dispute is created (with the amount, currency and reason). An approval's request body is never included; read it from the approval. webhooks.failing is sent at most once a day when deliveries to one endpoint fail three times in a row, and only to your other healthy endpoints, never to the failing one. With no healthy endpoint left, the alert email and the Notifications panel tell you instead.
Core business objects
Last Price provides a full suite of business objects for managing your commercial operations. All objects support standard CRUD operations and are accessible via RESTful endpoints.
Customers
Manage customer records including billing details, segments, and metadata.
# Create a customer
curl -X POST https://api.last-price.ai/api/customers \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"name": "Acme Corp",
"email": "billing@acme.com",
"externalId": "acme_123",
"metadata": { "industry": "technology" }
}'
# Response (201)
{
"id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"external_id": "acme_123",
"name": "Acme Corp",
"email": "billing@acme.com",
"metadata": { "industry": "technology" },
"created_at": "2026-01-15T14:30:00.000Z",
"updated_at": "2026-01-15T14:30:00.000Z"
}
# List customers
curl "https://api.last-price.ai/api/customers?limit=25&offset=0" \
-H "Authorization: Bearer lp_<hex>"
# Response
{
"data": [ /* customer rows */ ],
"pagination": { "limit": 25, "offset": 0, "total": 1 }
}
# Look one up by your own identifier
curl https://api.last-price.ai/api/customers/external/acme_123 \
-H "Authorization: Bearer lp_<hex>"Customer overview and intel
Two summaries of one customer, built from records you already keep. They are being released workspace by workspace behind the customer-overview-intel flag; until it is on, both answer 404 with code: not_released and the customer page shows only its record tabs. To have it switched on, write to support@last-price.ai.
Overview (GET /api/customers/{id}/overview): revenue invoiced over the lifetime and the last 30 and 90 days, outstanding and overdue invoices, payments collected, credit left, costs and margin, orders, contacts, the last activity, a 90 day series of usage signals and price quotes with its trend, the agents linked to the customer, and a health status that lists the reasons behind it. Money is per currency and never converted.
Value of agent work (work_value): what the agents' work for this customer would have cost done by a person. Each of the customer's usage signals is counted per agent and multiplied by the USD value that agent's value receipt sets for the signal (Settings, Value receipts). Signals without a value are left out, and the figure appears on the customer page only once at least one signal has a value. Intel names products by their title in Offers and prices each experiment variant in its own currency.
Intel (GET /api/customers/{id}/intel): how the customer reacts to price, set against the learned elasticity of their segment (agent buyers when most of their quotes came through an agent), their negotiations and how they ended, the buyer agents on their records with each spend policy, the price experiments they were in, the price changes they saw, and the team's notes. Notes are added with POST /api/customers/{id}/notes and edited, pinned or deleted at /api/customers/{id}/notes/{noteId}.
Both reads need billing:read; notes need billing:write to change. An agent can read them over MCP with get_customer_overview and get_customer_intel. A part that could not be read is null and named in unavailable, and the rest still answers.
curl https://api.last-price.ai/api/customers/7c9e6679-7425-40de-944b-e07fc1f90ae7/overview \
-H "Authorization: Bearer YOUR_TOKEN"
# Response (abridged)
{
"released": true,
"revenue": [{ "currency": "USD", "lifetime": 18420, "last_30_days": 2450, "last_90_days": 7180 }],
"invoices": { "outstanding": { "count": 3, "amounts": [{ "currency": "USD", "amount": 3120 }] },
"overdue": { "count": 1, "amounts": [{ "currency": "USD", "amount": 840 }] } },
"usage": { "window_days": 90, "trend": { "direction": "up", "change_pct": 29.6 } },
"health": {
"status": "watch",
"score": 75,
"reasons": [
{ "code": "overdue_invoices", "signal": "bad", "message": "1 invoice is overdue, the oldest since Sep 18, 2026." },
{ "code": "usage_up", "signal": "good", "message": "Usage is up 30% on the 30 days before." }
]
},
"unavailable": []
}
# Add a pinned note
curl -X POST https://api.last-price.ai/api/customers/7c9e6679-7425-40de-944b-e07fc1f90ae7/notes \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "body": "Asked for annual billing on the 3 October call.", "pinned": true }'Contacts
A contact is a person on a customer account: who an invoice is addressed to, and who an order can name as its billing contact. A contact belongs to exactly one customer and cannot be moved between them.
# Create a contact
curl -X POST https://api.last-price.ai/api/contacts \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"customerId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"name": "Jane Doe",
"email": "jane.doe@acme.com",
"phone": "+1-555-0123",
"externalId": "acme_contact_123",
"address": { "line1": "123 Business Ave", "city": "San Francisco", "country": "USA" }
}'
# Response (201)
{
"id": "3f1a9c88-2b47-4e0d-9f0a-6c2f7d5b1e34",
"customer_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"external_id": "acme_contact_123",
"name": "Jane Doe",
"email": "jane.doe@acme.com",
"phone": "+1-555-0123",
"address": { "line1": "123 Business Ave", "city": "San Francisco", "country": "USA" },
"metadata": {},
"created_at": "2026-01-15T14:30:00.000Z",
"updated_at": "2026-01-15T14:30:00.000Z"
}
# List one customer's contacts
curl "https://api.last-price.ai/api/contacts?customer_id=7c9e6679-7425-40de-944b-e07fc1f90ae7" \
-H "Authorization: Bearer lp_<hex>"
# Update one. Only the properties you send are written; send null to clear
# externalId, phone or address.
curl -X PATCH https://api.last-price.ai/api/contacts/3f1a9c88-2b47-4e0d-9f0a-6c2f7d5b1e34 \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{ "phone": null }'
# Look one up by your own identifier. External IDs are unique per customer,
# so the customer has to come with it.
curl "https://api.last-price.ai/api/contacts/external/acme_contact_123?customerId=7c9e6679-7425-40de-944b-e07fc1f90ae7" \
-H "Authorization: Bearer lp_<hex>"
# Delete one. An order billing this contact keeps its own row and has
# billing_contact_id cleared.
curl -X DELETE https://api.last-price.ai/api/contacts/3f1a9c88-2b47-4e0d-9f0a-6c2f7d5b1e34 \
-H "Authorization: Bearer lp_<hex>"Orders
Create and manage orders. Orders can contain multiple line items and track fulfillment status. An order that has started billing cannot be deleted outright: cancel it first, then delete it.
# Create an order. customerId is a customer UUID.
# Line items are added afterwards, one request each.
curl -X POST https://api.last-price.ai/api/orders \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"customerId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"totalAmount": 643.50,
"currency": "USD",
"metadata": { "channel": "self-serve" }
}'
# Response (201). Money columns come back as decimal strings, not numbers.
{
"id": "9b2d4f61-0c3a-4e58-8d77-1f5a6b9c0e23",
"customer_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"agent_id": null,
"status": "draft",
"total_amount": "643.5000",
"currency": "USD",
"metadata": { "channel": "self-serve" },
"created_at": "2026-01-15T14:30:00.000Z",
"updated_at": "2026-01-15T14:30:00.000Z"
}
# Add a line, one request per line
curl -X POST https://api.last-price.ai/api/orders/9b2d4f61-0c3a-4e58-8d77-1f5a6b9c0e23/lines \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{ "description": "Pro plan, January", "quantity": 2, "unitPrice": 19.99 }'
# Activate it
curl -X POST https://api.last-price.ai/api/orders/9b2d4f61-0c3a-4e58-8d77-1f5a6b9c0e23/activate \
-H "Authorization: Bearer lp_<hex>"
# List orders, optionally for one customer
curl "https://api.last-price.ai/api/orders?limit=25&offset=0&customer_id=7c9e6679-7425-40de-944b-e07fc1f90ae7" \
-H "Authorization: Bearer lp_<hex>"
# Response
{
"data": [ /* order rows */ ],
"pagination": { "limit": 25, "offset": 0, "total": 1 }
}
# List the line items on an order, oldest first
curl https://api.last-price.ai/api/orders/9b2d4f61-0c3a-4e58-8d77-1f5a6b9c0e23/lines \
-H "Authorization: Bearer lp_<hex>"
# Response
{ "data": [ /* order line rows */ ] }
# Cancel an order. This is also how you make one deletable.
curl -X PATCH https://api.last-price.ai/api/orders/9b2d4f61-0c3a-4e58-8d77-1f5a6b9c0e23 \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{ "status": "cancelled" }'
# Delete a draft or cancelled order, and its line items with it.
# Any other status answers 409 and tells you to cancel first.
curl -X DELETE https://api.last-price.ai/api/orders/9b2d4f61-0c3a-4e58-8d77-1f5a6b9c0e23 \
-H "Authorization: Bearer lp_<hex>"Invoices
Dashboard billing views follow the selected workspace. Changing workspace clears unsaved invoice, payment and credit bundle drafts. An operation already submitted may still complete in its original workspace; return there and refresh to check its result. New invoice drafts show USD, matching their creation request, while existing invoices display their recorded currency and invoice number. Credits granted from a plan display credit units; plan prices and monetary credits display their recorded currencies.
Settings, Billing saves invoice preferences per workspace. The first number is a floor for automatically numbered invoices; it never rewinds existing numbers or turns manual numbering on. Payment instructions appear separately from the email footer and on enabled public invoice links. An optional dispute link emails the seller's company contact; it does not process a refund.
Send invoice explicitly emails the customer. Post invoice uses the saved auto-send preference, off by default; creating a draft does neither. The same distinction is available onPOST /api/invoices/{id}/send andsend_invoice throughpost: true. ExplicitissueWithoutEmail: true always prevents email. Invalid send intent is refused before issuing the invoice.
Generate and manage invoices with line items, tax calculations, and due dates. Invoices can be synced to Stripe for automated collection.
The billing records keep themselves consistent: an invoice, payment or credit must name one of your customers (422 customer_not_found); a currency is an ISO code or USDC with no more decimals than it has; an invoice starts as draft or pending, keeps its amount once sent, only moves forward (paid and cancelled are final), and becomes paid when completed payments in its currency cover it; a payment is refunded in parts up to what is left (refundable_amount), and a refund that leaves a paid invoice short makes it owed again; a dispute is for at most its payment; a customer with orders, payments, sent invoices, credit or disputes is kept; and sending an invoice emails the customer's own address, leaving it a draft when nothing went out.
# Create an invoice
curl -X POST https://api.last-price.ai/api/invoices \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"customerId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"invoiceNumber": "INV-2026-0001",
"amount": 643.50,
"currency": "USD",
"dueDate": "2026-02-01T00:00:00.000Z"
}'
# Response (201). The amount comes back as a decimal string, not a number.
{
"id": "c5a7e310-84bd-4f62-9f0a-2d7c1b8e4a56",
"customer_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"invoice_number": "INV-2026-0001",
"status": "draft",
"amount": "643.5000",
"currency": "USD",
"due_date": "2026-02-01T00:00:00.000Z",
"metadata": {},
"created_at": "2026-01-15T14:30:00.000Z",
"updated_at": "2026-01-15T14:30:00.000Z"
}
# Issue it, and email it to the customer when delivery is configured
curl -X POST https://api.last-price.ai/api/invoices/c5a7e310-84bd-4f62-9f0a-2d7c1b8e4a56/send \
-H "Authorization: Bearer lp_<hex>"
# Response: the invoice row plus the delivery outcome
{
"id": "c5a7e310-84bd-4f62-9f0a-2d7c1b8e4a56",
"status": "sent",
"message": "Invoice issued and emailed to the customer.",
"email": { "delivered": true, "skipped": false }
}
# List invoices, optionally for one customer
curl "https://api.last-price.ai/api/invoices?limit=25&offset=0&customer_id=7c9e6679-7425-40de-944b-e07fc1f90ae7" \
-H "Authorization: Bearer lp_<hex>"
# Response
{
"data": [ /* invoice rows */ ],
"pagination": { "limit": 25, "offset": 0, "total": 1 }
}Invoice pay links
A sent invoice gets a pay link: a page for people and the same invoice as JSON for the software that pays the buyer's bills, including accounts-payable agents. The link reads one invoice and pays it, and shows nothing about your customer. Buyers can pay with USDC over x402, straight to your own wallet, or by card, into your connected card account. Last Price never holds the money. Each method appears only once you set it up, and the invoice email carries both links.
On the invoice page, Where payments go sets the name buyers see, your wallet and your card account. The pay link card shows both links and, once the invoice is paid, whether an agent or a person paid it and how.
# Where your invoice payments go (owner, admin or billing)
curl -X PUT https://api.last-price.ai/api/invoices/payment-settings \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "seller_name": "Acme Supplies", "x402_pay_to": "0xYourWallet", "card_account_id": "acct_..." }'
# Sending an invoice makes its pay link; this reads it (or POST to make one)
curl https://api.last-price.ai/api/invoices/c5a7e310-84bd-4f62-9f0a-2d7c1b8e4a56/pay-link \
-H "Authorization: Bearer YOUR_TOKEN"
# What the buyer's accounts-payable agent reads: no key needed
curl https://api.last-price.ai/api/public/invoices/PAY_TOKEN
{
"object": "invoice",
"invoice_number": "INV-2026-0001",
"status": "open",
"amount_due": "643.5000",
"currency": "USD",
"due_date": "2026-02-01T00:00:00.000Z",
"seller": { "name": "Acme Supplies" },
"accepted_methods": [
{ "method": "x402", "asset": "USDC", "pay_to": "0xYourWallet", "amount_atomic": "643500000",
"pay_url": "https://api.last-price.ai/api/public/invoices/PAY_TOKEN/pay" },
{ "method": "card", "checkout_url": "https://api.last-price.ai/api/public/invoices/PAY_TOKEN/checkout" }
]
}
# Pay with x402: POST once for the 402 terms, then again with the signed X-PAYMENT header
curl -X POST https://api.last-price.ai/api/public/invoices/PAY_TOKEN/pay -H "X-PAYMENT: ..."Agents connected over MCP read a pay link with read_payable_invoice (public, no key). Each payment authorization pays once, and only one payment per invoice can be in flight, so two agents paying at once are never both charged.
Payments
Record and track payments against invoices. Supports partial payments and multiple payment methods.
# Record a payment
curl -X POST https://api.last-price.ai/api/payments \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"customerId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"invoiceId": "c5a7e310-84bd-4f62-9f0a-2d7c1b8e4a56",
"amount": 643.50,
"currency": "USD",
"status": "completed",
"paymentMethod": "card",
"metadata": { "reference": "ch_abc123" }
}'
# Response (201). The amount comes back as a decimal string, not a number.
{
"id": "e81f0d45-6a2c-4b93-8177-0c9d3e5f2a68",
"invoice_id": "c5a7e310-84bd-4f62-9f0a-2d7c1b8e4a56",
"customer_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"amount": "643.5000",
"currency": "USD",
"status": "completed",
"payment_method": "card",
"metadata": { "reference": "ch_abc123" },
"created_at": "2026-01-15T14:30:00.000Z",
"updated_at": "2026-01-15T14:30:00.000Z"
}
# Refund it, in full or in part
curl -X POST https://api.last-price.ai/api/payments/e81f0d45-6a2c-4b93-8177-0c9d3e5f2a68/refund \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{ "amount": 100.00, "reason": "Partial credit" }'
# Response: the payment row plus a confirmation
{
"id": "e81f0d45-6a2c-4b93-8177-0c9d3e5f2a68",
"status": "completed",
"metadata": { "refund": { "amount": 100, "reason": "Partial credit" } },
"refunded_amount": 100,
"refundable_amount": 543.5,
"message": "Payment partly refunded"
}
# Empty body or JSON null records a full remaining refund.
# Malformed JSON returns 400 invalid_json and leaves the ledger unchanged.
# This records a refund; it does not transfer money through a payment provider.
# List payments
curl "https://api.last-price.ai/api/payments?limit=25&offset=0" \
-H "Authorization: Bearer lp_<hex>"
# Response
{
"data": [ /* payment rows */ ],
"pagination": { "limit": 25, "offset": 0, "total": 1 }
}Disputes
Manage payment disputes and chargebacks. Track status, submit evidence, and monitor resolutions.
# Open a dispute against a payment
curl -X POST https://api.last-price.ai/api/disputes \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"paymentId": "e81f0d45-6a2c-4b93-8177-0c9d3e5f2a68",
"amount": 643.50,
"currency": "USD",
"reason": "product_not_received"
}'
# List disputes
curl "https://api.last-price.ai/api/disputes?limit=25&offset=0" \
-H "Authorization: Bearer lp_<hex>"
# Response. The amount comes back as a decimal string, not a number.
{
"data": [
{
"id": "1d6b8f23-9e04-47ac-b5f1-3a8c0d2e7b94",
"payment_id": "e81f0d45-6a2c-4b93-8177-0c9d3e5f2a68",
"customer_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"amount": "643.5000",
"currency": "USD",
"status": "open",
"reason": "product_not_received",
"metadata": {},
"created_at": "2026-01-15T14:30:00.000Z",
"updated_at": "2026-01-15T14:30:00.000Z"
}
],
"pagination": { "limit": 25, "offset": 0, "total": 1 }
}
# Move it on. Valid states: open, under_review, resolved, rejected
curl -X PATCH https://api.last-price.ai/api/disputes/1d6b8f23-9e04-47ac-b5f1-3a8c0d2e7b94 \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{ "status": "resolved" }'Credits
Issue credits to customer accounts. Credits can be applied to future invoices automatically or manually.
# Issue a credit bundle
curl -X POST https://api.last-price.ai/api/credits \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"customerId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"amount": 50.00,
"currency": "USD",
"expiresAt": "2026-12-31T23:59:59.000Z",
"metadata": { "reason": "Service disruption compensation" }
}'
# Response (201). Amount and balance come back as decimal strings.
{
"id": "a3c05e78-1b94-4d26-8f50-6e7b2c9a1d43",
"customer_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"amount": "50.0000",
"balance": "50.0000",
"currency": "USD",
"expires_at": "2026-12-31T23:59:59.000Z",
"metadata": { "reason": "Service disruption compensation" },
"created_at": "2026-01-15T14:30:00.000Z",
"updated_at": "2026-01-15T14:30:00.000Z"
}
# View a customer's balance, summed over the bundles that have not expired
curl "https://api.last-price.ai/api/credits/balance?customerId=7c9e6679-7425-40de-944b-e07fc1f90ae7" \
-H "Authorization: Bearer lp_<hex>"
# Response: one row per currency, plus those rows added together
{
"customerId": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"balances": [
{
"customer_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
"total_balance": "50.0000",
"currency": "USD",
"bundle_count": "1"
}
],
"totalBalance": 50
}Billing reads over MCP
Your agent can read credits, invoices and payments from its MCP session with six tools: list_credits, get_credit_balance, list_invoices, get_invoice, list_payments and get_payment. They call the routes above and need billing read scope. The lists take customer_id, limit and offset; payments also take a status. Reads only: creating invoices, taking payments and issuing credit stay with the dashboard and the API.
Agents
Agents represent your own pricing bots and AI agents that automate pricing workflows. Each agent can have its own pricing model, metadata, and optional external identifier for integration with your systems. Managing agents requires a person's credential (a dashboard session or JWT), not a workspace API key.
Create agent
Register a new agent with a name, optional description, pricing model, and custom metadata.
- namestring, required
- Human-readable agent name
- externalIdstring
- Your own identifier for cross-system lookups
- descriptionstring
- Short description of the agent's purpose
- pricingModelstring
- Pricing model identifier to use
- metadataobject
- Arbitrary key-value pairs for custom data
# Create a new agent
curl -X POST https://api.last-price.ai/api/agents \
-H "Authorization: Bearer <YOUR_JWT_TOKEN>" \
-H "Content-Type: application/json" \
-d '{
"name": "Dynamic Pricer",
"description": "Adjusts SaaS pricing based on usage patterns",
"externalId": "agent-prod-001",
"pricingModel": "usage_based",
"metadata": {
"tier": "enterprise",
"region": "us-east"
}
}'
# Response (201)
{
"id": "a1b2c3d4-...",
"external_id": "agent-prod-001",
"name": "Dynamic Pricer",
"description": "Adjusts SaaS pricing based on usage patterns",
"pricing_model": "usage_based",
"metadata": { "tier": "enterprise", "region": "us-east" },
"created_at": "2025-01-10T09:00:00Z",
"updated_at": "2025-01-10T09:00:00Z"
}Manage agents
List, retrieve, update, or delete agents. Pagination is supported via limit (max 1000) and offset query parameters.
# List agents (paginated)
curl "https://api.last-price.ai/api/agents?limit=50&offset=0" \
-H "Authorization: Bearer <YOUR_JWT_TOKEN>"
# Get a single agent
curl https://api.last-price.ai/api/agents/AGENT_ID \
-H "Authorization: Bearer <YOUR_JWT_TOKEN>"
# Update an agent
curl -X PATCH https://api.last-price.ai/api/agents/AGENT_ID \
-H "Authorization: Bearer <YOUR_JWT_TOKEN>" \
-H "Content-Type: application/json" \
-d '{
"name": "Updated Pricer",
"metadata": { "tier": "premium" }
}'
# Delete an agent
curl -X DELETE https://api.last-price.ai/api/agents/AGENT_ID \
-H "Authorization: Bearer <YOUR_JWT_TOKEN>"A2A agent card
Last Price publishes an Agent2Agent (A2A) agent card at /.well-known/agent.json and at /.well-known/agent-card.json. It describes the skills an agent can call (compute a price, verify a price, record an outcome) with their security schemes, so an A2A client or registry can find them without reading these docs. Each skill is a plain HTTP operation: the card's http-operations extension lists the method, path and scope for each one. There is no A2A task endpoint yet. For limits, scopes and error shapes, read /.well-known/agents.json.
curl https://api.last-price.ai/.well-known/agent.json
# Response (abridged)
{
"protocolVersion": "0.3.0",
"name": "Last Price",
"url": "https://api.last-price.ai",
"preferredTransport": "HTTP+JSON",
"skills": [
{ "id": "compute-price", "name": "Compute a price" },
{ "id": "verify-price", "name": "Verify a price" },
{ "id": "record-outcome", "name": "Record an outcome" }
]
}Signed quotes
A price response can carry a signed_quote: a compact JWS signed with Ed25519 that binds the price, currency, pricing function, receipt and an expiry. Pass its jws to a buyer, for example in the extra.quote field of an HTTP 402 payment requirement, and the buyer can check it was issued by Last Price and not changed. Signed quotes are on per workspace: a response without the field was not signed.
Verify offline against the public keys at /.well-known/quote-keys.json (match the JWS kid), or send the JWS to POST /api/quotes/verify, which needs no key. A failed check still answers 200 with valid: false and a reason; an expired quote is genuine but stale, a bad_signature one is not ours or was changed.
# Part of a POST /api/compute/price response
"signed_quote": {
"jws": "eyJhbGciOiJFZERTQSIsInR5cCI6ImxwLXF1b3RlK2p3cyIs...",
"alg": "EdDSA",
"kid": "Xc3...",
"claims": { "price": 42.5, "currency": "USD", "jti": "REQUEST_ID", "exp": 1791115500 },
"expires_at": "2026-10-04T12:05:00.000Z",
"keys_url": "https://api.last-price.ai/.well-known/quote-keys.json",
"verify_url": "https://api.last-price.ai/api/quotes/verify"
}
# Check a quote you were given
curl -X POST https://api.last-price.ai/api/quotes/verify \
-H "Content-Type: application/json" \
-d '{"jws": "eyJhbGciOiJFZERTQSIs..."}'
# Response
{ "valid": true, "kid": "Xc3...", "claims": { "price": 42.5, "currency": "USD" }, "expires_at": "2026-10-04T12:05:00.000Z" }Over MCP, the keyless verify_signed_quote tool does the same check: pass the jws string and it answers withvalid and the claims. The tool packages offer it too.
The draft protocol for exchanging a signed quote over HTTP 402 is Signed quotes over HTTP 402.
Quotes within a buyer's limit
A buyer often acts on a limit a person approved: at most this much, from this merchant, until this time. Card networks and payment rails call it a mandate or an intent. Send it with a price request asintent and the answer says whether the price fits it, inintent_check: within_intent true or false, with the reasons when it is false (over_max_amount,currency_mismatch or intent_expired).
When the answer carries a signed_quote, its claims bind the same intent andwithin_intent, so an issuer or the buyer can check the price against the approved limit without trusting whoever passed the quote along. The merchant is carried as you sent it and never judged: whoever checks the quote compares it with the party that presented it. Works on POST /api/compute/price (with a key, a balance or an x402 payment), POST /api/price-router, and the MCP toolcompute_price.
curl -X POST https://api.last-price.ai/api/compute/price \
-H "Authorization: Bearer $LASTPRICE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"context": { "currency": "USD", "product_id": "search-v2" },
"intent": { "id": "mandate_8f2c", "max_amount": 50, "merchant": "shop.example", "expires_at": "2026-10-23T18:00:00Z" }
}'
# Part of the response
"intent_check": {
"intent_id": "mandate_8f2c",
"within_intent": true,
"reasons": [],
"max_amount": 50,
"currency": "USD",
"merchant": "shop.example",
"expires_at": "2026-10-23T18:00:00.000Z"
},
"signed_quote": {
"jws": "eyJhbGciOiJFZERTQSIs...",
"claims": { "price": 42.5, "currency": "USD", "within_intent": true, "intent": { "id": "mandate_8f2c", "max_amount": 50, "reasons": [] } }
}Pay or authenticate
One menu, in order, from no credential to a workspace key. Each step is the way past the one before it. The same list is pay_or_auth in /.well-known/agents.json and in /llms.txt, with the prices this deployment charges.
- Try the keyless demo:
POST /api/public/compute/demowith no credential. Free, 30 calls per IP per hour, on a demo tenant. - Register a sandbox key:
POST /api/agents/registerwith no credential to register, then the returned key as x-api-key. Free: 25 compute calls a day with built-in functions, and a key valid for 30 days. Features that need a claimed workspace answer 403 sandbox_restricted. - Pay on the 402:
POST /api/compute/pricewith a signed x402 payment in PAYMENT-SIGNATURE (v2) or X-PAYMENT (v1), with no credential or with the sandbox key. 0.01 USDC per call on base; or a day pass of 500 calls for 24 hours at 2.5 USDC, or a prepaid balance from 10 USDC at 0.008333 USDC a call. - Use a workspace API key:
POST /api/compute/pricewith an API key holding price:compute, as x-api-key, from a claimed or person-owned workspace. Billed to the workspace's plan. Every feature is open, within the key's scopes.
A 401 means send a credential, a 402 means pay or use a key, a 403 sandbox_restricted means a person must claim the workspace (see What needs a claim), and a 429 quota_exceeded lists the ways past the limit in next.
Testing your own payment flow: send your tester tag (x-lastprice-tester, from Settings, Tester tag) with each paid call, and it is counted as your testers' traffic rather than a customer's. Pay from a wallet used only for testing, with a few USDC on Base, and settle one 0.01 USDC call before anything else. Payments go to our receiving address as any payment does.
Sign up from MCP
An agent connected to the hosted MCP server with no key can sign itself up without leaving the connection: call register_agent with a name. It answers like POST /api/agents/register: a sandbox workspace, its key (shown once) and a claim link for a person. From then on the same MCP session runs as the new agent on every call, so a call that needed a key works when retried as it is, with no header to add and no client to reconfigure.
- A keyless call that needs a key fails and says to call
register_agent. register_agentwith{ "name": "your-system/role-name" }. The answer'smcp.uses_this_keyis true when the session keeps the key.- Retry the call that failed.
The session keeps the key until the session ends (24 hours) or the key is revoked or rotated, or a person claims the workspace without keeping it. Save the key anyway: a new session needs it as the x-api-key header, and a client that sends it on the same session keeps that session. A session registers once; asking again answers 409 session_already_registered. A client that sends no Mcp-Session-Id has no session to keep the key in, so it is told to send it itself. The stdio server keeps the key for its process when started with LASTPRICE_REGISTER_TOOL=1.
Already holding a key, saved by an earlier run in a file or in LASTPRICE_API_KEY, on a connection opened without one? Call use_api_key with { "api_key": "lp_..." } instead of signing up again. On the hosted server the session then runs as that key's agent, exactly as after register_agent, until the session or the key ends, whichever is first. The key is checked and never echoed back; a connection that already sends a key keeps it. Both tools are also listed on /api/mcp/rpc?profile=starter.
When a person claims the workspace and keeps the agent's key, the key keeps working in the claimed workspace with full access, every scope a key can hold by wildcard, so routing writes such as set_offer_settings work for it. Scopes granted only by name (workspace:claim, team:admin) are not included, and an agent's own key still cannot change a buyer spend policy. Both are being switched on gradually; until then register_agent and use_api_key are not listed and a kept key holds the sandbox scopes.
Card payments in the top-up (MPP)
An agent whose wallet speaks MPP, the Machine Payments Protocol, can have its person pay a balance top-up by card without leaving the conversation. The 402 fromPOST /api/billing/topup offers the card next to the x402 terms, for the same amount in US cents, and the balance is credited one USDC for each US dollar, with no bonus. Every later call draws on it. A card cannot pay a single call: the smallest card charge is 0.50 USD.
- Send the top-up with no payment. Read the
WWW-Authenticate: Paymentchallenge withmethod="stripe". It is valid for 5 minutes, for this workspace and this amount only. - Your wallet asks your person to approve the card payment and gets a Shared Payment Token (
spt_...). - Send the same request again with
Payment-Authorization: Payment <credential>. The answer is 201 withPayment-Receiptandpayer: "person_card".
A card payment is charged once and credited once. If the answer is a 503 (mpp_charge_unconfirmed ormpp_credit_pending), send the same request with the same credential: it is never charged twice, and a credential already credited answers mpp_already_credited.
A quote can also say who pays: context.payer on POST /api/compute/price (or thepayer argument of compute_price) is agent_wallet, person_card orcompany_invoice. It reaches buyer-aware pricing as metadata.payer, and the answer echoes it.
Pay each call in stablecoin on Tempo (MPP)
A wallet that speaks MPP can pay a single call, at the same per-call price as x402, in a stablecoin on Tempo. The 402 from a pay-per-call route such as POST /api/compute/price carries a second challenge, WWW-Authenticate: Payment with method="tempo", next to the x402 terms. Its request names the amount (6 decimals), the token, the recipient and the chain, and the body repeats them under mpp.tempo.
- Sign a Tempo transaction that makes one call:
transferortransferWithMemoof exactly the amount to the recipient, on the named token. Pay its network fee yourself; fee sponsorship is not offered. - Send the same request again with
Payment-Authorization: Payment <credential>, whose payload is{ type: "transaction", signature: "0x76..." }. Do not broadcast it yourself. - The transfer is checked, the call is computed, and only then is the transfer broadcast. The answer carries
Payment-Receipt, whosereferenceis the transaction hash.
A call that fails, or that is refused before the broadcast, sends nothing to the network, and the same signed transfer may be sent again. A transfer pays one call only: sent again after it paid, it answers invalid-challenge. If the network gives no clear answer, the call answers 503 payment_settlement_unknown with the transaction hash; do not sign a new transfer for that call.
What needs a claim
Rosetta, UCP checkout and quotes, the commerce control plane, usage reads and outcomes, and receipts need a claimed workspace: a self-registered sandbox key gets 403 sandbox_restricted (requires: claimed_workspace) on each of them until a person claims the workspace.
The refusal names what is missing: requires: "claimed_workspace", a hint, and the claim step in next. The claim must send keep_agent_key: true for the same key to keep working afterwards; without it the claim revokes the agent and its key.
- Rosetta schema translation: 7 operations, starting with
POST /api/rosetta/ingest - UCP checkout sessions and quotes: 7 operations, starting with
POST /api/ucp/checkout-sessions - Commerce control plane: 23 operations, starting with
GET /api/commerce/connectors - Usage reads and outcomes: 7 operations, starting with
GET /api/usage - Receipts: 2 operations, starting with
GET /api/receipts
# A sandbox key on a feature that needs a claimed workspace
HTTP/1.1 403
{
"error": "A sandbox credential cannot call this operation.",
"code": "sandbox_restricted",
"requires": "claimed_workspace",
"hint": "This operation needs a claimed workspace. ...",
"next": [{ "id": "claim", "method": "POST", "path": "/api/agents/claim", "description": "..." }]
}When a claim itself is refused, the body carries a code: claim_link_invalid, claim_link_expired, claim_cap_reached, claiming_workspace_ineligible, claim_rate_limited and others. An unexpected server error answers 500 claim_failed with a reference; nothing was changed, so retry, and quote the reference to support@last-price.ai if it keeps failing.
Partner workspaces
A partner sets up businesses for other people, runs them, and hands each one over. It opens a workspace for each business from Partner Workspaces in the sidebar or with POST /api/partner/workspaces, and gets back two things, each shown once: a management key for itself, and a claim link for the owner.
- A real workspace from the start. It is an ordinary production workspace, not a sandbox, so it can take offers, orders and customers at once. The management key has full access there and does not expire.
- The partner's own allowance. Each workspace spends one of the partner's daily allowance (50 by default), never the limit of 5 a day an address may self-register. Spent, the answer is 429
partner_allowance_spentwith the limit;GET /api/partnershows what is left today. - Handing it over. The owner opens the claim link (it works once, for 90 days), signs in, and the workspace becomes theirs. The claim page tells them who set it up and that the partner keeps running it unless they untick the box, which revokes the management key. They can revoke it later under Settings, API keys.
- Every business in one list.
GET /api/partner/workspacesand the list under the form show each workspace the partner opened: whether the owner has claimed it, and whether the partner still runs it. While it does, the list shows the last 30 days: orders and takings per currency, offers made and accepted, products and the last price change. Once the owner revokes the management key, the numbers are theirs and the list shows none. Filter withstatus(waiting,claimed,managing,released), search withq, and page withbeforeset to the last answer'snext_before. - Becoming a partner. Last Price staff set the allowance for a workspace. Email support@last-price.ai with what you build and for whom.
curl -X POST https://api.last-price.ai/api/partner/workspaces \
-H "x-api-key: YOUR_PARTNER_KEY" \
-H "Content-Type: application/json" \
-d '{ "name": "Ade Rides", "intended_use": "Airport runs around Lagos, booked on WhatsApp." }'
// 201
{ "workspace": { "id": "…", "name": "Ade Rides", "claimed": false },
"api_key": { "key": "lp_…", "header": "x-api-key", "scopes": ["*"], "expires_at": null },
"claim": { "claim_url": "https://app.last-price.ai/claim#token=lpc_…", "expires_at": "2027-01-20T22:00:00Z" } }The key needs the partner:workspaces scope, or full access. Over MCP the same three calls are get_partner_allowance, create_partner_workspace and list_partner_workspaces.
How an agent pays
The steps a person running an agent follows so it can pay for itself, from no wallet at all to a funded one.
- Start free. The keyless demo and a self-registered sandbox key need no wallet and no account (see Pay or Authenticate). If you would rather not use crypto at all, sign up on the free plan and give the agent an API key.
- Give the agent a wallet of its own. Create a new wallet used only by this agent, never a personal one, so what it can spend is what you put in it.
- Fund it with a few USDC on Base. A few dollars covers hundreds of 0.01 calls, or a day pass and more. No gas token is needed: x402 payments are signed authorizations and the facilitator pays the gas.
- Keep the key in the agent's secrets. Put the wallet's private key in the agent's environment or secret store, never in a prompt, a message, a file you share, or a log. Last Price never needs it.
- Pay on the 402. Call
POST /api/compute/pricewith no credential; the 402 names the amount, network, asset and receiving address inaccepts. An x402 client signs a payment for exactly those terms and sends it asPAYMENT-SIGNATURE(v2) orX-PAYMENT(v1) on the same request. - Settle one 0.01 call first. A 200 carries a settlement header with the transaction, which you can look up on a Base block explorer. Then use it freely, or buy a day pass or a prepaid balance with the sandbox key. A refused payment moves no money.
Found in the x402 Bazaar
The x402 Bazaar is the index agents with a wallet search for paid endpoints. The 402 from POST /api/compute/price describes the call for it, so an agent can find Last Price and pay for a price without an account.
extensions.bazaarin the 402 body and in the v2PAYMENT-REQUIREDheader:infoholds the method (POST, a JSON body), an example body and an example answer, andschemais the JSON Schema that validates them.- The v2
resourcealso names the service (serviceNameLast Price) and itstags; v1 clients find the same description inaccepts[0].outputSchema. - Nothing about the payment changes: the amount, network, asset and receiving address in
acceptsare the same, and a client that ignores the extension pays exactly as before.
"extensions": {
"bazaar": {
"info": {
"input": { "type": "http", "method": "POST", "bodyType": "json",
"body": { "context": { "product_id": "pro-plan", "product_type": "saas", "currency": "USD", "current_price": 49 } } },
"output": { "type": "json", "example": { "computed_price": 52.5, "currency": "USD", "function_name": "lastprice/cost-plus" } }
},
"schema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "...": "..." }
}
}Pay with signed vouchers
An agent whose business set it a spending limit can pay each call with a signed voucher instead of a transfer: a promise to pay within that limit. The answer comes at once, with nothing settled on chain per call, and Last Price redeems the vouchers with their issuer in one batch every hour, for the calls it delivered only. This is how Mastercard Agent Pay for Machines and the x402 deferred scheme pay.
- The 402 from
POST /api/compute/pricelists a second entry inacceptswithscheme: "deferred", the same price, network, asset and receiving address, and inextrathe issuer and the EIP-712 domain and types to sign. - Pick 32 random bytes as the series'
id. For each call sign the nextVoucher:nonceone higher,resourceset to theresourcethe 402 offered (a voucher pays for that route only), andvalueAggregatecovering every call so far plus this one, never above yourlimit. A voucher must stay valid (expiry) for at least two hours. - Send it in
X-PAYMENT(v1) orPAYMENT-SIGNATURE(v2) withscheme: "deferred". The first voucher of a series, and a new limit, are confirmed with the issuer once; after that each call is checked locally. - The 200 carries
X-PAYMENT-RESPONSEwithscheme: "deferred", your voucher id and nonce, and no transaction. A call that fails is never charged: sign the next voucher to retry.
- A voucher buys one call: a nonce that is not above the newest one is refused as
payment_replayed. - Each buyer's vouchers not yet redeemed are capped (1.00 USDC by default), and so are all buyers' together; past either, pay the call with the
exactscheme or wait for the next redemption. - See where a series stands, what you promised, what was delivered, redeemed and still owed, with
GET /api/public/x402-vouchers?voucher_id=...&buyer=...or the MCP toolget_x402_voucher_status. No credential needed.
{
"x402Version": 1,
"scheme": "deferred",
"network": "base",
"payload": {
"signature": "0x...",
"voucher": {
"id": "0x5f1c...e9a2", "buyer": "0xBuyer...", "seller": "0xLastPrice...",
"asset": "0xUSDC...", "issuer": "your-issuer",
"resource": "https://last-price.ai/api/compute/price",
"valueAggregate": "30000", "limit": "1000000", "nonce": "2",
"timestamp": "1792700000", "expiry": "1792786400"
}
}
}Found in an agent directory
Rolling out. Each directory that lists Last Price (the MCP Registry, the x402 Bazaar, x402scan, Glama, PulseMCP, Smithery and others) gives our address its own via tag, such as https://api.last-price.ai/api/mcp/rpc?via=glama. Call the address as the listing gives it and every call says where you found us.
- Keep the tag on the URL, or send it as the
x-lastprice-viaheader. Unknown tags are dropped. - The tag is only a label: it never changes an answer, a limit or a price, and it is not a credential.
- We read each of our listings once a day and call it the way it is listed, so an entry that has gone out of date is fixed quickly.
curl -X POST "https://api.last-price.ai/api/mcp/rpc?via=mcp-registry" \
-H "content-type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"compute_price","arguments":{"current_price":49,"currency":"USD"}}}'Agent skill
The last-price Agent Skill teaches any agent that loads skills to price something, check that a price is fair, and check a purchase against its owner's spend policy before paying, over MCP or x402. It is a SKILL.md and one script with no dependencies (Node.js 18 or later).
- Index:
https://last-price.ai/.well-known/agent-skills/index.json(Agent Skills discovery 0.2.0, with a SHA-256 digest for each download). - Whole skill:
last-price.tar.gz; single file:last-price/SKILL.md. - Pricing and price checks need no key. Spend checks need your
lp_key inLASTPRICE_API_KEY. - The same index lists a skill for each job, from the public last-price-ai/skills pack:
last-price-overviewto start, then compute, functions and routing, experiments, the learning loop, Rosetta, marketplace, webhooks, agents, commerce, workspace admin, order to cash, usage and billing, UCP, offers, auth and MCP. Each one downloads the same way, as<name>.tar.gzor<name>/SKILL.md. /.well-known/agents.jsonnames the pack indiscovery.skills_repositoryand the index indiscovery.agent_skills.
curl -sO https://last-price.ai/.well-known/agent-skills/last-price.tar.gz
tar xzf last-price.tar.gz -C ~/.claude/skills
node ~/.claude/skills/last-price/scripts/lastprice.mjs verify --price 59 --currency USDTool annotations (MCP)
Every tool in tools/list carries MCP annotations: a title, and hints your host uses to decide when to ask you before a call.
readOnlyHint: true only when the call changes nothing. A priced call such ascompute_priceis not read-only, because it records a metered usage event and is charged.destructiveHint: true when the call can overwrite, delete or irreversibly decide something, such asset_andupdate_tools, deletes, approvals andexecute_commerce_proposals.idempotentHint: true when repeating the same call changes nothing more.openWorldHint: true when the call reaches outside Last Price, such as a wallet payment, an email, a card checkout, your store or an endpoint you registered.
The local stdio servers carry them too, and so does every profile, the lean one included.
A listing can ask for a narrower set of tools: /api/mcp/rpc?profile=directory offers the pricing and workspace tools without the wallet payment, balance top-up, buyer spend and agent feed tools (rolling out).
By default /api/mcp/rpc lists a short list: the six tools that reach a price, plus search_tools, which finds any other tool by task with its full input schema, and call_tool, which runs one. Every tool still answers when called by name. Add ?profile=full to list every tool (over 300, about 135,000 tokens); the local stdio server takes LASTPRICE_TOOL_PROFILE=full.
Send only top-level argument names declared by the selected tool and profile. Unknown names are refused before execution; correct the named field and retry. Documented metadata objects remain open. For a keyless compute_price with both current_price and unit_cost, the demo keeps the declared cost and target margin for its existing guardrails while retaining its configured pricing function. This does not enable marketplace routing.
Writing your own MCP client? /api/mcp/rpc?profile=starter lists only the six tools that reach a price (pricing_conversation, compute_price, verify_price, report_outcome, list_functions, get_receipt), and you do not need tools/list at all: after initialize, call compute_price with what the work cost you. With no key it prices on the public demo with lastprice/cost-plus.
{"jsonrpc":"2.0","id":2,"method":"tools/call",
"params":{"name":"compute_price","arguments":{"unit_cost":0.47,"currency":"USD"}}}{ "name": "delete_function",
"annotations": { "title": "Delete function", "readOnlyHint": false,
"destructiveHint": true, "idempotentHint": true, "openWorldHint": false } }What kind of price it is
A price is only useful once you know who stands behind it and whether money moved. Every price the API returns carries a kind, and the vocabulary at /.well-known/lastprice-vocabulary.json defines the nine kinds under lp:price-kind, each with who speaks it and how binding it is.
computed: what a pricing function says the price should be, with a confidence.compute_priceand the photo price check answer this. An estimate, advice rather than a commitment.quoted: a computed price Last Price has signed and honours until it expires. Thesigned_quoteon a priced answer carries it.list,floor,ceiling: a seller's published price, the least a seller takes, the most a buyer pays. Proposals and constraints, never evidence that anyone paid.offer,agreed,settled: a round in a negotiation, the amount both sides accepted, the amount actually paid. Only a settled price is evidence of value by itself.observed: an amount a third party saw in a market, listed or sold. Product price lookups keep listings and sales apart.
The shape every price shares is published as a JSON Schema at /.well-known/price-statement.schema.json: a computed price must carry a confidence, a quoted price an expiry and a settled price a settlement time. The schema holds what Last Price returns; a price you read from elsewhere with a field missing is not wrong, that field is unknown.
Agent and usage reads (MCP)
Hosted tool calls accept optional params._meta.traceparent and params._meta.reason. A valid message trace context takes precedence over the HTTP header. The result's _meta["com.lastprice/trace"].trace_idlinks the call to your trace. Reasons are caller-stated, capped at 512 characters and pattern-redacted; do not include secrets or personal details. For metered pricing calls, list_usage_events and Usage show the reason and trace id in your own workspace ledger. Read-only tools add no priced event. Span costs use recorded USD; export and retention follow the deployment's existing tracing configuration.
Nine read-only tools let an agent check itself and its spend without a dashboard. The first six need a Last Price credential; the last three are public and need none.
get_agent_capabilities: an agent's effective scopes, pending approvals, rate limit and idempotency rules, so a planned action is checked before it is tried. Passagent_id; an agent's own credential reads only its own agent.get_agent_value_receipt: an agent's measured Value Receipt for a period (start_date,end_date; 30 days by default, at most 366). See Value Receipts and ROI.get_cut_advisor_settings: whether the cut advisor is released for the workspace, its defaults and the limitssimulate_agent_cutaccepts.get_usage_breakdown: usage grouped by pricing function over a period.get_llm_usageandlist_llm_usage_events: what model calls cost the workspace, in total and call by call, with the split between your own provider key and the platform's.get_public_leaderboard(windowof7d,30d,90dorall),list_verification_strategiesandverify_webhook_signature: public, limited per address. Use a test secret withverify_webhook_signature, because the secret travels in the request.
get_agent_capabilities { "agent_id": "AGENT_ID" }
get_agent_value_receipt { "agent_id": "AGENT_ID", "start_date": "2026-09-01T00:00:00Z" }
list_llm_usage_events { "operation": "agent_generation", "limit": 20 }Function health, review and costs (MCP)
Seven tools cover what the dashboard shows for your own external functions and for the costs you record. They need a Last Price credential, and the three that act need a claimed workspace.
get_function_healthandrun_function_health_probe: the recent endpoint probes of a function of yours, and one probe now. A probe is one sample call to your endpoint and feeds the router's circuit breaker. Only the owner can use them.get_function_reviewandrun_function_review: the latest marketplace review report, and a dry-run review now. The dry run makes one sample call, stores the report on the listing and never changes whether the listing is public.list_costsandget_cost_analytics: the costs recorded in the workspace, and their totals by day, week, month, agent, customer or type.record_cost: record a vendor or infrastructure cost (amount, and optionallycurrency,cost_type,agent_id,customer_id,metadata). Recorded costs count in the Value Receipt.
get_function_health { "function_id": "FUNCTION_ID" }
run_function_review { "function_id": "FUNCTION_ID" }
record_cost { "amount": 12.5, "currency": "USD", "cost_type": "vendor", "agent_id": "AGENT_ID" }Marketplace, disputes and readiness (MCP)
Twelve tools cover the marketplace, payment disputes and two checks. Two are public and need no credential; the rest need a Last Price credential, and the ones that change something or call a model need a claimed workspace.
list_marketplace_listings(public, limited per address) andlist_my_marketplace_listings: the marketplace, and your own listings, public or not. Page withlimitandoffset.create_marketplace_listing,update_marketplace_listinganddelete_marketplace_listing: list one of your functions, changeis_public,commission_rateormin_payout_threshold, or take it down. A listing made public is reviewed first; a function that fails the review stays private and the refusal carries the report. Where payouts go is set by a person in the dashboard, not by these tools.get_marketplace_earnings: the payout ledger for your listed functions. Needs billing read scope.list_disputes,get_dispute,create_disputeandupdate_dispute: payment disputes with the statusopen,under_review,resolvedorrejected. Opening one emails the workspace owners and admins and sendsdispute.openedto subscribed endpoints.check_agent_readiness(public, limited per address): the free agent-ready check on a store address. It answers 404 while the check is not released.estimate_task_cost: what a task would cost to do by people across countries. It makes a model call, billed to your own provider key when you set one.
list_disputes { "status": "open" }
update_dispute { "dispute_id": "DISPUTE_ID", "status": "under_review" }
create_marketplace_listing { "function_id": "FUNCTION_ID", "is_public": true }Customers and contacts (MCP)
Twelve tools let an agent keep the customer records the dashboard shows. They need a Last Price credential, and the ones that change something need a claimed workspace.
list_customers,get_customerandget_customer_by_external_id: read customers, by id or by the id your own system gives them.create_customer,update_customeranddelete_customer: add one (name, and optionallyemail,external_id,metadata), change its name, email or metadata, or remove it.list_contacts,get_contactandget_contact_by_external_id: read contacts, all of them or one customer's withcustomer_id. An external id is only unique within one customer, so the lookup names the customer.create_contact,update_contactanddelete_contact: add a contact to a customer, change it (nullclears the phone, address or external id) or remove it. A contact cannot be moved to another customer.
create_customer { "name": "Acme Ltd", "email": "billing@acme.test", "external_id": "acme-1" }
create_contact { "customer_id": "CUSTOMER_ID", "name": "Jo Smith", "email": "jo@acme.test", "address": { "city": "Leeds", "postal_code": "LS1 4AP" } }
get_contact_by_external_id { "external_id": "jo-1", "customer_id": "CUSTOMER_ID" }Orders (MCP)
Eight tools let an agent keep the orders the dashboard shows. They need a Last Price credential, and the ones that change something need a claimed workspace.
list_orders,get_orderandlist_order_lines: read orders, all of them or one customer's withcustomer_id, and the line items on one.create_orderandupdate_order: add an order for a customer, or change its status, total, currency, metadata or billing contact (nullclears it). The billing contact has to be a contact of that customer, and an order that has left draft cannot return to it.activate_order: move a draft order to active.add_order_line: add a line item withdescriptionandunit_price, and optionallyquantity.delete_order: remove a draft or cancelled order and its lines; cancel an order first to delete it.
create_order { "customer_id": "CUSTOMER_ID", "currency": "EUR" }
add_order_line { "order_id": "ORDER_ID", "description": "Setup", "unit_price": 49, "quantity": 2 }
activate_order { "order_id": "ORDER_ID" }Credits, invoices and payments (MCP)
Nine tools let an agent change the billing records the dashboard shows. Reading a credit needs a Last Price credential with billing read scope; the rest need a claimed workspace and billing write scope.
get_credit,create_creditanddelete_credit: read, grant (customer_idandamount, with an optionalexpires_at) or delete a prepaid credit bundle.create_invoice,update_invoiceanddelete_invoice: add an invoice, change its status, amount, currency,due_dateor metadata, or remove it. Creating one does not email anyone.send_invoice: email the invoice to the customer, or toto, and mark it sent. It sends a real email and answers 404 once the invoice is already sent.create_paymentandrefund_payment: record a payment against a customer or invoice, or mark one refunded in whole or part. Both record the change in Last Price; neither moves money.
create_invoice { "customer_id": "CUSTOMER_ID", "amount": 120, "currency": "EUR", "due_date": "2026-11-01T00:00:00Z" }
send_invoice { "invoice_id": "INVOICE_ID" }
refund_payment { "payment_id": "PAYMENT_ID", "amount": 20, "reason": "duplicate charge" }Universal Commerce Protocol (MCP)
Eight tools let an agent shop the way a UCP agent does. The profile needs no credential; the rest need a Last Price credential with price compute scope.
Checkout permission. Starting, changing, canceling or completing a checkout is buying, so it has its own tick box on an API key: commerce:checkout. Quotes and reading sessions stay on price:compute. Where the permission is enforced for the workspace, a key that can only compute prices is refused with a 403 insufficient_scope naming commerce:checkout; until then its checkout answers carry a Warning: 299 header saying so. Keys with no scopes, with * or with commerce:* already hold it. To move a key over, create a new one in Settings, API keys, with commerce:checkout ticked, and retire the old one.
Lasting sessions. Where lasting sessions are switched on for the workspace, a checkout session is kept for 24 hours (expires_at) and any later call sees it; past that it reads as canceled with a session_expired message, and changing it answers 409. Two creates with one Idempotency-Key make one session, and the second answers it with Idempotent-Replayed: true. A line with no unit_price is priced from your catalog by store id, SKU or GTIN; one the catalog does not know gets a price_unknown message and the session stays incomplete. Totals are in the currency's minor units, and a body with a fractional quantity, a negative price, mixed currencies or more than 500 lines is a 400 naming the field.
get_ucp_profile: read the business profile a UCP agent discovers first.get_ucp_quote: price acartofline_itemsthrough the pricing network, at a funnelstage.create_ucp_checkout,list_ucp_checkouts,get_ucp_checkoutandupdate_ucp_checkout: open, list, read and change checkout sessions. A completed or canceled session cannot be changed.- Pass
idempotency_keytocreate_ucp_checkoutto retry safely. The same key with the same body returns the first session instead of opening a second one; the same key with a different body is refused with a 409. cancel_ucp_checkoutandcomplete_ucp_checkout: cancel a session, or try to complete it. Payment processing is not configured yet, so completing an open session answers 501 until a payment provider is set up.- A quote line's
unit_pricemay be a number or{ amount, currency }. A quantity that is not a whole number from 1, or a price that is not above 0, is a 400validation_failednaming the line.tenant_idis optional: a quote prices your own workspace. - Every
get_ucp_quoteis recorded in your usage, like a compute call, so it shows inlist_usage_eventsand counts toward learned demand. - Pass
agentid_token(an AgentID ID token issued for Last Price) toget_ucp_quoteorcreate_ucp_checkoutto buy as a verified agent. Over HTTP it is theAgentID-Tokenheader; your Last Price credential stays inAuthorizationorx-api-key.
Verified buying agents. Where verified buying agents are on for the workspace (off by default), Last Price checks the token against AgentID's published keys: it must be signed with ES256 by https://auth.agentid.com, issued for Last Price, unexpired, and for an agent. A valid token records the quote's buyer_agent as source: "agentid", verified: true, with the agent's AgentID subject and, when its registration shares it, the owner it acts for; the answer carries the same buyer_agent. A token that does not verify is refused with a 401 whose error is invalid_agent_identity and whose reason says why (expired, wrong_audience, bad_signature and so on), so an agent never believes it bought verified when it did not. Leave the token out to buy unverified. Sellers can list only verified agents' calls with GET /api/usage/events?buyer_agent=verified or list_usage_events with buyer_agent: "verified".
Signed agent requests. An agent that signs its HTTP requests with Web Bot Auth (HTTP Message Signatures, RFC 9421), the way card networks and CDNs recognise trusted agents, is verified without a token. Send Signature-Agent (the https origin that publishes your Ed25519 keys at /.well-known/http-message-signatures-directory), Signature-Input and Signature on POST /api/ucp/quote or POST /api/ucp/checkout-sessions. Last Price reads each signature tagged web-bot-auth, which must cover @authority and signature-agent, use ed25519, and be current (at most an hour from created to expires). It fetches your key directory (cached ten minutes), finds the key whose JWK thumbprint or kid is the keyid, and checks the signature. A signature that verifies records the quote's buyer_agent as source: "web_bot_auth", verified: true, named by your directory's host, with the keyid as subject; it counts for buyer_agent=verified too. One that does not verify refuses nothing: the agent is recorded unverified, as signature_agent. An AgentID token, when sent, is checked first. Signed requests are an HTTP feature, so the MCP tools use agentid_token instead.
Signature-Agent: "https://agent.example.com"
Signature-Input: sig1=("@authority" "signature-agent");created=1793016000;expires=1793016300;keyid="poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U";alg="ed25519";tag="web-bot-auth"
Signature: sig1=:<base64 Ed25519 signature over the RFC 9421 signature base>:get_ucp_quote { "cart": { "line_items": [{ "product_id": "sku-1", "quantity": 2 }] }, "stage": "cart" }
create_ucp_checkout { "line_items": [{ "product_id": "sku-1", "quantity": 2 }], "buyer": { "email": "jo@acme.test" } }
create_ucp_checkout { "line_items": [{ "product_id": "sku-1", "quantity": 2 }], "idempotency_key": "order-77" }
cancel_ucp_checkout { "checkout_id": "CHECKOUT_ID" }
get_ucp_quote { "cart": { "line_items": [{ "product_id": "sku-1", "quantity": 1 }] }, "agentid_token": "eyJhbGciOiJFUzI1NiIs..." }Bandit, guardrail reset and demo apps (MCP)
Three more tools close gaps between the dashboard and MCP. They need a Last Price credential, and the two that change something need a claimed workspace.
set_experiment_bandit: switch bandit allocation on or off for an experiment withbandit_enabled, and set the floors withmin_weight_pctandcontrol_min_weight_pct. Read the result withget_experiment_stopping. It answers "not enabled" where sequential testing is off for your workspace.delete_price_guardrails: remove the saved guardrails so the defaults apply again. Read them first withget_price_guardrails.list_demo_apps: the demo apps Last Price ships, with the experiment each runs.
set_experiment_bandit { "experiment_key": "q2_pricing", "bandit_enabled": true, "min_weight_pct": 10 }
delete_price_guardrails {}Personal agent protocol file
The Personal Agent Protocol (draft 0.1) is how a personal agent, such as a shopping assistant acting for one person, learns what a company lets it do. The company publishes one file at https://your-domain/.well-known/poppy.json. Last Price writes that file for you: it names Last Price as the sign-in issuer and offers your prices, quotes, offers and checkout through the Last Price API. This is being switched on workspace by workspace; until it is on for yours, reading it says released: false and saving answers 404.
- Save your name and the domain that will serve the file with
PUT /api/agent-protocol(orset_agent_protocol). The answer hasfileandpublish_at. - Publish
fileexactly as given atpublish_at, over HTTPS, with no redirect. You may add fields of your own. - Call
POST /api/agent-protocol/verify(orverify_agent_protocol). Last Price fetches the file and checks the version, the domain, the issuer and your workspace's verification value. A pass verifies the domain for your workspace only; a failure says what to fix. Check again after any change: a file taken down stops counting.
Reading needs the routing read scope; saving and checking need routing write and a claimed workspace. A new domain gets a new verification value, so publish the new file before checking it.
curl -X PUT https://api.last-price.ai/api/agent-protocol \
-H "x-api-key: YOUR_API_KEY" -H "Content-Type: application/json" \
-d '{"organization_name": "Acme Outdoor", "domain": "acme-outdoor.com"}'
curl -X POST https://api.last-price.ai/api/agent-protocol/verify -H "x-api-key: YOUR_API_KEY"Payments over MCP
An agent can run its whole payment loop from its MCP session. The server holds no keys: the agent signs the x402 payment with its own wallet and passes it in. Every tool needs the price:compute scope, and a sandbox key may call them.
list_day_passesreads each day pass, newest first, with the calls left on it, the total left and what a new pass costs (GET /api/agents/allowance).get_wallet_balancereads the USDC a wallet holds on the payment network, from the chain, and how many paid calls and day passes it covers (GET /api/agents/wallet). Check it before signing.buy_day_passandtop_up_balance(with anamountin USDC) buy a pass or fund the prepaid balance. Called withoutpaymentthey spend nothing and return the 402 requirements to sign; call again withpaymentset to the signed base64 payment, the value of theX-PAYMENTorPAYMENT-SIGNATUREheader, which the tool sends in the header its version names.compute_pricetakes the samepaymentargument to pay for one call with no key and no balance.
A day pass is bought only by a self-registered agent workspace; any other workspace gets a 409. A refused or failed payment is an error that names why, and the 402 says whether the same payment may be presented again.
Child agent workspaces
An agent working in a workspace it registered for itself can create agent workspaces under its own, one per sub-agent or separate piece of work, with POST /api/agents/workspaces or the MCP tool create_child_workspace. Each child is registered exactly as a self-registered workspace is: a sandbox on the Agent Starter plan with its own agent, a key returned once, and its own one-time claim link. It sits under the workspace that created it. GET /api/agents/workspaces (MCP list_child_workspaces) lists the agent workspaces under yours and how many more you may create.
- Who can. Only an agent's key or token of a workspace an agent registered, claimed or not. A workspace a person signed up for answers 409
parent_ineligible; a key not bound to an agent answers 403agent_credential_required. - Limits. At most 10 children per workspace by default (409
child_cap_reached), at most 10 workspaces deep, and every child counts against the same daily registration budgets asPOST /api/agents/register. - Claiming. When a person claims the parent, its unclaimed children come with it and keep their place under it: the claim page lists them under "These agent workspaces come with it", and the claim's dry run returns them in
following_workspaces. A child can also be claimed on its own with its link, even under a claimed parent; it stays under its parent. A workspace a person already owns, and anything below it, never moves with someone else's claim. - Where to see them. Settings, API keys lists the agent workspaces under the workspace you are in.
Being switched on workspace by workspace: until then both operations answer 404 not_released.
curl -X POST https://api.last-price.ai/api/agents/workspaces \
-H "x-api-key: $LASTPRICE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name": "research-helper", "intended_use": "Compare supplier prices"}'Buyer spend policy
A spend policy is what your buyer agents may pay: the most per purchase, a daily cap, when a person approves first, and which sellers and categories. Any buyer agent asks before it pays, whatever wallet or checkout it uses, and gets allow, deny or ask. An allowed purchase reserves its amount against the daily cap at once, so two purchases racing for the last of a budget cannot both go through. An agent with no policy may not spend. Set the workspace policy on the Spend policy page.
Set a policy
PUT /api/spend-policy saves one policy whole. Leave out agent_id (or send null) for the workspace default, which covers every agent without its own. Only a workspace-wide key or the dashboard can save a policy: an agent's own credential reads the policies that bind it but never changes them. Needs pcn:routing:write.
- agent_iduuid | null
- The agent this policy binds; null for the workspace default
- currencystring
- ISO 4217, default USD; a check in another currency is denied
- max_per_purchasenumber | null
- The most one purchase may cost
- daily_capnumber | null
- The most reserved plus spent in one UTC day
- ask_abovenumber | null
- Above this a person approves first; below max_per_purchase
- allowed_sellersstring[] | null
- Only these sellers; null for any
- blocked_sellersstring[]
- Never these sellers
- allowed_categoriesstring[] | null
- Only these categories; null for any
- on_too_highoff | ask | deny
- What a verify_price verdict of too_high does
- hold_secondsinteger
- How long a reservation shows as held (30 to 86400, default 900)
curl -X PUT https://api.last-price.ai/api/spend-policy \
-H "x-api-key: YOUR_WORKSPACE_KEY" \
-H "Content-Type: application/json" \
-d '{
"currency": "USD",
"max_per_purchase": 50,
"daily_cap": 100,
"ask_above": 20,
"blocked_sellers": ["scam.example"]
}'Sign in again to raise limits
Some decisions move money: giving agents more room in a spend policy (a higher or removed cap or budget, more sellers, categories or agents, a weaker action), deleting a policy, approving a purchase or a payout, changing the wallet or card account invoice payments go to, opening payout setup, linking a wallet to your account, creating an API key (an agent's too) that could do any of these, and inviting someone or changing a role to anything but viewer. For these, a person must have signed in within the last 15 minutes with a password, Google, a wallet or an authenticator app. A sign-in link or code sent to your email does not count, so an agent that can read your inbox cannot raise its own limit or approve its own purchase. An authenticator app or passkey you added in the last 24 hours does not count yet.
Otherwise the API answers 403 reauth_required, withsign_in_methods, max_age_minutes andsign_in_url. Sign in again and repeat the request. Lowering a limit, rejecting a request and saving a policy that only tightens work from any session. API keys are not asked; a connected assistant acting on your consent is refused, so you make these decisions in the dashboard or the app. The audit log records the sign-in each decision was made under (sign_in_method,signed_in_at).
Check a purchase
Ask before paying with POST /api/spend-policy/check (MCP tool check_purchase). Needs price:compute. A deny carries a stable reason_code such as over_daily_cap or no_policy. An ask opens an approval that only a person decides; once it is approved, send the same check again to reserve.
curl -X POST https://api.last-price.ai/api/spend-policy/check \
-H "x-api-key: YOUR_AGENT_KEY" \
-H "Content-Type: application/json" \
-d '{ "seller": "shop.example", "amount": 12.5, "currency": "USD", "item": "candle" }'
# Response
{
"decision": "allow",
"reason_code": "within_policy",
"reservation": {
"id": "RESERVATION_ID",
"amount": 12.5,
"status": "reserved",
"consume": "POST /api/spend-policy/reservations/RESERVATION_ID/consume",
"release": "POST /api/spend-policy/reservations/RESERVATION_ID/release"
},
"policy": { "daily_cap": 100, "spent_today": 12.5, "remaining_today": 87.5 }
}x402 Market Price Band
What do paid x402 services charge per call for this kind of call? Once a day Last Price reads the public x402 discovery catalogs that facilitators publish (Coinbase's and PayAI's) and the MPP services directory (mpp.dev), keeps every listing priced in USDC on a mainnet, and computes a band per category (inference, search, scraping, markets, media, social, weather, other) plus one over every category: the 10th percentile, median and 90th percentile list price per call, how many services stand behind it (n) and the day it describes (as_of). Each service counts once, as the median of its listings, so a seller listing a thousand endpoints moves the band no more than a seller listing one.
List prices only. The band says what sellers ask, never what anyone pays, and it is never evidence of demand: some x402 volume is sellers paying themselves.
It is used in three places. verify_price weighs it as x402_market evidence (the median as reference, p10 to p90 as the band, at most half weight, half that for the overall band; a band with fewer than five services or older than a week is shown with zero weight). check_purchase shows it in price_verdict.market_band whenever the price is judged, with where the price sits (below, inside or above). And GET /api/public/x402-price-index (MCP get_x402_price_index) publishes it without a key. Name the category with category on the check, or metadata.x402_category on verify_price; otherwise it is read from the item. Where it is off, the index answers 404 not_released and verdicts are unchanged.
curl "https://api.last-price.ai/api/public/x402-price-index?category=inference&days=7"
# Response
{
"as_of": "2026-10-13",
"currency": "USD",
"unit": "price per call",
"caveat": "List prices from public x402 and MPP discovery catalogs only. Not evidence of demand: ...",
"overall": { "category": "all", "p10": 0.001, "median": 0.01, "p90": 0.1, "n": 212, "usable": true },
"bands": [{ "category": "inference", "p10": 0.001, "median": 0.003, "p90": 0.02, "n": 48, "usable": true }],
"history": [{ "as_of": "2026-10-13", "median": 0.003, "n": 48 }, ...],
"sources": [{ "catalog_url": "https://api.cdp.coinbase.com/platform/v2/x402/discovery/resources", "status": "ok" }]
}
# On check_purchase, when the price is judged
"price_verdict": {
"verdict": "too_high",
"market_band": { "category": "inference", "p10": 0.001, "median": 0.003, "p90": 0.02,
"n": 48, "as_of": "2026-10-13", "position": "above", "caveat": "..." }
}The buyer's approved intent
A spend policy is your standing rule. An intent is narrower: what the buyer approved for this purchase. American Express Intent Intelligence records the merchant the buyer chose, the most they will spend and other conditions, and issues an Intent ID with a Proof of Intent Token; an AP2 intent mandate carries the same terms. Send it as intent on check_purchase or open_spend_session, with source set to amex_intent, ap2_intent_mandate, mastercard_intent or declared.
Mastercard Agent Pay intents. Send sourcemastercard_intent with the intent's intentId asintent_id, its order total as max_amount andcurrency, the merchant the buyer chose as merchant, and the intent's status in conditions.status (other fields, such as the merchant identifier, can go inconditions too). An intent whose status is anything but ACTIVE is denied with intent_not_active; the other comparisons below apply as for every intent.
The purchase is compared with the intent before the policy is asked, and denied when it names another seller (intent_seller_mismatch), costs more than max_amount (intent_over_max), is in another currency (intent_currency_mismatch; nothing is converted) or comes after expires_at (intent_expired). The maximum covers every purchase under the same intent_id together, so two purchases cannot each fit an intent they pass together. Otherwise your policy decides as before.
The reservation records the intent: consuming more than its maximum is refused, confirming after it expired releases the hold, and a session closes when its intent expires. GET /api/spend-policy/intents/{id} (MCP get_purchase_intent) shows how much of the maximum is held, spent and left. On UCP checkout, an ap2.checkout_mandate is compared with the session the same way before completion.
Not verified yet. The token or mandate in evidence is kept only as a SHA-256, and verified stays false: American Express has not opened an API to check a Proof of Intent Token, and an AP2 signature needs the buyer's key. The comparison holds the agent to the terms it declared. Where it is off, a check with intent answers 404 not_released.
curl -X POST https://api.last-price.ai/api/spend-policy/check \
-H "x-api-key: $LAST_PRICE_API_KEY" -H "Content-Type: application/json" \
-d '{"seller": "acme-air.example", "amount": 420, "currency": "USD",
"intent": {"source": "amex_intent", "intent_id": "int_8Kq2", "merchant": "acme-air.example",
"max_amount": 450, "currency": "USD", "expires_at": "2026-10-16T18:00:00Z",
"evidence": "<Proof of Intent Token>"}}'
# A purchase from another seller under the same intent
{
"decision": "deny",
"reason_code": "intent_seller_mismatch",
"reason": "The buyer approved intent int_8Kq2 for acme-air.example, not budget-air.example.",
"intent": { "source": "amex_intent", "intent_id": "int_8Kq2", "max_amount": 450,
"evidence_sha256": "9f2c...", "verified": false }
}Bind the account paid
A policy judges the seller name, which is free text. An agent that was approved to pay "acme" could otherwise send the money to any wallet once the check passed. Name the account you will pay in pay_to: a wallet address (compared without regard to case, an eip155:<chain>: prefix kept) or a merchant account id (compared exactly). It is stored with the approval a person decides and with the reservation, so an approval for one account is never spent on another.
Once a check names pay_to, confirm, consume and every session draw must name the same one. Leaving it out is a 400; another account answers 409 payee_changed. At confirm the hold is released, because nothing has been paid. At consume the money has already moved, so the hold is kept as an unknown outcome for a person to reconcile, and it still counts against the daily cap. A session draw to another account draws nothing and leaves the session open. Where it is off, a request with pay_to answers 404 not_released.
curl -X POST https://api.last-price.ai/api/spend-policy/check \
-H "x-api-key: $LAST_PRICE_API_KEY" -H "Content-Type: application/json" \
-d '{"seller": "acme", "amount": 4, "pay_to": "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984"}'
# Right before paying, and again when you report it
curl -X POST https://api.last-price.ai/api/spend-policy/reservations/RESERVATION_ID/confirm \
-H "x-api-key: $LAST_PRICE_API_KEY" -H "Content-Type: application/json" \
-d '{"pay_to": "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984"}'
# 409 when another account is named
{ "code": "payee_changed", "pay_to": "0x1f98...f984", "sent_pay_to": "0x9a3c...", ... }Pay in USDC, sats or another currency
Your limits stay in your policy's currency, while an agent often pays in the payment rail's own unit: USDC over x402, sats over Lightning. Send that unit as currency on check_purchase (USDC,EURC, BTC, SATS or ETH, or any other three-letter currency) and the amount is converted into the policy's currency once, before any rule runs. Every rule and cap then judges the converted figure.
A stablecoin converts at its 1:1 peg (USDC to US dollars, EURC to euros), unless its market price sits more than 2% off the peg: then the check is denied (rail_unit_depegged) rather than counted at a rate that no longer holds. BTC, sats and ETH convert at the spot price read at the check, and another currency at the European Central Bank rate. When no rate can be read the check is denied (rate_unavailable): nothing is converted at an invented rate. The converted amount is rounded up, never down.
The answer's rail shows what was sent, the converted amount, the rate, where it came from and when, and the reservation keeps them for the receipt. Report the payment with amount in the unit you paid in: it counts at the rate from the check, or at the live rate if that has since risen more than 2%, so a move between check and payment never lets more leave than the cap counted (settle_rate says which). Confirming before paying refuses a purchase whose rate rose more than 2% (rate_moved); check it again at today's rate. A session opened in a unit is drawn in it, at the session's rate. An intent in USDC holds a USDC purchase under a dollar policy.
curl -X POST https://api.last-price.ai/api/spend-policy/check \
-H "x-api-key: $LAST_PRICE_API_KEY" -H "Content-Type: application/json" \
-d '{"seller": "api.example", "amount": 0.25, "currency": "USDC"}'
{
"decision": "allow",
"reason_code": "within_policy",
"reservation": { "id": "c0ffee00-...", "amount": 0.25, "currency": "USD", "status": "reserved" },
"rail": { "unit": "USDC", "amount": 0.25, "converted_amount": 0.25, "currency": "USD",
"rate": 1, "rate_source": "peg", "rate_as_of": "2026-10-22T16:00:00Z",
"pegged": true, "depeg_check": "ok", "market_price": 0.9998 }
}
# Then, once paid, in the unit you paid in
curl -X POST https://api.last-price.ai/api/spend-policy/reservations/c0ffee00-.../consume \
-H "x-api-key: $LAST_PRICE_API_KEY" -d '{"amount": 0.25}'Seller quote expiry
A seller's quote holds its price until a time. Send the quote's id and that time with the check (quote_id, quote_valid_until, or valid_until on the chosen seller's entry inquotes), and a stale price is never paid by mistake.
Past that time the check is denied (quote_expired), or, when your policy'sexpired_quote_action is ask, a person approves it first. An expired competing quote does not count toward the two quotes the procurement preset asks for. If the quote expires after the check, confirming the reservation releases its hold, and reporting it paid is refused unless a person approved it: the hold keeps counting, so report the outcome unknown if money moved and the owner reconciles it from the receipt.
curl -X POST https://api.last-price.ai/api/spend-policy/check \
-H "x-api-key: $LAST_PRICE_API_KEY" -H "Content-Type: application/json" \
-d '{"seller": "acme-data.example", "amount": 120, "quote_id": "Q-2291",
"quote_valid_until": "2026-10-22T12:00:00Z"}'
{
"decision": "deny",
"reason_code": "quote_expired",
"reason": "The seller's quote Q-2291 stopped being valid at 2026-10-22T12:00:00.000Z, so its price may no longer hold. Ask the seller for a fresh quote and check again.",
"quote": { "id": "Q-2291", "valid_until": "2026-10-22T12:00:00.000Z" }
}Consume or release
After the purchase, consume the reservation at the amount paid (never more than reserved), or release it if the purchase failed so the budget comes back. A reservation settles once; a second call answers 409. Nothing releases a hold by time, so always settle. The MCP tool settle_purchase does both.
# The purchase went through, for 11.90
curl -X POST https://api.last-price.ai/api/spend-policy/reservations/RESERVATION_ID/consume \
-H "x-api-key: YOUR_AGENT_KEY" \
-H "Content-Type: application/json" \
-d '{ "amount": 11.90 }'
# The purchase failed
curl -X POST https://api.last-price.ai/api/spend-policy/reservations/RESERVATION_ID/release \
-H "x-api-key: YOUR_AGENT_KEY"Outcome unknown
When a payment times out or the answer can't be read, the money may or may not have moved. Don't release the reservation: if the payment did go through, a retry would pay twice. Report the outcome unknown instead (settle_purchase with outcome unknown). The amount stays held against the daily cap, the reservation shows as unknown, and a later release answers 409 reconcile_required.
Close it with POST .../reconcile (MCP reconcile_purchase) once you know, with a note saying what you checked. Outcome paid counts it at the amount paid, and the agent may send it. Outcome not_paid gives the budget back, so only the owner may send it: a person on the Spend Policy page, or a workspace-wide key with pcn:routing:write. An agent's own key can't send it. List what is waiting with GET /api/spend-policy/reservations?status=unknown.
# The payment timed out: keep the hold
curl -X POST https://api.last-price.ai/api/spend-policy/reservations/RESERVATION_ID/unknown \
-H "x-api-key: YOUR_AGENT_KEY" \
-H "Content-Type: application/json" \
-d '{ "note": "checkout timed out after 30s" }'
# Later, the owner checked the processor: nothing was charged
curl -X POST https://api.last-price.ai/api/spend-policy/reservations/RESERVATION_ID/reconcile \
-H "x-api-key: YOUR_WORKSPACE_KEY" \
-H "Content-Type: application/json" \
-d '{ "outcome": "not_paid", "note": "No charge in the processor dashboard" }'Confirm before paying
An owner can tighten a policy between an agent's check and its payment: lower the most per purchase from 50 to 20, lower the daily cap, block a seller. Every save bumps the policy's version, and a reservation records the version it was approved under in policy_version. Right before paying, the agent confirms the reservation (POST .../confirm, MCP confirm_purchase). Under an unchanged policy it is confirmed at once. Under a changed one the purchase is checked again against the rules as they stand now, counting the day's other holds against the cap.
Still allowed: confirmed: true, so pay now. Refused: 409 policy_changed with the reason_code, the hold is released, and the agent must not pay; it checks the purchase again instead. A person's earlier approval of the exact purchase still stands, but every refusal applies. Where confirming is off for a workspace, an allowed check names no confirm link and the route answers 404 not_released.
# Right before paying
curl -X POST https://api.last-price.ai/api/spend-policy/reservations/RESERVATION_ID/confirm \
-H "x-api-key: YOUR_AGENT_KEY"
# 200: { "confirmed": true, "rechecked": true, "reservation": { "policy_version": 4, ... } }
# 409: { "code": "policy_changed", "reason_code": "over_max_per_purchase", ... }Sessions for many small calls
An agent that makes a run of small paid calls to one seller (a stream of x402 calls at a cent each, say) opens one budget for the run instead of checking every call. Send the check with "kind": "session" (MCP open_spend_session): the amount is the session's maximum, held against the daily cap, and ttl_seconds (default 3600) is how long it stays open. The policy judges the session like a purchase of its maximum, so a person approves a large budget before any of it is spent, but the most per purchase applies to each call.
Right before paying each call, draw its price (POST .../sessions/SESSION_ID/draw, MCP draw_session_spend). Draws are taken under the same lock as the cap, so racing draws never pass the maximum: a draw that would answers 409 over_session_budget with what is left. When the run is done, close the session (MCP close_spend_session): what it drew is spent, and the rest goes back to the cap at once. A session left open gives its remainder back when it expires.
A call that fails after its draw is settled failed and its draw comes back; one whose outcome is unknown is settled unknown and keeps counting until it is reconciled, as for a single purchase (MCP settle_session_draw). If the owner changes the policy mid-run, the next draw judges the session again: a lower cap shrinks what it may still draw, and a refusal closes it with 409 policy_changed. Sessions are off by default for a workspace: while they are off, a session check and the session routes answer 404 not_released.
# Open a session of up to 5 USD for an hour
curl -X POST https://api.last-price.ai/api/spend-policy/check \
-H "x-api-key: YOUR_AGENT_KEY" \
-H "Content-Type: application/json" \
-d '{ "seller": "api.example.com", "amount": 5, "kind": "session", "ttl_seconds": 3600 }'
# Right before paying each call, draw its price
curl -X POST https://api.last-price.ai/api/spend-policy/sessions/SESSION_ID/draw \
-H "x-api-key: YOUR_AGENT_KEY" \
-H "Content-Type: application/json" \
-d '{ "amount": 0.01, "item": "GET /v1/forecast" }'
# A call that failed after its draw
curl -X POST https://api.last-price.ai/api/spend-policy/sessions/SESSION_ID/draws/DRAW_ID/settle \
-H "x-api-key: YOUR_AGENT_KEY" \
-H "Content-Type: application/json" \
-d '{ "outcome": "failed" }'
# Done: what was not drawn goes back to the cap
curl -X POST https://api.last-price.ai/api/spend-policy/sessions/SESSION_ID/close \
-H "x-api-key: YOUR_AGENT_KEY"
# 200: { "closed": true, "returned": 4.63, "session": { "drawn_amount": 0.37, "draw_count": 37, ... } }Procurement preset
Company buying rules, switched on in one step with "preset": "procurement" on the same PUT. For each rule you leave out it fills in a default: a person approves anything above 500, and above 5,000 the agent brings quotes from two sellers. Name preferred sellers and unknown sellers are denied; leave the list out and nothing is blocked. Any field you send wins over the preset.GET /api/spend-policy says whether your workspace has it in procurement.available, and saving these fields elsewhere answers 400. Rules already saved always apply.
- presetprocurement | null
- Switch the preset on, filling its defaults for omitted rules
- preferred_sellersstring[] | null
- Vendors procurement approved; others wait for a person (seller_not_preferred)
- block_unknown_sellersboolean
- Deny sellers not on preferred_sellers (seller_unknown)
- category_monthly_budgetsobject | null
- Most spent per category in one UTC month, held like the daily cap (over_category_budget); checks must name a category
- quotes_required_abovenumber | null
- Above this a check carries quotes from two sellers, the chosen one among them (quotes_required)
curl -X PUT https://api.last-price.ai/api/spend-policy \
-H "x-api-key: YOUR_WORKSPACE_KEY" \
-H "Content-Type: application/json" \
-d '{
"preset": "procurement",
"daily_cap": 20000,
"preferred_sellers": ["office-supplies.example", "cloud.example"],
"category_monthly_budgets": { "software": 2000, "office": 500 }
}'
# A purchase above 5,000 then carries its quotes
curl -X POST https://api.last-price.ai/api/spend-policy/check \
-H "x-api-key: YOUR_AGENT_KEY" \
-H "Content-Type: application/json" \
-d '{ "seller": "cloud.example", "amount": 6000, "category": "software",
"quotes": [{ "seller": "cloud.example", "amount": 6000 }, { "seller": "other.example", "amount": 6400 }] }'Which agents may spend. A policy can also let only verified agents spend: with require_verified_agent a check must carry the agent's AgentID ID token in the AgentID-Token header (agentid_token on check_purchase), or it is denied with agent_not_verified; with allowed_agent_subjects only those AgentIDs may spend (agent_not_allowed). A token that does not verify is refused with a 401.GET /api/spend-policy says whether your workspace has it in verified_agents.available.
- require_verified_agentboolean
- Deny checks without a verified AgentID token (agent_not_verified)
- allowed_agent_subjectsstring[] | null
- Only these AgentIDs, exactly as in their token, may spend (agent_not_allowed)
Buyers' limits as a seller signal
A price a buyer's own policy refuses is never paid, whatever it is worth. When buyer agents name a category on check_purchase, those checks say how much room buyers have for it. Pooled, that becomes a signal: the spread (p25, median, p75) of the largest amount each buyer workspace's checks allowed in the category, and the share of checks refused for being over a per-purchase maximum, a daily cap or a category budget.
On verify_price, name the category in metadata.category and the evidence includes buyer_budget, with the pooled numbers in buyer_envelope and where your price sits against them. It has weight 0 and never changes the verdict or its confidence: what buyers may spend is a limit, not a valuation. On compute_price, send options.include_buyer_envelope to get buyer_envelope next to the price, which it never changes. A check that names a category carries the same numbers in spend_envelope, and they never change the decision.
Where your price sits is in band_position: below,inside or above the band, spelled like every other band in the API, or null when the numbers are not shown. The older position field (below_band,inside_band, above_band) carries the same answer for callers that already read it.
Privacy. Only pooled numbers leave the database. Numbers for a category show only once 5 or more buyer workspaces have had a check allowed in it; below that the answer says so and carries no count, so nobody learns that one or two others bought there. Above it, the count is a coarse band (5-9, 10-24 or 25+), never the exact number. Staff see the same view, and a category below 5 is not listed for them even by name. Each workspace counts once, by its largest allowed check. The lowest and highest are pulled in to their neighbours before the spread is taken, and every amount is rounded to a coarse step (20, 25, 30, 40, 50, 75, 100 and so on), so no workspace's exact limit or balance is shown. The refusal share shows only once 5 or more of those workspaces have had a check refused over a limit. This is a threshold on the crowd, not differential privacy: someone who already knows four of the five buyers, or who watches a category's numbers appear, could learn about the fifth. Noisy, bounded publication that closes that gap is still being built. Where it is not switched on, nothing is added.
curl -X POST https://api.last-price.ai/api/price-router/verify \
-H "x-api-key: $LAST_PRICE_API_KEY" -H "Content-Type: application/json" \
-d '{"proposed_price": 900, "context": {"currency": "USD", "metadata": {"category": "travel"}}}'
# Among the evidence
{ "source": "buyer_budget", "weight": 0, "band": null, "informational": true,
"buyer_envelope": { "category": "travel", "currency": "USD", "privacy_threshold_met": true,
"contributor_band": "5-9", "band_min": 200, "typical_amount": 400, "band_max": 750,
"over_cap_refusal_rate": 0.15, "position": "above_band", "band_position": "above", "caveat": "..." } }Signals
Signals is the behavioral data layer for pricing intelligence. It captures every meaningful event - agent pricing decisions, inference calls, conversion outcomes, customer interactions - and surfaces them as a queryable stream. The Commerce Control Plane, Jale, and Elo all emit signals automatically; you can also push custom signals via the API.
Overview
Navigate to /signals in the dashboard to browse the signal stream. Toggle Raw signals to see unprocessed events. Filter by time range and agent. Signals feed into Jale's optimization loop and are available via the usage-signals API endpoint.
Customer and Event filters. The Signals page also has a Customer select and an Event select, each listing what your workspace's signals use with how many signals each has. They combine with the range and agent, and the choice is kept in the page address (?range=last-7d&agent=…&customer=…&event=…), so a filtered view can be bookmarked or shared with your team. Event types read in words (refund_issued shows as Refund issued), and the raw view names the agent and customer of each signal and lists its details. GET /api/usage/signals/filters lists the customers and event types, and the MCP tool list_usage_signal_filters calls it. The customer_id and event_type parameters of GET /api/usage/signals work for every workspace, rollout or not, and the MCP tool list_usage_signals takes them too.
| Signal type | Emitted by | Use |
|---|---|---|
| price_computed | PCN / Price Router | Every routed inference call |
| variant_assigned | Elo | A/B test bucket assignment |
| conversion | Elo / Snippet / API | Revenue event attached to a variant |
| proposal_created | Commerce CP | Pricing policy produced a proposal |
| proposal_executed | Commerce CP | Price pushed to connector |
| agent_action | Agents | Any agent-driven pricing decision |
| custom | Your code | Any domain event you push via the API |
Agent pricing signals
AI agents that call the Price Router or PCN can record price_computed and agent_action signals via POST /api/usage/signals. The Agent Pricing Signals dashboard (/signals) lets you drill into per-agent decision histories, see which pricing models were used, and correlate outcomes with revenue.
# Record a signal from an agent pricing action
POST /api/usage/signals
Authorization: Bearer lp_<hex>
Content-Type: application/json
{
"eventType": "price_computed",
"agentId": "4f1b8a91-2e07-44b6-9a3a-1b8c2e72b001",
"customerId": "0b6c7d1e-5f43-4a8e-9d2b-3c1f6e8a7b90",
"properties": {
"function_used": "lastprice/jale-optimizer",
"input_price": 49.99,
"output_price": 54.99,
"confidence": 0.91,
"latency_ms": 230
},
"metadata": {}
}
// Response (201 Created)
{
"id": "9d3e2c71-6a4b-4f8e-b1c2-7e5d8a9f0b13",
"message": "Usage signal recorded successfully",
"signal": {
"id": "9d3e2c71-6a4b-4f8e-b1c2-7e5d8a9f0b13",
"tenant_id": "2a7c9e14-3b5d-4c6f-8e1a-6d4b2f9c7e05",
"agent_id": "4f1b8a91-2e07-44b6-9a3a-1b8c2e72b001",
"customer_id": "0b6c7d1e-5f43-4a8e-9d2b-3c1f6e8a7b90",
"event_type": "price_computed",
"properties": { "function_used": "lastprice/jale-optimizer", "output_price": 54.99 },
"metadata": {},
"created_at": "2025-01-15T10:23:00.000Z"
}
}Experiments & A/B testing
Run pricing experiments across your products. Define variants with different price points, assign users deterministically, track conversions, and view statistical results - all through a simple API.
Experiments take 2 to 10 arms, one of them control, assign each user a stable arm by hash, record each arm's views, conversions and revenue, and test every arm against control for statistical significance, with bandit allocation to split the next traffic; the Elo A/B test built-in function assigns arms by the same hash inside a compute call.
Create experiment
Create a new experiment with a unique key and from two to ten pricing variants, one of them named control: the baseline every other arm is compared with. Each variant can carry custom metadata (e.g., features, discount percentages) that gets forwarded to clients. How arms, weights and the comparison work is under Arms, weights and comparison.
- keystring, required
- Unique key (lowercase alphanumeric + underscores)
- namestring, required
- Human-readable experiment name
- descriptionstring
- Description of what is being tested
- variantsarray, required
- From 2 to 10 variants, one named 'control'
- variants[].namestring, required
- 1 to 40 lowercase letters, digits or underscores, starting with a letter, and unique. 'comparison' and 'summary' are reserved
- variants[].pricenumber, required
- Price for this variant (≥ 0)
- variants[].weightnumber
- Share of traffic. Set it on every arm or on none (default: equal). With three or more arms, whole percentages adding up to 100. With two arms, relative to each other as before, so 70/30 and 0.7/0.3 are the same split, and 1/99 is the most uneven accepted
- variants[].metadataobject
- Arbitrary data forwarded to clients
- targetSampleSizenumber
- Target number of users, stored with the experiment and returned with it. Nothing completes an experiment automatically yet, so this records your intent rather than triggering anything
# Discover your tenant first. Do not type a UUID: the tenant in
# the path must match the one your credential resolves to, or it is a 403.
curl https://api.last-price.ai/api/me -H "Authorization: Bearer lp_<hex>"
# => { "tenant_id": "...", ... } Use that value as TENANT_ID below.
# Create a pricing experiment. A JWT goes in Authorization; an API key goes
# in x-api-key and is not accepted as a bearer token. Send one or the other.
curl -X POST https://api.last-price.ai/api/tenants/TENANT_ID/experiments \
-H "Authorization: Bearer <YOUR_JWT_TOKEN>" \
-H "Content-Type: application/json" \
-d '{
"key": "homepage_pricing",
"name": "Homepage Pricing Test",
"description": "Testing $29 vs $39 price points",
"variants": [
{
"name": "control",
"price": 29,
"weight": 0.7,
"metadata": {
"plan": "Pro",
"features": ["Unlimited projects", "Priority support"]
}
},
{
"name": "experiment",
"price": 39,
"weight": 0.3,
"metadata": {
"plan": "Pro Plus",
"features": ["Unlimited projects", "Priority support", "API access"]
}
}
],
"targetSampleSize": 1000
}'
# Three or more arms: weights are whole percentages that add up to 100
curl -X POST https://api.last-price.ai/api/tenants/TENANT_ID/experiments \
-H "x-api-key: lp_YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"key": "pro_price_ladder",
"name": "Pro price ladder",
"variants": [
{ "name": "control", "price": 29, "weight": 40 },
{ "name": "mid", "price": 34, "weight": 30 },
{ "name": "high", "price": 39, "weight": 30 }
],
"targetSampleSize": 1000
}'
# List experiments
curl "https://api.last-price.ai/api/tenants/TENANT_ID/experiments?status=active" \
-H "Authorization: Bearer lp_<hex>"Arms, weights and comparison
An experiment has from two to ten arms. One is always named control: your current price, and the baseline each other arm is measured against. The other arms can be called anything that fits the naming rule, such as mid or annual_discount. A two-arm experiment named control and experiment works exactly as it always has.
- Weights. Leave every weight out for an even split. With three or more arms, give every arm a whole-number percentage and make them add up to 100, for example 40, 30 and 30. With two arms, weights stay relative to each other, as before.
- Assignment. The same user always gets the same arm. Each arm takes its percentage of 100 buckets, so the split you set is the split you get. Users already assigned keep their arm if arms are added later.
- Comparison. The results response adds a
comparisonfield: for every arm, the chance it converts better than control (the same Bayesian test asPOST /api/compute/significance), its lift, and a verdict ofbetter,worseorinconclusive. - More arms, higher bar. Every extra arm is another chance of a lucky winner, so the bar is raised (a Bonferroni correction): with k arms against control, an arm is called better only at a chance of 1 − 0.05 / k. That is 95% with one challenger, 97.5% with two and 98.75% with four.
In the dashboard, open Experiments, choose Create Experiment, and use Add variant to add arms; Split evenly fills in percentages that add up to 100. Each experiment's Results & Analytics shows every arm against control.
Get pricing
Retrieve the pricing for a specific user. The system deterministically assigns the user to a variant and returns the full pricing payload including any variant metadata. The path parameter is the experiment key you chose, such as homepage_pricing, not the UUID of the experiment record.
# From your server, with your secret API key
curl "https://api.last-price.ai/api/experiments/homepage_pricing/pricing?userId=user_abc123" \
-H "x-api-key: lp_YOUR_API_KEY"
# From a web page, the snippet sends a publishable embed token instead
# x-embed-token: lpe_YOUR_EMBED_TOKEN
# Response
{
"userId": "user_abc123",
"experimentId": "homepage_pricing",
"variant": "control",
"pricing": {
"plan": "Control",
"price": 29
}
}The pricing object includes the variant's plan, price, and any additional metadata fields (such as features) from the variant definition.
Track conversions
Record a conversion event when a user completes a purchase or desired action. Send the amount you actually settled, including 0 for a free trial activation or a fully discounted order: an explicit zero is recorded as zero. Omitting revenue is what asks for the assigned variant's list price instead. The tenant comes from your credential; the optional tenantId in the body is only checked against it, and a mismatch is rejected.
# From your server, with your secret API key. A browser sends
# x-embed-token instead; the snippet does this for you.
curl -X POST https://api.last-price.ai/api/experiments/homepage_pricing/convert \
-H "x-api-key: lp_YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"userId": "user_abc123",
"revenue": 29.00
}'
# Response
{
"success": true,
"userId": "user_abc123",
"experimentId": "homepage_pricing",
"variant": "control",
"revenue": 29
}View results
Retrieve experiment performance data including per-variant views, conversions, conversion rates, and revenue metrics, keyed by arm name, plus comparison: every arm against control (see Arms, weights and comparison). Use the definition endpoint for the full experiment configuration.
# Get experiment results. Server side only: an embed token does not
# reach these, and there is no cross-origin access to them.
curl https://api.last-price.ai/api/experiments/homepage_pricing/results \
-H "x-api-key: lp_YOUR_API_KEY"
# Get experiment definition
curl https://api.last-price.ai/api/experiments/homepage_pricing/definition \
-H "x-api-key: lp_YOUR_API_KEY"
# Results response
{
"experimentId": "EXPERIMENT_ID",
"control": {
"views": 523,
"conversions": 47,
"revenue": "1363.00",
"conversionRate": "8.99%",
"arpu": "29.00"
},
"experiment": {
"views": 477,
"conversions": 31,
"revenue": "1209.00",
"conversionRate": "6.50%",
"arpu": "39.00"
},
"comparison": {
"method": "bayesian_beta_binomial",
"control": "control",
"correction": "bonferroni",
"comparisons": 1,
"threshold": 0.95,
"arms": [
{ "name": "control", "views": 523, "conversions": 47, "conversionRate": 0.089866,
"liftVsControl": null, "chanceBeatsControl": null, "verdict": "control" },
{ "name": "experiment", "views": 477, "conversions": 31, "conversionRate": 0.06499,
"liftVsControl": -0.2768, "chanceBeatsControl": 0.0728, "verdict": "inconclusive" }
]
}
}Experiments over MCP
Your agent can run the owner side of an experiment from its MCP session with four tools: list_experiments, get_experiment_definition, get_experiment_results and create_experiment. They call the routes above with the same rules: two to ten arms, one named control, a price on each, and weights the engine can deliver. A new experiment starts as a draft. Serving prices to buyers and recording conversions stay on the buyer-facing routes.
Pause, delete and correct
Keep an experiment's numbers honest: stop it when you are done, count each buyer once, and take out a conversion that should not be there. Every route below takes the experiment key or the id the create call returned.
- Start, pause, complete.
PATCH /api/experiments/KEYwith{"status":"paused"}(oractive,completed). A paused or completed experiment shows every visitor the control price and records nothing; completed is final.DELETE /api/experiments/KEYremoves it and its data.GET /api/experimentslists them. - One conversion per buyer. A second convert for the same user answers 409
already_converted. If your server records repeat purchases on purpose, send"allow_repeat": true. Send anIdempotency-Keyheader and a retried convert is answered from the first one, never counted twice. - Correct a conversion.
DELETE /api/experiments/KEY/conversions?userId=user_abc123removes that buyer's conversions (or?variant=experimentfor a whole arm), and the buyer can convert again. Each one is in your audit log. - From an agent. The MCP tools
set_experiment_status,delete_experimentandremove_experiment_conversions(give ituser_idorvariant, not both) call these same routes, andlist_experimentslists them. They need a key for a claimed workspace. - Lock an embed token to its experiments. Create it with
experiment_keysand it prices and converts on those only. From a web page, a conversion cannot report more than the arm's price; report larger orders from your server.
# Pause
curl -X PATCH https://api.last-price.ai/api/experiments/homepage_pricing \
-H "x-api-key: lp_YOUR_API_KEY" -H "Content-Type: application/json" \
-d '{"status":"paused"}'
# Take out one buyer's conversion
curl -X DELETE "https://api.last-price.ai/api/experiments/homepage_pricing/conversions?userId=user_abc123" \
-H "x-api-key: lp_YOUR_API_KEY"
# Response
{ "experimentId": "homepage_pricing", "userId": "user_abc123", "voided": 1, "revenue": "29.00" }Results also list every arm from the start, at zero until it has data, with a summary of totals and the first test arm against control.
Two more tools run the statistics on any trials and conversions you pass, from an experiment or not: check_variant_significance calls POST /api/compute/significance (is there a winner yet: each variant's chance of being best, its expected loss, and a verdict), and allocate_variant_traffic calls POST /api/compute/allocation (how to split the next traffic by Thompson sampling). Each is billed as one call at its function's cost multiplier (1x and 2x), needs the price:compute scope, and needs a claimed workspace.
Stopping and bandit allocation
Sequential testing tells you when an experiment can stop, and can move traffic toward the arms most likely to win. Where it is off for a workspace, the endpoint answers 404 with the code not_enabled and the Experiments page shows nothing new.
- Can you stop? Each arm is tested against control with a sequential test that stays valid however often you check (a mixture sequential probability ratio test). Checking every hour does not raise the chance of a false winner, which stays at 5% across all arms (the bar rises with the number of arms). The verdict is
stop(an arm beats control, every arm loses to it, or the arms are too close to matter),keep_running(too little data, or an arm is ahead but not proven) orno_winner_yet. An arm needs at least 100 views before it can be called. Act on the first stop. - Bandit allocation. Opt an experiment in and, once a day while it is active, Thompson sampling recomputes its weights as whole percentages adding up to 100. Every arm keeps at least 5% and control at least 20% (set your own floors with min_weight_pct and control_min_weight_pct). Weights move only after 200 views across the arms.
- What it does to bucketing. Assignment stays deterministic. A visitor who already has an arm keeps it. New visitors are bucketed exactly as before; the new weights only move the boundaries between arms, so they decide which arm a new visitor lands on. The trade-off: arms fill at different rates over time, so a conversion rate that drifts (weekdays, a campaign) affects them unevenly, and the less traffic control gets, the longer a verdict against it takes. That is why control keeps a higher floor.
- Audit. Every weight change, with the weights before and after and the counts behind them, and every change to the opt-in is recorded. Read them in the response's weight_history or in the audit log. Agents can read the verdict and history with the MCP tool get_experiment_stopping.
Try your own numbers. The picture is worked out again by the same rules.
# Can this experiment stop? Verdict, split, bandit settings and weight history
curl https://api.last-price.ai/api/experiments/homepage_pricing/sequential \
-H "x-api-key: lp_YOUR_API_KEY"
# Opt in to bandit allocation (floors are optional)
curl -X PUT https://api.last-price.ai/api/experiments/homepage_pricing/sequential \
-H "x-api-key: lp_YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"bandit_enabled": true, "min_weight_pct": 5, "control_min_weight_pct": 20}'
# Response (shortened)
{
"experimentId": "homepage_pricing",
"stopping": {
"method": "msprt",
"verdict": "keep_running",
"reason": "leaning",
"headline": "Keep running: premium is ahead of control (91.2% chance it is better) but not proven yet.",
"comparisons": 2,
"arms": [ ... ]
},
"weights": { "arms": [ { "name": "control", "weight_pct": 34 }, ... ], "even": false },
"bandit": { "enabled": true, "min_weight_pct": 5, "control_min_weight_pct": 20, "proposed_weights": [ ... ] },
"weight_history": [ { "kind": "reweight", "before": [ ... ], "after": [ ... ], "created_at": "..." } ]
}Jale: AI price optimizer
Jale is the built-in AI pricing optimization engine. It learns from your experiment data and quote outcomes to recommend optimal prices and can automatically propose new variants based on conversion performance.
Optimize pricing
Submit an optimization request to get AI pricing recommendations, learned from the data, for an active experiment. Optionally specify an objective (e.g., maximize revenue or conversions) and candidate price points. Invalid candidate prices return 400. Missing experiments return 404. Unavailable or malformed experiment data returns 502 without a recommendation.
- experimentIdstring, required
- Experiment to optimize
- objectivestring
- Optimization goal (e.g., 'maximize_revenue', 'maximize_conversions')
- candidatesarray
- Candidate price points to evaluate
- lookbackDaysnumber
- Days of historical data to consider
# Get pricing optimization recommendation
curl -X POST https://api.last-price.ai/api/jale/optimize \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"experimentId": "homepage_pricing",
"objective": "maximize_revenue",
"candidates": [19, 24, 29, 34, 39],
"lookbackDays": 30
}'Propose variant
Adds an arm to an existing experiment, up to ten. The new arm has no weight, so it works on an experiment that splits traffic evenly: traffic is then shared evenly across every arm for users not yet assigned. An experiment whose arms carry weights is refused with a 400, because how the traffic is reshared is your call; create a new experiment with the weights you want.
- experimentIdstring, required
- Target experiment
- pricenumber, required
- Price point for the new variant (must be greater than 0)
- labelstring
- Human-readable variant name (auto-generated if omitted)
- metadataobject
- Custom data for the variant
# Propose a new variant
curl -X POST https://api.last-price.ai/api/jale/propose-variant \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"experimentId": "homepage_pricing",
"price": 34,
"label": "mid_tier_test",
"metadata": {
"plan": "Pro",
"features": ["Unlimited projects", "Priority support", "Custom branding"]
}
}'
# Response
{
"success": true,
"experimentId": "homepage_pricing",
"variant": { "name": "mid_tier_test", "price": 34, "metadata": { ... } },
"message": "Variant 'mid_tier_test' proposed successfully",
"experiment": { "id": "...", "key": "homepage_pricing", "variants": [ ... ] }
}
# On an experiment whose arms carry weights
{
"error": "Cannot propose an additional variant",
"message": "Set a weight on every variant or on none. ..."
}Recommend a price (MCP)
recommend_jale_price asks Jale for the price to run next in one of your experiments. Pass experiment_id; optionally objective (revenue, conversion, profit or market_share, default revenue), candidates (the prices to compare) and lookback_days. It recommends only and changes no price. It needs a Last Price credential; it calls the same route as POST /api/jale/optimize.
propose_experiment_variant acts on the advice: it adds one price arm to an existing experiment (experiment_key, price, optional label and metadata), as POST /api/jale/propose-variant does. It needs a claimed workspace. An experiment whose arms carry weights refuses, and a running experiment starts serving the new price to its share of buyers.
recommend_jale_price { "experiment_id": "exp_123", "objective": "profit", "candidates": [9, 11, 13] }
propose_experiment_variant { "experiment_key": "exp_123", "price": 11 }Data exchange (MCP)
Workspaces share observed prices in a data exchange: contribute public prices to earn tokens, spend tokens to read what others shared. Five MCP tools cover it, so an agent can run the loop itself. They need a Last Price credential of a claimed workspace; a sandbox key is refused, because a contribution joins a pool other workspaces read.
get_jale_token_balance: your balance, tokens earned and spent, with the latest movements when you passhistory. Free.list_jale_contributions: the data points your workspace contributed, with status, quality score and tokens earned. Filter bystatusorvertical. Free.query_jale_pool: the newest shared data points, for oneverticalor all. Costs 5 tokens a query; below 5 it is refused with your balance.contribute_price_data: share one price (vertical,source_url,product_name,price) and earn 10 tokens. The same source, product and price within 24 hours is a duplicate and earns nothing.contribute_price_data_batch: up to 100 data points in one call; duplicates are reported and do not stop the rest.
# Earn tokens, then read the pool
contribute_price_data { "vertical": "saas", "source_url": "https://acme.example/pricing", "product_name": "Pro", "price": 29, "currency": "USD" }
get_jale_token_balance { }
query_jale_pool { "vertical": "saas", "limit": 20 }JavaScript SDK
A lightweight (~4 KB minified, ~1.5 KB gzipped) vanilla JavaScript SDK for embedding A/B tested pricing on any website. Zero dependencies - works with any framework or static site.
Installation
Include the SDK via a script tag. You can either configure it programmatically or use data attributes for automatic initialization.
<!-- Option 1: Script tag with manual configuration -->
<div id="pricing-container"></div>
<script src="https://last-price.ai/lastprice.js"></script>
<script>
LastPrice.configure({
apiBase: 'https://api.last-price.ai',
embedToken: 'lpe_YOUR_EMBED_TOKEN',
tenantId: 'YOUR_TENANT_ID',
experimentId: 'homepage_pricing'
});
LastPrice.showPricing('#pricing-container');
</script>
<!-- Option 2: Data attributes (auto-load) -->
<div id="pricing-container"></div>
<script
src="https://last-price.ai/lastprice.js"
data-api-base="https://api.last-price.ai"
data-embed-token="lpe_YOUR_EMBED_TOKEN"
data-tenant-id="YOUR_TENANT_ID"
data-experiment-id="homepage_pricing"
data-auto-load
data-container="#pricing-container"
></script>Configuration
Configure the SDK with your API base URL, embed token, tenant ID, and experiment key. Optional settings control cookie behavior and debug logging.
The embed token is required: the SDK refuses to call the API without one. Create it on the Embed Snippet page and register every site the snippet runs on. It is publishable, so it belongs in page source; your secret API key does not. The API also refuses a secret key on a cross-origin call, because the preflight does not allow its header, but do not read that as a safety net: it says nothing about the key being readable by every visitor once it is in the page.
- apiBasestring, required
- Your Last Price API base URL
- embedTokenstring, required
- Publishable embed token (lpe_...), valid only from the sites registered on it
- tenantIdstring, required
- Your tenant identifier
- experimentIdstring, required
- Experiment key to load pricing from, such as homepage_pricing. Not the UUID of the experiment record.
- cookieNamestring
- Cookie name for user ID persistence (default: lp_user_id)
- cookieMaxAgenumber
- Cookie expiry in seconds (default: 1 year)
- debugboolean
- Enable debug logging to console (default: false)
LastPrice.configure({
apiBase: 'https://api.last-price.ai',
embedToken: 'lpe_YOUR_EMBED_TOKEN',
tenantId: 'YOUR_TENANT_ID',
experimentId: 'homepage_pricing',
cookieName: 'lp_user_id', // optional
cookieMaxAge: 31536000, // optional (1 year)
debug: false // optional
});
// Helper methods
const userId = LastPrice.getUserId(); // Get or create persistent user ID
const variant = LastPrice.getVariant(); // Get current variant assignmentShow pricing
Render a pricing card into a container element. The SDK fetches the user's assigned variant and renders it automatically. Use a custom renderer for full control over the UI.
// Default renderer - pricing card with "Buy Now" button
LastPrice.showPricing('#pricing-container');
// With conversion callback. It REPLACES the default handler, so record the
// conversion yourself: the button records nothing otherwise.
LastPrice.showPricing('#pricing-container', {
onConvert: async function(pricing) {
await LastPrice.convert({ revenue: pricing.price });
window.location.href = '/checkout';
}
});
// Custom renderer - full control over markup
let convertPricing;
LastPrice.showPricing('#pricing-container', {
customRenderer: function(pricing, convertFn) {
convertPricing = convertFn;
// The plan name and the features come from the variant's metadata and
// end up in innerHTML, so escape them the way the default card does.
var esc = function(value) {
return String(value)
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/"/g, '"').replace(/'/g, ''');
};
return '<div class="my-pricing">'
+ '<h2>' + esc(pricing.plan) + '</h2>'
+ '<p class="price">$' + esc(pricing.price) + '/mo</p>'
+ '<ul>' + (pricing.features || []).map(function(f) {
return '<li>' + esc(f) + '</li>';
}).join('') + '</ul>'
// Deliberately NOT id="lp-convert-btn". The SDK wires that id up
// itself, so a button carrying it and the handler below would both
// fire on one click and record two conversions. Use the reserved id
// and drop this listener, or use your own id and keep it.
+ '<button id="my-subscribe-btn" type="button">Subscribe</button>'
+ '</div>';
}
});
document.addEventListener('click', function(event) {
if (event.target && event.target.id === 'my-subscribe-btn' && convertPricing) {
convertPricing();
}
});Track conversions (SDK)
Record conversion events programmatically. Useful when the purchase flow happens outside the embedded pricing card (e.g., after a checkout process).
// Record a conversion with revenue
LastPrice.convert({
revenue: 29.00,
onSuccess: function(response) {
console.log('Conversion recorded:', response);
},
onError: function(error) {
console.error('Conversion failed:', error);
}
});
// Simple conversion without revenue
LastPrice.convert();Cost tracking
Track costs across agents, customers, and operations. Record individual cost events and retrieve aggregated analytics to understand spending patterns over time.
Record costs
Record a cost event associated with an agent, customer, or custom cost type.
- costTypestring, required
- Category of cost (e.g., 'inference', 'compute', 'api_call')
- amountnumber, required
- Cost amount
- currencystring, required
- ISO 4217 currency code (e.g., USD)
- agentIduuid
- Associated agent identifier
- customerIduuid
- Associated customer identifier
- metadataobject
- Additional context about the cost
# Record a cost
curl -X POST https://api.last-price.ai/api/costs \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{
"agentId": "a1b2c3d4-e5f6-4789-8abc-1234567890ab",
"customerId": "b2c3d4e5-f6a7-4890-bcde-2345678901bc",
"costType": "inference",
"amount": 0.0042,
"currency": "USD",
"metadata": {
"model": "gpt-4",
"tokens": 1250
}
}'List costs
Retrieve cost records with optional date-range filtering and pagination.
# List costs with date range
curl "https://api.last-price.ai/api/costs?startDate=2025-01-01T00:00:00Z&endDate=2025-01-31T23:59:59Z&limit=100&offset=0" \
-H "Authorization: Bearer lp_<hex>"
# Response
{
"data": [
{
"id": "d4e5f6a7-b8c9-4012-def0-456789012345",
"agent_id": "a1b2c3d4-e5f6-4789-8abc-1234567890ab",
"customer_id": "b2c3d4e5-f6a7-4890-bcde-2345678901bc",
"cost_type": "inference",
"amount": "0.0042",
"currency": "USD",
"metadata": { "model": "gpt-4", "tokens": 1250 },
"created_at": "2025-01-15T14:30:00Z"
}
],
"pagination": {
"limit": 100,
"offset": 0,
"total": 1
}
}Cost analytics
Get aggregated cost analytics grouped by time period, agent, customer, or cost type.
- startDateISO 8601
- Start of the analysis window
- endDateISO 8601
- End of the analysis window
- groupByenum
- Group results by: day, week, month, agent, customer, or type (default: day)
# Get cost analytics grouped by day
curl "https://api.last-price.ai/api/costs/analytics?startDate=2025-01-01&endDate=2025-01-31&groupBy=day" \
-H "Authorization: Bearer lp_<hex>"
# Response. Every count and sum is aggregated in Postgres and arrives as a
# decimal string, not a number.
{
"analytics": [
{
"group_key": "2025-01-15T00:00:00.000Z",
"count": "42",
"total_amount": "1.7600",
"avg_amount": "0.0420",
"min_amount": "0.0010",
"max_amount": "0.1500",
"currency": "USD"
}
],
"totals": [
{
"total_count": "1250",
"total_amount": "52.3000",
"currency": "USD"
}
],
"groupBy": "day"
}Demo apps
Pre-built demo applications that showcase Last Price pricing experiments in action. Three demo apps are included: an e-commerce store, a marketplace, and a digital products platform - each with its own pricing experiment and variant configurations.
Overview
List all demo apps with their current status, variant counts, and performance metrics. Demo apps use a special demo tenant managed by the system.
# List demo apps
curl https://api.last-price.ai/api/demo-apps \
-H "Authorization: Bearer lp_<hex>"
# Response
{
"apps": [
{
"id": "ecommerce-store",
"name": "E-Commerce Store",
"description": "Product pricing experiment",
"experimentKey": "ecommerce_pricing",
"status": "active",
"variants": 3,
"views": 1250,
"conversions": 89,
"conversionRate": "7.1%"
},
{
"id": "marketplace",
"name": "Marketplace",
"description": "Seller commission experiment",
"experimentKey": "marketplace_commission",
"status": "not_seeded",
"variants": 2,
"views": 0,
"conversions": 0,
"conversionRate": "0.0%"
},
{
"id": "digital-products",
"name": "Digital Products",
"description": "Course pricing experiment",
"experimentKey": "course_pricing",
"status": "active",
"variants": 3,
"views": 620,
"conversions": 41,
"conversionRate": "6.6%"
}
]
}Seed data
Initialize demo experiments by seeding sample data. You can seed all demo apps at once or a specific app by passing the app query parameter.
# Seed all demo apps
curl -X POST https://api.last-price.ai/api/demo-apps/seed \
-H "Authorization: Bearer lp_<hex>"
# Seed a specific demo app
curl -X POST "https://api.last-price.ai/api/demo-apps/seed?app=ecommerce-store" \
-H "Authorization: Bearer lp_<hex>"
# Response (201)
{
"tenantId": "00000000-0000-0000-0000-000000000000",
"results": [
{
"app": "ecommerce-store",
"experimentId": "exp_uuid_...",
"experimentKey": "ecommerce_pricing",
"status": "active",
"action": "created"
}
]
}Hosted demos
Six of the demo apps run on this site under /demos/<slug>: CloudNote (a SaaS plan page), AgentBank, CloudAI (an AI API), ModernGoods (a storefront), SkillHub (a freelancer marketplace) and LearnFast (courses). Each runs a real pricing experiment, and a strip at the top of every page shows the arm the visitor got and what it sets. Nothing is charged.
- The demo workspace. Every demo runs in the Last Price demo workspace this deployment owns, the same one the keyless pricing demo uses. Each demo's experiment is created there the first time it is needed, from the definition the Seed Data button above uses, and started; an existing one is left as it is. No key is involved: the site runs the experiment on its own server, and the browser only sends a random visitor id.
- Real arms and conversions. A visitor's arm is assigned by the same code as
GET /api/experiments/{key}/pricing, stored, and its view recorded. A purchase records a conversion on that arm, asPOST /api/experiments/{key}/convertdoes, up to 100000 per purchase. The CloudNote buyer agents are visitors too: each one gets an arm, decides against its own budget, and its purchase is a conversion.GET /api/public/demos/{slug}/resultsreads each arm's visitors, buyers and revenue back. - Working apps. Each app runs end to end at the visitor's arm: a ModernGoods cart and checkout, AgentBank accounts whose operations answer HTTP 402 when the balance or the monthly limit runs short and debit nothing, SkillHub hiring and listings, LearnFast checkout, a CloudAI cost calculator, and CloudNote team pages read from the live results. A visitor's carts, accounts and listings stay in their browser, keyed to their visitor id; the arms, views and conversions are in the demo workspace.
- Release flag. The demos sit behind the
hosted-demo-appsrelease flag, off by default and checked on the server. While it is off every demo page and demo route answers 404, and the gallery shows its cards without a Live badge or a link.HOSTED_DEMOS_PREVIEW=1shows them on a local or preview build. - Health. A demo keeps its Live badge, its link and its pages only while its experiment is ready to serve in the demo workspace; on a deployment without a reachable database the demos are simply not offered.
HOSTED_DEMOS_DISABLED(a comma separated list of slugs) takes one down at once. - Limits. The demo routes take no credential and are limited per client address: 120 assign and convert calls and 60 list, results and health reads per 15 minutes.
# List the hosted demos (also the list_hosted_demos MCP tool)
curl https://api.last-price.ai/api/public/demos
# The arm a visitor gets
curl -X POST https://api.last-price.ai/api/public/demos/ecommerce-store/assign \
-H "Content-Type: application/json" \
-d '{"visitor_id": "3f2b9c1e-7a4d-4e8b-9c0f-1d2e3f4a5b6c"}'
# Response
{
"demo": "ecommerce-store",
"experiment_key": "ecommerce_pricing",
"arm": "experiment",
"pricing": { "plan": "Higher", "price": 59.99, "firstPurchaseDiscount": 15, "freeShippingThreshold": 50 }
}
# A purchase: a conversion on the visitor's arm
curl -X POST https://api.last-price.ai/api/public/demos/ecommerce-store/convert \
-H "Content-Type: application/json" \
-d '{"visitor_id": "3f2b9c1e-7a4d-4e8b-9c0f-1d2e3f4a5b6c", "revenue": 59.99}'
# What each arm has recorded
curl https://api.last-price.ai/api/public/demos/ecommerce-store/results
# Health, for an uptime monitor: 200 when live, 503 when not
curl https://api.last-price.ai/api/public/demos/ecommerce-store/healthA/B testing with Elo
Elo is the A/B testing engine that powers deterministic variant assignment, experiment management, and conversion tracking.
Experiments take 2 to 10 arms, one of them control, assign each user a stable arm by hash, record each arm's views, conversions and revenue, and test every arm against control for statistical significance, with bandit allocation to split the next traffic; the Elo A/B test built-in function assigns arms by the same hash inside a compute call.
How variant assignment works
Elo uses SHA-256 hashing for deterministic variant assignment:
- Same
userId + experimentId→ always the same variant - Assignment is deterministic, though the server may still read or persist assignment and view data
- 100-bucket system supports percentage-based splits
- Consistent across sessions, devices, and servers
Every request needs a credential: your secret API key from a server, or a publishable embed token from a page, which is what the snippet sends. Without one the API answers 401. The workspace comes from that credential, so tenantId is optional and only has to agree with it. The same user and experiment always return the same variant, using a 100-bucket SHA-256 hashing scheme.
- userIdstring, required
- Unique user/visitor identifier
- tenantIdstring
- Optional. The workspace comes from your credential; when this is present it only has to agree with it. Query parameter for GET, body field for POST
# From a server. A page sends x-embed-token instead.
curl "https://api.last-price.ai/api/experiments/EXPERIMENT_KEY/pricing?userId=USER_ID" \
-H "x-api-key: YOUR_API_KEY"
# Response
{
"userId": "USER_ID",
"experimentId": "EXPERIMENT_KEY",
"variant": "control",
"pricing": {
"plan": "control",
"price": 29,
"metadata": {}
}
}Create an experiment
Create a new pricing experiment. Variant names must be "control" and "experiment" to match Elo's assignVariant() output. weight is optional - Elo defaults to an even 50/50 split when weights are not provided.
- namestring, required
- Human-readable experiment name
- keystring, required
- Unique key used in API URLs
- variants[].namestring, required
- Variant name: must be "control" or "experiment", lowercase
- variants[].pricenumber, required
- Price for this variant
- variants[].weightnumber
- Relative traffic weight, normalised against the other arm, so 70/30 and 0.7/0.3 are the same split. Set both or neither (default: even). The engine resolves traffic to 1%, so 1/99 is the most uneven split accepted
curl -X POST https://api.last-price.ai/api/tenants/YOUR_TENANT_ID/experiments \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Q2 Pricing Test",
"key": "q2_pricing",
"variants": [
{ "name": "control", "price": 29 },
{ "name": "experiment", "price": 39 }
]
}'View experiment results
- tenantIdstring
- Optional tenant identifier. When present, it must match the credential's tenant
curl "https://api.last-price.ai/api/experiments/EXPERIMENT_KEY/results" \
-H "x-api-key: YOUR_API_KEY"
# Response
{
"experimentId": "q2_pricing",
"control": {
"views": 5000,
"conversions": 150,
"revenue": "4350.00",
"conversionRate": "3.00%",
"arpu": "29.00"
},
"experiment": {
"views": 5000,
"conversions": 120,
"revenue": "4680.00",
"conversionRate": "2.40%",
"arpu": "39.00"
}
}AI pricing optimization (Jale)
Jale is the AI pricing optimization engine. It learns elasticity from your own sales, simulates revenue, and makes data-driven price recommendations; for a model of your own, see Hosted models.
Price recommendations
curl -X POST https://api.last-price.ai/api/compute/price \
-H "Content-Type: application/json" \
-H "x-api-key: YOUR_API_KEY" \
-d '{
"function_name": "lastprice/jale-optimizer",
"input": {
"current_price": 49.99,
"product_type": "saas_subscription",
"market_data": {
"competitor_prices": [29, 39, 59, 79],
"current_conversion_rate": 0.025,
"monthly_visitors": 10000,
"churn_rate": 0.05
}
}
}'Elasticity analysis
curl -X POST https://api.last-price.ai/api/compute/price \
-H "Content-Type: application/json" \
-H "x-api-key: YOUR_API_KEY" \
-d '{
"function_name": "lastprice/jale-elasticity",
"input": {
"prices": [19, 29, 39, 49, 59],
"quantities": [500, 350, 200, 120, 60],
"product_category": "software"
}
}'Psychological pricing
curl -X POST https://api.last-price.ai/api/compute/price \
-H "Content-Type: application/json" \
-H "x-api-key: YOUR_API_KEY" \
-d '{
"function_name": "lastprice/jale-psychological",
"input": {
"base_price": 50,
"strategies": ["charm", "prestige", "anchor"]
}
}'Competitive price scraping
The built-in scraper collects competitor pricing data to feed into Jale's optimization engine.
# Setup
cd scraper
pip install -r requirements.txtfrom scrape_api import scrape_competitor_prices
# Scrape competitor pricing data
results = scrape_competitor_prices(
urls=["https://competitor1.com/pricing", "https://competitor2.com/pricing"],
selectors={"price": ".price-amount", "plan": ".plan-name"}
)
# Feed into Jale for optimization
import requests
requests.post("https://api.last-price.ai/api/compute/price", json={
"function_name": "lastprice/jale-optimizer",
"input": {
"current_price": 49.99,
"competitor_prices": [r["price"] for r in results]
}
}, headers={"X-Tenant-ID": "YOUR_TENANT_ID"})Hosted scraping jobs
Instead of running your own scraper, save a scraping job: a competitor's pricing page and the CSS selectors that read its prices. Last Price fetches it on your schedule (hourly, daily, weekly, or only when you run it), reads the prices, and adds each new one to the shared pool for you, earning 10 credits per validated price exactly as POST /api/jale/contribute does. On the dashboard, jobs appear on the Price Intelligence page. For a workspace without hosted scraping, every /api/scrape-jobs route answers 501 with the code hosted_scraping_not_enabled.
- Selectors. price_selector picks the elements that hold prices; the optional plan_selector picks the plan names, paired with the prices in page order. Prices like $1,299.00, €9,99 and 1.299 € are read with their currency; elements with no number are skipped. Test a pair before saving with POST /api/scrape-jobs/preview, which reads the page without saving or contributing anything.
- Polite fetching. Jobs fetch only public https pages, as LastPriceBot, after reading the site's robots.txt: a page it disallows is not fetched (the run fails with blocked_by_robots). At most three redirects, ten seconds and 2 MB per page.
- Model fallback. With extraction_mode css_with_llm_fallback, a run whose selectors find nothing asks a model to read the page's text instead, using your workspace's own Anthropic key when it has one and platform credits otherwise. The call is metered as llm.scrape-extract.
- Runs. Every run is kept with the prices it read, how many it added to the pool, duplicates already there from the last 24 hours, and why it failed when it did. A job that fails five runs in a row is paused; fix it and resume it with enabled: true. A workspace keeps at most 25 jobs. Prices a job added stay in the pool when the job is deleted.
- Access. Reading jobs and runs needs commerce:catalog:read; saving, changing, running, testing and deleting need commerce:configure. Agents can use the list_scrape_jobs, create_scrape_job, update_scrape_job, delete_scrape_job, run_scrape_job, list_scrape_job_runs and preview_scrape_job MCP tools.
curl -X POST https://api.last-price.ai/api/scrape-jobs \
-H "x-api-key: $LASTPRICE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Example Cloud",
"url": "https://example.com/pricing",
"price_selector": ".plan .price",
"plan_selector": ".plan h3",
"schedule": "daily"
}'
# Run it now
curl -X POST https://api.last-price.ai/api/scrape-jobs/$JOB_ID/run -H "x-api-key: $LASTPRICE_API_KEY"// Run response (abridged)
{
"run": {
"status": "succeeded",
"extraction": "css",
"prices": [ { "plan": "Starter", "price": 19, "currency": "USD", "raw": "$19/mo" } ],
"prices_found": 3,
"contributed": 3,
"duplicates": 0,
"credits_earned": 30,
"error_code": null
}
}Commerce control plane
The commerce control plane turns computed prices into actually-shipped prices. It sits on top of the core PriceRouter and automates the full pipeline: pull catalog data from your stores → observe competitor pricing → match items → apply pricing policies → queue proposals for approval → push approved prices back via connector adapters.
The pipeline runs in seven stages, orchestrated end-to-end:
| Stage | Purpose |
|---|---|
| Connectors | Pull catalog data from Shopify, Amazon SP-API, and memory adapters |
| Observations | Ingest competitor prices from PriceAPI, Keepa, or manual POST |
| Matching | Match catalog items to observed competitor items via Rosetta |
| Pricing Policy | Evaluate floor/ceiling/competitor rules; calls PriceRouter internally |
| Approvals | Queue proposals; auto-approve or hold for manual review |
| Execution Router | Push approved prices back to connectors with retry/backoff |
| Orchestration | End-to-end runCycle(); exposes /api/commerce/* routes |
Overview
Navigate to /commerce in the Oja dashboard to access the Commerce Control Plane UI. Tabs cover each pipeline stage. The Run cycle button at the top executes one full end-to-end pass (dry-run by default; set execute: true to actually push prices).
A scoped API key or token needs the scope for each step: commerce:catalog:read to read, commerce:configure to set up connectors, policies and data, commerce:proposal:draft to run a cycle, commerce:proposal:approve or commerce:proposal:reject to decide a proposal, and commerce:execute to push prices, including a cycle run with execute: true. A missing scope answers 403 insufficient_scope. Your dashboard session and unscoped keys have full access.
POST /api/commerce/cycle
{
"execute": true // set false for a dry-run (default)
}
// Response
{
"counts": {
"items": 42,
"observations": 120,
"matches": 38,
"proposals": 38,
"auto_approved": 12,
"executed": 12,
"failed": 0
},
"proposals": 38,
"matches": 38,
"executions": [
{ "proposal_id": "prop_...", "status": "executed", "attempts": 1, "last_response": {} },
{ "proposal_id": "prop_...", "status": "failed", "attempts": 2, "reason": "connector_error" }
]
}Connectors
In Commerce, Add connector offers the platforms available to the selected workspace. The form names the required credentials and checks them before saving. Credentials and metadata must be JSON objects. For Algolia, metadata also needs index_name.
Connector accounts link your storefronts to the pipeline. Supported platforms: shopify, amazon-sp, ucp-http (your own site, see Your own site), algolia (see Algolia), stripe (see Stripe), memory (testing).
# List connector accounts
GET /api/commerce/connectors
# Create a connector account
POST /api/commerce/connectors
{
"platform": "shopify",
"display_name": "My Shopify Store",
"credentials": {
"shop_domain": "mystore.myshopify.com",
"client_id": "...",
"client_secret": "..."
},
"metadata": {}
}
# Shopify credentials: a Dev Dashboard app's client_id and client_secret
# (Last Price fetches and refreshes its 24-hour token), or the access_token
# of a custom app created in the Shopify admin before 2026.
# Trigger a catalog sync
POST /api/commerce/connectors/{id}/syncEach store platform needs its own credentials, and a connection without them is refused with 400 credentials_missing, listing each field in missing_credentials:
shopify:shop_domain(the store'syour-store.myshopify.comaddress; any other host is refused), plusclient_idandclient_secret, or anaccess_token.amazon-sp:region,marketplace_id,seller_id,refresh_token,lwa_client_idandlwa_client_secret.ucp-http:base_url(a publichttpsaddress), and theapi_keyyour site checks.memory, the sample store: none.
A sync of an account that still lacks them answers 409 credentials_missing, and one whose store refuses the saved credentials answers 409 connector_unauthorized. Reconnect the account before syncing again. A 502 means the store itself failed; its error code is in code.
Algolia
If your store search runs on Algolia, link the product index as a connector with platform algolia. A catalog sync reads every product record with its price, and adds what your shoppers did with each product over the last 30 days: how often it came up in searches, clicks, add-to-carts, purchases, the rate of each and the revenue. You and your pricing agents see buyer interest at today's price next to each product, and the next sync shows how it moved after a price change.
POST /api/commerce/connectors
{
"platform": "algolia",
"display_name": "Store search",
"credentials": { "app_id": "YourAppID", "api_key": "..." },
"metadata": {
"index_name": "prod_products",
"currency": "USD",
"price_attribute": "price",
"analytics_region": "us",
"demand_days": 30
}
}
# Each synced catalog item carries:
"attributes": {
"shopper_demand": {
"window_days": 30, "tracked_searches": 3000, "clicks": 300,
"add_to_carts": 60, "purchases": 27, "click_through_rate": 0.1,
"purchase_rate": 0.009, "revenue": { "USD": 3375 }
}
}- Make an API key in Algolia for this with the
browseandanalyticspermissions, limited to the product index. Shopper demand needs an Algolia plan that includes the Analytics API and covers the 1,000 most returned products; without it the catalog still syncs. - Approved prices are not written to Algolia unless you set
"price_write_back": true(and add theaddObjectpermission). Your store's checkout charges its own price, so for a Shopify store, change prices through the Shopify connector and let Algolia copy them. - Building a shopping agent in Algolia Agent Studio? Add Last Price as an MCP tool: URL
https://api.last-price.ai/api/mcp/rpc, your Last Price API key as the authorization token. The agent can then callcompute_pricefor a quote.
Stripe
If your shop takes payment through your own Stripe account, link it as a connector with platform stripe. That covers a site you built yourself, a site an AI site builder made for you, and Stripe payment links. A catalog sync reads every active product that has a fixed price, and an orders sync reads your completed checkouts, so Last Price learns from what sold at which price. When you approve a new price, Last Price makes it the product's default price in Stripe.
POST /api/commerce/connectors
{
"platform": "stripe",
"display_name": "My shop",
"credentials": {
"secret_key": "rk_live_..."
},
"metadata": {
"price_write_back": true
}
}
# Then, with the id it returns:
# read products and their prices
POST /api/commerce/connectors/
{id}/sync
# read completed checkouts
POST /api/commerce/connectors/
{id}/orders/syncAlready connected your Stripe account to Last Price on the Monetization page? Link that account instead, with no key to copy: choose "Stripe account connected to Last Price" in Commerce, Connectors, or send "connection": "workspace" as the only credential. Last Price uses the account your workspace connected, never an account id you type in. It needs write access: Connect with Stripe asks for it, and an account opened for owner payouts has it. If the account is disconnected or replaced later, syncs and write-back stop until you connect it again.
POST /api/commerce/connectors
{
"platform": "stripe",
"display_name": "My shop",
"credentials": {
"connection": "workspace"
},
"metadata": {
"price_write_back": true
}
}
# 409 stripe_not_connected: connect the account
# on the Monetization page first- Linking with a key instead? Make a restricted key in your Stripe dashboard (Developers, API keys, Create restricted key) with Read on Products, Prices and Checkout Sessions. Add Write on Products and Prices only if you want approved prices written back.
- Stripe prices cannot be edited, so a write-back creates a new price with the same currency, billing interval and tax setting, moves the old price's lookup key to it, and makes it the default. Checkouts that ask for the product's default price or its lookup key charge the new price straight away. A checkout that names the old price id keeps charging the old price until your site changes.
- The old price stays active, so existing payment links and subscriptions keep working. Set
"archive_previous_price": trueto archive it instead. Every price Last Price creates is named "Set by Last Price" in your Stripe dashboard. - Only the products, prices and checkout totals are read. Who bought is kept as a one-way hash, never a name or an email.
Built your shop with an AI site builder or an AI agent? Paste this to it so your checkout follows the prices you approve in Last Price:
When a customer checks out, charge each product's current default price in Stripe. Look the price up when the checkout starts (the product's default_price, or its lookup key if it has one). Never save a price id in the site's code or database. My prices change in Stripe when I approve them in Last Price, and the checkout must follow without a new deploy.Your own site
A site with no store platform behind it can still take live prices: a site you wrote, or one an AI site builder made (Foundable's Ted, Lovable, Bolt). The site answers four small requests, and you link it as a connector with platform ucp-http. Last Price reads its products and sales, and when you approve a price it sends the new price to the site, which charges it from then on.
Every request carries
Authorization: Bearer <your key>.
Refuse any other key with 401.
GET /health
-> 200 {}
GET /catalog?cursor=&limit=
-> { "items": [
{ "external_id": "nightly-check",
"title": "Nightly check",
"current_price": 29,
"currency": "EUR" } ],
"next_cursor": null }
POST /prices
{ "external_id": "nightly-check",
"new_price": 32,
"currency": "EUR" }
-> { "ok": true }
GET /orders?since=&cursor=&limit=
Orders placed or changed at or
after since, oldest first.
-> { "orders": [
{ "id": "ord_1",
"placed_at": "2026-10-24T10:00:00Z",
"updated_at": "2026-10-24T10:05:00Z",
"status": "paid",
"currency": "EUR",
"total": 58,
"customer_id": "c_42",
"channel": "web",
"lines": [
{ "external_id": "nightly-check",
"sku": "NC-1",
"title": "Nightly check",
"quantity": 2,
"unit_price": 29 } ] } ],
"next_cursor": null }
Both lists: return at most limit
entries (100 when it is missing),
and a next_cursor while more remain.POST /api/commerce/connectors
{
"platform": "ucp-http",
"display_name": "My site",
"credentials": {
"base_url": "https://mysite.com/api/last-price",
"api_key": "<the key your site checks>"
}
}
# Then, with the id it returns:
POST /api/commerce/connectors/
{id}/sync
POST /api/commerce/connectors/
{id}/orders/sync- Make up a long random key and keep it as one of your site's secrets (in Foundable: Build, Tools, Secrets). Give the same key to Last Price as
api_key. It only lets Last Price talk to your site; it is not a Last Price key. - The address must be public and use
https. Last Price never follows a redirect from it. statusispaid,pendingorcancelled. Send an order again, with a newupdated_at, when it is paid or refunded, so the sale is counted right.customer_idis optional and is stored only as a hash: send your own customer number, never an email address. A page longer than thelimitasked for (at most 250) is refused, so no order is skipped.- Your site stays in charge: it can refuse a price with
{ "ok": false, "error": "below_cost" }, and Last Price records the refusal. - Once linked, press Check on the connector (or call
POST /api/commerce/connectors/{id}/check, or the MCP toolcheck_commerce_connector). It asks your site for its health, its first products and the last day's orders, changes nothing, and says which request answered and which did not, with your site's own error.
Paste this to your AI site builder and it will add the four requests for you:
Connect my site to Last Price so my prices can change without a new deploy. Add a secret named LAST_PRICE_SITE_KEY with a long random value and show it to me once. Under /api/last-price add four server routes that refuse any request whose Authorization header is not "Bearer " plus that secret: GET /health returns {}; GET /catalog returns the products I sell as { items: [{ external_id, title, current_price, currency }], next_cursor }; POST /prices takes { external_id, new_price, currency }, saves new_price as that product's price in the database and returns { ok: true }; GET /orders returns the orders placed or changed at or after the since parameter, oldest first, as { orders: [{ id, placed_at, updated_at, status, currency, total, customer_id, channel, lines: [{ external_id, sku, title, quantity, unit_price }] }], next_cursor }, where status is "paid", "pending" or "cancelled" (use "cancelled" for refunds too) and customer_id is my internal customer number, never an email. Both lists return at most the limit parameter (100 when it is missing) and a next_cursor string while more remain, otherwise null. Checkout must always read the price from the database, never from code.Store sales
A Shopify, Stripe or your own site connector can send its orders back to Last Price, so every sale becomes demand data for learned prices without anyone reporting it. Each order is stored with its lines: the item (the variant id the catalog uses), quantity, price charged and time. The customer is kept only as a hash of the store's customer id; names, emails and addresses are never stored. Give your Shopify app the read_orders scope.
Orders arrive two ways, and both land on the same record. Webhooks deliver them as they happen; subscribe orders/create, orders/updated, orders/paid and orders/cancelled to the address shown on the account in Commerce, Connectors. A pull backfills the last 60 days and catches anything a webhook missed. Webhooks your app subscribes to are signed with its client secret; webhooks created in the store admin are signed with the key shown there, so add it to the account as webhook_secret.
# Pull orders changed since the last pull (or the last 60 days);
# the body is optional
POST /api/commerce/connectors/{id}/orders/sync
{ "since": "2026-10-01T00:00:00Z" }
# Shopify sends order webhooks here
POST /api/webhooks/shopify/{id}
# Your app's shopify.app.toml
[webhooks]
api_version = "2026-07"
[[webhooks.subscriptions]]
topics = ["orders/create", "orders/updated", "orders/paid", "orders/cancelled"]
uri = "https://api.last-price.ai/api/webhooks/shopify/{id}"Two cart attributes make the data sharper. Set lp_quote_request_id to the request_id of the price the buyer saw, and the sale is tied to that exact quote. Orders from your own buyers, such as agents you run to test the store or staff purchases, should not teach a price: tag them lp-own-buyer or set the cart attribute lp_own_buyer, and they are recorded but left out of learning.
// In the storefront, before checkout
await fetch('/cart/update.js', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ attributes: { lp_quote_request_id: quote.request_id } }),
});Catalog
Catalog items are pulled from connectors during a sync. Each item carries a current price, SKU, and optional GTIN used for competitor matching.
GET /api/commerce/catalog?limit=200
// Response
{
"items": [
{
"id": "ci_...",
"connector_account_id": "ca_...",
"external_id": "shopify_prod_001",
"title": "Blue Widget",
"sku": "BLUE-WGT-001",
"gtin": "00012345678905",
"current_price": 29.99,
"currency": "USD"
}
]
}Observations
Competitor observations are ingested automatically by the observation sources (PriceAPI, Keepa) during a cycle, or pushed manually via the API.
# Manually ingest a competitor observation
POST /api/commerce/observations
{
"source": "manual",
"competitor": "acme-widgets",
"gtin": "00012345678905",
"observed_price": 24.99,
"currency": "USD"
}
// 201: the stored row, with its "id"
# Delete one, such as a test row
DELETE /api/commerce/observations/{id}Pricing policies
Policies define the rules that produce price proposals. Each policy has an approval_mode: manual (human reviews all), auto (auto-approve when delta is within auto_approve_max_delta_pct), or shadow (log-only, never executes).
POST /api/commerce/policies
{
"name": "Undercut competitors by 2%",
"rules": [{ "id": "r1", "kind": "undercut_competitor", "by_pct": 2 }],
"approval_mode": "auto",
"auto_approve_max_delta_pct": 10,
"is_active": true,
"scope": {}
}
# Dry-run a policy against current catalog
POST /api/commerce/policies/{id}/evaluateA policy needs at least one rule, and each rule a known kind: undercut_competitor (by_pct), match_competitor, beat_lowest_by_abs (by_abs), percent_off_msrp (off_pct), router or fixed (price). Percentages run from 0 to 100, prices are never negative, and floor_price cannot be above ceiling_price; anything else is refused with 400 validation_failed naming each field.
Approvals
Proposals generated by the pricing policy engine land in the approval queue with status proposed. Review and approve or reject them individually, or let auto-approval handle them.
GET /api/commerce/proposals?limit=200
POST /api/commerce/proposals/{id}/approve
{}
POST /api/commerce/proposals/{id}/reject
{ "reason": "price too aggressive" }Proposed prices are rounded to the currency's minor units (cents for USD). Each item has at most one pending proposal: when a cycle finds a new price, the older pending one is marked expired with reason superseded, and an item whose price would not change gets none. Every proposal has an expires_at, seven days after it was made unless the cycle set expires_in_seconds; past it the proposal lists as expired and approving it answers 409 proposal_expired. Two approves or rejects racing on one proposal never both win: the second answers 409.
Execution
The execution router drains all approved proposals through the connector adapters, applying exponential backoff on transient failures. Terminal failures move the proposal to failed and capture the adapter response in the audit log.
POST /api/commerce/execution
// Drains all approved proposals
GET /api/commerce/audit?limit=200
// Append-only event log for the entire pipelineAn executed price is written to the catalog at once, so GET /api/commerce/catalog shows what the store now charges without a sync. The sample store executes like a real one, whichever server answers the request.
Run pipeline cycle
A single POST /api/commerce/cycle runs every stage in order: pull catalogs → pull observations → match snapshots → decide prices → create proposals from decisions → execute approved. All stages are logged to the audit table. The dashboard Run cycle button calls this endpoint with execute: false (dry-run) by default.
POST /api/commerce/cycle
{ "execute": true }
// Cycle summary response
{
"counts": {
"items": 42, "observations": 120, "matches": 38,
"proposals": 38, "auto_approved": 12, "executed": 12, "failed": 0
},
"proposals": 38,
"matches": 38,
"executions": [{ "proposal_id": "prop_...", "status": "executed", "attempts": 1 }]
}Commerce tools (MCP)
An agent can read and run the whole commerce pipeline over MCP, with the same scopes the dashboard uses: commerce:catalog:read to read, commerce:configure to change settings, and the proposal and execute scopes for the steps that decide and act. A sandbox key is refused until a person claims the workspace.
list_commerce_cataloglists the items the pipeline tracks, andlist_commerce_observationsthe competitor prices it collected.list_commerce_policiesandget_commerce_policyread the pricing policies.list_commerce_proposalslists the price proposals, filtered by status.list_commerce_audit_eventsreads the commerce trail for a proposal or the whole workspace. It is separate fromlist_audit_events.list_commerce_connectorslists linked stores, never their credentials, and the platforms you can connect.create_commerce_policy,update_commerce_policyanddelete_commerce_policymanage the pricing policies, andtest_commerce_policydry-runs one against an item and competitor prices without saving anything.add_commerce_observationrecords a competitor price by hand.run_commerce_cycleruns the pipeline once. It is a dry run unlessexecuteis true, which also pushes approved proposals to the store and needs the execute scope.approve_commerce_proposalandreject_commerce_proposaldecide a drafted proposal; a rejection needs a reason.execute_commerce_proposalsthen pushes the approved ones to the store, which changes live prices.create_commerce_connector,set_commerce_connector_active,sync_commerce_connectorandsync_commerce_orderslink, pause and sync stores, andcheck_commerce_connectortries a linked store read-only, step by step, before its first sync.seed_commerce_sampleloads a demo store so a first cycle has something to price.
Store credentials passed to create_commerce_connector are kept encrypted and never returned, but they pass through the agent's conversation, so give an agent a key made for the purpose. Every decision is recorded in the commerce audit trail with who made it.
Pricing controls
Settings that shape every price your workspace is given: what the optimizer learns from your buyers, the limits a price may not cross, what happens when a price goes unused, and which model computes it.
Learned pricing
In the app: Learned pricing
Last Price learns how sensitive your buyers are to price, per product and pooled across the workspace, from the quotes you report as accepted or rejected and from what buyers did after the quotes nobody reported on. Turned on, the default optimizer prices from what it learned instead of a generic assumption. It is off until you turn it on, and it never moves a price without telling you.
- Every night, quotes from the last 90 days with an outcome are used to estimate the sensitivity, with a sample size and a 95% interval. An outcome inferred from a later order or re-quote counts half as much as a reported one.
- Counter-offers and accepted offers from offer negotiations are not learned from: a counter's price depends on what that buyer offered, so it says how far one buyer would come, not how buyers react to your price. A sale after a negotiation is still credited to it.
- An estimate is only used when it can be trusted: at least 30 quotes with an outcome and at least 5 of each, prices that actually varied, and an interval clearly below zero. Otherwise the reason is shown, with how far it is from each requirement.
- The optimizer goes only a little past the prices an estimate was learned from, so a slope measured over small price changes is not stretched to a large one.
- A
metadata.elasticityyou send still wins, guardrails still cap every price, and the explanation says when a price came from a learned estimate. - Learning discount, off by default: with learned pricing on and a reported outcome for at least 30% of your last 30 days' quotes (at least 50 quotes), you get 10% of each day's call spend back as bonus credit the next day, at most 25 USDC a day. It shows in your balance history as “learning discount” with the date.
How new estimates are applied
- Automatically: a new estimate prices at once, and you are notified of every change.
- After I approve: each change waits in the Price changes list, and prices keep the last estimate you approved until you approve the new one. Choose it before or after turning learning on; it is one click away.
- Not chosen yet: turning learning on without choosing keeps the mode you chose before. If you never chose one, learned pricing runs in preview: it learns every night and lists each change with the status preview, but no price moves and no change email is sent. It stays in preview until you choose, or until price exploration is on: exploration tries prices near the current one so estimates stay accurate, and learning without it was shown to cost about 19% of profit in a price-sensitive market. Only then does a workspace that never chose apply new estimates automatically, and only while you have not turned exploration off.
- Turning learning off keeps your choice for next time.
modein the API answer says which applies now:off,preview,autoorapprove.
Preview, history and approvals
- While learning is off or in preview, the page shows what it would do: the price the optimizer would give with each estimate against what it gives today. While it is off, you are told once when learned pricing is ready to preview.
- Every time a usable estimate starts, changes or stops, a change is recorded with the old and new example price at the typical current price it was learned from, how many quotes it used, and its status: applied, waiting for approval, approved, rejected, replaced by a newer one, or preview.
- A waiting change is approved or rejected from the list. A rejected estimate is not asked about again, and a newer estimate replaces one still waiting. Each decision records who made it: a person, an agent or an API key.
- "How buyers react to price" charts how often reported quotes were accepted at each price against the current one, with the fitted line, what a 10% raise does to sales, and how the estimate has moved over time.
- Agent buyers (off by default): learning can also fit separate estimates from the quotes you sent with
buyer_type: "agent", pooled and per product, and price agent buyers from them. They are listed as "Agent buyers: …" and recorded, approved and announced like any other estimate; in the API they carrybuyer_segment: "agent". Until agents' own estimate is usable, agents are priced like everyone else. - Collusion guardrail (off by default; the owner switches it on): learning uses only the price tests made within each day, never how your price moved from day to day. When rivals' prices move with yours, day-to-day moves make buyers look less price-sensitive than they are and pull prices above the competitive level; same-day tests do not. It needs price tests within the day to learn anything, and it learns more slowly where no rival reacts.
Notifications, email and the webhook
- Applied and waiting changes appear in Notifications.
- Owners and admins, and agents with an inbox that own or administer the workspace, get one email after a night with changes and a reminder for a change still waiting after three days. Each recipient gets their own message. Turn it off on the Learned pricing page or with the unsubscribe link in the email, which asks you to confirm; mail apps with one-click unsubscribe do it in one step.
- The signed webhook event
learned_elasticity.changedis sent for each applied or waiting change. Its payload carrieschange_idand, for a waiting change, adecideblock with the approve and reject calls, so an agent can decide in one step.
For agents: API and MCP
- Reading needs
pcn:routing:read; changing the settings and deciding changes needspcn:routing:writeor a workspace owner or admin. An agent that registered its own workspace, unclaimed, can do all of it with its own key. - Endpoints:
GETandPUT /api/learned-elasticity(enabled,apply_mode,email_notifications),GET /api/learned-elasticity/changes(?status=pending,limit),POST /api/learned-elasticity/changes/{id}/approveand/reject, andGET /api/learned-elasticity/curve. - MCP tools:
get_learned_pricing,set_learned_pricing,list_learned_price_changesanddecide_learned_price_change.
# Read the settings, estimates and recent changes
curl https://api.last-price.ai/api/learned-elasticity \
-H "x-api-key: YOUR_API_KEY"
# Turn learned pricing on, approving each change first
curl -X PUT https://api.last-price.ai/api/learned-elasticity \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"enabled": true, "apply_mode": "approve"}'
# List what waits for a decision, then approve one
curl "https://api.last-price.ai/api/learned-elasticity/changes?status=pending" \
-H "x-api-key: YOUR_API_KEY"
curl -X POST https://api.last-price.ai/api/learned-elasticity/changes/CHANGE_ID/approve \
-H "x-api-key: YOUR_API_KEY"Pricing analysis
In the app: Learned pricing, Pricing analysis
A free analyst reads your workspace's own quotes, outcomes, estimates, guardrails and approvals and says what is ready, what is stuck and what to do next, most urgent first. It uses no AI model, costs nothing, and changes nothing: you, or your agent, act on what it finds.
- Findings: a learned estimate ready while learned pricing is off; what a stuck estimate still needs (for example 12 more quotes with a reported outcome); too few quotes with a reported outcome (under 20% over the last 30 days); guardrails that moved at least half of a product's quotes (over at least 20 quotes); approvals waiting, or expiring within 48 hours. At most 50 findings are returned.
- Each finding has a
severity(action,watchorinfo), a plainmessage, thenumbersit states, and anext_stepnaming the call that would act on it. Product ids are quoted as data. - Per-product findings list up to 10 products; the rest are summed in one finding with
numbers.summaryset tomore_products. - Reading needs the
pcn:routing:readscope; an unclaimed agent sandbox cannot call it until it is claimed. Agents get the same answer from the MCP toolget_pricing_analysis.
curl https://api.last-price.ai/api/pricing-analyst/findings \
-H "Authorization: Bearer lp_<hex>"Preview a price change
In the app: Learned pricing, Preview a price change
Before you change a function's price, replay the new price over the calls it already served and see what each customer would have paid. Every call keeps the units it was metered on, so the replay uses the same formula that charged it: once at today's price and once at the new one. The difference is your change alone. Nothing is saved or charged; to use a price, save it on the function (PATCH /api/functions/{id}).
- function_idstring
- One of your functions. Leave it out to move every function you own by change_pct.
- change_pctnumber
- Move the price by this percent, -90 to 1000. Send this, or a new price below. A change that would take a function's multiplier outside 0.0001 to 100 is refused.
- cost_per_unitnumber
- A new cost per unit for function_id, up to 9999.999999.
- cost_multipliernumber
- A new multiplier for function_id, 0.0001 to 100.
- from, tostring
- The window of past calls, as ISO 8601 dates (a date-only to covers that whole day). Default the last 30 days; up to 366 days.
- threshold_usdnumber
- Count the customers whose spend in the window would newly reach this amount or drop below it, and those already above it.
- moversinteger
- How many of the biggest movers to list, 1 to 25. Default 10.
- The answer gives totals at today's price and at the new one, what the calls were charged when served, the change per function, how many customers would pay more, less or the same, the spread of their changes, the threshold crossings, and the customers whose bill moves most.
- A customer is a workspace that called your function, or a paying wallet for pay-per-call buyers. They are lettered by how much their bill moves ("Customer A"), never named;
customer_refstays the same across previews so an agent can match runs. Your own calls count in the totals but are not listed as a customer. Test calls (keyless calls with a tester tag, the demo) are left out. confidencesays how far to trust the replay. A charged call with no usage recorded is left out of both prices and counted; a call charged a different amount at the time (an earlier price, a free first call or a free-tier rule) is compared with today's price rather than with what was paid. The replay keeps every past call: it does not guess how many buyers a new price would win or lose.- The new multiplier is rounded to the four decimals a function stores, so the preview is what saving it would charge. A preview that runs longer than 15 seconds answers 503
preview_timeout: try a shorter window or one function. GET /api/pricing/previewlists your functions with today's prices. Both need thebilling:readscope. Agents get the same answer from the MCP toolpreview_price_change.
curl -X POST https://api.last-price.ai/api/pricing/preview \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{"function_id": "FUNCTION_ID", "change_pct": 10, "from": "2026-09-01", "to": "2026-09-30", "threshold_usd": 100}'Cut advisor
In the app: Learned pricing, Cut advisor
AI agent platforms that buy for people (shopping agents, agent marketplaces) plan to charge sellers a cut of each sale, from about 2.5% to 30%. If a platform shows sellers who pay a bigger cut more often, choosing the cut becomes a pricing decision. The cut advisor shows what each cut would earn you under your own numbers. It is a simulation, not a forecast: no platform publishes how it ranks sellers, so you state how many more sales one extra point of cut brings, and it also runs half, double and none of that. It changes nothing. The cut advisor is off by default; write to support@last-price.ai to use it.
- pricenumber, required
- Your own price before any channel cut.
- unit_costnumber, required
- What one unit costs you.
- current_cut_pctnumber, required
- The cut the channel takes today, 0 to 60.
- base_unitsnumber, required
- Units sold through the channel per period at the current cut.
- visibility_per_point_pctnumber
- Your assumption: percent more channel sales per extra point of cut, 0 to 50. Default 2.
- passed_on_pctnumber
- How much of the cut is added to the price the buyer sees, 0 to 100. Default 100.
- price_elasticitynumber
- How channel buyers respond to price, -20 to 0. Default -1.5.
- min_cut_pct, max_cut_pct, step_pctnumber
- The cuts to try. Default 2.5 to 30 in steps of 0.5, widened to include your current cut.
- channelstring
- The channel name, put in the channel rate the answer suggests.
- The buyer pays
price / (1 - cut * passed_on_pct / 10000), as channel rates price it, and you keep that price less the cut and your unit cost. - The answer gives the profit at each cut, the
recommendedcut (best under your assumption), therobust_cut_pct(smallest worst case across the four scenarios), the break-even (how many more sales one extra point must bring to pay for itself), and achannel_rateready to save withPUT /api/channel-rates. GET /api/cut-advisorsays whether it is on for your workspace;POSTanswers 404not_releaseduntil it is. Both need thepcn:routing:readscope. Agents get the same answer from the MCP toolsimulate_agent_cut.
curl -X POST https://api.last-price.ai/api/cut-advisor \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{"price": 40, "unit_cost": 22, "current_cut_pct": 10, "base_units": 100, "visibility_per_point_pct": 2}'Product categories
In the app: Product categories
Put each of your products in a category from a short tree (software, agent services, ecommerce goods, digital goods, professional services, connectivity, other; at most three levels), so what Last Price learns from your buyers can be read by kind of product. Categories and outcomes are your workspace's own: nothing is pooled with, shared with or read from another workspace.
- Your products are the product ids your quotes send in
context.product_idonce the nightly learning run has seen them, and the items a connected store syncs (keyed by SKU). - A product with no confirmed category gets one suggested from keywords in its name, marked as suggested and never saved until you confirm it. A name with no keyword gets none.
- Each category shows how many outcomes its products have toward the 30 an estimate needs, counting a parent's subcategories too. An outcome inferred from what a buyer did counts half of a reported one.
- Under your products, All categories shows the whole tree, empty branches included, with each category's product count and progress. It starts at the top level; open a branch with its arrow button, or use Expand all.
- Reading needs the
pcn:routing:readscope; confirming needspcn:routing:writeand, from the dashboard, a workspace owner or admin. - Agents use the MCP tools
list_product_categoriesandset_product_category.
# Read the tree, your products and progress per category
curl https://api.last-price.ai/api/product-categories \
-H "Authorization: Bearer lp_<hex>"
# Confirm a product's category
curl -X PUT https://api.last-price.ai/api/product-categories \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{"product_id": "sku-9", "category_id": "api-metering"}'Price guardrails
In the app: Settings, Price guardrails
Save limits once for the workspace and every price respects them, whichever pricing function computes it: compute calls, price router calls, batch items, pay-per-call requests, MCP compute_price calls and the alternatives returned too.
- Your own margin: send
metadata.unit_costwithmetadata.target_margin_pctand the price is at least unit_cost / (1 minus margin), with or without saved guardrails: a cost of 100 at 20% is never priced under 125. - Cost inputs are read or refused: a unit cost that is not a number or is negative, a margin outside 0 to under 100, or either one sent anywhere but
context.metadatais a 400validation_failednaming the field. - The explanation leads with the price returned: when a limit moved it, the first sentence says so, such as "The price returned is 64.99 USD, raised from the function's 57.15 USD by the workspace minimum margin".
- When a change applies: a save answers
applies_within_seconds, and with instant settings it is 1. GET answers anETag; send it back asIf-Matchon PUT and a save that would overwrite someone else's newer one answers 412precondition_failed. - The margin floor applies to every workspace now. The cost checks, the explanation and instant settings are switching on workspace by workspace.
- max_change_pctnumber | null
- The most a price may move from the current price, in percent (above 0, up to 1000). Default null: no limit.
- min_margin_pctnumber | null
- Minimum margin over metadata.unit_cost, in percent (0 up to under 100). Default null: none.
- never_below_costboolean
- Never price below metadata.unit_cost when a call sends it. Default true.
- band_lower_rationumber
- Lowest price the default optimizer searches, as a share of the current price (above 0, up to 1). Default 0.5.
- band_upper_rationumber
- Highest price the default optimizer searches, as a multiple of the current price (1 to 100). Default 2.
PUTsaves the guardrails whole: a field you omit takes its default. Unknown fields are refused.- When a guardrail moves a price, the response trace and the explanation name it.
- Reading needs the
pcn:routing:readscope and saving or removing needspcn:routing:write. - With nothing saved, only the optimizer's own 0.5x to 2x range and the never-below-cost rule apply.
- The Price guardrails page in Settings saves the same values and works out the lowest and highest price allowed for an example product as you type, the way the API applies them. Routing policies links to it.
# Save the workspace guardrails
curl -X PUT https://api.last-price.ai/api/price-guardrails \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{"max_change_pct": 15, "min_margin_pct": 20, "never_below_cost": true}'
# Read what is saved (the response also lists the defaults), and remove it
curl https://api.last-price.ai/api/price-guardrails -H "Authorization: Bearer lp_<hex>"
curl -X DELETE https://api.last-price.ai/api/price-guardrails -H "Authorization: Bearer lp_<hex>"Sales playbook
In the app: Settings, Sales playbook
Write your discount policy and commercial terms the way you would for a new salesperson, and every price and counter-offer your workspace gives is held to them. The playbook is read while the sales-playbook-pricing release is on for your workspace (off by default; ask us to switch it on). While it is off, the playbook is saved and nothing prices from it.
- listPricestring
- For example "$1,200/mo". Discounts are taken from a request's own current_price, or from this when a request has none (same currency only).
- standardDiscountstring
- For example "10%". The only discount allowed below the minimum commitment.
- maximumDiscountstring
- For example "25% with VP approval". The floor: no price or counter goes below the list price less this.
- volumeDiscountsstring
- For example "100+ seats 10%, 500+ seats 15%". A buyer at a tier gets it in the asking price.
- annualCommitmentstring
- For example "15% off annual prepay" or "2 months free". Applied for a commitment of a year or more.
- paymentTermsstring
- For example "Net 30", "due on receipt" or "annual prepay". Attached to every counter-offer.
- minimumCommitmentstring
- For example "12 months", "10 seats" or "$5,000". Below it only the standard discount applies.
- Pricing. Compute, batch, price router chain and agent pricing calls are held between the floor (list price less the maximum discount) and the ceiling (list price less any volume or annual discount the deal is entitled to). Send
metadata.quantity(orseats),metadata.billing_period: "annual"andmetadata.commitment_monthsto describe the deal. - Your price guardrails (cost, margin, change limit) still win: the playbook never puts a price below them. When the playbook moved a price, the response carries
sales_playbook(rule, floor, ceiling, entitled discount), the trace has aplaybookstep, and the explanation, the logged quote and the value receipt say so. - Negotiation. Counter-offers never go below the playbook floor, a buyer's
quantity,annual_commitmentandterm_monthsearn the volume and commitment terms, and each answer carries amessagewritten from your value proposition, ROI promise and pain points, and the buyer-safeterms. A buyer never sees the standard or maximum discount. - Negotiation agents get the playbook's voice and terms in their instructions, and an offer whose terms differ from the playbook (payment terms, a term below the minimum commitment) is flagged.
- Could not read. Each field is read on its own; a field that cannot be read ("whatever the VP says") is shown as Could not read in Settings and in the API answer, and is ignored until it is rewritten. The other fields still apply.
- Reading needs the
pcn:routing:readscope and saving needspcn:routing:write(an owner or admin in the app). Agents use the MCP toolsget_sales_playbookandupdate_sales_playbook(claimed workspaces only).
# Change some fields: one you send replaces the text, "" clears it, one you leave out is kept
curl -X PATCH https://api.last-price.ai/api/sales-playbook \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"listPrice": "$1,200/mo", "maximumDiscount": "25% with VP approval", "paymentTerms": "Net 30"}'
# Read it back with what pricing reads from each field, the price band and the buyer terms
curl https://api.last-price.ai/api/sales-playbook -H "Authorization: Bearer YOUR_TOKEN"Price exploration
In the app: Learned pricing, Price exploration
A price that never changes teaches nothing: learned pricing can only measure how buyers react to price when prices move. With price exploration on, prices for the same product vary slightly from quote to quote, by up to the rate you set either way (10% by default, which is also the most), so Last Price can learn what your buyers will pay. The variation is never below your unit cost and always stays inside your own limits and your price guardrails, and you can turn it off at any time. Once learned pricing has measured enough about a product (the nightly fit stores what it measured beside each usable estimate), the variation is steered instead (Thompson sampling) toward the price it expects to earn most, by up to 10% either way and never more than 10% past the prices already tried.
- enabledboolean | null
- On or off. null (the default) means on while learned pricing sets live prices (automatic or approve, not preview).
- ratenumber | null
- The most a price may vary either way, as a fraction from 0.005 to 0.1 (0.03 is 3%). null means 0.1, the default. A higher value is refused with a 400.
- beyond_pctnumber | null
- With the analyst brief. How far past the prices a learned estimate was measured at the optimizer may go, in percent, from 1 to 10 in steps of 0.5. null means 5, the default. 10 is the most because it is the trust region the steered variation was evaluated in.
- Only learned and optimizer prices vary: the default optimizer (
lastprice/jale-optimizer) andlastprice/jale-elasticity, the functions learned pricing learns from. A price from another built-in, from your own functions, or withmin_priceequal tomax_pricenever varies. - Each call draws afresh, from a cryptographic random source, and nothing about the buyer is used, so the variation cannot be aimed at anyone.
- The variation is applied after the pricing function and before your
min_price/max_priceand the guardrails, which still hold the price. A downward move stops atmetadata.unit_cost. - Send
"options": {"no_explore": true}to give one call its price exactly as computed. A call that explores is never answered from, or stored in, the response cache. - The response carries
exploration(scheme,rate,factor,propensityandbase_price, the price before the variation) and the trace has anexplorestep. The logged quote keeps the factor, scheme and propensity, and these quotes are what learned pricing learns from. - It runs where the feature is on for your workspace; elsewhere the setting is saved and nothing varies. Reading needs the
pcn:routing:readscope; saving needspcn:routing:writeand, from the dashboard, a workspace owner or admin. Agents use the MCPget_price_explorationandset_price_explorationtools. - Reach past tried prices (
beyond_pct) applies to every product with a usable estimate, whether or not exploration is on. It shows on the Price exploration card, and saving it answers 404not_releasedwhere the analyst brief is off for your workspace.
# Read what applies now
curl https://api.last-price.ai/api/learned-elasticity/exploration \
-H "Authorization: Bearer lp_<hex>"
# Turn it off (or send {"rate": 0.05} for a 5% variation)
curl -X PUT https://api.last-price.ai/api/learned-elasticity/exploration \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{"enabled": false}'
# Price one call exactly as computed
curl -X POST https://api.last-price.ai/api/compute/price \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{"context": {"currency": "USD", "current_price": 100}, "options": {"no_explore": true}}'Buyer-aware pricing
In the app: Learned pricing, Buyer-aware pricing
Different buyers accept different prices. An AI agent comparing ten sellers walks away from a high price sooner than a person buying once. Learned pricing fits one demand curve per product; buyer-aware pricing goes further and learns a curve per kind of buyer, then prices each quote for who is asking. Two models are fitted every night from your own quotes and their outcomes: the contextual bandit (from 100 outcomes, Thompson sampling per context, so it keeps trying prices it is unsure of) and the boosted demand model (gradient-boosted trees, from 2,000 outcomes, which finds interactions between fields). With hosted models switched on, the demand model you promoted last prices through the same path as hosted.
- modestring | null
- shadow (the default): each model prices every quote on the side and only logs its price; live: the chosen model sets learned and optimizer prices; off: nothing runs. null goes back to shadow.
- modelstring | null
- Which model prices in live mode: auto (a promoted hosted model, else the bandit, else the boosted model), bandit, boosted or hosted. null goes back to auto.
- featuresstring[] | null
- The request fields the models may read: buyer_type and channel by default; customer_segment and geo only when you add them. At least one. null goes back to the default.
- Start in shadow. Every quote then logs what each model would have charged (
buyer_aware_priceson the quote), and the Learned pricing page shows, per model and buyer type, how its price compared with the price quoted. Go live when you like what you see. - In live mode the model replaces price exploration for that quote. Its price stays inside the exploration band around the learned price, never below
metadata.unit_cost, and yourmin_price/max_priceand price guardrails still hold it. Only the learned and optimizer functions are priced this way, never a fixed price or your own functions. - The context is read from the request:
buyer_type(a namedbuyer_agentcounts as an agent),channel, and, if you add them,customer_segmentandgeo. A value gets its own column only once it has been seen 20 times; anything rarer is treated as other. Nothing else about the buyer is read. - With a feature contract saved, the models also learn from up to 8 of its fields, in the contract's order (such as
metadata.device.type), from the labels each quote kept, and read the same labels off each new request. A contract field that is one of the four above follows the setting here, so segment and location still stay off until you turn them on. - Customer segment and location are off by default: in the EU, pricing consumers by location is restricted and personalised prices must be disclosed to them. Turn them on only where that is allowed and disclosed.
- The response carries
buyer_aware_pricing(mode,context,modelin live mode, andshadow, each other model's price) and the trace has acontextstep. A live price also carriesexplorationwith schemecontextual, and is never answered from, or stored in, the response cache."options": {"no_explore": true}turns it off for one call. - It runs where the feature is on for your workspace. Reading needs the
pcn:routing:readscope; saving needspcn:routing:writeand, from the dashboard, a workspace owner or admin. Agents use the MCPget_buyer_aware_pricingandset_buyer_aware_pricingtools.
# Read the mode, what each model learned and the last 30 days
curl https://api.last-price.ai/api/learned-elasticity/buyer-models \
-H "Authorization: Bearer lp_<hex>"
# Go live with the contextual bandit, reading buyer type only
curl -X PUT https://api.last-price.ai/api/learned-elasticity/buyer-models \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{"mode": "live", "model": "bandit", "features": ["buyer_type"]}'Frontier price model
In the app: Learned pricing, Frontier price model
Learned pricing needs a few hundred outcomes for a product before its curve is any good. The frontier price model is one network, trained on millions of simulated markets across every kind of product, pricing model, unit, buyer and channel, that reads the quotes a product already has (even one, even with no outcome yet) and draws the whole acceptance curve from them. It runs inside Last Price when you ask for a suggestion, with no GPU and no call to another service. Here it only suggests: it does not change the price a buyer is quoted. Early access, being rolled out by workspace.
- product_idstring, required
- The product to price. The model reads this workspace's quotes for it from the last 90 days, without bot or monitor traffic, rebased onto today's price.
- current_pricenumber
- Today's price. Defaults to the price the product's latest quote was given against; with no quotes it is required.
- unit_costnumber
- What one unit costs you. With it, the suggestion maximises margin per quote; without it, revenue per quote.
- category, topology, unitstring
- Where the offer sits, in your own words (such as hotel room, subscription, per seat). Read like a pricing request's product category.
- buyer_type, channelstring
- Who is buying (person, agent or business) and where. Left out, the model prices for any buyer.
- min_price, max_pricenumber
- Your own limits for the suggestion.
- The answer has the suggested
priceandratioto today's, the model'sacceptancethere and today (acceptance_now), margin per quote at both when you gave a cost, how many quotes it read, and the whole curve asgrid. - It looks at most 10% past the prices already quoted (15% either way with none), so a curve the model has to guess cannot move the price far from where there is evidence.
GET /api/frontier-modelsays which version runs and its score: the share of the best possible profit it gives up on simulated markets where it sees one quote (lower is better). A new version is stored as a candidate and runs only once it scores better than the one running.- The model never learns from other workspaces' quotes. It was trained on simulated markets, shaped by public retail data.
- Both routes need the
pcn:routing:readscope. Agents use the MCPget_frontier_modelandsuggest_frontier_pricetools. Until the feature is switched on for your workspace,/api/frontier-modelanswers{"released": false}and the suggestion answers 404not_released.
# Which model runs, and how it scores
curl https://api.last-price.ai/api/frontier-model \
-H "Authorization: Bearer lp_<hex>"
# A price for one product, from its own quotes
curl "https://api.last-price.ai/api/frontier-model/suggest?product_id=pro-plan&unit_cost=22" \
-H "Authorization: Bearer lp_<hex>"Feature contract
Buyer-aware pricing learns how different buyers react to price from the fields of each pricing request. Out of the box that is the buyer type and channel. A feature contract lets it learn from your own metadata too, nested objects and lists included. The contract names each field by its path in the request and says how it becomes a label the models can use. Each logged quote then keeps those labels, and only those: never the raw metadata. Off by default for a workspace.
- namestring, required
- The field's path in the request context. Top-level fields are buyer_type, channel, currency, current_price, product_id and product_type, plus customer_segment and geo when you opt in. A field inside metadata is named metadata plus its path, for example metadata.device.type, at most four levels deep.
- typestring, required
- category: the value if it is in vocabulary, otherwise unknown. bucket: a number placed between edges (b0, b1, ...). flag: true or false.
- vocabularystring[]
- For a category, 1 to 50 values. Values that look like an email, phone number, address or IP are refused.
- edgesnumber[]
- For a bucket, rising numbers; a value below the first is b0, at or above the last is the top bin.
- A list is always reduced, never spread into numbered columns:
metadata.items[]:count,metadata.items[].price:sum(ormean,min,max), ormetadata.items[].kind:has=hdmi. A list inside a list is not read. - A discriminator, such as a product
typethat decides which other fields are present, is an ordinary category. A field missing from a request reads as unknown. - One name per meaning: use the API's own name. The older model names
segmentandproductare read ascustomer_segmentandproduct_id. - An exported model (ONNX) names its columns by the same paths, with underscores instead of dots and brackets (
metadata_device_type), and carries the contract in its metadata, so it can be served without Last Price. POST /api/learned-elasticity/feature-contract/inferproposes a contract from sample requests. It leaves out fields whose names identify someone (ids, emails, names, addresses, tokens) and fields where almost every value differs, and says why for each one. Nothing is stored.- Reading and inferring need the
pcn:routing:readscope. Saving and removing needpcn:routing:writeand, from the dashboard, a workspace owner or admin. Agents use the MCPget_feature_contract,infer_feature_contract,set_feature_contractanddelete_feature_contracttools. Where the feature is off for your workspace, every route answers 404not_released.
# Propose a contract from a few real requests (nothing is stored)
curl -X POST https://api.last-price.ai/api/learned-elasticity/feature-contract/infer \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{"samples": [{"buyer_type": "agent", "metadata": {"device": {"type": "oled"}, "items": [{"kind": "hdmi", "price": 20}]}}]}'
# Save it
curl -X PUT https://api.last-price.ai/api/learned-elasticity/feature-contract \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{"contract": {"inputs": [
{"name": "buyer_type", "type": "category", "vocabulary": ["agent", "person"]},
{"name": "metadata.device.type", "type": "category", "vocabulary": ["lcd", "oled"]},
{"name": "metadata.items[]:count", "type": "bucket", "edges": [2, 4]},
{"name": "metadata.items[].kind:has=hdmi", "type": "flag"}
]}}'Forge
In the app: Learned pricing, Forge
Forge keeps your pricing models learning on their own. Each night it retrains them on your own reported quotes, for your workspace as a whole and its ten busiest products (up to 25 workspaces a night, busiest first, so a quieter workspace may wait for a later night): it tries each model over all your history and over your most recent quotes, keeps the one that predicts your buyers best, and starts afresh when your market moves. Separately, a coder writes new pricing experts as code and tests them on the pricing test bench. Off by default for a workspace.
Every candidate climbs the same ladder and stops at the first gate it fails. Retrained models climb through replay on your own quotes and shadow pricing on your live ones, and can then be promoted to price live quotes; generated experts are workspace-wide and stop after the bench for now, since they never see a workspace's data:
- sandboxedgate, required
- Generated code loads in the sandbox and passes the static check. It runs in its own process with no network, no files, no secrets and a memory cap. Retrained models are our own code and pass at once.
- benchgate, required
- It beats the current model (tier 2) on the pricing test bench on average, and is not much worse on any one market.
- replaygate, required
- Retrained models only: on your own logged quotes it would have earned more than the current model, with the lower end of a 90% bootstrap interval above zero. It needs at least 200 reported quotes.
- shadowgate, required
- Retrained models only. The newest model that passed replay for a product is frozen, and from then on each new reported quote for that product also gets its price, recorded next to the price you charged. Buyers never see or pay the shadow price. One model per product is in shadow at a time. At 400 live quotes, or after 28 days with at least 200, it is judged once on those quotes, which it never trained on: it passes when the lower end of a 90% bootstrap interval for what it would have earned over your live prices is above zero.
- promotedresult
- Retrained models only, while Forge promotion is on for your workspace. The newest model that passed shadow for a product prices that product's live quotes from then on (a workspace-wide model: every product without its own). It is promoted on its own if your workspace applies learned prices automatically; otherwise an owner or admin chooses Use for live prices on the Forge card. It prices only learned and optimizer prices, never a price you fixed, a channel price or a pricing chain stage, and draws from the prices it would quote next, inside the range your quotes were charged at widened by 10%, never below unit cost, then held by your limits and guardrails. It keeps retraining each night on every quote so far, its own included.
- retiredresult
- A promoted model stops pricing and your learned price prices those quotes again. The learned price it replaced is recorded next to every quote it prices, and at 400 of those quotes or after 28 days it is compared once with them: when the learned price would clearly have earned more (the lower end of a 90% bootstrap interval above zero) it is retired, and otherwise the next window starts. It is also retired when a newer model for the same product is promoted, or when an owner or admin chooses Stop using.
- The Forge card on Learned pricing shows when it last trained, each model it trained with the rung it reached and the latest gate's evidence in one sentence, how many live quotes a model in shadow has priced and when it will be judged, how many quotes a promoted model has priced and when it is next compared with your learned price, and, while models written as code are on, the best generated expert so far. Owners and admins can reject a model there, put a model that passed shadow on live prices, and stop a promoted one; each asks once first.
- Only a promoted model changes a price, and only while Forge promotion is on for your workspace. A quote it priced says so in the response's
forgefield (candidate_id, theratioto your current price it drew, itspropensity,factorand the learnedbase_priceit replaced) and in its explanation, and skips the response cache. Forge learns only from the quotes learned pricing learns from: reported outcomes, from prices your pricing functions chose, leaving out negotiations and channel-raised prices. GET /api/forgelists recent runs and candidates with each gate's evidence and, once a candidate starts shadow pricing, itsshadowprogress (started_at,quotes,decide_at_quotes,decide_by), once it is promoted itsliveprogress (promoted_at,retired_at,plan_refreshed_at,quotesand the currentwatchwindow), whether it ispromotable, and inreleased.promotionwhether promotion is on, filtered bystage,loop(self_trainingorself_recoding) andlimit. Generated experts are shown by size and hash, never their source.POST /api/forge/candidates/{id}/rejectstops one of your workspace's retrained candidates climbing, with an optionalreasonkept with its evidence. Generated experts are shared by every workspace, so no one workspace can reject them.POST /api/forge/candidates/{id}/promoteputs the newest model that passed shadow for its product on live prices and retires the one it replaces (409not_promotablefor any other).POST /api/forge/candidates/{id}/retirestops a promoted model, with an optionalreason(409not_promotedfor one that is not); it works even with promotion off, so a promoted model can always be stopped.- Reading needs the
pcn:routing:readscope; rejecting, promoting and stopping needpcn:routing:writeand, from the dashboard, a workspace owner or admin. Agents use the MCPget_forge_status,reject_forge_candidate,promote_forge_candidateandretire_forge_candidatetools. Where Forge is off for your workspace, every route answers 404not_released; promoting does too while promotion is off.
# What Forge trained, and how far each candidate got
curl "https://api.last-price.ai/api/forge?loop=self_training&stage=replay" \
-H "Authorization: Bearer lp_<hex>"
# Stop one climbing
curl -X POST https://api.last-price.ai/api/forge/candidates/CANDIDATE_ID/reject \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{"reason": "Too aggressive on our launch SKU"}'
# Put a model that passed shadow on live prices, or stop a promoted one
curl -X POST https://api.last-price.ai/api/forge/candidates/CANDIDATE_ID/promote \
-H "Authorization: Bearer lp_<hex>"
curl -X POST https://api.last-price.ai/api/forge/candidates/CANDIDATE_ID/retire \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{"reason": "Holiday sale this week"}'Outcome pricing
In the app: Settings, Billing, Outcome pricing
Pay full price only for prices you use. With outcome pricing on, every compute call paid from your prepaid balance opens a 7-day window. Report the price as rejected inside it and 70% goes back to your balance; the other 30% is a base fee that is never refunded. No report counts as accepted.
- Each response carries an
outcome_windowwith the report request and when the window closes. - Once 40% of a workspace's decided calls in the last 30 days are rejected, a rejection needs evidence such as an order reference. At 60%, rejections are recorded but refund nothing.
- A rejection can carry
evidencewith at least one ofreference,url(https) ornote; without it a rejection is refused withevidence_requiredonce the 40% guard applies. - Reporting and reading outcomes needs the
price:computescope. Turning outcome pricing or balance billing on or off needsbilling:write(or a dashboard session with the owner, admin or billing role), because it changes how every key in the workspace is charged.GET /api/outcomestakesstatus=open|decidedandlimit(1 to 200). - Corrections to ordinary learning signals remain allowed. Every successful ordinary or AI-usage outcome report keeps its before and after verdict, quality score and reporting identity in the workspace audit log. A decided monetary window still refuses a conflicting outcome. The event, audit and any monetary decision made by that report commit together.
- Settings, Audit log shows the reporting event and time. With
audit:read, read the before and after values throughGET /api/audit: filteractionbyusage.outcome_recordedorllm_usage.outcome_recorded, andsubject_idby the usage event id. Evidence text is not copied into audit history. - Webhook events:
usage.outcome_recordedwhen you report,outcome.settledwhen a window is decided. - Reporting credit, off by default: a report with
evidencethat decides a window, accepted or rejected, earns 5% of the call's price as bonus credit, at most 1 USDC per workspace per UTC day. It is never paid on a rejection past the 60% guard, and never more than the call cost after its refund. The response showscredited_amount, andno_credit_reasonwhen nothing was paid. - Agents report with the MCP
report_outcometool. On the local (stdio) MCP server, and with the tools packages for LangChain, the AI SDK and the Agents SDK, an agent can leave outusage_event_idto report the last pricecompute_price(or a completedpricing_conversation) returned on that connection, once. The hosted endpoint remembers nothing between calls, so passreceipt.idthere.
# Turn it on
curl -X PATCH https://api.last-price.ai/api/billing/balance \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{"outcome_pricing": true}'
# Report a price as rejected inside the window
curl -X PATCH https://api.last-price.ai/api/usage/events/EVENT_ID/outcome \
-H "Authorization: Bearer lp_<hex>" \
-H "Content-Type: application/json" \
-d '{"outcome": "rejected", "evidence": {"reference": "order-1042"}}'
# Open and decided windows, totals and refunds
curl https://api.last-price.ai/api/outcomes -H "Authorization: Bearer lp_<hex>"Bring your own AI
When your customer brings their own AI subscription or key, model cost drops out of your cost basis, so you can offer a cheaper plan and keep your margin.
Play 1: Cheaper bring-your-own tier ($20 / $10 / $5 math)
In Play 1, the customer pays their own model inference directly. Deducting model cost from the standard price preserves your exact dollar gross margin while giving the customer a substantial discount:
- Standard plan ($20 sticker): Vendor pays $10 model inference cost plus $5 non-model unit cost ($15 vendor cost). Gross margin is $5 (25% margin).
- BYO tier ($10 sticker): Customer pays model inference directly, so vendor model cost is $0. Vendor carries only $5 unit cost ($5 vendor cost). Gross margin is $5 (50% margin).
- Result: The customer gets a 50% discount ($10 savings), while the vendor preserves 100% of their dollar margin ($5 gross profit).
Play 2: Unlimited BYOAI with authoritative credit fallback
In Play 2, customers retain standard subscription pricing while using their own model key for unlimited usage with zero credit deductions. If their provider session limit is exceeded or the provider call fails, Last Price falls back to credit deduction:
- While BYOAI is active and within provider session limits, calls run with unlimited usage and zero credits deducted.
- When provider limits are reached (server-tracked session calls reach the provider session limit) or provider errors occur, the router falls back to deducting workspace credits.
- If workspace credit balance is depleted, the call is rejected with an
insufficient_creditsrefusal code.
Pricing request and routing rules
Configure BYOAI pricing via first-class context fields or metadata:
POST /api/compute/price
{
"routing_preference": "policy",
"context": {
"currency": "USD",
"inference_payer": "customer",
"inference_provider": "anthropic",
"metadata": {
"unit_cost": 5,
"inference_cost": 10,
"target_margin_pct": 25
}
}
}context.inference_payer:vendor(default) orcustomer. When set tocustomer, vendor model cost is recorded as 0 in cost attribution and trace steps. Also accepted atcontext.metadata.inference_payer.context.inference_provider: Provider identifier such asopenai,anthropic,openrouter, ortogether-ai. Also accepted atcontext.metadata.inference_provider.- Route bring-your-own requests to a dedicated tier function using a routing policy rule on
context.inference_payer,inference_payer, orcontext.metadata.inference_payer. - Responses carry top-level and metadata
cost_attribution(sale price, unit cost, effective model cost, vendor cost, dollar margin, margin percentage) andcredit_fallback(deduct credits flag, credits deducted, fallback status, mode, reason).
Worked examples are on the Bring your own AI feature page.
Functions on your model
In the app: Functions, edit a function
An LLM prompt or ML model pricing function runs on an inference provider your workspace connected, with your own model and pricing instructions. Calls use your workspace's key.
# On POST /api/functions or PATCH /api/functions/{id}, for llm_prompt and ml_model functions
"inference_config": {
"provider": "anthropic",
"model": "your-model-id",
"prompt": "Price relative to the current price. Never go below unit cost."
}provideris one ofopenai,anthropic,openrouter,together-ai,huggingface,replicate,basetenoraitune.model(up to 200 characters) andprompt(your pricing instructions, up to 4000) are optional.- Requests to these functions need a current price; the model prices relative to it.
- If the provider is not connected, calls are refused with a message naming it. They are never answered by the rule-based formula behind your back.
- Your provider, model and instructions are returned only to your workspace, even for a public function. Keep secrets out of the instructions, since a model can be talked into repeating them.
- Switch a function back to the rule-based formula at any time from its edit dialog.
Receipts and value
Proof of what a priced call cost and what an agent's work was worth. Nothing is sent unless someone asks for it.
Receipts and statements
Statements use limit and offset with start_date and end_date. Cursor, since, page and per_page return 400 invalid_query with the supported paging parameters. The outcomes list supports status and limit only and refuses unsupported paging or date filters rather than ignoring them.
In the app: Invoices, Value receipts
Ask for a receipt for one priced call by its id, or a statement of many by date range, as JSON, CSV or a printable page. A key bound to an agent only gets receipts for that agent's calls.
- idsstring
- Comma-separated usage event ids, up to 50. Use this or a period, not both.
- start_date / end_dateISO 8601
- A period of at most 366 days. A bare end date covers that whole day. Default: this calendar month (UTC) so far.
- function_id / agent_iduuid
- Narrow a period statement to one function or agent.
- limit / offsetinteger
- Paging: 100 by default, at most 500.
- formatstring
- json (default), csv, or html for a printable statement.
# One priced call
curl https://api.last-price.ai/api/receipts/CALL_ID -H "Authorization: Bearer lp_<hex>"
# A statement for a period, as a spreadsheet
curl "https://api.last-price.ai/api/receipts?start_date=2026-10-01&end_date=2026-10-31&format=csv" \
-H "Authorization: Bearer lp_<hex>"A period statement also reports totals for the whole period, not only the page, and a X-Receipts-Truncated header when it was cut. Agents can ask with the MCP tools get_receipt and list_receipts.
Value receipts and ROI
In the app: Settings, Value receipts
A Value Receipt shows what an agent cost, what its work would have cost done by a person, and the ROI, measured from your own data over the last 30 days. Statements show the same figures per agent.
- Costs are the agent's pricing calls at list price plus any costs you record with
POST /api/costs. Only US dollars are added up; other currencies are listed, never converted. - Human value equivalent comes from a value you set on each signal in Settings, Value receipts. A signal without a value is listed and left out of the total.
- ROI appears only when a signal has a value and the agent has US dollar costs; otherwise it says what is missing.
curl "https://api.last-price.ai/api/agents/AGENT_ID/value-receipt" -H "Authorization: Bearer lp_<hex>"Pass start_date and end_date for another period (30 days by default, at most 366). An agent can read its own receipt with its own key; any other key with limited scopes needs billing:read, since the receipt carries costs.
Workspace tools
Screens and tools for running a workspace day to day.
Notifications
The Notifications panel in the sidebar lists the newest 50 items for the selected workspace: approval requests, failed webhook deliveries, email to your agents, disputes, price changes proposed by Commerce, learned pricing changes, pricing briefs, directory listing reviews, invoices sent, paid or overdue, payments received, members joining, leaving or changing role, API keys created or revoked, and a low prepaid balance. Each item opens the page it is about, and the Monitor tab counts what is new since you last opened the panel. Opening it marks items read for you only. The In-app notifications switches in your profile hide the kinds you turn off, in every workspace.
Failed webhook deliveries and API key changes appear for owners and admins. Email to an agent with a private inbox never appears.
The same alerts reach people by email, and agents through the feed, MCP, webhooks and their own inbox, so a workspace with no person in it still hears about them.
- Alert types for assistants. Through MCP,
update_alert_preferencesswitches each type on or off, or moves it to the daily summary:approval_requested,dispute_opened,webhook_failing,payout_update,outcomes_needed,analyst_brief,invoice_update,payment_received,team_change,security_alertandbalance_low. An email also needs its switch on under Email notifications in the person's profile, where one exists. - Email alerts. Owners and admins get an email when a call is held for approval, when an open dispute is created, and when deliveries to one webhook endpoint fail three times in a row (at most one email per endpoint a day). An hour with more than 20 alerts for one person sends one summary instead. Every email has a one-click unsubscribe link. Nothing is sent to a suspended member or an unverified address, and a retried or summarised alert is left out once its approval is decided, its dispute is closed or its endpoint recovers.
- Outcome reporting reminders. Off by default. A workspace that quoted 50 or more prices in the last 30 days, with a reported outcome for under 20% of them, gets at most one email a week saying how many have one, with a link to its Pricing analysis. It is the same test as the analyst's
outcomes_missingfinding, and the type (outcomes_needed) appears in your settings where it is on for your workspace. - Your own settings. Each person turns each alert type on or off for themselves in Profile, Notifications, or with
GETandPATCH /api/workspaces/{workspaceId}/alert-preferences. Turning one off for yourself changes nothing for anyone else. - Once a day. For any alert type that is on, choose “Once a day” instead of “Right away” to get one summary email at 8:00 in your time zone (the one in your settings), listing what arrived since the last one. With the API, send
{"delivery": {"dispute_opened": "daily"}}in the samePATCH. An owning agent's summary goes out at 8:00 UTC. - Agent inboxes. In an unclaimed workspace that an agent registered, the agent that owns it gets the same alerts at its agent inbox, under the same settings, limits and unsubscribe. After a person claims the workspace, the alerts go to that person instead. Other agents get no alert email; they read the feed.
- The feed with an API key.
GET /api/workspaces/{workspaceId}/notificationslists the workspace's notifications with an unread count, andPOST .../notifications/readmarks them read. Both take the dashboard session, or an API key or token holdingnotifications:readornotifications:write; the agent that owns an unclaimed workspace needs neither scope. Read state is per reader: one per agent, or one per key bound to no agent. - Archive. The panel has Inbox and Archived views, a count of what is new, Mark all read, Archive all, and an Archive button on each item (with Undo). Archived items leave your inbox and your unread count, for you only, and Move back returns one. With the API,
POST .../notifications/archivetakes{"ids": [...]}or{"all": true},POST .../notifications/unarchivebrings items back, and?view=archivedlists what is archived. They neednotifications:write(the list needsnotifications:read), and archive is per reader, like read state. - MCP tools.
list_notificationsreads the feed,mark_notifications_readmarks it read,archive_notificationsandunarchive_notificationsarchive one item, several or all and bring them back, andread_my_inboxreads the inbox of the agent your key or token is bound to, and no other agent's.get_alert_preferencesandupdate_alert_preferencesread and change which alert emails the caller gets and whether each comes right away or in the daily summary, with the same scopes. - Webhook events.
approval.requested,dispute.openedandwebhooks.failing, described under Webhooks in Authentication & Security.webhooks.failinggoes only to your other healthy endpoints, never the failing one.
Workspaces
In the app: Settings, Company
The workspace you pick in the switcher is the one every page opens on, Settings included, and it stays picked after a reload, on another page and on your next visit. Requests the dashboard makes without naming a workspace use it too, as long as you still belong there; if you leave it, your own workspace opens instead.
- The switcher lists each workspace with your role there and the first eight characters of its id, so two with the same name are told apart.
- Settings has its own workspace picker above its menu.
- Settings, Company starts with the workspace's name, its full id with a copy button (the value API paths such as
/api/tenants/:tenantId/...take), and your role. Owners and admins rename the workspace there, and the switcher shows the new name at once. - Get started asks the owner of a workspace still called "My Workspace" to name it.
- Your own user id is on your profile, under Security, with a copy button.
- A new workspace needs only a name: the contact email is optional, and a name whose address is taken is refused saying so.
# Choose the active workspace (dashboard session)
curl -X POST https://api.last-price.ai/api/user/active-workspace \
-H "Content-Type: application/json" \
-d '{"workspace_id": "<workspace id>"}'
# The list says which one is active
curl https://api.last-price.ai/api/user/workspacesLanguage
In the app: Profile, Locale & display
Pick a language under Locale & display and the app switches to it at once, on every device you sign in on. Before you sign in, it follows your browser's language.
- English, Español, Français, Deutsch, Português, 日本語, 中文, 한국어 and العربية.
- The menus, page titles, Settings, the workspace switcher, invitations and the Agents page are translated; more pages follow screen by screen, and a page not translated yet stays in English.
- Numbers, plurals and dates follow the language's own rules, and Arabic reads right to left.
- The API keeps answering in English; only the app changes.
# Save the language (dashboard session); one of en, es, fr, de, pt, ja, zh, ko, ar
curl -X PATCH https://api.last-price.ai/api/user/settings \
-H "Content-Type: application/json" \
-d '{"language": "fr"}'Team and invitations
In the app: Settings, Team
Owners and admins invite people by email from the Team page. The invitee gets an email with a link to join; the page also shows the link itself, so you can send it another way, and says when the email could not be sent.
- Each pending invitation shows when it expires, with Copy link and Resend.
- The link opens a page naming the workspace, the role and who invited you, with sign in or create an account. After signing in you come back to the same page and join.
- Someone who signs in with an invited email sees the invitation at the top of the dashboard, with Accept and Decline. Accepting opens the workspace.
- Joining a workspace closes your other pending invitations to it, so nobody is listed both as a member and as invited. Inviting someone who is already a member is refused.
- A person who already has an account can be added straight away by their email, without an invitation.
# Invite; the answer carries the accept link and whether the email went
curl -X POST https://api.last-price.ai/api/workspaces/<workspace id>/invitations \
-H "Content-Type: application/json" \
-d '{"email": "colleague@your-company.com", "role": "member"}'
# { ..., "accept_url": "https://app.last-price.ai/invitations/accept?token=...",
# "email_delivery": { "status": "sent" } }
# Send the email again
curl -X POST https://api.last-price.ai/api/workspaces/<workspace id>/invitations/<invitation id>/resend
# Invitations addressed to you, and answering one
curl https://api.last-price.ai/api/user/invitations
curl -X POST https://api.last-price.ai/api/user/invitations/<invitation id> -d '{"action": "accept"}'Team roles
A role decides what a person may do in a workspace, and the same rule holds whether they use the dashboard or an API key they made. A key can do no more than its maker: it can only be given scopes the maker's role holds, and a full access key from a member, viewer or billing person carries exactly their role's scopes. The dashboard greys out what your role cannot do and says which roles can.
| Role | What it may do |
|---|---|
| owner | Everything, including deleting the workspace and making someone an admin. |
| admin | Everything but deleting the workspace: invite people, manage keys, change settings. |
| member | Build and run pricing: functions, routing, guardrails, experiments, commerce, prices. Reads billing; no team, keys for others, or settings changes. |
| viewer | Sees functions, routing, commerce, settings and notifications. Changes nothing and runs no prices. |
| billing | Invoices, payments, credits and the audit log, plus what a viewer sees. |
A request your role cannot make is refused with 403 role_forbidden, naming the roles that can; a key with scopes beyond your role is refused with 403 scope_beyond_role. The exact scopes of each role are listed by the API:
curl https://api.last-price.ai/api/workspaces/roles -H "x-api-key: lp_..."Audit log
In the app: Settings, Audit log
Every change recorded in the workspace, newest first, in plain words: who made it, what changed and when. Open a line for the request behind it. Filter by team, API keys, workspace or pricing, and load older changes at the bottom.
- Changes made in the dashboard are recorded: invitations sent, revoked, accepted and declined; people added, removed or given another role; API keys created and revoked; the workspace renamed.
- Changes made with API keys and by agents are listed too, including what a key tried and was refused.
- Team changes are shown to owners and admins only. Reading the log needs
audit:read, which owners, admins and billing hold.
curl "https://api.last-price.ai/api/audit?limit=50" -H "x-api-key: lp_..."AI providers
In the app: Settings, AI providers
Settings, AI providers holds every inference provider a pricing function can call: OpenAI, Anthropic, OpenRouter, Together AI, Hugging Face, Replicate, Baseten, Apify and AITune. Configure saves a key after checking it with the provider; keys are stored encrypted and never shown again; Disconnect removes one. The same connections appear under Compute, Inference.
The Anthropic key at the top of the page is separate: it runs Last Price's own AI features, such as task estimates and agent drafts, billed to your workspace instead of the shared key.
Approvals
In the app: Approvals
Some agent calls are held until a person signs off. The Approvals page lists pending requests first and decided ones (approved, rejected or expired) on their own tab; the approval link in a held call's response opens that request. A request nobody decides within seven days expires.
Approving does not run the call. The agent sends the same request again once it shows as approved, and that one call goes through; sending it a third time is held again.
The pricing analyst's proposals are the exception: the analyst never sends its own request, so they show Approve and apply, which runs the stored call as you (see Analyst Brief).
Deciding from an agent
Agents can work the queue too. The workspace owner, a person or the owner's own agent, can approve or reject over the API and the MCP server. The owner's own agent means an API key made without scope limits and not bound to an agent. An agent's own keys and tokens, and any key limited to scopes, can read the queue but cannot decide. Nobody decides a request they made themselves: the same agent or the same key gets a 403, and a person or another owner key has to. The audit log records who decided each one.
- MCP tools:
list_approvals,get_approval,decide_approval(approveorreject, with an optional reason),apply_analyst_proposal(for the pricing analyst's proposals) andlist_audit_events. - API:
GET /api/approvals,GET /api/approvals/{id},POST /api/approvals/{id}/approveand/reject, andGET /api/audit.
Deciding from your phone
In the Last Price mobile app, the Agents tab lists every request waiting for you, with Approve and Decline, and your agents. Each new request also arrives as a notification on the phones of the workspace's owners and admins, saying who asks, how much and what for; its Approve and Decline buttons decide it. The same tab claims an agent from its claim link, with the same owner or admin check as the website. The app registers a phone with POST /api/mobile/push-token.
System blocks
In the app: Blocks
The Usage table, Invoice table, Payments table, Container and Pricing calculator blocks ship working code you copy into your app.
- The three tables fetch through a server route included with each block, so your API key stays on your server.
- The route refuses every request until you fill in its
authorize()function with your own sign-in check, so only the people you choose see billing data. Return acustomerIdfrom it to show a customer only their own records. - The Pricing calculator takes
tiers(each withupToandunitPrice; the last hasupTo: null),currencyandbasePrice(a flat monthly fee) and shows the monthly total with a line per tier.
Model profiling
In the app: Compute, Model profiling
Model Profiling runs on an NVIDIA AITune server on a GPU machine that you connect on the Compute page, under Inference: the AITune provider's Sidecar URL (https) and, if it has one, its key. Last Price checks that it answers before saving it. Each workspace uses its own server, and only public https addresses are accepted.
Model profiling (MCP)
An agent can read what your AITune server reports, with no dashboard. Each tool needs a Last Price credential. The three reads never start a profiling run; start_aitune_profiling does, and it needs a claimed workspace.
list_aitune_backends: the inference backends the server offers and the state of each.get_aitune_profiling: the latest profiling report for amodel(up to 200 characters).start_aitune_profiling: start a run for amodel, with optionalbatch_sizes,measurement_steps,saturation_cutoffandinclude_warmup. It uses GPU time on your server.get_aitune_system_stats: current GPU and CPU load. Passhistorytrue withduration_minutes(1 to 1440, default 60) for the readings over time.
list_aitune_backends { }
get_aitune_profiling { "model": "llama-3" }
get_aitune_system_stats { "history": true, "duration_minutes": 30 }MCP workspace tools
An agent can set up and watch its workspace over MCP. Every tool needs a Last Price credential and the scope of the route it calls, and refuses unknown or out-of-range arguments before making any call.
get_function,create_function,update_function,delete_function: read, register, change and delete a pricing function. See Function tools below.list_vendor_adapters: which outside pricing engines (Pricefx, Prisync) this deployment has switched on, and what blocks one that is not ready. Read only; it never shows a setting value.get_billing_settings,update_billing_settings: read the prepaid balance, turn outcome pricing or balance billing on or off, set or clear the auto top-up offer.list_outcomes,report_outcome: read outcome pricing and report a price as used or not.get_usage,list_usage_events: total priced calls over a period and list them.get_receipt,list_receipts: see Receipts and Statements.list_webhooks,create_webhook,update_webhook,delete_webhook,rotate_webhook_secret,ping_webhook,list_webhook_deliveries: see Webhook tools below.revoke_my_key: revoke the API key the connection calls with, when the agent's work is done. It reaches no other key.list_feature_launches,get_feature_launch_plan: for Last Price staff only. They read the launch plans of features built behind a release flag and never switch, schedule or send anything; launching takes the owner's go code through the launch command. Any key not made by staff withlaunches:readgets 404, and they are left out of directory listings.
The LangChain, AI SDK and Agents SDK tool packages offer them too.
Sandbox keys. A key from self-registration works on an unclaimed workspace, which some tools refuse (403) until a person claims it: guardrails, the sales playbook, channel rates, pricing analysis, update_function, run_pricing_chain, outcomes, usage, receipts, approvals, the audit log, webhooks, spend policy and purchase checks, product categories, offer settings and negotiations, prompt class benchmarks, vendor adapters, routing policy changes, credits, invoices and payments, simulate_agent_cut, preview_price_change and revoke_my_key. In tools/list each of these ends its description with “Needs a claimed workspace” and carries the _meta key ai.last-price/requires set to claimed_workspace; the manifest at /.well-known/mcp.json lists them under auth.claimed_workspace_only. Everything else works with a sandbox key, including the agent's own notifications, alert settings and inbox.
Webhook tools
An agent that owns a workspace can set up the endpoints that send it events, and check they work, without the dashboard. They call the same routes as the Webhooks page, so the same rules hold: listing, creating, changing, deleting and rotating need the owner or admin role when a person signs in. A key needs webhooks:read to list endpoints and deliveries, and webhooks:write for the rest; a key with no scope limits has both.
list_webhooks: each endpoint's id, url, events and status, with its signing secret masked to the last four characters.create_webhook: an https url and the events to send; the answer carries the signing secret.update_webhook: change the url or events, or set status toinactiveto pause it.delete_webhook: delete an endpoint and its delivery history. This cannot be undone.rotate_webhook_secret: replace an endpoint's signing secret and return the new one, once. Deliveries are signed with it from then on, so update the receiver straight away.ping_webhook: send one signedwebhook.testevent to an active endpoint.list_webhook_deliveries: recent delivery attempts, newest first, to find an endpoint that fails.
# An agent sets up an endpoint for the things a person has to act on, then tests it
create_webhook { "url": "https://your-app.com/hooks/last-price",
"events": ["approval.requested", "dispute.opened", "price_proposal.created"] }
ping_webhook { "webhook_id": "<id from the create_webhook answer>" }
list_webhook_deliveries { "limit": 5 }Function tools
An agent can manage the pricing functions its workspace owns over MCP, with the pcn:function:publish scope. A sandbox key is refused until a person claims the workspace.
create_functionregisters a function: a unique lowercasename, adisplay_nameand anexecution_type(rule based, ML model, LLM prompt, external API or composite), plus optionally the endpoint, its credential, the input and output schemas, the model to run, the cost and tags. It starts as a draft.update_functionchanges any of those fields on a function the workspace owns; only the fields sent change. Setstatusto active to have it routed to.delete_functiondeletes one for good. To stop routing to a function and keep it, set it inactive instead.
The credential in auth_config is stored encrypted and never returned: a read says only whether one is saved. Because the value passes through the agent's conversation, give an agent a scoped credential made for the endpoint. Built-in functions and other workspaces' functions cannot be changed or deleted.
Team tools
An agent can look after who is in the workspace without the dashboard. The tools call the same routes as the Team page, and the same rules hold: only an owner can grant or remove the owner role, and the last owner stays. They need an API key that holds team:admin by name, made on the API keys page by someone who is still an owner or admin. A key with * or no scope limits does not carry it, and a token from an agent exchange is refused. Every refusal is written to the audit log.
list_team_members: each person's user id and role.add_team_member: add someone who already has an account, with a role.change_team_member_roleandremove_team_member: change a role or take a person out.list_invitations: invitations still waiting, without their links.invite_team_member: invite an email address with a role; the link is emailed, never returned.revoke_invitation: withdraw a pending invitation.
# An agent invites a colleague as a viewer, then checks the invitation is waiting
invite_team_member { "email": "colleague@your-company.com", "role": "viewer" }
list_invitations {}Payout tools
An agent can look after your marketplace payouts with the same routes as payout runs and the payout schedule, and the same rules hold. Payout runs are not switched on for every workspace yet: while they are off for yours, the two read tools say enabled: false and the others answer 404. Reading needs billing:read, everything else billing:write, and a sandbox key is refused until the workspace is claimed.
list_payout_runsandget_payout_run: runs, newest first, and one run with its transfers.request_payout_run: a dry run unless you senddry_run: false; a request then waits for approval.approve_payout_run: pays the run. Whoever requested it is refused (403), the same person through another key, their sign-in or an agent they created included, so an agent cannot approve its own request.reject_payout_runandretry_payout_run: withdraw a request, or re-send transfers due for a retry with the same keys.get_payout_scheduleandset_payout_schedule: read or save the weekly or monthly schedule.
# An agent checks what September would pay, then asks for it
request_payout_run { "period_start": "2026-09-01", "period_end": "2026-09-30" }
request_payout_run { "period_start": "2026-09-01", "period_end": "2026-09-30", "dry_run": false }
# Someone else approves: a person, or an agent another person created
approve_payout_run { "run_id": "RUN_ID" }Workspace settings tools
An agent can read and change the details the Settings page holds, with an API key or token of the workspace. Reading needs workspace:settings:read and changing needs workspace:settings:write; a person's token still has to be an owner or admin to change anything. A key sees its own workspace only. Model keys are never returned and cannot be sent here; connect them in the dashboard. A sandbox key is refused until a person claims the workspace.
get_workspace_settings: company details, tax id, default currency, payment terms, invoice prefix and footer, tax on or off, tax registrations and the sales playbook.update_workspace_settings: change any of those; only the fields you send change, and a bad value is refused naming the field.list_inference_providers: which model providers are connected, status only, and whether key storage is available.
The invoice terms apply to every invoice made after: one created without a currency gets the default currency, without a due date is due the payment terms after it is made, and without a number gets the prefix and the next free four-digit sequence (ACME-0001, ACME-0002). The footer closes the invoice email. If concurrent requests choose the same generated number, creation retries with the next free number. A number you supply is kept and a duplicate is refused.
# An agent sets the invoice terms, then checks which model providers are connected
update_workspace_settings { "default_currency": "EUR", "payment_terms_days": 14, "invoice_prefix": "ACME-" }
list_inference_providers {}Changelog and releases
Two pages tell you what changed. The changelog has one note for every change, with filters, feeds and links to the docs and the screen each one is about. The releases page is for what we release: numbered versions, the MCP server, npm packages, apps, extensions, plugins, connectors and open source launches. Below those it lists each deploy to production, newest first, with its date and the notes it shipped.
- A note is live once the release that carries it is deployed. Until then it shows only on previews.
- Deploys are unnumbered, so each one is identified by its date. A versioned release shows its version.
- Deploys that shipped no user-facing note are left out.
- Feeds:
/changelog/feed.xmland/changelog/feed.jsoncarry the notes;/releases/feed.xmlcarries one item per release. - One feature only:
/changelog/features/<feature>/feed.jsonandfeed.xml, for example/changelog/features/billing/feed.json. The names are the feature tags on every note (the_lastprice.featuresfield of a feed item lists them), and a renamed tag keeps its old address. - From an agent: the
get_changelogMCP tool returns the newest notes, optionally for one feature, since a date (since, YYYY-MM-DD) and foragentsorusers. It needs no API key; the same data is at/api/public/changelog. - In the dashboard: a blue dot beside a sidebar link means a release note about that page shipped since you last opened it. Opening the page clears it. It is remembered in the browser only.
Using the Oja dashboard
The Oja dashboard is your control center for managing all aspects of the platform.
| Section | What you do there |
|---|---|
| Dashboard | Overview of active experiments, conversions, revenue |
| Functions | Register and manage pricing functions (built-in + custom) |
| Compute | Run single or batch pricing computations |
| Routing policies | Configure how pricing requests are routed |
| Commerce | Commerce control plane - connectors, catalog, policies, approvals, execution |
| Usage & costs | View token metering, cost breakdowns, billing periods |
| Marketplace | Browse community pricing functions, publish your own |
| Customers | Manage customer records |
| Orders | View and manage orders |
| Invoices | Generate and track invoices |
| Payments | Track payment status |
| Credits | Manage credit bundles |
| Integrations | Configure inference providers (OpenAI, Anthropic, etc.) |
| API keys | Generate and manage API keys |
| Settings | Company info, team management, billing, tax configuration |
Workflow: Setting Up a Price Test
- Go to Functions → Verify your pricing functions are registered
- Go to Routing policies → Set routing strategy
- Create an experiment via the API
- Embed the snippet or integrate via API on your site
- Go to Dashboard → Monitor impressions, conversions, and revenue
- Go to Usage & Costs → Track API usage and costs
Glossary
| Term | Definition |
|---|---|
| Tenant | An isolated account on Last Price (your store/company) |
| Experiment | An A/B test comparing two or more price variants |
| Variant | One of the price options in an experiment (e.g., "$29" vs "$39") |
| Assignment | The process of deterministically placing a user into a variant |
| Conversion | A purchase or subscription triggered by a variant |
| PCN | Pricing Compute Network - the execution engine for pricing functions |
| Elo | The A/B testing engine (named after the Elo rating system) |
| Jale | The built-in AI pricing optimization engine |
| Oja | The admin dashboard for managing everything |
| Function | A pricing computation unit (built-in or custom) |
| Routing Policy | Rules for how pricing requests are distributed across functions |
| Metering | Token-based usage tracking for billing |
| Cost Multiplier | A scaling factor on function execution cost (e.g., 5× for advanced AI) |
| Snippet | The embeddable JavaScript widget for any website |
| Fallback Chain | Ordered backup functions used when the primary fails |
| Circuit Breaker | Automatic failure detection that stops routing to unhealthy functions |
| Price Router | Multi-vendor pricing facade - one API endpoint in front of all built-in and custom pricing models |
| Rosetta | Schema translation service - maps any price data format to canonical schemas using AI-assisted adapters |
| Canonical Schema | A standardized price data structure all platforms are mapped to (e.g., lastprice.price.v1) |
| Frozen Adapter | An immutable, versioned schema mapping promoted from a Rosetta plan |
| Commerce Control Plane | End-to-end pipeline: connectors → observations → matching → policies → approvals → execution |
| Connector | An integration adapter that pulls catalog data and pushes prices to a platform (Shopify, Amazon, etc.) |
| Observation | A competitor price data point ingested by the Commerce Control Plane |
| Proposal | A candidate price change produced by a pricing policy, awaiting approval before execution |
| Signals | Behavioral event stream capturing pricing decisions, assignments, conversions, and agent actions |