Introducing Socket Firewall: Free, Proactive Protection for Your Software Supply Chain.Learn More
Socket
Book a DemoInstallSign in
Socket

myavana-ai-bot-xai

Package Overview
Dependencies
Maintainers
0
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

myavana-ai-bot-xai

Myavana-specific bot implementation

latest
npmnpm
Version
1.1.2
Version published
Weekly downloads
0
-100%
Maintainers
0
Weekly downloads
 
Created
Source

Myavana xAI Chatbot Package

Specialized implementation using xAI's Grok models for advanced reasoning and hair care consultation.

=� Package Overview

Package Name: myavana-ai-bot-xai
Version: 2.0.0
Purpose: xAI Grok-powered chatbot for advanced reasoning and complex hair care analysis

>� xAI Integration

Why xAI Grok?

xAI's Grok models offer:

  • Advanced Reasoning: Superior logical thinking for complex hair problems
  • Real-time Knowledge: Up-to-date information and trends
  • Conversational Excellence: Natural, engaging dialogue
  • Multi-modal Capabilities: Text and image understanding
  • Fast Response Times: Optimized for quick interactions

<� Features

  • =� xAI Grok Models: Grok-3-mini-fast and Grok-2-vision-latest
  • Advanced Reasoning: Complex problem-solving capabilities

  • =� Vision Analysis: Advanced image understanding with Grok-2-vision
  • Fast Processing: Optimized for quick responses
  • = Smart Fallbacks: Intelligent model switching
  • =� Performance Tracking: Detailed analytics and monitoring
  • <� JSON Responses: Structured, consistent output format

<� Architecture

myavana-xai/
�� src/
   �� index.js              # Main xAI implementation
   �� constructPrompt.js    # xAI-optimized prompts
   �� eventHandlers.js      # Event handling with xAI models
   �� system.js            # System prompts for Grok
�� package.json
�� README.md

=� Quick Start

Installation

# Install dependencies
cd packages/myavana-xai
npm install

# Start server
npm start
# or
node src/index.js

Environment Variables

# xAI Configuration
XAI_API_KEY=your_xai_api_key

# Database
POSTGRES_HOST=localhost
POSTGRES_DB=myavana_bot
POSTGRES_USER=username
POSTGRES_PASSWORD=password

# Redis
REDIS_HOST=localhost
REDIS_PASSWORD=redis_password

# Application
NODE_ENV=production
LOG_LEVEL=info
PORT=3000

> xAI Model Configuration

Model Selection

const xaiModels = {
  chat: 'grok-3-mini-fast',        // Fast chat responses
  vision: 'grok-2-vision-latest',  // Image analysis
  reasoning: 'grok-3-mini-fast'    // Complex problem solving
};

Model Characteristics

Grok-3-mini-fast

  • Speed: Ultra-fast responses (~1-2 seconds)
  • Use Case: Regular chat interactions
  • Strengths: Quick reasoning, conversational
  • Token Limit: Optimized for efficiency

Grok-2-vision-latest

  • Capability: Advanced image understanding
  • Use Case: Hair photo analysis
  • Strengths: Visual reasoning, detailed analysis
  • Multimodal: Text + image processing

=� Chat Flow

xAI-Specific Features

Structured JSON Output

const response = await xai.chat.completions.create({
  model: 'grok-3-mini-fast',
  messages: messages,
  temperature: 1.1,
  response_format: { type: 'json_object' }
});

Advanced Reasoning Prompts

const prompt = `
You are an expert hair care consultant powered by xAI's advanced reasoning.
Analyze the user's hair concern using logical thinking and provide:
1. Root cause analysis
2. Step-by-step solution
3. Scientific reasoning
4. Product recommendations with explanations
`;

=� Advanced Image Analysis

Grok-2-vision Capabilities

When users upload hair photos, Grok-2-vision analyzes:

  • Hair Structure: Detailed curl pattern analysis
  • Condition Assessment: Health indicators and damage signs
  • Scalp Analysis: Visible scalp condition evaluation
  • Product Matching: AI-powered product recommendations
  • Progress Tracking: Comparison with previous photos

Vision Model Implementation

const response = await xai.chat.completions.create({
  model: 'grok-2-vision-latest',
  messages: [
    { role: 'system', content: imageAnalysisPrompt },
    {
      role: 'user',
      content: [
        { type: 'text', text: `User's message: ${message}` },
        { type: 'image_url', image_url: { url: imageUrl } }
      ]
    }
  ]
});

� Performance Optimizations

Response Time Optimization

// Optimized xAI configuration
const xaiConfig = {
  timeout: 360000,  // 6 minutes for complex reasoning
  baseURL: 'https://api.x.ai/v1',
  headers: {
    'Content-Type': 'application/json'
  }
};

// Fast response settings
const chatConfig = {
  model: 'grok-3-mini-fast',
  temperature: 1.1,
  max_tokens: 2000,
  response_format: { type: 'json_object' }
};

= Error Handling & Fallbacks

xAI-Specific Error Handling

try {
  // Primary xAI request
  const response = await xai.chat.completions.create(config);
  return JSON.parse(response.choices[0].message.content);
  
} catch (error) {
  if (error.code === 'rate_limit_exceeded') {
    // Wait and retry
    await sleep(2000);
    return await retryXAIRequest(config);
  }
  
  if (error.code === 'model_overloaded') {
    // Switch to different model
    config.model = 'grok-3-mini-fast';
    return await xai.chat.completions.create(config);
  }
  
  throw error; // Let unified handler manage other errors
}

