AI Model Wiki

    Skip to main content
    20 min
    Lesson 5 of 5

    Hands-On Practice

    From the course Serverless AI Deployment

    Put what you have learned in this course into practice with the structured exercise below. Working through it end-to-end is the single best way to consolidate the concepts.

    Concrete Starter Project: Build a Serverless AI Document Summarizer

    This project wires together every concept from the course: a serverless function that accepts file uploads, summarizes documents using an AI API, returns results via polling, and protects against abuse with rate limiting.

    What You'll Build

    A URL-based document summarizer: POST a public URL (PDF, article, blog post), receive a job ID, poll for the result. No local server required — deploy to Supabase Edge Functions in minutes.

    Step 1 — Create the Edge Function

    // supabase/functions/summarize/index.ts
    import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
    import { Ratelimit } from "https://esm.sh/@upstash/ratelimit@1";
    import { Redis } from "https://esm.sh/@upstash/redis@1";
    
    const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(5, "60 s") });
    
    Deno.serve(async (req) => {
      const userId = req.headers.get("x-user-id") ?? "anonymous";
      const { success } = await ratelimit.limit(userId);
      if (!success) return new Response("Rate limit exceeded", { status: 429 });
    
      const { url } = await req.json();
      const jobId = crypto.randomUUID();
    
      // Store pending job
      const supabase = createClient(Deno.env.get("SUPABASE_URL")!, Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!);
      await supabase.from("summary_jobs").insert({ id: jobId, status: "pending", url });
    
      // Fire-and-forget: process async
      EdgeRuntime.waitUntil(processJob(jobId, url, supabase));
    
      return new Response(JSON.stringify({ jobId }), { headers: { "Content-Type": "application/json" } });
    });
    

    Step 2 — Process the Job Async

    async function processJob(jobId: string, url: string, supabase: any) {
      try {
        const text = await fetch(url).then(r => r.text());
        const truncated = text.slice(0, 12000); // Stay within token budget
    
        const response = await fetch("https://api.anthropic.com/v1/messages", {
          method: "POST",
          headers: { "x-api-key": Deno.env.get("ANTHROPIC_API_KEY")!, "content-type": "application/json", "anthropic-version": "2023-06-01" },
          body: JSON.stringify({ model: "claude-haiku-4-5", max_tokens: 512, messages: [{ role: "user", content: `Summarize this in 3 bullet points:\n\n${truncated}` }] }),
        });
        const data = await response.json();
        const summary = data.content[0].text;
    
        await supabase.from("summary_jobs").update({ status: "done", summary }).eq("id", jobId);
      } catch (e) {
        await supabase.from("summary_jobs").update({ status: "error", error: String(e) }).eq("id", jobId);
      }
    }
    

    Step 3 — Poll for Results

    # Check status
    curl https://<project>.supabase.co/rest/v1/summary_jobs?id=eq.<jobId> \
      -H "apikey: <anon-key>"
    

    Self-Check Questions

    • What happens if the source URL returns an HTML page with ads and nav — how do you extract clean text?
    • How would you add authentication so only logged-in users can submit jobs?
    • What is the maximum document size before you exceed the AI model's context window?

    Stretch Goal

    Add a webhook callback: instead of polling, POST the summary to a client-supplied URL when the job completes. Validate the callback URL with a SSRF check before storing it.

    Key Takeaways

    • •Hands-on application converts course concepts into real skill
    • •Start small with an MVP before optimising
    • •Self-check questions catch gaps in understanding before they ship to production
    0 of 5 lessons marked complete

    Progress is kept in this browser only.