Skip to main content

Overview

The AI Service provides intelligent, context-aware DeFi strategy generation using Google’s Gemini 1.5 Flash model. It analyzes user portfolios, risk profiles, and available protocols to deliver personalized recommendations. Source: src/services/aiService.js

getAIStrategy

Generate a personalized DeFi strategy based on user portfolio and preferences.

Function Signature

async function getAIStrategy({
  address,
  stxBalance,
  sbtcBalance,
  totalUSD,
  riskProfile,
  protocols,
  strategyCount = 0,
  txCount = 0,
}): Promise<string>

Parameters

address
string
required
User’s Stacks wallet address (used for context in AI prompt)
stxBalance
string
required
User’s STX token balance (e.g., “100.5000”)
sbtcBalance
string
required
User’s sBTC token balance (e.g., “0.00500000”)
totalUSD
string
required
Total portfolio value in USD (e.g., “285.50”)
riskProfile
string
required
User’s risk tolerance: "Conservative", "Balanced", or "Aggressive"
protocols
array
required
Array of available DeFi protocols. Each protocol should have:
  • name (string): Protocol name
  • type (string): Protocol type (Lending, DEX, Yield, Stacking)
  • apy (string): Annual percentage yield
  • risk (string): Risk level (Low, Medium, High)
  • asset (string): Accepted assets (STX, sBTC, etc.)
  • tvl (string): Total value locked
strategyCount
number
default:0
Number of strategies previously generated for this user. Used to personalize recommendations for new vs. experienced users.
txCount
number
default:0
User’s transaction count. Helps identify DeFi experience level.

Return Value

strategy
string
Formatted markdown strategy text with personalized recommendations. Includes:
  • Welcome message (for new users) or strategy overview
  • Specific protocol recommendations
  • Allocation percentages
  • Projected returns
  • Risk assessment
  • Step-by-step execution instructions

User Experience Personalization

The AI adapts its response based on user experience:
Criteria: strategyCount === 0 && txCount < 3Strategy Format:
  • Warm welcome to Bitcoin DeFi
  • Single, simple starting protocol
  • Plain English explanations
  • Basic concepts and analogies
  • Conservative recommendations
  • Detailed step-by-step guide
👋 WELCOME TO BITCOIN DEFI
🎯 YOUR FIRST STRATEGY
📖 WHAT THIS MEANS
💰 WHAT YOU COULD EARN
🛡️ IS IT SAFE?
🚀 HOW TO START

Usage Example

import { getAIStrategy } from './services/aiService';
import { PROTOCOLS } from './services/protocolData';

// Get strategy for a new user
const strategy = await getAIStrategy({
  address: 'SP2H8PY27SEZ03MWRKS5XABZYQN17ETGQS3527SA5',
  stxBalance: '100.0000',
  sbtcBalance: '0.00000000',
  totalUSD: '285.00',
  riskProfile: 'Balanced',
  protocols: PROTOCOLS,
  strategyCount: 0,
  txCount: 1,
});

console.log(strategy);

API Configuration

VITE_GEMINI_API_KEY
string
required
Google Gemini API key. Set this in your .env file:
VITE_GEMINI_API_KEY=your_gemini_api_key_here
The service automatically uses:
  • Direct API access in production (Vercel)
  • Localhost proxy in development (optional)
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${import.meta.env.VITE_GEMINI_API_KEY}`;

AI Model Configuration

temperature
number
Controls randomness in AI responses (0.0 = deterministic, 1.0 = creative)
maxOutputTokens
number
default:1500
Maximum length of generated strategy text
generationConfig: {
  temperature: 0.7,
  maxOutputTokens: 1500,
}

Error Handling

The service throws errors with descriptive messages:
try {
  const strategy = await getAIStrategy({...});
} catch (error) {
  console.error('AI strategy generation failed:', error.message);
  // Example errors:
  // - "AI request failed"
  // - "Invalid API key"
  // - "Rate limit exceeded"
}

Protocol Data Format

The protocols parameter expects this structure:
const protocols = [
  {
    name: 'Zest Protocol',
    type: 'Lending',
    apy: '8.2',
    tvl: '$48.2M',
    asset: 'sBTC',
    risk: 'Low',
    description: 'Lend and borrow Bitcoin-backed assets...',
    url: 'https://zestprotocol.com',
  },
  // ... more protocols
];

Prompt Engineering

The AI uses a sophisticated prompt that includes:
1

Context Setting

Establishes AI persona as “Staxiq, the smartest Bitcoin DeFi copilot”
2

User Analysis

Provides complete portfolio snapshot and transaction history
3

Protocol Overview

Lists all available protocols with APY, TVL, and risk metrics
4

Experience Adaptation

Adjusts instruction style based on user’s DeFi experience level
5

Format Specification

Enforces consistent markdown output format for easy parsing

Performance Optimization

Fast Model

Uses Gemini 1.5 Flash for sub-second response times

Direct API

Bypasses proxies in production for minimal latency

Efficient Prompts

Optimized token usage with concise protocol summaries

Error Recovery

Graceful fallbacks with descriptive error messages

Best Practices

  1. Always provide up-to-date protocol data to ensure accurate recommendations
  2. Include transaction history for better user experience personalization
  3. Handle loading states to inform users the AI is working (can take 2-5 seconds)
  4. Cache strategies if user re-requests without changing parameters
  5. Sanitize strategy output before rendering (remove potentially unsafe markdown)

Build docs developers (and LLMs) love