Developments in LLM/RAG

Ryan Singh

Agenda

  1. LLM Foundations
  2. RAG (Retrieval-Augmented Generation)
  3. LLM Agents
  4. LLM Evals

LLM Foundations

About SIGHT

Safety Immersion and Gamified Hazard Training for Industry 5.0 Workers
$1.5M Ohio BWC grant | Miami University | 2025–2027

AI + VR + AR safety training platform for Ohio manufacturing workers.
Two components: gamified VR hazard simulation + real-time AR coaching. How can we create AI based training to prevent workplace injuries in manufacturing?

My role in SIGHT

  • Create and maintain the LLM/RAG backend that powers the AR coaching component.
  • Evaluate the responses from the LLM/RAG. How do you know if the LLM is giving good advice? How do you improve it?
  • In the course of this project, we created a benchmark for questions in the manufacturing domain, and we will be using that benchmark.

Test out here

Before we begin

This workshop has three goals:

  • Make you conversational. By the end, you should be able to hold your own in any discussion about LLMs, RAG, and agents. Hopefully give you more confidence in the workplace.
  • Learn the vocabulary. Terms like embeddings, vector stores, temperature, and MCP should feel familiar, not foreign. If we ran an AI trivia round after this, you should see a statistically significant improvement.
  • Concepts >> code. I will move through code quickly. If you get lost in the syntax, that is fine — an LLM can write the code for you. What it cannot do is decide when and why to use these patterns.

Why Should You Care?

  • Every company sits on mountains of unstructured data: emails, docs, Slack threads, support tickets.
  • LLMs + RAG let you build systems that understand that data, not just keyword-search it.
  • Running example: A company receives 50,000+ customer emails a year. A new support rep needs to answer: “What’s our return policy for international orders?” Today they dig through folders. With RAG, they ask in plain English and get a grounded answer in seconds.

What Is an LLM?

  • A large language model predicts the next token given some initial tokens.
  • Training objective: minimize next-token prediction error across massive text corpora.

How an LLM processes text:

Text → Tokens → Token IDs → Embeddings → Transformer -> Neural Network -> Decode -> Tokens → Text

LLM Architecture

Source: Geeks for Geeks

1. Tokenization

  • Models do not read words directly; they read tokens.
  • A token can be a full word, subword, punctuation mark, or whitespace chunk.
  • Pricing, latency, and context limits are token-based.
    • 1 token ≈ 0.75 words or 1.33 \(\times\) words
    • $2.50 / 1M tokens (input) | $0.25 / 1M tokens (cached input) | $15.00 / 1M tokens (output)
  • GPT-2’s vocabulary has 50,257 unique tokens. 1

1. Tokenization

  • Same sentence can produce different token counts across tokenizers.
text = "NotebookLM is a RAG app."
# ['Note', 'book', 'LM', ' is', ' a', ' R', 'AG', ' app', '.']

1. Tokenization

OpenAI Tokenizer

https://platform.openai.com/tokenizer

2. Embedding Layers

  • Map discrete token IDs to continuous vector space.
  • Capture semantic relationships and contextual nuances.

source: CauserWriter

Semantic: relating to meaning in language or logic.

2. Embedding Layers

Great Video from 3blue1brown



🤔 Question

Can we use this for classification?

Full 3Blue1Brown Playlist

3. Transformers

Example:

  • “I deposited money at the _ _ _ _”

  • “I sat on the river _ _ _ _”

  • Text-generative Transformer models operate on the principle of next-token prediction: given a text prompt from the user, what is the most probable next token (a word or part of a word) that will follow this input.

  • Transformers allow the LLM to understand things like: based on ALL the tokens I have seen, what should each token mean in this specific context.

3. Transformers

  • When I predict the next token, how much attention should the model pay to all the preceding tokens?

  • Attention blocks in transformer models allow all tokens to talk to each other.

  • Within each Transformer block, the multi-head self-attention layer is what allows tokens to communicate with each other.

  • Without it, each token would be processed in isolation. The FFN layers that follow operate per-token, so attention is the only mechanism for inter-token information flow.

3. Transformers

Source: Cho et al. (2024). Transformer Explainer. IEEE VIS. — Click here

3. Transformers

Attention Is All You Need

Original Paper

Annotated Implementation

The main take-aways

  • LLMs are just recursively predicting the next token.

  • Preceding tokens dictate the output probability. By adding “OH,” probability increases by double.

  • Temp changes the probability distribution of the predicted tokens. Higher temp = more randomness.

