Agents & GenAI

Large language models and agentic systems have become essential tools for data scientists. This topic covers how LLMs work, how to build reliable pipelines on top of them (RAG, function calling, multi-step agents), how to evaluate their outputs rigorously, and the unique risks they introduce.

Key Takeaways

  • LLMs predict the next token; all emergent capabilities arise from scale + RLHF alignment on top of this.
  • RAG (Retrieval-Augmented Generation) grounds LLMs in proprietary data without fine-tuning — retrieval quality bounds generation quality.
  • Agents extend LLMs with tools (search, code execution, APIs) and a loop: observe → reason → act → observe. Reliability degrades with loop depth.
  • Hallucination is irreducible at zero temperature and must be mitigated architecturally (grounding, self-consistency, human-in-the-loop).
  • Prompt engineering is a first-class discipline: few-shot > zero-shot; chain-of-thought improves reasoning; structured output reduces parsing failures.
  • GenAI evaluation is multi-dimensional: factuality, faithfulness, relevance, coherence, safety. No single metric suffices.

1. How LLMs Work

Transformer Architecture

Input text is tokenized and embedded into dense vectors. Multi-head self-attention lets every token attend to every other token:

$$\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^T}{\sqrt{d_k}}\right)V$$

The $\frac{1}{\sqrt{d_k}}$ scaling prevents softmax saturation when key dimension is large. Stacked transformer blocks progressively build richer representations; the final layer projects to vocabulary logits.

Training Pipeline

Stage What Happens
Pre-training Next-token prediction on massive text corpus. Learns world knowledge, syntax, reasoning.
Supervised Fine-Tuning (SFT) Fine-tune on instruction-response pairs. Teaches instruction following.
RLHF Human raters rank outputs → reward model → PPO optimizes LLM. Aligns tone, safety, helpfulness.
DPO Cheaper RLHF alternative: direct preference optimization without a separate reward model.

Context Window

Context window = maximum tokens the model can attend to at once (4K–1M+ depending on model). Rule of thumb: ~750 words ≈ 1,000 tokens. Long-context models degrade in the middle of the context ("lost in the middle" effect) — important for document QA tasks.

2. Retrieval-Augmented Generation (RAG)

RAG is the standard pattern for giving LLMs access to proprietary or up-to-date data without fine-tuning.

Classic RAG Pipeline

from sentence_transformers import SentenceTransformer
import numpy as np

model = SentenceTransformer("all-MiniLM-L6-v2")

# Index documents
docs = ["Capital One Q3 earnings beat expectations...", "Fraud detection system updated..."]
doc_embeddings = model.encode(docs)  # shape: (n_docs, 384)

# At query time
query_emb = model.encode(["What were Q3 earnings?"])
scores = np.dot(query_emb, doc_embeddings.T)  # cosine similarity
top_k = np.argsort(scores[0])[::-1][:3]
retrieved = [docs[i] for i in top_k]

RAG Evaluation Metrics

Metric Measures How
Recall@k Are relevant docs in top k? relevant in top-k / total relevant
MRR Rank of first relevant doc $\frac{1}{Q}\sum_{q}\frac{1}{\text{rank}_q}$
Faithfulness Answer uses only retrieved context? LLM judge / human eval
Answer Relevance Answer addresses the question? Embedding similarity

Chunking Strategy

  • Fixed-size chunks (512 tokens, 50-token overlap) — simple, works well for uniform documents.
  • Semantic chunking — split at sentence/paragraph boundaries; better for heterogeneous documents.
  • Hierarchical indexing — store both document-level summaries and fine-grained chunks; retrieve at both levels.

3. Agents and Tool Use

The Agent Loop

while not done:
    observation = env.get_state()
    thought = llm.reason(observation, tools, history)
    action = parse_action(thought)
    result = tools.execute(action)
    history.append((action, result))

ReAct Pattern

Reasoning + Acting interleaved. The model emits a Thought: (chain-of-thought) before each Action:. CoT before action dramatically reduces hallucination in tool selection.

Thought: I need the customer's transaction history.
Action: query_database(customer_id=12345, table="transactions", limit=10)
Observation: [{"date": "2025-01-15", "amount": 250.00}, ...]
Thought: I now have the data. The last 10 transactions show...
Final Answer: ...

Multi-Agent Reliability

Each added hop multiplies failure probability. A 90%-reliable step run 8 times sequentially succeeds only $0.9^8 \approx 43\%$ of the time. Mitigations: parallelism where possible, retry logic, checkpointing long workflows, human-in-the-loop for irreversible actions.

4. Prompt Engineering

Core Techniques

Technique When to Use Effect
Zero-shot Simple classification, summarization Baseline
Few-shot Structured extraction, custom formats +10–30% accuracy
Chain-of-Thought Math, logic, multi-step reasoning Large gains on complex tasks
JSON mode Any structured output Eliminates parsing failures

Prompt Injection Defense

External content (user input, retrieved docs) can contain adversarial instructions. Defenses: separate system context from user-controlled input; sanitize input for instruction-like patterns; validate outputs against expected schema before acting on them.

5. Fine-Tuning vs. RAG vs. Prompting

