Chat API

The Chat API is the core endpoint that powers Mika402's autonomous payment agent conversations.

Endpoint

POST /api/chat

Overview

This endpoint receives user messages, processes them through Google's Gemini AI model, detects x402 payment requirements, and handles autonomous blockchain payments while streaming responses back to the client in real-time.

Configuration

Maximum Duration

export const maxDuration = 50;

The endpoint can run for up to 50 seconds to accommodate:

  • Complex payment processing

  • Blockchain transaction confirmations

  • Multi-step service access workflows

  • x402 protocol handshakes

Platform limits:

  • Vercel Hobby: 10 seconds max

  • Vercel Pro: 60 seconds max

  • Vercel Enterprise: 900 seconds max

Request Format

Headers

Body

With payment context:

Message Structure

Field
Type
Required
Description

messages

Array

Yes

Array of message objects

messages[].role

String

Yes

"user", "assistant", or "system"

messages[].content

String

Yes

Message text content

walletAddress

String

No

User's wallet address for payments

spendingLimits

Object

No

Current spending limit configuration

Response Format

The endpoint returns a streaming response using Server-Sent Events (SSE).

Stream Format

Response Events

Event Type
Description

0:

Text content chunks

d:

Metadata (finish reason, transaction hash, etc.)

e:

Error messages

p:

Payment status updates

Finish Reasons

  • stop - Normal completion

  • payment-complete - Payment processed successfully

  • payment-failed - Payment failed

  • limit-exceeded - Spending limit exceeded

  • insufficient-balance - Not enough funds

  • service-unavailable - x402 service offline

AI Model Configuration

Model Selection

Available models:

  • gemini-2.0-flash-exp - Latest, fastest (default)

  • gemini-1.5-pro - More capable for complex reasoning

  • gemini-1.5-flash - Balanced performance

Parameters

Temperature

Controls response creativity:

  • 0.0-0.3: Focused, deterministic (good for payment confirmations)

  • 0.4-0.7: Balanced (default, recommended)

  • 0.8-1.0: Creative, varied (good for service discovery)

Max Tokens

Maximum response length:

  • 1000: Brief confirmations

  • 4000: Detailed responses (default)

  • 8000: Very comprehensive service comparisons

x402 Integration

The AI integrates with the x402 protocol for autonomous payments:

Payment Detection

Service Discovery

Payment Processing

System Prompt

The endpoint includes a comprehensive system prompt that defines:

  1. Identity: "Mika402" autonomous payment agent

  2. Capabilities:

    • x402 service discovery

    • Autonomous payment processing

    • Spending limit enforcement

    • Multi-chain transaction handling

  3. Payment directives:

    • Check limits before every payment

    • Show cost estimates

    • Provide transaction transparency

  4. Personality traits: Helpful, transparent, security-conscious

  5. Instructions: How to handle payments and communicate with users

Key System Directives

Error Handling

Common Errors

400 Bad Request

Cause: Malformed request body

402 Payment Required

Cause: User wallet doesn't have enough cryptocurrency

403 Forbidden

Cause: Payment would exceed spending limits

429 Too Many Requests

Cause: Too many requests (50-second cooldown)

500 Internal Server Error

Cause: Blockchain or x402 service error

503 Service Unavailable

Cause: Requested x402 service is down

Example Usage

Using Fetch API

Payment Workflow Example

Performance Considerations

Streaming Benefits

  • Faster UX: Users see payment progress in real-time

  • Transparency: Live updates on transaction status

  • Efficient: Reduces server memory usage

  • Better Error Handling: Immediate feedback on failures

Response Times

Typical timings:

  • Simple service request: 3-5 seconds total

  • Payment processing: 2-4 seconds (blockchain confirmation)

  • Service data delivery: 1-3 seconds

  • Total end-to-end: 5-10 seconds for most requests

Optimization Tips

  1. Use appropriate chains: Solana for speed, Ethereum for compatibility

  2. Batch requests: Multiple services in one transaction (coming soon)

  3. Cache service discovery: Store x402 registry results

  4. Pre-approve gas: Higher gas price for faster confirmations

Security Features

Spending Limit Enforcement

Transaction Verification

Rate Limiting

  • Client-side: 50-second cooldown between requests

  • Server-side: maxDuration prevents long-running abuse

  • Wallet-side: Transaction signing requires user approval

Input Validation

The endpoint validates:

  • Request structure and types

  • Wallet address format

  • Spending limit values

  • Message content safety

Monitoring

Track in production:

  • Request count: Total API calls

  • Payment success rate: % of successful transactions

  • Average payment time: Blockchain confirmation speed

  • Error rate: Failed payments and reasons

  • Service usage: Which x402 services are most popular

  • Gas costs: Average gas fees per transaction

  • Spending by user: Total spent per wallet address

Logging Example

Cost Optimization

Gas Optimization

Service Selection

Testing

Manual Testing

Automated Testing


Need help? Check Troubleshooting or open an issue.

Last updated