ChatGPT API

  • temperature=0: most deterministic. Use for evals, grading, data extraction — anywhere reproducibility matters. In SIGHT, our LLM-as-judge uses temp=0 so the same question gets the same grade every run.
  • temperature=0.7–1.0: more creative, varied outputs. Use for brainstorming, marketing copy, conversational agents.
  • max_tokens: hard cap on generated output length.
  • reasoning_effort: controls how much internal reasoning budget is used.
  • Tradeoff: higher quality often means more latency and cost.
response = client.responses.create(
    model="gpt-4.1",
    input="Summarize this report in 3 bullets.",
    temperature=0,
    max_output_tokens=120,
    reasoning={"effort": "medium"}
)

State of Open-Source LLMs

  • Strong families: Gemma 3, Llama, Qwen, Mistral, DeepSeek, and domain-specific variants.
  • Practical benefits: self-hosting, lower marginal cost, data residency control.
  • Typical constraints: hardware needs, ops complexity, eval/finetune overhead.
  • Common pattern: open-source for retrieval/structured steps, frontier API for hardest reasoning.

RAG

The Same Model, Two Very Different Answers

Without Context

response = client.responses.create(
    model="gpt-4.1-mini",
    input="What are the three software 
    safety modes on the UR5e cobot?",
    temperature=0,
)

❌ The model will confidently list modes like “Safeguard,” “Emergency,” or “Automatic” — plausible-sounding but wrong.

With Retrieved Context

context = """
Some key excerpts from the UR5e manual
"""

response = client.responses.create(
    model="gpt-4.1-mini",
    input=f"Answer using ONLY this context:
    {context}
    
    Question: What are the three software 
    safety modes on the UR5e cobot?",
    temperature=0,
)

✅ Normal, Reduced, Recovery — grounded in the manual.

The model didn’t get smarter. We just gave it the right context. That’s RAG.

Grounding to the Truth

  • We know that base LLM knowledge — especially smaller models — can be stale or incomplete. Ask a small model “Where is Miami University?” and it may say Florida.

  • We also know that preceding tokens play a pivotal role. Add “Ohio” to the prompt and the answer changes entirely. Prompting and context matter.

  • You probably already know that giving your notes to an LLM as context and asking for a study guide is better than just asking for a study guide on a certain topic.

🤔 Question

Is there a way, every time we ask an LLM a question, it injects the right context into the prompt?

Before Semantic Search

  • Keyword / full-text search (TF-IDF, BM25): matches exact terms only. “gelatin silver print” never matches “black and white photo.”
  • SQL LIKE / regex: rigid, requires knowing the schema and exact vocabulary.
  • Manual tagging / taxonomy: humans hand-label every record. Expensive, inconsistent, doesn’t scale.
  • Boolean search (AND/OR/NOT): better than raw keyword, but still no understanding of meaning.

These all break when data is messy, incomplete, or described inconsistently — which is most real-world data.

Retrieval Patterns: SQL & Vector

  • SQL retrieval for exact, structured data:
    • transactional facts
    • filtered records
  • Vector retrieval for semantic relevance:
    • semantic matching and fuzzy matching
    • unstructured text

🤔 Question

Say you are building a RAG system for all your emails you have received (50000+). When would you use SQL retrieval vs. vector retrieval?

Minimal RAG Flow (Pseudo-code)

query = "What changed in the policy this quarter?"
hits = retriever.search(query, top_k=5)
context = "\n\n".join([h["text"] for h in hits])
prompt = f"Answer using only this context:\n{context}\n\nQuestion: {query}"
answer = llm(prompt)

LangGraph in 30 Seconds

Think of LangGraph like a flowchart you can run.

  • Each box (node) is a step: retrieve docs, call an LLM, run a SQL query.
  • Each arrow (edge) says what happens next — and it can branch based on conditions.
  • A shared clipboard (state) passes information between steps so each box knows what the previous one did.

If LangChain is a recipe (step 1, step 2, step 3), LangGraph is a choose-your-own-adventure book.

LangChain and LangGraph

  • LangChain provides modular abstractions — prompts, retrievers, tools, and chains — so you can swap components without rewriting glue code.
  • LangGraph extends this with stateful, graph-based workflows: define nodes, edges, and control flow for multi-step agentic pipelines.
  • Rule of thumb: if your task is a single retrieval → generate pass, LangChain alone is fine. If you need branching, retries, or loops, reach for LangGraph.

