LabHub

Blog

AI Engineering in Practice — LLM API, RAG, Agents, LoRA/DPO, Vector DB, Evaluation, Observability, Prompt Injection (2025)

한국어English日本語

Why "AI Engineering" became its own discipline

What AI engineers actually solve:

This is a different discipline from traditional SRE/backend. This post is the practical playbook.


Part 1 — LLM API calls, really

Beyond the toy example

# Naive
response = client.chat.completions.create(model="gpt-4o", messages=[...])
return response.choices[0].message.content

Production must wrap 6 concerns:

  1. Retry + exponential backoff — rate limits, transient errors.
  2. Timeouts — defaults are too long (60s+).
  3. Streaming — time-to-first-token is the UX.
  4. Token counting — stay below context limit.
  5. Logging / observability — request, response, latency, cost.
  6. Fallback — switch models on provider failure.

Streaming pipeline

async for chunk in client.chat.completions.create(..., stream=True):
    delta = chunk.choices[0].delta.content
    if delta:
        yield delta

Buffer, flush on punctuation, measure TTFT (time-to-first-token) as a first-class SLO.

Structured output


Part 2 — RAG is not lookup

The naive pipeline (and why it breaks)

  1. Chunk docs → 2. Embed → 3. Store in vector DB → 4. Top-k cosine search → 5. Stuff into prompt.

What goes wrong:

The 2025 RAG stack


Part 3 — Agents

Core patterns

Frameworks (2025)

Production gotchas


Part 4 — Fine-tuning: when and when NOT

Don't fine-tune first

Prompt engineering + RAG + few-shot handles 90% of cases cheaper, faster, with updatable knowledge.

Fine-tune when

Techniques

Stack


Part 5 — Vector DB decision matrix

DBTypeStrengthWeakness
pgvectorPostgres extensionColocated with relational, transactionsLess specialized scale
QdrantRust nativeFilters, fastAnother service
WeaviateJavaModules, hybridHeavier
MilvusC++Scale (billions)Ops complexity
PineconeManagedZero opsExpensive, vendor lock
TurbopufferManaged, cheapCheap cold storageNew
LanceDBEmbeddedLocal, simpleSmall scale

Default for 2025: pgvector unless vector count >10M or you need advanced filters → Qdrant. Pinecone/Turbopuffer if ops is a bottleneck.


Part 6 — Evaluation: the hard problem

Why it's hard

The layered approach

  1. Unit tests for prompts — pytest fixtures, golden outputs for regression.
  2. LLM-as-judge — cheap, noisy; use GPT-4o to grade; calibrate vs human.
  3. Task-specific metrics — BLEU/ROUGE for summaries, exact match for extraction.
  4. RAG metrics — Ragas: faithfulness, answer relevance, context precision.
  5. Human eval — small, focused, for ground-truth calibration.
  6. Production telemetry — thumbs up/down, session analysis.

Tools

Langfuse, LangSmith, Phoenix (Arize), Braintrust, Weights & Biases, Helicone.


Part 7 — Cost optimization

Every $1 saved at scale matters.

  1. Model tiering — route easy queries to Haiku/mini, escalate to Sonnet/GPT-4.
  2. Prompt caching (Anthropic, OpenAI) — 90% discount on cached prefix.
  3. Batch API — 50% discount, async.
  4. Structured outputs — fewer retries from parse failures.
  5. Context pruning — summarize old turns, not verbatim.
  6. Semantic caching — Redis + embeddings; hit rate 20–40% is common.
  7. Shorter prompts — every token billed.

Part 8 — Security: prompt injection & data leakage

Attack surface

Defenses (defense in depth)

  1. Separate system and user — never concat user into system prompt.
  2. Input validation — strip suspicious patterns, length limits.
  3. Output validation — refuse / re-prompt on suspicious output.
  4. Tool allow-list + permissions — LLM never touches prod DB directly.
  5. Human-in-the-loop for high-risk tools (email send, payments).
  6. Sandboxing — code interpreter in isolated container.
  7. Prompt shields (Azure AI Content Safety, Lakera Guard).
  8. Audit logs for every tool invocation.

OWASP LLM Top 10 is the canonical reference.


Part 9 — Observability

An AI app without observability is blind. Minimum:

Tools: Langfuse (open-source, self-hostable), LangSmith (LangChain's paid SaaS), Phoenix (Arize, OSS), Helicone, Braintrust.


Part 10 — 12-item production checklist

  1. Retry + exponential backoff + jitter?
  2. Timeout set explicitly (not default)?
  3. Streaming enabled, TTFT measured?
  4. Token counting + context guardrails?
  5. Structured outputs or validated JSON?
  6. RAG uses hybrid + re-ranker + citations?
  7. Agent has step cap + tool budget?
  8. Evaluation suite runs in CI (golden + LLM-judge)?
  9. Observability platform deployed?
  10. Cost dashboard and alert?
  11. Prompt injection defenses (separation, allow-list, human-in-loop)?
  12. Fallback model + graceful degradation?

10 anti-patterns

  1. Treating demo code as production.
  2. RAG with naive top-k, no re-rank.
  3. Fine-tuning before prompt engineering.
  4. LLM-as-judge with no human calibration.
  5. Ignoring cost until the bill arrives.
  6. Concatenating user input into system prompt.
  7. Giving agents unrestricted tool access.
  8. No observability "we can add it later."
  9. Trusting LLM output without schema validation.
  10. Hallucinating packages — letting LLM install arbitrary deps.

Next post

Production AI engineering is as much about systems as models. Pick one of: agent orchestration deep dive, RAG at scale, or LLM cost engineering for the next post.

— End of AI Engineering in Practice.

Comments

No comments yet.

Sign in to leave a comment