Skip to content
ai-feature-template logo

Creating AI Features with xAI Grok

ai-feature-template

Create new AI-powered features using xAI Grok. Use when user mentions "new AI feature", "add Grok", "create prompt", "AI analysis", or "generate with AI".

SKILL.md

Full skill instructions

Creating AI Features with xAI Grok

This project uses xAI's Grok model for AI-powered features with X (Twitter) search capabilities.

Instructions

  1. Create API route at app/​api/<feature-name>/​route.ts

  2. Use this template for Grok with X search:

import { NextRequest, NextResponse } from 'next/​server';

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};

// Define your AI persona and instructions
const systemPrompt = `You are [PERSONA NAME], a [ROLE DESCRIPTION].

Your task is to [WHAT TO DO] based on the X account data.

Output Requirements:
- [REQUIREMENT 1]
- [REQUIREMENT 2]
- [FORMAT INSTRUCTIONS]

CRITICAL: Output ONLY the result. No preamble, no explanations.`;

export async function OPTIONS() {
  return NextResponse.json(null, { headers: corsHeaders });
}

export async function POST(req: NextRequest) {
  try {
    const { handle } = await req.json();

    const HANDLE_REGEX = /^[a-zA-Z0-9_]{1,15}$/;
    if (!handle || !HANDLE_REGEX.test(handle)) {
      return NextResponse.json(
        { error: 'Invalid X handle format.' },
        { status: 400, headers: corsHeaders }
      );
    }

    const xaiApiKey = process.env.XAI_API_KEY;
    if (!xaiApiKey) {
      return NextResponse.json(
        { error: 'XAI_API_KEY not configured' },
        { status: 500, headers: corsHeaders }
      );
    }

    // Build 6-month date range for X search
    const today = new Date();
    const toDate = today.toISOString().split('T')[0];
    const sixMonthsAgo = new Date(today.getTime() - 182 * 24 * 60 * 60 * 1000);
    const fromDate = sixMonthsAgo.toISOString().split('T')[0];

    const response = await fetch('https://api.x.ai/​v1/​chat/​completions', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${xaiApiKey}`,
        'Content-Type': 'application/​json',
      },
      body: JSON.stringify({
        // DO NOT CHANGE - grok-4-1-fast required for X search
        model: 'grok-4-1-fast',
        messages: [
          { role: 'system', content: systemPrompt },
          {
            role: 'user',
            content: `Analyze @${handle}'s posts and [SPECIFIC INSTRUCTION].`,
          },
        ],
        search_parameters: {
          mode: 'on',
          sources: [{ type: 'x' }],
          from_date: fromDate,
          to_date: toDate,
        },
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error('xAI API error:', response.status, errorText);
      return NextResponse.json(
        { error: `xAI API error: ${response.status}` },
        { status: response.status, headers: corsHeaders }
      );
    }

    const data = await response.json();
    const result = data.choices?.[0]?.message?.content;

    if (!result) {
      return NextResponse.json(
        { error: 'No result generated' },
        { status: 500, headers: corsHeaders }
      );
    }

    return NextResponse.json({ result }, { headers: corsHeaders });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500, headers: corsHeaders }
    );
  }
}
  1. Add frontend handler in app/​page.tsx:
const handleNewFeature = async () => {
  setIsLoading(true);
  try {
    const response = await fetch('/​api/​feature-name', {
      method: 'POST',
      headers: { 'Content-Type': 'application/​json' },
      body: JSON.stringify({ handle: normalizedHandle }),
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.error);
    setResult(data.result);
    toast.success('Generated!');
  } catch (err) {
    toast.error('Failed');
  } finally {
    setIsLoading(false);
  }
};

Existing AI Prompts (Reference)

FeaturePersonaOutput
analyze-accountArt Director4-6 sentence image prompt
roast-accountDr. Burn Notice300-400 word therapy letter
fbi-profileFBI AnalystClassified behavioral report

Prompt Best Practices

  • Define clear persona with voice/​tone
  • Specify exact output format and length
  • Include "Output ONLY..." to prevent preamble
  • Add examples for complex outputs
  • Use "CRITICAL RULES" section for must-follow instructions

Examples

  • "Create a horoscope generator" → New route with astrologer persona
  • "Add personality summary" → New route with psychologist persona

Guardrails

  • Always use grok-4-1-fast model for X search capability
  • Include 6-month date range for search parameters
  • Never log or expose API keys
  • Handle API errors gracefully with user-friendly messages
  • Test prompts for safety/​appropriateness before deploying

More Marketing skills

copywriting logo
Marketing

copywriting

Marketing copy for homepages, landing pages, pricing pages, and other conversion-focused web pages.

53.3K 216.1K
View
flux-2-klein logo
Marketing

flux-2-klein

Fast image generation with Flux 2 Klein, optimized for sub-second iteration and multi-reference brand styling.

52 176.2K
View

Psychological principles and mental models for understanding customer behavior and influencing marketing decisions.

53.3K 153K
View

Plan searchable and shareable content that drives traffic, builds authority, and generates leads.

53.3K 150.9K
View

Build SEO-optimized pages at scale using templates, data, and proven playbook patterns.

53.3K 140.1K
View

Brainstorm and prioritize marketing strategies tailored to your SaaS stage, budget, and goals.

53.3K 137.2K
View
ai-seo logo
Marketing

ai-seo

Optimize content for discovery, citation, and visibility across AI search platforms and LLM assistants.

53.3K 136.7K
View
copy-editing logo
Marketing

copy-editing

Systematic improvement of existing marketing copy through seven focused editing passes.

53.3K 136.4K
View

Plan and optimize your website's page hierarchy, navigation, URL structure, and internal linking.

53.3K 112.8K
View
revops logo
Marketing

revops

Design and optimize systems connecting marketing, sales, and customer success into a unified revenue engine.

53.3K 104.9K
View

Applies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.

179.7K 100.1K
View

Convert websites into professional HyperFrames videos with guided storyboarding and brand-aligned composition.

57K 93.5K
View

Sales & marketing AI tools

KreadoAI logo
Sales & marketing

KreadoAI

Revolutionize Video Creation with AI-Generated Avatars and Voices

Paid
View
Followr logo
Sales & marketing

Followr

Social media on autopilot

Paid
View
Logodiffusion logo
Sales & marketing

Logodiffusion

Design custom logos instantly with AI.

Paid
View
I
Sales & marketing

Ideogram

Text-heavy marketing and design images

Freemium
View
Prompt Silo logo
Sales & marketing

Prompt Silo

Boost Your SEO with Content and SEO Silos

Free
View
Marketing Blocks logo
Sales & marketing

Marketing Blocks

Revolutionize Your Marketing with AI-Powered MarketingBlocks!

Paid
View
Scrip AI logo
Sales & marketing

Scrip AI

10X faster & free AI content creation for 100+ use cases

Free
View
Tribescaler logo
Sales & marketing

Tribescaler

Tribescaler | Make Your Tweets Go Viral

Paid
View