Think of these like lego block libraries for building LLM apps. They handle the nuisance code so you can focus on the architecture and logic of your application.

RAG in Practice: Art Museum Search

This is the case we will be working with in the code-along.

  • Curators had to write exact SQL queries to search the collection — but records were often incomplete, inconsistently tagged or missing metadata entirely.
  • Exact-match SQL fails when the data is messy. A search for “black and white portrait photography” returns nothing if the record only says “gelatin silver print, 1940.”
    • Vector Embeddings capture semantic similarity, so the retriever can surface relevant records
  • The goal: replace rigid SQL lookup with natural language retrieval.1

Vector Stores

  • A vector store indexes embedding vectors alongside metadata for fast nearest-neighbor lookup.
  • At query time, your question is embedded into the same vector space, and the store returns the closest matching chunks.
  • Pre-filters (date, source, department) narrow the search space before similarity ranking runs.
  • Chunk size, overlap, and reranking strategy directly affect recall and precision — these are tunable knobs.
  • We will be using FAISS in our demo today. 1
  • Other popular options include Pinecone, MongoDB, Chroma

Visualizing the Vector Store

Chunking Strategies

  • The way you split documents into chunks can make or break retrieval quality.
  • For example, in our museum data each object is a single point in the vector store. But if we are working with long documents, we might want to chunk them into sections or paragraphs.
  • Overlap is important to preserve context across chunk boundaries. A common heuristic is 200-300 tokens of overlap, but this depends on your data and retrieval needs.

Appendix LangGraph: Stateful Agent Graphs

  • LangGraph models workflows as directed graphs where a shared state object flows through each step.
  • Each node is a plain Python function: it reads from state, does work (LLM call, retrieval, tool use), and returns the keys it wants to update.
  • Edges wire nodes together — fixed, conditional, or looping — giving you explicit control over execution order.
  • This makes multi-step tasks debuggable and reproducible: you can inspect state at every node boundary.
builder = StateGraph(State)
# Nodes
builder.add_node("retrieve", retrieve)
builder.add_node("generate", generate)
builder.add_node("extract_keywords", extract_keywords)
# Edges
builder.add_edge(START, "extract_keywords")
builder.add_edge("extract_keywords", "retrieve")
builder.add_edge("retrieve", "generate")
builder.add_edge("generate", END)
# Compile & view
graph = builder.compile()
display(Image(graph.get_graph().draw_mermaid_png()))

Appendix State in LangGraph

  • State is a TypedDict — a typed Python dict that every node in the graph can read and write to.
  • Nodes return a partial dict with only the keys they want to update; LangGraph merges it back automatically.
  • Reducers control merge behavior per key. The default is last-write-wins, but add_messages appends instead — useful for building up a conversation history.
from typing import TypedDict, Annotated, List
from langchain_core.messages import AnyMessage
from langgraph.graph.message import add_messages

class State(TypedDict):
    messages: Annotated[list[AnyMessage], add_messages]  # appends each turn
    question: str       # overwritten each call
    documents: List[str]
    generation: str

LangGraph: Nodes and Edges

Nodes

  • Any callable with signature fn(state) -> dict
  • Return only the keys you want to update — everything else stays untouched
  • Can call LLMs, retrievers, tools, APIs, or even nested sub-graphs

Edges

  • Fixed: add_edge(a, b) — always routes a → b
  • Conditional: add_conditional_edges(a, router_fn) — routes dynamically based on state values
  • START and END are built-in sentinels that mark entry and exit points
def retrieve(state: State) -> dict:
    docs = retriever.invoke(state["question"])
    return {"documents": docs}          # only updates 'documents'

builder.add_conditional_edges(
    "grade",
    lambda s: "generate" if s["relevant"] else "retrieve",
)

NotebookLM Is a RAG App

  • You provide docs.
  • It indexes and retrieves relevant chunks.
  • It answers with source-grounded context.
  • This is RAG behavior, wrapped in a consumer-friendly interface.

LLM Agents

Agency

  • An agent is an LLM that can autonomously take actions in a loop (tool use, code execution, web browsing), plan multi-step tasks, and course-correct based on feedback
  • Agentic behavior is useful when tasks require multi-step decisions.

