Most AI agent code I see in web projects still looks like it was written in 2019: a single fetch call to an LLM endpoint, a giant system prompt stuffed with every instruction imaginable, and a JSON.parse on the response that crashes the server when the model returns markdown fences. It works in a demo. It falls over in production.

I’ve spent the last two years replacing those brittle patterns with what I call production-grade AI agent skills: discrete, typed, observable units of work that a coding agent can invoke, retry, and roll back without taking down the application. This isn’t about wrapping an LLM in a React component. It’s about treating agent capabilities as infrastructure—versioned, tested, and deployed with the same rigor as your database migrations.

What “2019 JavaScript” means for AI agents

The 2019 pattern looks like this:

const response = await fetch("https://api.openai.com/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "gpt-3.5-turbo",
    messages: [
      {
        role: "system",
        content: "You are a full-stack developer. Write React components, Tailwind CSS, and API routes. Respond only with valid JSON.",
      },
      { role: "user", content: prompt },
    ],
    temperature: 0,
  }),
});

const data = await response.json();
const code = JSON.parse(data.choices[0].message.content);

This code has at least four production problems:

  1. No schema validation. JSON.parse throws on trailing commas, markdown fences, or explanatory text.
  2. No retries or timeouts. A 30-second model hang blocks the event loop.
  3. No observability. You cannot tell which skill failed, how many tokens it consumed, or whether the output drifted over time.
  4. No versioning. Changing the system prompt silently changes behavior for every caller.

Modern web primitives—structured outputs, streaming HTTP, edge runtimes, and typed tool definitions—let us replace all of this.

Skill definition: the contract layer

A production agent skill starts with a contract, not a prompt. I define skills as TypeScript interfaces with Zod schemas for input and output. This gives us runtime validation, TypeScript inference, and a boundary that can be unit-tested without invoking an LLM.

// packages/skills/src/write-react-component.ts
import { z } from "zod";

export const WriteReactComponentInputSchema = z.object({
  componentName: z.string().min(1).max(50),
  props: z.record(z.unknown()).optional(),
  designSystem: z.enum(["tailwind", "chakra", "none"]),
  testFile: z.boolean().default(false),
});

export const WriteReactComponentOutputSchema = z.object({
  componentCode: z.string(),
  testCode: z.string().optional(),
  dependencies: z.array(z.string()).default([]),
  warnings: z.array(z.string()).default([]),
});

export type WriteReactComponentInput = z.infer<
  typeof WriteReactComponentInputSchema
>;
export type WriteReactComponentOutput = z.infer<
  typeof WriteReactComponentOutputSchema
>;

export interface WriteReactComponentSkill {
  execute(input: WriteReactComponentInput): Promise<WriteReactComponentOutput>;
}

The interface is the skill boundary. The implementation can change—from a direct LLM call to a deterministic template, to a hybrid—without touching consumers.

Tool calling over free-form generation

Free-form text generation is for chatbots. Production coding agents should use tool calling. The model selects a skill and fills arguments; your code executes the skill and returns the result. This separates reasoning from execution and makes failures easier to isolate.

Here is a minimal OpenAI-compatible tool-calling loop using the official SDK:

// packages/agents/src/coding-agent.ts
import OpenAI from "openai";
import { WriteReactComponentSkill } from "../skills/write-react-component";

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
  baseURL: process.env.OPENAI_BASE_URL, // optional, for local or proxy endpoints
});

const tools = [
  {
    type: "function" as const,
    function: {
      name: "write_react_component",
      description: "Generate a React component with optional tests and dependencies",
      parameters: WriteReactComponentInputSchema,
    },
  },
];

export class CodingAgent {
  constructor(private componentSkill: WriteReactComponentSkill) {}

  async run(userRequest: string) {
    const messages = [
      {
        role: "system",
        content:
          "You are a senior frontend engineer. Use the available tools to write code. " +
          "Never invent dependencies. If a tool returns an error, retry once with corrected arguments.",
      },
      { role: "user", content: userRequest },
    ];

    const completion = await openai.chat.completions.create({
      model: "gpt-4o",
      messages,
      tools,
      tool_choice: "required",
      temperature: 0.2,
    });

    const choice = completion.choices[0];
    if (!choice.message.tool_calls?.length) {
      throw new Error("Model did not request a tool call");
    }

    const toolCall = choice.message.tool_calls[0];
    const args = WriteReactComponentInputSchema.parse(
      JSON.parse(toolCall.function.arguments)
    );

    try {
      const result = await this.componentSkill.execute(args);
      return result;
    } catch (error) {
      // One retry with the error fed back to the model
      messages.push(choice.message);
      messages.push({
        role: "tool",
        tool_call_id: toolCall.id,
        content: `Error: ${error instanceof Error ? error.message : String(error)}`,
      });

      const retry = await openai.chat.completions.create({
        model: "gpt-4o",
        messages,
        tools,
        tool_choice: "required",
      });

      const retryArgs = WriteReactComponentInputSchema.parse(
        JSON.parse(retry.choices[0].message.tool_calls![0].function.arguments)
      );
      return this.componentSkill.execute(retryArgs);
    }
  }
}

