דלג לתוכן הראשי
AI • מערכות חכמות

מערכות AI מתקדמות ב-Next.js 14 - מהתחלה ועד ייצור

לומדים לבנות מערכות AI מתקדמות ב-Next.js 14. כולל דוגמאות קוד, ארכיטקטורה, וטיפים מקצועיים. מדריך מקיף לבניית מערכות AI production-ready.

4 דקות קריאהAI

במדריך הזה נלמד איך לבנות מערכות AI מתקדמות ב-Next.js 14, מהתחלה ועד ייצור.

ארכיטקטורה מומלצת

1. Server Components

השתמש ב-Server Components לעיבוד ראשוני:

// app/ai-chat/page.tsx
export default async function AIChatPage() {
  const initialData = await fetchInitialData();
  return <AIChat initialData={initialData} />;
}

2. API Routes

צור API routes ייעודיים ל-AI:

// app/api/ai/chat/route.ts
export async function POST(req: Request) {
  const { prompt } = await req.json();
  
  // Validation
  if (!prompt || prompt.length < 3) {
    return Response.json({ error: 'Prompt too short' }, { status: 400 });
  }
  
  // Rate limiting
  const rateLimit = await checkRateLimit(req);
  if (!rateLimit.allowed) {
    return Response.json({ error: 'Rate limit exceeded' }, { status: 429 });
  }
  
  // AI processing
  const response = await aiService.generate(prompt);
  return Response.json({ response });
}

3. Client Components

השתמש ב-Client Components לאינטראקטיביות:

// components/ai-chat.tsx
'use client';

export function AIChat() {
  const [messages, setMessages] = useState([]);
  const [loading, setLoading] = useState(false);
  
  const sendMessage = async (prompt: string) => {
    setLoading(true);
    try {
      const response = await fetch('/api/ai/chat', {
        method: 'POST',
        body: JSON.stringify({ prompt }),
      });
      const data = await response.json();
      setMessages([...messages, data.response]);
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <div>
      {/* Chat UI */}
    </div>
  );
}

דפוסים מתקדמים

1. Streaming Responses

// app/api/ai/stream/route.ts
export async function POST(req: Request) {
  const { prompt } = await req.json();
  
  const stream = new ReadableStream({
    async start(controller) {
      const aiStream = await aiService.streamResponse(prompt);
      
      for await (const chunk of aiStream) {
        controller.enqueue(new TextEncoder().encode(chunk));
      }
      
      controller.close();
    },
  });
  
  return new Response(stream, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
    },
  });
}

2. Error Recovery

async function generateWithRetry(prompt: string, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await aiService.generate(prompt);
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await sleep(1000 * (i + 1)); // Exponential backoff
    }
  }
}

3. Context Management

class AIContextManager {
  private context: Message[] = [];
  
  addMessage(message: Message) {
    this.context.push(message);
    // Keep only last 10 messages
    if (this.context.length > 10) {
      this.context.shift();
    }
  }
  
  getContext(): Message[] {
    return this.context;
  }
  
  clear() {
    this.context = [];
  }
}

אופטימיזציות Production

1. Caching Strategy

// Use Redis for production caching
import { Redis } from 'ioredis';

const redis = new Redis(process.env.REDIS_URL);

async function getCachedResponse(prompt: string) {
  const key = `ai:${hashPrompt(prompt)}`;
  const cached = await redis.get(key);
  
  if (cached) {
    return JSON.parse(cached);
  }
  
  const response = await aiService.generate(prompt);
  await redis.setex(key, 3600, JSON.stringify(response)); // 1 hour TTL
  
  return response;
}

2. Monitoring

// Track AI usage
async function trackAIUsage(prompt: string, response: string, latency: number) {
  await analytics.track('ai_request', {
    prompt_length: prompt.length,
    response_length: response.length,
    latency,
    timestamp: Date.now(),
  });
}

3. Rate Limiting

// Implement rate limiting
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';

const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(10, '1 m'), // 10 requests per minute
});

export async function checkRateLimit(req: Request) {
  const ip = req.headers.get('x-forwarded-for') || 'unknown';
  const { success, limit, remaining } = await ratelimit.limit(ip);
  
  return { allowed: success, limit, remaining };
}

Security Best Practices

1. Input Validation

import { z } from 'zod';

const promptSchema = z.object({
  prompt: z.string().min(3).max(1000),
  context: z.string().optional(),
});

export async function POST(req: Request) {
  const body = await req.json();
  const validated = promptSchema.safeParse(body);
  
  if (!validated.success) {
    return Response.json({ error: 'Invalid input' }, { status: 400 });
  }
  
  // Use validated.data
}

2. API Key Management

// Never expose API keys in client code
// Use environment variables
const apiKey = process.env.OPENAI_API_KEY;

if (!apiKey) {
  throw new Error('OPENAI_API_KEY not configured');
}

סיכום

בניית מערכות AI מתקדמות ב-Next.js 14 דורשת:

  • ✅ ארכיטקטורה נכונה (Server + Client Components)
  • ✅ Streaming responses
  • ✅ Error recovery
  • ✅ Caching strategy
  • ✅ Rate limiting
  • ✅ Security best practices

עם הדפוסים האלה, תוכל לבנות מערכות AI production-ready.

מאמרים קשורים