01. LLM System Building Blocks#
A fast, conceptual revision guide for 01-llm-system-building-blocks. Focused on mental models, why each building block exists, how the pieces fit together, and key trade-offs — without boilerplate code clutter. Refer to the linked Python files when you want to see exact syntax.
Stateless LLM Calls & Probabilistic Thinking#
Revision Notes#
Reference file: 01_first_llm_call.py (requires API key)
Concept#
Traditional software is deterministic: the same input always produces the exact same output. Working with an LLM shifts you to probabilistic computing: the model predicts likely continuations rather than executing rigid logic, so the output is probably right and wording may vary from run to run.
At the protocol level, calling an LLM is just a stateless HTTP request. You send a model name and an ordered list of messages (each tagged with a role and content), and the API returns a structured response containing one or more candidate completions (choices).
Key Mental Models#
- Stateless by default: The API has zero memory of previous requests. Multi-turn chat is an illusion maintained by your application — on every turn, you must send the relevant conversation history back inside
messages. - Messages as a conversation transcript: Even a single-turn prompt is sent as a list (
messages=[{"role": "user", "content": "..."}]) because modern chat models are trained to continue structured dialogues, not isolated strings. - Why responses contain
choices: An API call can request multiple candidate completions for the same prompt (n > 1), so the response wraps replies in a list wherechoices[0]is the primary answer.
Every Chat Completions call is a stateless HTTP request: your client supplies the full role-tagged message history, the model computes a next-token probability distribution scaled by temperature, and multi-turn memory exists only because your app appends and resends prior replies.
Code Reference#
"""Worked example: your first LLM call. Send one prompt and print the answer."""
from _common import MODEL, get_client
client = get_client()
# The Chat Completions API is stateless: every call sends a list of role-tagged
# messages (system, user, assistant). Here a single "user" message carries the task.
reply = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": "Write a 5-word tagline for a chai shop."}],
)
# -> ChatCompletion(choices=[
# Choice(message=ChatCompletionMessage(
# role='assistant', content='Warmth steeped in every cup.'
# ))
# ])
# `choices` holds candidate completions (1 by default, controlled by `n`).
# Index [0] selects the primary completion and `.message.content` extracts its text.
print(reply.choices[0].message.content)
$ python 01_first_llm_call.py
Warmth steeped in every cup.
Rules vs. Machine Learning#
Revision Notes#
Reference file: 02_rules_vs_learning.py (runs offline — no API key needed)
Concept#
Traditional programming and machine learning solve problems from opposite directions:
- Rule-based programming:
Input Data + Human-Written Rules → Output. Works great when rules are crisp and finite (tax brackets, validation schemas), but breaks down on messy human language. - Supervised machine learning:
Input Data + Labelled Examples → Learned Patterns (Model). Instead of hand-coding every variation, you show the model labelled examples (e.g.,"spam"vs."not spam") and let it learn statistical patterns that generalize to unseen inputs.
How the Spam Example Illustrates the Shift#
- Why rules fail: A rule checking
"lottery" in emailimmediately misses"You won a l0ttery!!". Patching every typo or leetspeak variant (l0ttery,m0ney,fr33) turns into an endless game of whack-a-mole. - Turning text into numbers (Feature Extraction): ML models only operate on numbers. Using character n-grams (overlapping 2–4 character slices within word boundaries), the model breaks words into sub-word chunks. Even if
"l0ttery"never appeared in training, it shares chunks like"tter","tery", and"won"with known spam examples. - Probabilistic classification: A classifier (Naive Bayes here) weighs the observed feature counts to compute whether the input is more likely
"spam"or"not spam". - Two distinct lifecycle phases:
- Training (
fit): Feed labelled examples so the model learns feature weights. - Inference (
predict): Feed brand-new, unseen input to the trained model to get a prediction.
- Training (
- Connection to LLMs: LLMs are the massive, general-purpose evolution of this exact paradigm — trained on vast corpora to learn deep statistical representations of language rather than hand-coded grammar rules.
Code Reference#
"""Worked example: rules vs learning (the heart of ML). Runs offline.
The chapter shows the ML side as pseudo-code (model.fit / model.predict);
here it is made runnable with a tiny scikit-learn classifier.
"""
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
# Old way: you write the rules.
# Brittle because exact substring checks break on minor spelling tricks ("l0ttery").
def is_spam(email):
if "lottery" in email: return True
if "free money" in email: return True
return False
print("Rule-based:", is_spam("You won a l0ttery!!"), "<- spammers write 'l0ttery', the rule fails")
# ML way: the model learns statistical patterns from labelled examples
# (the chapter imagines 1 million examples; a handful is enough to see the idea).
emails = [
"You won a lottery", "Claim your free m0ney now", "Win a fr33 prize today",
"Congratulations, you are a lottery winner", "Cheap pr1ze, click now",
"Meeting moved to 3pm", "Lunch tomorrow?", "Please review the attached report",
"Your invoice for October", "Team standup notes",
]
# Parallel ground-truth labels aligned 1-to-1 with `emails`: 5 spam, then 5 not spam.
labels = ["spam"] * 5 + ["not spam"] * 5
# Pipeline chains feature extraction -> classifier so training and prediction apply
# the exact same text preprocessing:
# - analyzer="char_wb" with ngram_range=(2, 4) splits words into 2–4 character
# substrings inside word boundaries, so "l0ttery" still shares n-grams like "tter"
# and "tery" with "lottery", plus "You won" tokens.
# - MultinomialNB computes class probabilities from those n-gram counts.
model = make_pipeline(CountVectorizer(analyzer="char_wb", ngram_range=(2, 4)), MultinomialNB())
# Learn n-gram weights for each class directly from the labelled data.
model.fit(emails, labels)
# -> CountVectorizer builds a (10, ~310) matrix of 2-4 char n-grams (e.g. ' won',
# 'tter', 'tery'); MultinomialNB learns spam vs. not-spam log-probabilities.
# Predict on an unseen obfuscated message; `[0]` unwraps the single-item array.
print("Learned: ", model.predict(["You won a l0ttery!!"])[0], "<- it learned the pattern itself")
# -> model.predict(...) returns array(['spam'], dtype='<U8'); [0] -> 'spam'
$ python 02_rules_vs_learning.py
Rule-based: False <- spammers write 'l0ttery', the rule fails
Learned: spam <- it learned the pattern itself
Text Embeddings & Semantic Space#
Revision Notes#
Reference file: 03_embeddings.py (requires API key)
Concept#
Keyword search only matches exact characters — it has no idea that "How do I reset my UPI PIN?" and "I forgot my UPI passcode" mean almost the same thing. Embeddings solve this by mapping text into a dense vector of floating-point numbers (e.g., 1,536 numbers for text-embedding-3-small) that encodes semantic meaning.
Key Mental Models#
- Meaning becomes geometry: In embedding space, texts with similar meaning point in nearly the same direction, regardless of exact wording. Measuring "how similar are two texts?" becomes a fast mathematical operation (dot product or cosine similarity).
- Fixed dimensionality regardless of length: Whether the input is 3 words or 3 paragraphs, the embedding model compresses it into a vector of the exact same length (e.g., 1,536 floats).
- Batching for efficiency: Embedding APIs accept either a single string or a list of strings in one call, which is essential when indexing many documents.
- The Model Consistency Rule (Critical Pitfall): You must always compare vectors generated by the exact same embedding model. Vectors from two different models live in completely incompatible coordinate systems — comparing them produces meaningless scores.
Code Reference#
"""Worked example: getting a real embedding (a list of numbers that captures meaning)."""
from _common import EMBEDDING_MODEL, get_client
client = get_client()
# Call the embeddings endpoint to map the input text into a dense floating-point
# vector. Semantically similar sentences land close together in this vector space,
# enabling semantic search and RAG retrieval.
emb = client.embeddings.create(
model=EMBEDDING_MODEL,
input="How do I reset my UPI PIN?",
)
# -> CreateEmbeddingResponse(data=[
# Embedding(index=0, embedding=[-0.0184231, 0.0319402, ...])
# ])
# `emb.data` matches the order of inputs; index [0] retrieves the vector for our string.
vector = emb.data[0].embedding
# -> list[float] of length 1536: [-0.0184231, 0.0319402, -0.0048715, 0.0251094, ...]
print(len(vector)) # dimensionality of the vector (1536 for text-embedding-3-small)
print(vector[:5]) # preview the first five normalized float coordinates
$ python 03_embeddings.py
1536
[-0.0184231, 0.0319402, -0.0048715, 0.0251094, -0.0412867]
Prompt Roles & Structured Output#
Revision Notes#
Reference file: 04_prompt_roles_json.py (requires API key)
Concept#
Production LLM systems rarely send a single bare question. They separate developer instructions (system role) from end-user input (user role) and constrain the reply into a machine-readable format (like JSON) so downstream software can parse and act on it reliably.
The Four Core Elements of a Strong Prompt#
- Persona (in
system): Defines who the model is (e.g., "a friendly personal-finance teacher"). Shapes tone, vocabulary, and depth. - Context & Guardrails (in
system): Sets audience background and boundaries (e.g., "first salary; suggest only safe options"), preventing off-policy or risky advice. - Output Format (in
system): Specifies the exact structure expected (e.g., JSON withsummaryand 3tips), turning free-form prose into structured data your app can consume. - User Instruction (in
user): The dynamic, per-request task that changes for every user query.
Key Trade-offs & Pitfalls#
- Separation of authority: Keeping rules in
systemand raw input inusermakes prompts cleaner to maintain and harder for casual user input to override instructions. - Prompted JSON is not a guarantee: Asking "Reply ONLY as JSON" works for demos, but models may still wrap output in markdown code fences (
`json) or add commentary. In production, always pair it with API-native Structured Outputs (response_format) and schema validation (e.g., Pydantic).
Code Reference#
"""Worked example: system vs user messages, with the reply forced into a JSON shape."""
from _common import MODEL, get_client
client = get_client()
# Separating `system` (persistent rules, persona, output contract) from `user`
# (the specific request) makes instructions easier to reuse and harder for user
# input to override. Implicit string concatenation keeps the system prompt readable.
reply = client.chat.completions.create(
model=MODEL,
messages=[
{"role": "system",
"content":
"You are a friendly personal-finance teacher. " # persona: sets tone & expertise
"The user just got their first salary; suggest only safe options. " # context & guardrails
"Reply ONLY as JSON: {\"summary\": str, \"tips\": [3 strings]}" # output schema for downstream code
},
{"role": "user",
"content":
"Explain compound interest with a ₹5,000 monthly SIP example." # concrete task
},
],
)
# -> reply.choices[0].message.content is a JSON str:
# '{"summary": "Compound interest means ...", "tips": ["Build a 3-6 month ...", ...]}'
# The model returns a raw JSON string that downstream code can parse with json.loads().
print(reply.choices[0].message.content)
$ python 04_prompt_roles_json.py
{
"summary": "Compound interest means your returns earn their own returns over time. Investing ₹5,000/month in a steady index-fund SIP at an illustrative 10% annual return for 10 years puts in ₹6,00,000 of your money and can grow to roughly ₹10,24,000.",
"tips": [
"Build a 3–6 month emergency fund in a liquid fund or sweep-in FD before increasing SIP amounts.",
"Automate your ₹5,000 SIP right after salary credit so you invest consistently without timing the market.",
"Stick to low-cost broad-market index funds or PPF/EPF rather than speculative tips when starting out."
]
}
Abstract Syntax Trees (ASTs) for Code#
Revision Notes#
Reference file: 05_ast_explorer.py (runs offline — no API key needed)
Concept#
Source code is not flat prose — it has strict hierarchical grammar. An Abstract Syntax Tree (AST) is a tree representation of code's structure (modules, classes, functions, loops, expressions) parsed directly from source text without executing it. Each node carries metadata such as its symbol name and exact start/end line numbers.
Why ASTs Matter in LLM Systems#
- Structure-aware code chunking: Naive chunking (splitting every 500 characters or 50 lines) slices functions in half, separating a function's signature from its logic and ruining retrieval quality. Walking an AST lets you chunk cleanly along whole
ClassDefandFunctionDefboundaries. - Accurate retrieval and citations: Because AST nodes preserve exact symbol names (
Cart,add,total) and line ranges (linenotoend_lineno), coding agents and code-RAG systems can retrieve complete implementations and cite exact file locations. - Safe static analysis: Parsing into an AST inspects untrusted code safely without running it.
Code Reference#
"""Worked example: see a real AST with Python's built-in ast module. Runs offline."""
import ast
# AST (Abstract Syntax Tree) exploration example:
# Coding agents and code-chunking RAG pipelines parse source into an AST so they
# can locate exact class/function boundaries instead of splitting text blindly.
code = """
class Cart:
def add(self, item):
self.items.append(item)
def total(self):
return sum(i.price for i in self.items)
"""
# Parse raw source text into a structured syntax tree without executing any code.
tree = ast.parse(code)
# -> Module(body=[
# ClassDef(name='Cart', lineno=2, end_lineno=7, body=[
# FunctionDef(name='add', lineno=3, end_lineno=4, ...),
# FunctionDef(name='total', lineno=6, end_lineno=7, ...)
# ])
# ])
# Walk every node in the tree and filter for class/function definitions,
# printing each symbol's exact start and end line numbers.
for node in ast.walk(tree):
# -> yields every AST node (Module, ClassDef, FunctionDef, Call, Attribute, ...)
if isinstance(node, (ast.ClassDef, ast.FunctionDef)):
# -> matches: (Cart, lines 2..7), (add, lines 3..4), (total, lines 6..7)
print(type(node).__name__, node.name,
"lines", node.lineno, "to", node.end_lineno)
$ python 05_ast_explorer.py
ClassDef Cart lines 2 to 7
FunctionDef add lines 3 to 4
FunctionDef total lines 6 to 7
Temperature & Sampling Control#
Revision Notes#
Reference file: 06_temperature.py (requires API key)
Concept#
When generating text, an LLM does not pick a single predetermined word. At every step, it computes a probability distribution over its entire vocabulary for the next token. The temperature parameter rescales that distribution before sampling, giving you a direct dial between consistency and creativity.
The Three Practical Regimes#
- Low / Zero (
temperature = 0— Greedy & Repeatable):- Sharpens the distribution so the model almost always selects the highest-probability token.
- Running the same prompt repeatedly produces nearly identical outputs.
- Best for: JSON extraction, classification, RAG factual Q&A, code generation, and testable pipelines.
- Medium (
temperature ≈ 0.5— Balanced):- Allows mild phrasing variety while staying coherent and on-topic.
- Best for: General chat assistants, summarization, and customer support.
- High (
temperature = 1.0+— Creative & Varied):- Flattens the distribution so lower-probability tokens have a real chance of being chosen.
- Running the same prompt repeatedly yields diverse ideas (and if pushed too high, incoherent drift).
- Best for: Brainstorming, marketing taglines, and creative writing.
Important Nuance#
- **
temperature = 0is nearly deterministic, not mathematically guaranteed**: Floating-point GPU batching and server-side routing can still produce occasional minor differences across calls. - Reasoning models: Some newer reasoning models ignore custom temperature settings entirely.
Code Reference#
"""Worked example: same prompt, two temperatures (0 = repeatable, 1.0 = varied)."""
from _common import MODEL, get_client
client = get_client()
# Temperature scales the token probability distribution before sampling:
# - 0.0: greedy/deterministic (best for extraction, classification, JSON, code)
# - 0.5: balanced slight variation
# - 1.0: flatter distribution, higher creativity and diversity across runs
for t in [0, 0.5, 1.0]:
# Run the exact same prompt 3 times per temperature to observe output spread.
for run in range(3):
r = client.chat.completions.create(model=MODEL, temperature=t,
messages=[{"role": "user", "content": "Name a monsoon snack in 2 words."}])
print(t, r.choices[0].message.content)
$ python 06_temperature.py
0 Onion pakoras
0 Onion pakoras
0 Onion pakoras
0.5 Hot pakoras
0.5 Roasted bhutta
0.5 Hot pakoras
1.0 Spicy samosas
1.0 Masala bhutta
1.0 Crispy vadas
Minimal RAG Pipeline#
Revision Notes#
Reference file: 07_minimal_rag.py (requires API key)
Concept#
Base LLMs have two fundamental blind spots: their training data has a knowledge cutoff (stale facts) and they have zero access to your private data (company policies, user records, internal docs). Retrieval-Augmented Generation (RAG) solves both without retraining the model by searching your knowledge base at query time and injecting only the most relevant snippets into the prompt.
Data Flow#
RAG grounds frozen LLMs in private or fast-changing data without retraining: documents are embedded once offline into unit-normalized vectors, and live queries are embedded with the exact same model for dot-product Top-K retrieval before generation.
The 4 Conceptual Stages of RAG#
- Stage 1 — Index (Offline): Split documents into chunks, convert them into vectors using an embedding model, and store them (in memory for demos, or a vector database in production). You only re-index when source documents change.
- Stage 2 — Embed the Query (Online): Convert the user's incoming question into a vector using the exact same embedding model.
- Stage 3 — Retrieve Top-K: Score similarity between the query vector and every document vector, sort highest-first, and keep only the top
Kmatches.- Math note: Because OpenAI embeddings are unit-normalized (vector length = 1.0), a simple dot product (
doc_vecs @ q_vec) is mathematically identical to cosine similarity. - Filtering to Top-K keeps the prompt focused, lowers token cost, and avoids distracting the model with irrelevant context (e.g., dropping a cash-limit policy when the user asked about UPI refunds).
- Math note: Because OpenAI embeddings are unit-normalized (vector length = 1.0), a simple dot product (
- Stage 4 — Augment & Generate: Inject the retrieved snippets into the
systemprompt alongside a strict grounding instruction ("Answer only from this context"), so the LLM synthesizes a factual answer instead of hallucinating from memory.
Code Reference#
"""Worked example: a minimal RAG in about 20 lines (index, retrieve, augment, generate)."""
import numpy as np
from _common import EMBEDDING_MODEL, MODEL, get_client
client = get_client()
# Small knowledge base of policy facts that the LLM would not otherwise know.
docs = ["Refunds for cancelled orders take 5-7 working days.",
"UPI refunds are usually faster: 1-3 working days.",
"Delivery partners can't accept cash above ₹2,000."]
# Batch-embed a list of strings in a single API round-trip and return a 2D NumPy
# matrix of shape (num_texts, embedding_dim) for fast vectorized math.
def embed(texts):
out = client.embeddings.create(model=EMBEDDING_MODEL, input=texts)
return np.array([d.embedding for d in out.data])
# 1. INDEX: Embed the documents once upfront (re-run only when docs change).
doc_vecs = embed(docs)
# -> ndarray of shape (3, 1536) — 1 unit-normalized vector per doc:
# [[-0.012, 0.041, ...], [0.029, -0.018, ...], [0.007, 0.053, ...]]
# 2. QUERY: Embed the user's question into the exact same vector space.
question = "I paid by UPI, when will my refund come?"
q_vec = embed([question])[0]
# -> ndarray of shape (1536,) — single query vector: [0.025, -0.014, ...]
# 3. SCORE: Matrix-vector dot product (`@`) computes similarity against every doc
# at once. OpenAI embeddings are unit-normalized, so dot product == cosine similarity.
scores = doc_vecs @ q_vec
# -> ndarray of shape (3,) — cosine similarity in `docs` order:
# array([0.62, 0.78, 0.14])
# 4. RETRIEVE: Keep only the top 2 most relevant documents to bound context size.
# top = [docs[i] for i in scores.argsort()[::-1][:2]]
# Pair each score with its doc and sort highest similarity first.
scored_docs = sorted(zip(scores, docs), reverse=True)
# -> [(0.78, 'UPI refunds are usually faster: 1-3 working days.'),
# (0.62, 'Refunds for cancelled orders take 5-7 working days.'),
# (0.14, "Delivery partners can't accept cash above ₹2,000.")]
# Drop the numeric scores and keep just the top 2 document strings.
top = [doc for score, doc in scored_docs[:2]]
# -> ['UPI refunds are usually faster: 1-3 working days.',
# 'Refunds for cancelled orders take 5-7 working days.']
print("Retrieved Top 2:", top)
# 5. AUGMENT & GENERATE: Inject retrieved chunks into the system prompt and instruct
# the model to answer strictly from that context to minimize hallucinations.
answer = client.chat.completions.create(model=MODEL, messages=[
{"role": "system", "content": "Answer only from this context:\n" + "\n".join(top)},
{"role": "user", "content": question}])
print(answer.choices[0].message.content)
$ python 07_minimal_rag.py
Retrieved Top 2: ['UPI refunds are usually faster: 1-3 working days.', 'Refunds for cancelled orders take 5-7 working days.']
Since you paid by UPI, your refund will usually arrive in 1–3 working days.
Fine-Tuning & Choosing the Right Customization Lever#
Revision Notes#
Reference file: data/fine_tuning_example.jsonl
Concept#
Fine-tuning updates the model's internal weights using curated input/output examples so a desired behavior becomes the model's default instinct. Training datasets use JSONL (JSON Lines) — one self-contained JSON object per line — where each example contains:
system: The persona and behavioral policy (e.g., "You are BankBuddy. Be polite, brief, never promise timelines.").user: A realistic, messy end-user query (e.g., "my card got blocked why").assistant: The exact gold-standard reply you want the model to learn to imitate.
During training, the model adjusts its weights to maximize the likelihood of producing the assistant response given the system and user context.
Choosing the Right Customization Lever#
- Prompt Engineering — Change instructions at runtime:
- Fastest, cheapest, and easiest to iterate.
- Best for task instructions, persona, few-shot examples, and output formatting.
- RAG — Inject external knowledge at runtime:
- Best for private, large, or frequently changing facts (policies, catalogs, tickets).
- Updating knowledge only requires re-indexing documents — no retraining.
- Fine-Tuning — Bake behavior into model weights:
- Best for consistent brand voice, tone, brevity, strict refusal style, or domain-specific response patterns across thousands of calls without repeating massive system prompts.
- Not ideal for fast-changing facts — fine-tuning teaches how to respond, while RAG supplies what facts to use.
Prompting, RAG, and fine-tuning solve orthogonal problems: start with prompts for instructions and schemas, add RAG for dynamic or private facts, and reserve JSONL fine-tuning for baking consistent tone and behavioral style into model weights.
Code Reference#
{
"messages": [
{
"role": "system",
"content": "You are BankBuddy. Be polite, brief, never promise timelines."
},
{
"role": "user",
"content": "my card got blocked why"
},
{
"role": "assistant",
"content": "Sorry about that! Cards are usually blocked after 3 wrong PIN attempts. You can unblock it in the app under Cards \u2192 Manage."
}
]
}
# Each line in a .jsonl file is one complete training example (system + user + ideal assistant reply).
# Upload for OpenAI supervised fine-tuning:
$ openai api files.create -f data/fine_tuning_example.jsonl -p fine-tune
{
"id": "file-abc123xyz",
"purpose": "fine-tune",
"filename": "fine_tuning_example.jsonl",
"status": "processed"
}
How All Building Blocks Connect#
Revision Notes#
- Foundation — Learning over Hardcoded Rules (
02): Modern AI replaces brittleif/elserules with models that learn statistical patterns from data. - Core LLM Control (
01,04,06): You interact via statelessmessages, separate developer contracts (system) from user input (user), enforce structured outputs, and dial consistency vs. creativity withtemperature. - Semantic Representation & Smart Chunking (
03,05): Embeddings turn meaning into geometry for similarity search, while structural parsers like ASTs split complex artifacts (like code) along logical boundaries instead of arbitrary character counts. - Grounding & Behavior Shaping (
07,fine_tuning_example.jsonl): Combine Prompting (instructions), RAG (live/private facts), and Fine-Tuning (baked-in style and behavior) to build reliable production LLM systems.
Quick Self-Check Questions#
Self-Check Questions#
Why do you have to resend previous messages to have a multi-turn conversation with an LLM API?
Because LLM APIs are stateless; the model retains no memory between HTTP requests.
Why did the ML spam filter catch "l0ttery" when the rule-based function missed it?
Character n-grams broke words into overlapping sub-word chunks (like tter, tery), letting the classifier match learned spam patterns despite the 0 typo.
Why does a simple dot product (doc_vecs @ q_vec) work as cosine similarity in minimal RAG?
Because OpenAI embeddings are unit-normalized (magnitude = 1), making dot product mathematically identical to cosine similarity.
What breaks if you index documents with one embedding model and embed user queries with another?
Retrieval fails because different embedding models produce incompatible vector spaces (and often different dimensions).
When should you choose temperature = 0 vs. temperature = 1.0?
Use 0 for repeatable, factual, or structured tasks (JSON extraction, RAG, classification, code); use 1.0 for varied, creative tasks (brainstorming, taglines).
Why parse code with an AST instead of chunking by fixed line counts?
ASTs preserve syntax boundaries (whole classes and functions) and exact line numbers, preventing broken context and enabling accurate citations.
A company's refund policy changes every week. Should you use RAG or fine-tuning?
Use RAG — updating a policy only requires re-indexing the document, whereas fine-tuning is meant for stable behavioral style and tone rather than fast-changing facts.