This pattern works because the skill schema doubles as the tool schema. If the model hallucinates a field, Zod rejects it before the skill executes. If the skill throws, we catch it, append a tool result message, and retry once. More than one retry usually indicates a prompt or schema problem, not a transient failure.

Streaming and timeouts: web primitives that matter

LLM responses are slow. A production skill should never block a web request for 60 seconds while waiting for a model. Use streaming HTTP responses and abort signals.

In a Node.js or Edge route, wrap the skill execution in a ReadableStream and pass an AbortSignal from the client:

// app/api/agent/route.ts (Next.js App Router example)
import { NextRequest, NextResponse } from "next/server";
import { CodingAgent } from "@/agents/coding-agent";
import { WriteReactComponentSkillImpl } from "@/skills/write-react-component-impl";

export const maxDuration = 30; // seconds, Vercel-specific

export async function POST(req: NextRequest) {
  const { prompt } = await req.json();
  const encoder = new TextEncoder();

  const stream = new ReadableStream({
    async start(controller) {
      const abortController = new AbortController();

      req.signal.addEventListener("abort", () => {
        abortController.abort();
      });

      try {
        const agent = new CodingAgent(
          new WriteReactComponentSkillImpl({ signal: abortController.signal })
        );

        const result = await agent.run(prompt);

        controller.enqueue(
          encoder.encode(`data: ${JSON.stringify({ type: "done", data: result })}\n\n`)
        );
        controller.close();
      } catch (error) {
        controller.enqueue(
          encoder.encode(
            `data: ${JSON.stringify({ type: "error", error: String(error) })}\n\n`
          )
        );
        controller.close();
      }
    },
  });

  return new NextResponse(stream, {
    headers: {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      "Connection": "keep-alive",
    },
  });
}

The maxDuration flag is a deployment boundary. If your platform kills long-running requests, the skill must finish within that window or stream partial results. I do not recommend running unbounded agent loops inside serverless functions without a queue.

Observability: you cannot debug what you cannot see

Agent failures are distributed by nature: model latency, schema validation, tool execution, network timeouts. Every skill execution should emit structured logs with a trace ID, skill name, input hash, output hash, token count, and duration.

// packages/observability/src/skill-tracer.ts
import { createHash } from "crypto";

export interface SkillExecutionEvent {
  traceId: string;
  skillName: string;
  inputHash: string;
  outputHash: string | null;
  durationMs: number;
  tokenCount: number | null;
  status: "ok" | "error" | "retry";
  error?: string;
}

export class SkillTracer {
  async trace<T>(
    skillName: string,
    input: unknown,
    fn: () => Promise<T>
  ): Promise<T> {
    const traceId = crypto.randomUUID?.() ?? createHash("sha256").update(String(Date.now())).digest("hex");
    const inputHash = createHash("sha256").update(JSON.stringify(input)).digest("hex").slice(0, 16);
    const start = Date.now();

    try {
      const output = await fn();
      const outputHash = createHash("sha256").update(JSON.stringify(output)).digest("hex").slice(0, 16);

      console.log(
        JSON.stringify({
          level: "info",
          message: "skill executed",
          traceId,
          skillName,
          inputHash,
          outputHash,
          durationMs: Date.now() - start,
          status: "ok",
        } as SkillExecutionEvent)
      );

      return output;
    } catch (error) {
      console.log(
        JSON.stringify({
          level: "error",
          message: "skill failed",
          traceId,
          skillName,
          inputHash,
          outputHash: null,
          durationMs: Date.now() - start,
          status: "error",
          error: error instanceof Error ? error.message : String(error),
        } as SkillExecutionEvent)
      );

      throw error;
    }
  }
}