Approach When to Use Cost Data Freshness
Prompting / RAG Frequently changing data; few labeled examples Low High
SFT with LoRA Task-specific format; 1K+ examples; latency-sensitive Medium Low
Full fine-tune Extreme domain shift; massive labeled data High Low

LoRA: Fine-tune only low-rank decomposition of weight matrices: $\Delta W = AB$ where $A \in \mathbb{R}^{d \times r}$, $B \in \mathbb{R}^{r \times k}$, $r \ll \min(d,k)$. Reduces trainable parameters by ~10,000× vs. full fine-tune; base weights are unchanged and the adapters can be merged at inference.

6. Evaluation of GenAI Systems

Dimension What to Measure Method
Factuality Hallucination rate Fact-check against source / LLM judge
Faithfulness Answer grounded in context? RAGAS, human eval
Relevance Does answer address the question? BERTScore, LLM judge
Safety Harmful / biased outputs? Classifier, red-team
Latency / Cost P95 latency, $/query Logging, load tests

LLM-as-Judge Pitfalls

  • Position bias — prefers the first option in pairwise comparisons
  • Verbosity bias — prefers longer answers regardless of quality
  • Self-preference bias — GPT-4 rates GPT-4 outputs higher

Mitigation: swap order across evaluation runs, use rubrics, calibrate against human judgments.

7. End-to-End RAG Example

import anthropic
from sentence_transformers import SentenceTransformer
import faiss, numpy as np

# --- Indexing (offline) ---
embedder = SentenceTransformer("all-MiniLM-L6-v2")
chunks = load_and_chunk_documents("reports/")
embeddings = embedder.encode(chunks).astype("float32")
index = faiss.IndexFlatIP(embeddings.shape[1])
faiss.normalize_L2(embeddings)
index.add(embeddings)

# --- Query (online) ---
client = anthropic.Anthropic()

def answer(query: str, k: int = 4) -> str:
    q_emb = embedder.encode([query]).astype("float32")
    faiss.normalize_L2(q_emb)
    _, idx = index.search(q_emb, k)
    context = "\n\n---\n\n".join(chunks[i] for i in idx[0])

    msg = client.messages.create(
        model="claude-opus-4-6",
        max_tokens=1024,
        system=(
            "You are a financial analyst assistant. Answer only from the provided context. "
            "If the answer isn't in the context, say 'I don't have that information.'"
        ),
        messages=[{
            "role": "user",
            "content": f"Context:\n{context}\n\nQuestion: {query}"
        }]
    )
    return msg.content[0].text

Capital One example: A document Q&A system over earnings reports, regulatory filings, and internal risk memos allows analysts to query thousands of pages in seconds, with citations back to source paragraphs for auditability.

Practice Questions

What is the difference between RAG and fine-tuning? When do you use each?

RAG retrieves relevant documents at query time and injects them into the prompt — model weights are unchanged. Fine-tuning updates the model weights on a task-specific dataset. Use RAG when your data changes frequently, when you have limited labeled examples, or when you need citations. Use fine-tuning when the task has a specific format/style requirement, you have thousands of labeled examples, and latency is critical. In most enterprise settings, RAG is the right starting point because data changes and labeled data is scarce.

An agent loop has 8 sequential steps, each with 95% reliability. What is the end-to-end success rate?

$0.95^8 \approx 0.663$, or about 66%. This illustrates why long agent chains are unreliable and should be avoided or parallelized where possible. At 90% per step over 8 steps: $0.9^8 \approx 43\%$. Mitigations include retry logic, checkpointing, and breaking loops into shorter parallel sub-chains.

How would you detect and measure hallucination in a RAG pipeline?

Compare each factual claim in the generated answer against the retrieved source chunks. Approaches: (1) LLM-as-judge — ask a separate model to verify each sentence is supported by the context; (2) NLI classifier — check entailment between source and generated sentence; (3) human evaluation on a random sample. Report faithfulness rate (% of sentences supported by context) and track it alongside retrieval recall@k in production monitoring.

A product manager wants to deploy a GenAI feature that autonomously sends emails to customers. What concerns would you raise?

Key concerns: (1) Irreversibility — sent emails cannot be unsent; require human approval initially. (2) Hallucination — incorrect content in customer-facing emails is a brand and legal risk. (3) Data privacy — customer PII must not be sent to external APIs without proper agreements. (4) Bias audit — ensure email content isn't systematically different across demographic groups. (5) Auditability — log every generated email with the prompt, retrieved context, and model version for post-hoc review. Recommend a staged rollout with human-in-the-loop initially, automated only after quality metrics exceed a defined threshold.

Action Items

  • Explain the transformer attention mechanism: role of Q, K, V matrices and the scaling factor
  • Describe the RAG pipeline end-to-end and the metrics used to evaluate it (recall@k, faithfulness)
  • Walk through the ReAct agent loop and explain when and why agents fail
  • Compare prompting, RAG, and fine-tuning — know when to recommend each
  • Explain hallucination mitigation strategies and their tradeoffs
  • Understand LoRA: what gets updated, why it's parameter-efficient, how adapters are merged
  • Know GenAI evaluation dimensions: factuality, faithfulness, relevance, safety
  • Articulate the risks of agentic systems to a non-technical stakeholder