=� Analytics & Monitoring

xAI-Specific Metrics

const metrics = {
  modelUsage: {
    'grok-3-mini-fast': { requests: 1250, avgResponseTime: 1500 },
    'grok-2-vision-latest': { requests: 340, avgResponseTime: 3200 }
  },
  responseQuality: {
    jsonParseSuccess: 0.98,
    userSatisfaction: 4.6,
    reasoningAccuracy: 0.94
  },
  performanceStats: {
    averageLatency: 1800, // ms
    errorRate: 0.02,
    cacheHitRate: 0.35
  }
};

>� Testing

xAI-Specific Tests

# Run all tests
npm test

# Test xAI integration
npm test -- --grep "xai"

# Test vision capabilities
npm test -- --grep "vision"

# Test response formatting
npm test -- --grep "response"

=� Deployment

Production Configuration

// Production xAI setup
const productionConfig = {
  xai: {
    apiKey: process.env.XAI_API_KEY,
    baseURL: 'https://api.x.ai/v1',
    timeout: 30000,
    retries: 3,
    retryDelay: 1000
  },
  models: {
    primary: 'grok-3-mini-fast',
    vision: 'grok-2-vision-latest',
    fallback: 'grok-3-mini-fast'
  },
  optimization: {
    enableCaching: true,
    cacheTimeout: 300,
    enableMetrics: true,
    enableErrorRecovery: true
  }
};

Health Monitoring

# Check xAI API status
curl -H "Authorization: Bearer $XAI_API_KEY" \
  https://api.x.ai/v1/models

# Test chat endpoint
curl -X POST http://localhost:3000/webhook \
  -H "Content-Type: application/json" \
  -d '{"message": "Test xAI integration", "from": "health-check", "groupId": "test"}'

=� API Documentation

Main Endpoint

POST /webhook

Standard Chat Request

{
  "message": "I have dry, brittle 4C hair. What's the best treatment approach?",
  "from": "user-123",
  "groupId": "conversation-456",
  "eventName": "REGULAR"
}

xAI Processing: Uses Grok-3-mini-fast for advanced reasoning about hair care solutions.

Image Analysis Request

{
  "message": "Please analyze my hair condition",
  "from": "user-123",
  "groupId": "conversation-456",
  "eventName": "KOMMUNICATE_MEDIA_EVENT",
  "metadata": {
    "KM_CHAT_CONTEXT": {
      "attachments": [{
        "type": "image/jpeg",
        "payload": { "url": "https://example.com/hair-photo.jpg" }
      }]
    }
  }
}

xAI Processing: Uses Grok-2-vision-latest for detailed visual analysis.

=' Configuration

xAI Model Settings

const modelSettings = {
  'grok-3-mini-fast': {
    temperature: 1.1,
    maxTokens: 2000,
    topP: 0.9,
    frequencyPenalty: 0.1,
    presencePenalty: 0.1
  },
  'grok-2-vision-latest': {
    temperature: 0.9,
    maxTokens: 3000,
    detail: 'high'
  }
};

= Security

API Key Management

// Secure xAI configuration
const xaiClient = new OpenAI({
  apiKey: process.env.XAI_API_KEY, // Never hardcode
  baseURL: 'https://api.x.ai/v1',
  organization: process.env.XAI_ORG_ID // If applicable
});

<� Troubleshooting

Common xAI Issues

API Rate Limits

Error: Rate limit exceeded
Solution: Implement exponential backoff and request queuing

JSON Parsing Errors

Error: Unexpected token in JSON
Solution: Improve response cleaning and validation

Vision Model Timeouts

Error: Request timeout
Solution: Increase timeout for image analysis requests

Debug Commands

# Test xAI API connectivity
curl -H "Authorization: Bearer $XAI_API_KEY" \
  https://api.x.ai/v1/models

# Enable debug logging
DEBUG=xai:* NODE_ENV=development node src/index.js

=� Performance Metrics

Benchmarks

  • Chat Response: ~1-2 seconds (Grok-3-mini-fast)
  • Image Analysis: ~3-5 seconds (Grok-2-vision-latest)
  • JSON Parse Success: ~98%
  • Error Rate: <2%
  • Cache Hit Rate: ~35%

Optimization Tips

  • Use Appropriate Models: Grok-3-mini-fast for chat, Grok-2-vision for images
  • Implement Caching: Cache common responses to reduce API calls
  • Optimize Prompts: Clear, concise prompts for better performance
  • Handle Errors Gracefully: Implement robust error recovery
  • Monitor Costs: Track token usage and API costs

> Contributing

Development Guidelines

  • Follow xAI Best Practices: Use structured prompts and JSON responses
  • Test Thoroughly: Ensure all xAI integrations work correctly
  • Handle Errors: Implement comprehensive error handling
  • Monitor Performance: Track response times and success rates
  • Document Changes: Update documentation for new features

=� License

Proprietary - Myavana Technology

  • xAI API Documentation - Official xAI documentation
  • Core Package - Shared infrastructure
  • Myavana Package - Main platform bot

Version: 2.0.0
Last Updated: 2024-01-15
Maintainer: Myavana Development Team
Status: Production Ready
Powered by: xAI Grok Models

FAQs

Package last updated on 24 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts