Skip to main content

Endpoint

POST /query
Process user queries using AI agents with optional image input. This endpoint orchestrates multiple specialized agents (Oracle, Scout, News, etc.) to generate comprehensive responses.
Rate Limit: 10 queries per minute per IP address

Request Body

query
string
The natural language query to process. Can be omitted if imageData is provided.Example: "What is the current price of Bitcoin?"
txHash
string
required
USDC payment transaction hash for query verification. The transaction must be confirmed on-chain.Example: "0x1234567890abcdef..."
userAddress
string
required
Wallet address of the user making the payment.Example: "0xabcdef1234567890..."
imageData
string
Base64-encoded image data for image-based queries. Allows image-only queries when query is omitted.
conversationHistory
array
Array of previous messages for context-aware responses.
[
  { "role": "user", "content": "Previous question" },
  { "role": "assistant", "content": "Previous answer" }
]
sessionId
string
Session identifier for tracking conversation state and spending across multiple queries.
budgetUsd
number
default:"1"
Maximum budget in USD for x402 agent calls during this query. Prevents runaway costs.Defaults to X402_DEFAULT_BUDGET_USD environment variable (1 USD).

Response Fields

success
boolean
required
Indicates whether the query was processed successfully.
response
string
required
AI-generated response to the user’s query.
agentsUsed
array
required
List of agent IDs that were called to generate the response.Example: ["oracle", "scout", "news"]
cost
string
required
Query cost in USDC (always “0.03” for direct user queries).
txHash
string
required
The verified payment transaction hash.
traceId
string
Unique identifier for this query’s execution trace.
totalSpendUsd
number
Total USD spent on x402 agent calls during query processing.
trace
object
Detailed execution trace with budget tracking and agent call logs.

Examples

curl -X POST http://localhost:3001/query \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What is the current price of Bitcoin?",
    "txHash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
    "userAddress": "0xabcdef1234567890abcdef1234567890abcdef12"
  }'

Response Example

{
  "success": true,
  "response": "Bitcoin (BTC) is currently trading at $67,234.56 USD with a 24-hour change of +2.3%. The market cap is $1.32T with a 24-hour volume of $28.4B.",
  "agentsUsed": ["oracle"],
  "cost": "0.03",
  "txHash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
  "traceId": "trace-1234567890-abc123",
  "totalSpendUsd": 0.01,
  "trace": {
    "traceId": "trace-1234567890-abc123",
    "totalSpendUsd": 0.01,
    "budget": {
      "limitUsd": 1.5,
      "spentUsdStart": 0,
      "spentUsdEnd": 0.01,
      "remainingUsdEnd": 1.49
    },
    "steps": [
      {
        "toolName": "fetchPrice",
        "agentId": "oracle",
        "endpoint": "/api/x402/oracle/price",
        "amountUsd": 0.01,
        "success": true,
        "latencyMs": 234
      }
    ]
  }
}

Error Responses

Missing Required Fields

{
  "success": false,
  "error": "Query or image is required"
}

Payment Verification Failed

{
  "success": false,
  "error": "Payment verification failed: Transaction not found"
}

Payment Transaction Failed

{
  "success": false,
  "error": "Payment transaction failed"
}

AI Generation Failed (Payment Confirmed)

{
  "success": false,
  "error": "Payment Confirmed, but AI Generation failed: API rate limit exceeded. Payment verification was successful (Block: 12345678).",
  "txHash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
}

Rate Limit Exceeded

{
  "error": "Query rate limit exceeded. Please wait before sending more queries."
}

Payment Flow

1

User Sends USDC Payment

User initiates a USDC transfer transaction worth $0.03 to the marketplace contract.
2

Submit Query with Transaction Hash

Frontend submits the query along with txHash and userAddress to the /query endpoint.
3

Backend Verifies Payment

Backend calls publicClient.waitForTransactionReceipt() to verify:
  • Transaction is mined
  • Transaction status is ‘success’
  • Transaction matches the provided hash
4

AI Processing

Once verified, the query is processed using Gemini and x402 agents with budget tracking.
5

Response Returned

AI response, agent usage, and spending details are returned to the user.

Legacy Flow (Backward Compatibility)

If txHash is not provided, the backend falls back to the legacy escrow-based flow:
// Legacy: Backend creates escrow automatically
const result = await resellerAgent.processQuery(query);
This mode is maintained for backward compatibility but is not the recommended approach.

Budget Management

The budgetUsd parameter controls spending on x402 agent calls during query processing:
  • Default: 1 USD (configurable via X402_DEFAULT_BUDGET_USD environment variable)
  • Purpose: Prevents runaway costs if AI makes excessive agent calls
  • Behavior: Query execution stops when budget is exhausted
  • Tracking: Real-time budget tracking in the trace object
For complex queries requiring multiple agent calls, consider increasing the budget to 2-5 USD.

Build docs developers (and LLMs) love