← back to Dear Bubbe Nextjs
app/api/generate/social/route.ts
199 lines
import { NextRequest, NextResponse } from 'next/server'
import Anthropic from '@anthropic-ai/sdk'
import { updateStat } from '../../stats/route'
import { chat as ollamaChat } from '@/lib/llm-local'
// Anthropic SDK kept for optional fallback (USE_ANTHROPIC=1).
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY || ''
})
interface SocialGenerationRequest {
platform: 'instagram' | 'facebook' | 'twitter' | 'pinterest' | 'linkedin'
product?: {
title?: string
sku?: string
description?: string
imageUrl?: string
}
topic?: string
style?: 'casual' | 'professional' | 'humorous' | 'inspirational'
includeHashtags?: boolean
maxLength?: number
}
const PLATFORM_PROMPTS = {
instagram: {
description: 'Instagram post with emojis and hashtags',
maxLength: 2200,
requirements: 'Include 5-10 relevant hashtags, use emojis, keep it visual and engaging'
},
facebook: {
description: 'Facebook post with engaging copy',
maxLength: 500,
requirements: 'Conversational tone, include a call-to-action, encourage engagement'
},
twitter: {
description: 'Twitter/X post',
maxLength: 280,
requirements: 'Concise, witty, include 2-3 hashtags, encourage retweets'
},
pinterest: {
description: 'Pinterest pin description',
maxLength: 500,
requirements: 'SEO-friendly, descriptive, include relevant keywords'
},
linkedin: {
description: 'LinkedIn professional post',
maxLength: 1300,
requirements: 'Professional tone, industry insights, encourage discussion'
}
}
async function generateSocialContent(request: SocialGenerationRequest): Promise<string> {
const platform = PLATFORM_PROMPTS[request.platform]
let prompt = `Create a ${platform.description} for the following:`
if (request.product) {
prompt += `
Product Information:
${request.product.title ? `- Title: ${request.product.title}` : ''}
${request.product.sku ? `- SKU: ${request.product.sku}` : ''}
${request.product.description ? `- Description: ${request.product.description}` : ''}
`
}
if (request.topic) {
prompt += `
Topic: ${request.topic}
`
}
prompt += `
Requirements:
- Maximum length: ${request.maxLength || platform.maxLength} characters
- Platform: ${request.platform.toUpperCase()}
- Style: ${request.style || 'engaging'}
- ${platform.requirements}
${request.includeHashtags !== false ? '- Include relevant hashtags' : '- No hashtags'}
Generate engaging, platform-appropriate content that drives engagement and follows ${request.platform} best practices.`
if (process.env.USE_ANTHROPIC === '1') {
const response = await anthropic.messages.create({
model: 'claude-opus-4-8',
max_tokens: 1024,
messages: [{ role: 'user', content: prompt }]
})
return response.content[0].type === 'text' ? response.content[0].text : ''
}
const { content } = await ollamaChat(
[{ role: 'user', content: prompt }],
{ maxTokens: 1024, temperature: 0.8 }
)
return content
}
export async function POST(request: NextRequest) {
try {
const startTime = Date.now()
const body = await request.json()
const { platform } = body
if (!platform || !(platform in PLATFORM_PROMPTS)) {
return NextResponse.json({
error: 'Valid platform is required',
validPlatforms: Object.keys(PLATFORM_PROMPTS)
}, { status: 400 })
}
const validPlatform = platform as keyof typeof PLATFORM_PROMPTS
const generationRequest: SocialGenerationRequest = {
platform: validPlatform,
product: body.product,
topic: body.topic,
style: body.style || 'engaging',
includeHashtags: body.includeHashtags !== false,
maxLength: body.maxLength
}
console.log(`[SOCIAL] Generating ${validPlatform} content`)
const content = await generateSocialContent(generationRequest)
// Update stats
updateStat('socialPostsGenerated', 1)
updateStat('tasksCompleted', 1)
const responseTime = Date.now() - startTime
console.log(`[SOCIAL] ${validPlatform} content generated in ${responseTime}ms`)
// Check if content exceeds platform limits
const platformLimit = PLATFORM_PROMPTS[validPlatform].maxLength
const isWithinLimit = content.length <= (generationRequest.maxLength || platformLimit)
return NextResponse.json({
success: true,
platform: validPlatform,
content,
meta: {
characterCount: content.length,
maxLength: generationRequest.maxLength || platformLimit,
isWithinLimit,
generationTime: responseTime,
style: generationRequest.style
}
})
} catch (error) {
console.error('[SOCIAL] Error generating social content:', error)
// Update error stats
updateStat('errorsToday', 1)
return NextResponse.json({
error: 'Failed to generate social media content',
details: error instanceof Error ? error.message : String(error)
}, { status: 500 })
}
}
export async function GET(request: NextRequest) {
try {
const url = new URL(request.url)
const examples = url.searchParams.get('examples')
if (examples === 'true') {
// Return example posts for each platform
const exampleContent = {
instagram: "🌟 Introducing our latest masterpiece! ✨\n\nThis stunning wallcovering transforms any space into a work of art. Perfect for accent walls, dining rooms, or anywhere you want to make a statement! 🏠💫\n\nWhat's your favorite room to decorate? Tell us below! 👇\n\n#InteriorDesign #WallCovering #HomeDecor #DesignLovers #WallpaperDesign #HomeStyle #AccentWall #InteriorStyling #DesignInspiration #HomeRenovation",
facebook: "Transform your space with our stunning new wallcovering collection! 🎨\n\nWhether you're updating your dining room, creating a cozy reading nook, or adding drama to an accent wall, our designs bring personality and style to every corner of your home.\n\nReady to reimagine your space? Browse our collection and find your perfect match! What room would you love to transform next?",
twitter: "New wallcovering drop! 🔥 Transform your space with designs that make a statement. Perfect for accent walls and bold interiors. #WallCovering #InteriorDesign #HomeDecor",
pinterest: "Stunning wallcovering design perfect for modern interiors. Features bold patterns and rich colors that create dramatic accent walls. Ideal for dining rooms, living spaces, and bedrooms. High-quality materials ensure long-lasting beauty. Transform your home with sophisticated wall coverings that reflect your personal style.",
linkedin: "The interior design industry continues to evolve, with wallcoverings experiencing a renaissance in both residential and commercial spaces.\n\nOur latest collection reflects current market trends toward bold patterns and sustainable materials. As design professionals seek unique solutions for their clients, quality wallcoverings offer both aesthetic appeal and practical durability.\n\nWhat trends are you seeing in your design projects? How are clients responding to statement walls?"
}
return NextResponse.json({
examples: exampleContent,
platforms: Object.keys(PLATFORM_PROMPTS),
platformLimits: PLATFORM_PROMPTS
})
}
return NextResponse.json({
availablePlatforms: Object.keys(PLATFORM_PROMPTS),
platformLimits: PLATFORM_PROMPTS,
usage: "POST to generate content, add ?examples=true to see sample content"
})
} catch (error) {
console.error('[SOCIAL] Error in GET request:', error)
return NextResponse.json({ error: 'Failed to process request' }, { status: 500 })
}
}