Backend ai microservice

From NaveedTechLab/skills-library · View interactive version

Backend ai microservice is an AI agent skill from the GitHub repository NaveedTechLab/skills-library. Build production-ready AI microservices with Docker and streaming support. Use when the user needs to: (1) create REST endpoints that call an LLM API (OpenAI, Anthropic, or compatible), (2) stream LLM responses to clients via SSE (Server-Sent Events), (3) containerize a Node.js/Express AI service wi

How to use this skill

Skill file

Backend AI Microservice

Build containerized, observable, and secrets-safe AI services.

Build Workflow

1. Validate environment variables at startup (fail fast, never silently)
2. Add request ID middleware (first middleware in the chain)
3. Implement LLM client with retry and timeout
4. Build REST endpoint — non-streaming first, then add SSE variant
5. Write Dockerfile (multi-stage) and docker-compose.yml
6. Add .env.example; verify no secrets in committed files

Constraints — enforce always:


Boilerplate Template

A complete starter scaffold is in assets/microservice-template/. Copy it as the starting point and adapt. Files included:

microservice-template/
├── src/
│   ├── index.ts              Express app + server startup
│   ├── config/env.ts         Env var validation (Zod)
│   ├── middleware/
│   │   ├── requestId.ts      Attach X-Request-ID to every request
│   │   └── logger.ts         Structured JSON logger (pino)
│   └── routes/
│       └── generate.ts       /generate (batch) + /generate/stream (SSE)
├── Dockerfile                Multi-stage Node.js build
├── docker-compose.yml        Service + healthcheck
├── .env.example              All required vars, no values
└── package.json

1. Environment Variable Management

// src/config/env.ts — validates at startup; throws if missing
import { z } from 'zod';

const EnvSchema = z.object({
  LLM_API_KEY:    z.string().min(1),
  LLM_BASE_URL:   z.string().url().default('https://api.openai.com/v1'),
  LLM_MODEL:      z.string().default('gpt-4o-mini'),
  PORT:           z.coerce.number().default(3000),
  LOG_LEVEL:      z.enum(['trace','debug','info','warn','error']).default('info'),
  NODE_ENV:       z.enum(['development','production','test']).default('development'),
});

export const env = EnvSchema.parse(process.env); // throws ZodError on missing vars

NEVER pass API keys as docker-compose environment defaults. Use .env file or a secrets manager:

# docker-compose.yml — correct pattern
environment:
  - LLM_API_KEY       # reads from shell env or .env file — no default value
  - LLM_MODEL=gpt-4o-mini  # non-secret defaults are fine

2. Request ID Logging

// Every log line must include the request ID for traceability
import pino from 'pino';
import { randomUUID } from 'crypto';

export const rootLogger = pino({ level: env.LOG_LEVEL });

// middleware/requestId.ts
export function requestIdMiddleware(req, res, next) {
  req.id = (req.headers['x-request-id'] as string) ?? randomUUID();
  res.setHeader('x-request-id', req.id);
  req.log = rootLogger.child({ requestId: req.id });
  next();
}

// Usage in any handler
req.log.info({ userId, model }, 'LLM generation started');

3. SSE Streaming Pattern

router.get('/generate/stream', async (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  res.flushHeaders();

  const stream = await llmClient.stream(req.query.prompt as string);

  for await (const chunk of stream) {
    res.write(`data: ${JSON.stringify({ text: chunk })}\n\n`);
  }

  res.write('data: [DONE]\n\n');
  res.end();
});

Resources

When NOT to Use This Skill

Common Mistakes

Related Skills

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.