Skip to content
Shell
5.8 KB
Raw Blame
/**
 * Thread Analyzer using Claude
 * Extracts market research insights from Reddit threads
 */

import Anthropic from '@anthropic-ai/sdk';
import type { ThreadData, MarketInsight, PainPoint, Opportunity, CompetitorMention, BuyingSignal, KeyQuote } from '../types.js';

const ANALYSIS_PROMPT = `You are a market research analyst. Analyze this Reddit thread and extract actionable business insights.

Return your analysis as JSON with this exact structure:
{
  "painPoints": [
    {
      "description": "Brief description of the pain point",
      "frequency": 1-10 (how often mentioned),
      "sentiment": "frustrated" | "annoyed" | "desperate" | "neutral",
      "quotes": ["exact quote 1", "exact quote 2"]
    }
  ],
  "opportunities": [
    {
      "description": "Product/feature/service opportunity",
      "type": "product" | "feature" | "service" | "content",
      "confidence": "high" | "medium" | "low",
      "targetAudience": "Who would buy this"
    }
  ],
  "competitorMentions": [
    {
      "name": "Product/Company name",
      "sentiment": "positive" | "negative" | "neutral",
      "context": "Why they mentioned it",
      "frequency": 1
    }
  ],
  "buyingSignals": [
    {
      "quote": "Exact quote showing buying intent",
      "author": "username",
      "signalType": "looking" | "considering" | "ready" | "switched",
      "score": comment_score
    }
  ],
  "keyQuotes": [
    {
      "text": "Insightful quote",
      "author": "username",
      "score": comment_score,
      "insightType": "pain_point" | "opportunity" | "competitor" | "general"
    }
  ],
  "summary": "2-3 sentence summary of key insights and opportunities"
}

Focus on:
1. Real pain points people are experiencing
2. Products/features they wish existed
3. Competitors mentioned (positively or negatively)
4. Buying signals (looking for, considering, switched to)
5. High-engagement comments (high score = resonates with community)

THREAD DATA:
`;

/**
 * Format thread for analysis
 */
function formatThreadForAnalysis(data: ThreadData): string {
  const { post, metrics, topComments } = data;

  let content = `# ${post.title}\n\n`;
  content += `**Subreddit:** r/${post.subreddit}\n`;
  content += `**Score:** ${post.score} | **Upvote Ratio:** ${Math.round(post.upvoteRatio * 100)}%\n`;
  content += `**Comments:** ${metrics.totalComments} | **Unique Authors:** ${metrics.uniqueAuthors}\n\n`;

  content += `## Original Post\n\n${post.selftext || '*No content*'}\n\n`;

  content += `## Top Comments (${topComments.length})\n\n`;

  for (const comment of topComments) {
    const indent = '  '.repeat(comment.depth);
    content += `${indent}### [${comment.score} pts] u/${comment.author}\n`;
    content += `${indent}${comment.body.slice(0, 600)}${comment.body.length > 600 ? '...' : ''}\n\n`;
  }

  return content;
}

/**
 * Analyze a thread using Claude
 */
export async function analyzeThread(
  data: ThreadData,
  options: { apiKey?: string } = {}
): Promise<MarketInsight> {
  const client = new Anthropic({
    apiKey: options.apiKey || process.env.ANTHROPIC_API_KEY,
  });

  const threadContent = formatThreadForAnalysis(data);

  const response = await client.messages.create({
    model: 'claude-sonnet-4-20250514',
    max_tokens: 4096,
    messages: [
      {
        role: 'user',
        content: ANALYSIS_PROMPT + threadContent,
      },
    ],
  });

  // Extract JSON from response
  const responseText = response.content[0].type === 'text' ? response.content[0].text : '';

  // Find JSON in response (may be wrapped in markdown code block)
  const jsonMatch = responseText.match(/\{[\s\S]*\}/);
  if (!jsonMatch) {
    throw new Error('Failed to extract JSON from Claude response');
  }

  const analysis = JSON.parse(jsonMatch[0]);

  return {
    id: crypto.randomUUID(),
    threadUrl: data.post.url,
    subreddit: data.post.subreddit,
    extractedAt: new Date().toISOString(),
    painPoints: analysis.painPoints || [],
    opportunities: analysis.opportunities || [],
    competitorMentions: analysis.competitorMentions || [],
    buyingSignals: analysis.buyingSignals || [],
    keyQuotes: analysis.keyQuotes || [],
    summary: analysis.summary || '',
  };
}

/**
 * Quick analysis without Claude (pattern matching)
 */
export function quickAnalyze(data: ThreadData): Partial<MarketInsight> {
  const allText = [
    data.post.title,
    data.post.selftext,
    ...data.allComments.map(c => c.body),
  ].join('\n').toLowerCase();

  // Pattern-based competitor detection
  const competitorPatterns = [
    /canva/gi, /figma/gi, /notion/gi, /slack/gi, /shopify/gi,
    /stripe/gi, /mailchimp/gi, /hubspot/gi, /salesforce/gi,
    /airtable/gi, /zapier/gi, /vercel/gi, /supabase/gi,
  ];

  const competitors: CompetitorMention[] = [];
  for (const pattern of competitorPatterns) {
    const matches = allText.match(pattern);
    if (matches) {
      competitors.push({
        name: matches[0],
        sentiment: 'neutral',
        context: 'Mentioned in discussion',
        frequency: matches.length,
      });
    }
  }

  // Pattern-based buying signals
  const buyingPatterns = [
    { pattern: /looking for|searching for|need a/gi, type: 'looking' as const },
    { pattern: /considering|thinking about|might try/gi, type: 'considering' as const },
    { pattern: /just bought|just purchased|signed up for/gi, type: 'ready' as const },
    { pattern: /switched from|moved from|replaced/gi, type: 'switched' as const },
  ];

  const signals: BuyingSignal[] = [];
  for (const comment of data.topComments.slice(0, 10)) {
    for (const { pattern, type } of buyingPatterns) {
      if (pattern.test(comment.body)) {
        signals.push({
          quote: comment.body.slice(0, 200),
          author: comment.author,
          signalType: type,
          score: comment.score,
        });
        break;
      }
    }
  }

  return {
    competitorMentions: competitors,
    buyingSignals: signals,
  };
}