Skip to main content

Overview

The Groq Service provides AI-powered natural language processing for cryptocurrency trading commands and investment advice. It uses OpenRouter AI (Grok-4.1-fast) to parse user commands into structured trade requests and generate intelligent responses.

Core Functions

generateAIResponse

Generates AI-powered responses for general cryptocurrency advice and conversation.
userMessage
string
required
The user’s input message to process
conversationHistory
ChatMessage[]
default:"[]"
Previous conversation context for contextual responses
response
Promise<string>
AI-generated response text in markdown format

Example Usage

import { generateAIResponse } from './services/groqService';

// Simple query
const response = await generateAIResponse(
  "What's the best DCA strategy for Bitcoin?"
);

// With conversation history
const history = [
  { role: 'user', content: 'Tell me about Bitcoin' },
  { role: 'assistant', content: 'Bitcoin is...' }
];
const contextualResponse = await generateAIResponse(
  "What about its price trends?",
  history
);

parseTradeRequest

Parses natural language trading commands into structured trade requests using AI.
message
string
required
The user’s trading command (e.g., “buy $100 btc”, “sell all eth”)
lastToken
string
Last mentioned token from conversation context for contextual commands
tradeRequest
TradeRequest | null
Parsed trade request object or null if not a trade command

Supported Trade Types

interface BuyRequest {
  type: 'buy';
  amount: number;
  token: string;
  slippage?: number;      // Default: 0.5%
  isTokenAmount?: boolean; // true = token amount, false = USD
}

Supported Tokens

  • Major Cryptocurrencies: BTC, ETH, SOL, BNB, XRP
  • Layer 1s: TON, AVAX, ADA, TRX
  • Meme Coins: DOGE
  • Stablecoins: USDC

Token Aliases

The parser recognizes common aliases:
  • bitcoin, btc → BTC
  • ethereum, eth, ether → ETH
  • solana, sol → SOL
  • binance coin, bnb → BNB
  • ripple, xrp → XRP
  • And more…

Example Patterns

// USD amount
await parseTradeRequest("buy $100 btc");
// Result: { type: 'buy', amount: 100, token: 'BTC', isTokenAmount: false }

// Token amount
await parseTradeRequest("buy 0.1 btc");
// Result: { type: 'buy', amount: 0.1, token: 'BTC', isTokenAmount: true }

// Hindi/Hinglish
await parseTradeRequest("kharido 75$ sol");
// Result: { type: 'buy', amount: 75, token: 'SOL', isTokenAmount: false }

Usage in DCAPage.tsx

DCAPage.tsx (Line 541-617)
// Check for trade commands
const tradeRequest = await parseTradeRequest(userInput, lastMentionedToken || undefined);

if (tradeRequest) {
  // Convert MAX to actual balance
  if (typeof tradeRequest.amount === 'string' && tradeRequest.amount === 'MAX') {
    const balanceMap = {
      'BTC': btcBalance || '0',
      'ETH': ethBalance || '0',
      'SOL': solBalance || '0',
      // ... other tokens
    };
    
    let tokenToCheck = '';
    if (tradeRequest.type === 'buy') tokenToCheck = 'USDC';
    else if (tradeRequest.type === 'sell') tokenToCheck = tradeRequest.token;
    else if (tradeRequest.type === 'swap') tokenToCheck = tradeRequest.fromToken;
    
    const actualBalance = parseFloat(balanceMap[tokenToCheck]);
    if (actualBalance > 0) {
      tradeRequest.amount = actualBalance;
    }
  }
  
  // Create trade confirmation card
  const tradeCardMessage = {
    id: generateChatId(),
    text: `I've created a ${tradeRequest.type} order based on your request.`,
    sender: 'ai',
    type: 'trade-card',
    tradeParams: tradeRequest
  };
  
  setMessages(prev => [...prev, tradeCardMessage]);
}

parseDCARequest

Parses natural language DCA/SIP investment plan requests.
message
string
required
User message containing DCA/SIP plan details
dcaRequest
DCARequest | null
Parsed DCA parameters or null if not a DCA request

DCARequest Interface

interface DCARequest {
  amount: number;      // USD amount per interval
  token: string;       // BTC, ETH, or SOL
  frequency: 'daily' | 'weekly' | 'monthly';
  duration: number;    // Duration in months
  startDay?: string;   // e.g., "Monday", "1st", "15th"
}

Example Patterns

await parseDCARequest("DCA $100 in BTC every Monday for 6 months");
// Result:
// {
//   amount: 100,
//   token: 'BTC',
//   frequency: 'weekly',
//   duration: 6,
//   startDay: 'Monday'
// }

Usage Example

DCAPage.tsx (Line 619-638)
const dcaRequest = parseDCARequest(userInput);

if (dcaRequest) {
  setTimeout(() => {
    const dcaCardMessage = {
      id: generateChatId(),
      text: 'I\'ve created a DCA plan based on your request.',
      sender: 'ai',
      timestamp: new Date(),
      type: 'dca-card',
      dcaParams: dcaRequest
    };
    
    setMessages(prev => [...prev, dcaCardMessage]);
    addMessageToConversation(chatId, dcaCardMessage, address);
    setIsTyping(false);
  }, 1500);
  
  return;
}

Type Definitions

ChatMessage

interface ChatMessage {
  role: 'system' | 'user' | 'assistant';
  content: string;
}

TradeRequest Union Type

type TradeRequest = 
  | BuyRequest 
  | SellRequest 
  | SwapRequest 
  | VaultRequest 
  | null;

AI Training Data

The trade parser is trained on 614,097 real-world examples with:
  • Portfolio queries: 1,497 variations
  • Buy commands: 56,940 variations
  • Sell commands: 32,940 variations
  • Swap commands: 522,720 variations
  • Target accuracy: 99.5%

Error Handling

All functions include fallback mechanisms:
try {
  const tradeRequest = await parseTradeRequest("buy btc");
  if (!tradeRequest) {
    console.log('Not a trade command');
  }
} catch (error) {
  console.error('AI parsing error:', error);
  // Falls back to regex-based parser
}

Best Practices

Context Awareness

Always pass lastToken parameter when using parseTradeRequest for contextual commands like “sell these” or “buy more”.

Balance Validation

Always validate user balances before executing MAX orders. The parser returns ‘MAX’ as a string that needs conversion to actual balance.

Conversation History

Maintain conversation history for better AI responses. The AI uses context to provide more relevant answers.

Slippage Defaults

All trade requests default to 0.5% slippage. Adjust based on market conditions and user preferences.

Language Support

  • English: buy, sell, swap, stake
  • Hindi/Hinglish: kharido, becho, badlo, jama, nikalo

API Configuration

const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/chat/completions';
const OPENROUTER_MODEL = 'x-ai/grok-4.1-fast:free';
const SITE_URL = 'https://gweai.com';
const SITE_NAME = 'GweAI';
Requires VITE_OPENAI_API_KEY environment variable for OpenRouter API access.

Build docs developers (and LLMs) love