Chat API
The Chat API is the core endpoint that powers Mika402's autonomous payment agent conversations.
Endpoint
POST /api/chatOverview
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
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
0:
Text content chunks
d:
Metadata (finish reason, transaction hash, etc.)
e:
Error messages
p:
Payment status updates
Finish Reasons
stop- Normal completionpayment-complete- Payment processed successfullypayment-failed- Payment failedlimit-exceeded- Spending limit exceededinsufficient-balance- Not enough fundsservice-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 reasoninggemini-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:
Identity: "Mika402" autonomous payment agent
Capabilities:
x402 service discovery
Autonomous payment processing
Spending limit enforcement
Multi-chain transaction handling
Payment directives:
Check limits before every payment
Show cost estimates
Provide transaction transparency
Personality traits: Helpful, transparent, security-conscious
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
Using Vercel AI SDK (Recommended)
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
Use appropriate chains: Solana for speed, Ethereum for compatibility
Batch requests: Multiple services in one transaction (coming soon)
Cache service discovery: Store x402 registry results
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:
maxDurationprevents long-running abuseWallet-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
Recommended Metrics
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
Related Documentation
Need help? Check Troubleshooting or open an issue.
Last updated