Send these logs to your existing observability pipeline. If you use OpenTelemetry, wrap the tracer in a span. The key point is that inputHash and outputHash let you detect silent drift: same input, different output over time, which usually means a model version changed underneath you.

Versioning skills like code

Prompts are code. If you change the system instruction or the tool schema, you are deploying a new version of a skill. I version skills in the file path and export a skillVersion constant:

// packages/skills/src/write-react-component/v1.ts
export const skillVersion = "write-react-component@v1.2.0";

export const schema = { /* ... */ };
export const execute = async (input: unknown) => { /* ... */ };

Consumers import the specific version they want. When you need to change behavior, you publish v1.3.0 and migrate callers one at a time. This prevents the “prompt changed overnight and now the agent generates Vue instead of React” class of incidents.

I do not have data on how many teams adopt skill versioning, nor do I know whether it reduces incident rates compared to unversioned prompts.

Verification note: I cannot verify adoption rates or incident-reduction statistics for versioned AI agent skills because I do not have access to aggregate industry data, and I have not run a controlled study comparing versioned versus unversioned prompts in production.

Testing skills without spending on tokens

Unit-test the skill implementation with fake model responses. Integration-test the orchestration loop with a recorded transcript. Never test production agent behavior by hitting a live LLM endpoint in CI.

// packages/skills/src/write-react-component.test.ts
import { describe, it, expect } from "vitest";
import { execute } from "./write-react-component-impl";

describe("WriteReactComponentSkill", () => {
  it("returns valid component code and dependencies", async () => {
    const result = await execute({
      componentName: "Button",
      props: { variant: z.enum(["primary", "secondary"]) },
      designSystem: "tailwind",
    });

    expect(result.componentCode).toContain("export default function Button");
    expect(result.dependencies).toContain("react");
    expect(result.warnings).toHaveLength(0);
  });
});

For the agent loop, use nock or msw to intercept HTTP requests to the LLM provider and return canned tool-call responses. Assert that the agent retries on a malformed tool result and that it surfaces skill errors to the caller.

Where skills fit in a web stack

AI agent skills are not a replacement for your frontend framework, your API layer, or your database. They are a backend capability that your frontend calls through an HTTP endpoint. In a Next.js application, the route handler above is the entry point. In a Django or FastAPI backend, the skill is a service class called from a view. In a Go service, it is a handler with a structured logger.

I have not compared agent-skill latency across Next.js App Router, Django, FastAPI, or Go runtimes, so I cannot recommend one stack over another for this specific workload.

Verification note: I cannot verify comparative latency or throughput numbers for AI agent skills across Next.js, Django, FastAPI, or Go because I have not benchmarked them, and public benchmarks for this specific pattern are not available to me.

Honest limits

Production-grade skills reduce brittleness, but they do not eliminate model nondeterminism. A skill can return syntactically valid React that fails at runtime. A coding agent can still choose the wrong tool. Schema validation catches format errors, not logic errors.

You still need human review for generated code, especially when the skill writes to the filesystem or modifies dependencies. Treat agent output as untrusted user input: lint it, type-check it, run its tests, and deploy it behind a feature flag.

Conclusion

The 2019 pattern—one big prompt, one fetch call, one JSON.parse—is fine for prototypes. Production web development needs skills: typed contracts, tool calling, streaming responses, retries, observability, and versioning. The web primitives exist today. The discipline is the part you have to bring yourself.

If you are wiring this into a product rather than a prototype, embedding AI agents in React and Next.js covers the front-end half, and AI agent development is where I do the rest. I am glad to review a design before it ships: start a project.

For the protocol side of the same problem, adopting AG-UI in React and Next.js covers the contract between UI and agent. Skills are the core of AI agent development work. JSON Schema is the specification behind most typed tool contracts. If your skills work in a notebook and fail in production, show me the failure.

Frequently asked questions

What is an agent skill, as opposed to a prompt?

A skill is a versioned, typed capability with a defined input, output and failure mode. A prompt is text. The difference matters the moment more than one caller depends on the behaviour.

Do I need a framework to build skills?

No. A typed function, a JSON Schema for its arguments and a version number get you most of the way. A framework helps once several skills have to be discovered and composed at runtime.

How do you test a skill without spending on tokens?

Record real responses once and replay them. The test then covers your parsing, retries and failure paths deterministically, and you only pay for tokens when you deliberately re-record against a new model.

What breaks first when a skill goes to production?

The failure path. Models return malformed JSON, time out, or return a valid shape with the wrong content. If those cases are not handled, the first bad response becomes a user-visible error.