A.I. Integration

A.I. Integration

AI Integration — Plans and builds LLM API connections (OpenAI, Anthropic, and more) into real apps. Covers model selection, cost estimation, key safety, error handling, and working code. Adapts to non-engineers and developers alike. Stops the #1 mistake: shipping your API key to the browser.
#الهندسة#التحليل#التصميم
التقييم
مطلوب المزيد من التقييمات
المبيعات
0
كيفية الاستخدام
تنزيل

🤖 AI Integration Skill

🧠 What It Does

Capability Description
📋 Integration Plan Picks the right model, estimates cost, identifies risks before a line of code is written
🔐 Key-Safe Architecture Enforces server-side key storage — never exposes API keys to the browser
⚙️ Working Code Delivers a complete, runnable integration tailored to the user's stack
🧩 Structured Output Builds defensively-parsed JSON pipelines when the app consumes the result
💸 Cost Discipline Right-sizes the model to the task — doesn't default to the expensive one
🔁 Error Handling Wraps calls with retries, backoff, and clean fallbacks — no silent crashes
🎯 Audience Adaptation Plain steps for non-engineers; architecture + trade-offs for developers

⚡ Quick Example — Non-Engineer (Lovable + ChatGPT Chatbot)

User prompt:

"I have a Lovable site. I want to add a chatbot using ChatGPT. How do I connect it?"

Skill output (server function piece):

// Runs on the SERVER — browser never sees the key
export default async function handler(req) {
  try {
    const { message } = await req.json();
    if (!message) return new Response(
      JSON.stringify({ error: "No message" }), { status: 400 }
    );

    const res = await fetch("https://api.openai.com/v1/chat/completions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${process.env.OPENAI_API_KEY}`, // env var, not hardcoded
      },
      body: JSON.stringify({
        model: "<current-model-id>",  // confirm in OpenAI docs
        max_tokens: 500,              // cost guard
        messages: [
          { role: "system", content: "You are a friendly assistant for this website." },
          { role: "user", content: message },
        ],
      }),
    });

    if (!res.ok) throw new Error("OpenAI error " + res.status);
    const data = await res.json();
    const reply = data.choices?.[0]?.message?.content ?? "Sorry, try again.";
    return new Response(JSON.stringify({ reply }), { status: 200 });

  } catch {
    return new Response(
      JSON.stringify({ reply: "Assistant is busy, please try again." }),
      { status: 200 }
    );
  }
}

Also included in output: plain-language plan, setup steps (env var, deploy, test), spending-limit reminder.


⚡ Quick Example — Developer (Express + Anthropic, JSON Classification)

User prompt:

"Node/Express app. Classify support emails as billing / technical / general. Return JSON. Use Anthropic."

Skill output (classification function):

const ALLOWED = ["billing", "technical", "general"];

async function classifyEmail(emailText) {
  const res = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": process.env.ANTHROPIC_API_KEY,  // server-side only
      "anthropic-version": "2023-06-01",            // confirm current in docs
    },
    body: JSON.stringify({
      model: "<current Haiku-tier model id>",       // small model — right-sized for this task
      max_tokens: 50,                               // tiny output = near-zero cost
      system: `Classify the support email into exactly one category: billing, technical, or general.
Respond ONLY with JSON: {"category": "billing|technical|general", "confidence": 0-1}.
No preamble, no markdown, no code fences.`,
      messages: [{ role: "user", content: emailText }],
    }),
  });

  if (!res.ok) throw new Error(`Anthropic error: ${res.status}`);
  const data = await res.json();
  const text = (data.content?.[0]?.text ?? "").replace(/```json|```/g, "").trim();

  let parsed;
  try {
    parsed = JSON.parse(text);
  } catch {
    return { category: "general", confidence: 0, note: "unparseable output" }; // safe fallback
  }

  // Validate — never blindly trust the model's label
  if (!ALLOWED.includes(parsed.category)) {
    return { category: "general", confidence: 0, note: "unexpected category" };
  }
  return parsed;
}

Also included: full Express route, setup steps, retry pattern, cost breakdown.


🏗️ Architecture Pattern (Always Enforced)

Browser / Client
      │
      │  POST /api/chat  (your message, no keys)
      ▼
Your Server / Serverless Function
      │  process.env.LLM_API_KEY  ← lives here, never leaves
      │
      │  POST → LLM Provider API
      ▼
OpenAI / Anthropic / etc.
      │
      │  Response
      ▼
Your Server → Browser

⚠️ The #1 integration mistake: putting the API key in frontend/client code.
Anyone can read it from browser dev tools and spend your money.
This skill enforces server-side keys on every output — no exceptions.


💸 Cost Discipline

The skill matches model size to task complexity — not the biggest model by default:

Task type Model tier Why
Classify / tag / extract Small / cheap Capable enough; 10–30× cheaper
Summarize / draft / Q&A Mid-tier Balanced quality + cost
Hard reasoning / long context / agentic Frontier Only when justified

Cost levers surfaced in every output:

  • Model choice (biggest lever)
  • Prompt / input size
  • max_tokens cap on output
  • Call volume + caching
  • Retry cap (uncapped retries multiply cost)

🛡️ Production-Grade Output Handling

LLMs are non-deterministic — they sometimes return malformed JSON, wrong categories,
or nothing at all. Every structured-output integration this skill produces includes:

// ✅ Strip stray markdown fences
const text = rawOutput.replace(/```json|```/g, "").trim();

// ✅ Parse inside try/catch — never assume valid JSON
let parsed;
try { parsed = JSON.parse(text); }
catch { return safeFallback; }

// ✅ Validate against the allowed set before using
if (!ALLOWED.includes(parsed.category)) return safeFallback;

📦 What's in the Package

ai-integration/
├── SKILL.md                  — main skill instructions
└── references/
    ├── providers.md          — model selection guide + cost levers
    └── patterns.md           — ready code patterns:
                                  basic call · chat endpoint · streaming
                                  structured JSON · retries · RAG outline

🎯 Trigger Phrases

This skill activates on:

  • "Add AI to my app" / "connect ChatGPT/Claude to my site"
  • "Integrate an LLM" / "build an AI chatbot"
  • "Call the OpenAI/Anthropic API" / "add a /chat endpoint"
  • "Use AI to process this data" / "set up RAG"
  • Any request to wire a language model into an existing app or workflow

⚠️ What It Won't Do

Rule Reason
Won't put real API keys in code output Already compromised the moment it's written down
Won't state specific model names as facts Model IDs drift; a wrong endpoint wastes hours
Won't over-build Delivers the integration asked for, nothing more
Won't recommend an expensive model for a simple task Costs the client real money for no gain

📊 Market Signal

AI integration skills grew +178% year-over-year on Upwork in 2025,
making it the second-fastest growing skill category behind AI video editing (+329%).
Upwork In-Demand Skills Report 2026 (official earnings data)


Built using the skill-creator skill. Validated across 2 test cases (non-engineer + developer). Passed skill-creator package validation.