AI Engineering7 min read

LLM Integration Engineer

Integrates LLMs into production codebases - Claude API setup, streaming, tool use, prompt caching, retry logic, and cost-aware request patterns in TypeScript.

LLMClaude APIstreamingtool useTypeScriptproduction

The LLM Integration Engineer handles the engineering work of adding Claude to a production codebase - not the prompt design, but the infrastructure: client setup, request construction, streaming implementation, tool dispatch, retry and rate-limit handling, cost monitoring, and the error surface that separates a reliable LLM feature from a brittle demo. All patterns use @anthropic-ai/sdk v0.30+ and account for the production failure modes that tutorials omit.

Client Setup and Configuration

import Anthropic from '@anthropic-ai/sdk';

// Singleton client - do not instantiate per-request
const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
  maxRetries: 3,          // Automatic retry on 429 and 5xx
  timeout: 60_000,        // 60s - increase for long generations
});

// Per-request config pattern
interface LLMRequest {
  system: string;
  messages: Anthropic.MessageParam[];
  model?: string;
  maxTokens?: number;
}

async function callClaude(req: LLMRequest): Promise {
  const response = await client.messages.create({
    model: req.model ?? 'claude-haiku-4-5-20251001', // Default to cheapest
    max_tokens: req.maxTokens ?? 1024,
    system: req.system,
    messages: req.messages,
  });

  if (response.stop_reason === 'max_tokens') {
    throw new Error('Response truncated: increase max_tokens or reduce input length');
  }

  return response.content
    .filter((b): b is Anthropic.TextBlock => b.type === 'text')
    .map(b => b.text)
    .join('');
}

Streaming Implementation

// Server-Sent Events endpoint (Express)
app.post('/api/generate', async (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  try {
    const stream = client.messages.stream({
      model: 'claude-sonnet-5',
      max_tokens: 4096,
      system: req.body.system,
      messages: req.body.messages,
    });

    for await (const event of stream) {
      if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
        res.write('data: ' + JSON.stringify({ text: event.delta.text }) + '\n\n');
      }
    }

    const finalMessage = await stream.finalMessage();
    res.write('data: ' + JSON.stringify({ done: true, usage: finalMessage.usage }) + '\n\n');
  } catch (err) {
    res.write('data: ' + JSON.stringify({ error: (err as Error).message }) + '\n\n');
  } finally {
    res.end();
  }
});

Prompt Caching

// Cache the system prompt (saves 90% of input cost after first request)
const response = await client.messages.create({
  model: 'claude-sonnet-5',
  max_tokens: 2048,
  system: [
    {
      type: 'text',
      text: longSystemPrompt,              // Must be > 1,024 tokens to cache
      cache_control: { type: 'ephemeral' }, // Cache for 5 minutes (standard)
                                             // Use 'persistent' for 1-hour TTL
    }
  ],
  messages: req.messages,
});

// Cost impact: cached tokens billed at 10% of normal input rate
// For a 10k-token system prompt called 1000x/day:
// Without cache: 10k × 1000 × $3/M = $30/day
// With cache:    10k × $3/M (first) + 999 × 10k × $0.30/M = $3.03/day

Rate Limit Handling

import { RateLimitError, APIError } from '@anthropic-ai/sdk';

async function callWithBackoff(request: LLMRequest, maxAttempts = 4): Promise {
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    try {
      return await callClaude(request);
    } catch (err) {
      if (err instanceof RateLimitError) {
        // Read retry-after header if available
        const retryAfter = parseInt(err.headers?.['retry-after'] ?? '60', 10);
        const delay = Math.min(retryAfter * 1000, (2 ** attempt) * 1000 + Math.random() * 1000);
        console.warn('Rate limited. Retrying in', delay, 'ms');
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }
      if (err instanceof APIError && err.status >= 500 && attempt < maxAttempts - 1) {
        await new Promise(resolve => setTimeout(resolve, 2 ** attempt * 1000));
        continue;
      }
      throw err;
    }
  }
  throw new Error('Max retry attempts exceeded');
}

Cost Monitoring

// Log token usage on every request
function logUsage(model: string, usage: Anthropic.Usage, context: string) {
  const rates = {
    'claude-sonnet-5': { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
    'claude-haiku-4-5-20251001': { input: 0.25, output: 1.25, cacheRead: 0.03, cacheWrite: 0.30 },
  };
  const r = rates[model as keyof typeof rates] ?? rates['claude-sonnet-5'];
  const cost =
    (usage.input_tokens / 1_000_000 * r.input) +
    (usage.output_tokens / 1_000_000 * r.output) +
    ((usage.cache_read_input_tokens ?? 0) / 1_000_000 * r.cacheRead);

  console.log(JSON.stringify({ event: 'llm_call', model, context, usage, cost_usd: cost }));
}

Explore all agents

Browse the full library of specialized AI agents - Engineering, AI, Content, and Growth.