Simple Agent: SQL Tooling

  • Pattern: user question -> intent parsing -> SQL generation -> execution -> final answer.
  • Risk: SQL injection, unsafe queries, and accidental data exposure.
  • Controls:
    • allowlisted tables/columns
    • parameterized queries
    • read-only DB roles
    • query validators before execution

MCP (Model Context Protocol)

  • MCP standardizes how models discover and use external tools/context.
  • Think of it as a common interface between model runtimes and tool servers.
  • Before USB-C, every device had its own weird plug. MCP is the USB-C of model-tool integration.
  • Before MCP, every tool (Slack, Google Drive, Notion) needed its own custom integration code.
  • Real-world MCP servers already exist for: Slack (search channels), GitHub (read PRs), Postgres (run queries), file system (read/write files).

MCP Example

# MCP Server: expose a tool
@server.list_tools()
async def list_tools():
    return [Tool(name="get_weather", inputSchema={...})]

@server.call_tool()
async def call_tool(name, arguments):
    return get_weather(arguments["city"])

# MCP Client: discover and use it
tools = await session.list_tools()        # "What can you do?"
result = await session.call_tool(         # "Do this thing"
    "get_weather", {"city": "Cincinnati"}
)

MCP: Explore the Spec

  • MCP is an open standard — browse the full spec and available integrations below.

Auto Research — Recursive Agent Example

  • The core idea: give an AI agent a small but real LLM training setup and let it experiment autonomously overnight. It modifies the code, trains for 5 minutes, checks if the result improved.
  • I forked this repo and ran it for our 591 project. The agent ran 20 experiments overnight and 2 saw small improvements in the target metric. 1

LLM Evals

What Is Right or Wrong?

  • Define task-specific rubrics before testing.
  • Separate objective checks (exact match, schema validity) from subjective checks (tone, clarity).
  • Require evidence/citations for factual outputs where possible.
  • Without a rubric, you’re grading with vibes.

Deterministic vs. Non-Deterministic Questions

  • Deterministic: one correct answer. “How many paintings?” → 644. Gradeable with exact match.
  • Non-deterministic: many valid answers. “Describe the African art.” Requires judgment.
  • Most real-world RAG questions are non-deterministic — this is what makes LLM evals hard.
  • Your golden set should include both types so you know where your system is strong and where it’s fuzzy.
Type Example Grading
Deterministic “How many paintings?” Exact match / simple comparison
Non-deterministic “Describe the African art” LLM-as-judge or human review

Randomness and Determinacy

  • LLM outputs vary due to sampling and model uncertainty.
  • temperature=0 improves repeatability but does not guarantee identical output.
  • Even the same deterministic question can get different wording across runs.
  • This is why LLM evals require repeated runs and distributions, not single samples.

Accuracy, Latency, Cost

  • Quality alone is not enough; track all three.
  • Accuracy: does the model answer correctly?
  • Latency: fast enough for the user experience?
  • Cost: sustainable per request and at scale?

LLM as a Judge

  • Use a strong model to score outputs against a rubric.
  • LLMs are really good at spotting inconsistencies between 2 given texts.
  • Two criteria we’ll use:
    • Helpfulness: Is the answer relevant and concise?
    • Correctness: Does it match the gold answer factually? This is more important.
  • Watch for judge bias and rubric leakage.
  • There have been instances where an LLM knows it is being graded and will try to cheat on the test or won’t take it seriously. 1

Golden Set (How We Did It for the Research Project)

  1. We had a team of 8 students, professors and phd candidates manually curate a set of 100 questions related to machinery, like a CNC lathe or Mill.
  2. Our questions were non-deterministic only.
  3. Each question was sent to a subject matter expert (SME) for revision. We had a safety consultant review all the questions.

Continuous Evals

  • Notice the like/dislike buttons on ChatGPT responses? Those are user feedback signals that feed into OpenAI’s eval system.
  • Also, I’m sure you notice the A/B tests now too.
  • This is a good way to understand where the Agent failed and how to improve it.
  • For example, if users consistently dislike responses to a certain question, that signals a weakness in the retrieval or generation for that query type. You can then add more examples of that question type to your eval set and iterate on improving it.

What to Try Next

  • BUILD BUILD BUILD there is no substitute for hands-on experience. Use coding agents in a code.
  • Fork the code-along and swap in your own data (emails, reports, tickets).
  • Look at cool projects: https://github.com/kyrolabs/awesome-langchain and https://streamlit.io/gallery

The best way to learn this stuff is to build something small and iterate.