Contents
1What it does2The big picture3How to run it4What changed and why0Imports and settings1The State2The agent's 4 methods3The graph4One question = one trace5The main block▶One question in LangSmith6Reading the output↔Link to the lecture✎Exercises★Glossary{}Full sourceThe personality bot: caching plus full observability with LangSmith
Type a famous person's name and the bot answers in two lines. Repeated questions are answered from a cache for free, and every step of every question is recorded in LangSmith, so you can see exactly what happened, how long it took and what it cost.
What it does, in one minute
💡 The story
The script asks seven questions in a row:
| # | Question | What happens | Cost |
|---|---|---|---|
| 1 | Elon Musk | New question → ask OpenAI, save the answer | a tiny bit |
| 2 | Elon Musk | Exact same text → reuse the saved answer | free |
| 3 | Who is Elon Musk? | Different words, same meaning → reuse the saved answer | almost free |
| 4 | Marie Curie | New → ask OpenAI | a tiny bit |
| 5 | " marie curie " | Same text after cleaning (lower case, extra spaces removed) → exact hit | free |
| 6 | Tell me about Marie Curie | Same meaning → semantic hit | almost free |
| 7 | Albert Einstein | New → ask OpenAI | a tiny bit |
Seven questions, only three paid model calls. And for every question, LangSmith keeps a trace: a step-by-step record you can open in the browser.
🍛 Analogy: the chai stall that keeps a notebook
A busy chai stall gets the same orders all day. The owner writes each new order and its recipe in a notebook (cache). "One cutting chai" again? Read it from the notebook (exact hit). "Half a glass of tea, please"? Different words, same thing (semantic hit). And a CCTV camera records every order from start to finish (tracing), so when a customer complains you can rewind and see exactly what happened.
The big picture: three checkpoints in a row
after_exact, after_semantic) choose the arrow, so only the steps that actually ran appear in the trace.💡 Where the four MELT pillars live in this file
| Pillar | In plain words | In this code |
|---|---|---|
| Metrics | Numbers to track over time | Tokens, cost and seconds per question ([metric] lines), session totals at the end |
| Events | Named, meaningful moments | record_event("cache_hit_exact"), "cache_hit_semantic", "llm_call_started", "answer_cached" |
| Logs | The exact words in and out | wrap_openai() stores every prompt and answer; [log] line for the closest match |
| Traces | The step-by-step story of one request | @traceable plus LangGraph: one tree per question in LangSmith |
How to run it
⌨️ Setup (5 minutes)
- Put
obs_demo_langsmith.py,requirements.txtand.env.examplein one folder. - Install:
pip install -r requirements.txt(Python 3.10+). - Create a free LangSmith account at smith.langchain.com → Settings → API Keys → create a key.
- Copy
.env.exampleto.envand fill in both keys:OPENAI_API_KEY=sk-... LANGSMITH_TRACING=true LANGSMITH_API_KEY=lsv2_... LANGSMITH_PROJECT=observability_demo
- Run:
python obs_demo_langsmith.py - Open smith.langchain.com → Tracing Projects → observability_demo. You'll see seven
personality_queryruns, one per question.
What the terminal prints:
[1/7] 'Elon Musk'
[event] llm_call_started {'question': 'Elon Musk'}
[metric] embedding: 3 tokens, $0.0000001
[event] answer_cached {'question': 'elon musk', 'llm_seconds': 0.84}
[metric] FRESH | 1.21s | 67 tokens | $0.000023
-> Elon Musk is famously bold and relentless, known for huge risks and very long working hours.
He leads Tesla and SpaceX and helped make electric cars and reusable rockets mainstream.
[2/7] 'Elon Musk'
[event] cache_hit_exact {'question': 'elon musk'}
[metric] EXACT | 0.00s | 0 tokens | $0.000000
-> Elon Musk is famously bold and relentless, known for huge risks and very long working hours.
He leads Tesla and SpaceX and helped make electric cars and reusable rockets mainstream.
[3/7] 'Who is Elon Musk?'
[metric] embedding: 5 tokens, $0.0000001
[log] closest saved question: 'elon musk' (similarity 0.84)
[event] cache_hit_semantic {'question': 'Who is Elon Musk?', 'matched': 'elon musk', 'similarity': 0.84}
[metric] SEMANTIC | 0.29s | 0 tokens | $0.000000
-> Elon Musk is famously bold and relentless, known for huge risks and very long working hours.
He leads Tesla and SpaceX and helped make electric cars and reusable rockets mainstream.
[4/7] 'Marie Curie'
[metric] embedding: 3 tokens, $0.0000001
[log] closest saved question: 'elon musk' (similarity 0.29)
[event] llm_call_started {'question': 'Marie Curie'}
[metric] embedding: 3 tokens, $0.0000001
[event] answer_cached {'question': 'marie curie', 'llm_seconds': 0.91}
[metric] FRESH | 1.56s | 69 tokens | $0.000024
-> Marie Curie was determined, patient and deeply curious, working for years in tough conditions.
She discovered polonium and radium and was the first person to win Nobel Prizes in two sciences.
[5/7] ' marie curie '
[event] cache_hit_exact {'question': 'marie curie'}
[metric] EXACT | 0.00s | 0 tokens | $0.000000
-> Marie Curie was determined, patient and deeply curious, working for years in tough conditions.
She discovered polonium and radium and was the first person to win Nobel Prizes in two sciences.
[6/7] 'Tell me about Marie Curie'
[metric] embedding: 5 tokens, $0.0000001
[log] closest saved question: 'marie curie' (similarity 0.78)
[event] cache_hit_semantic {'question': 'Tell me about Marie Curie', 'matched': 'marie curie', 'similarity': 0.78}
[metric] SEMANTIC | 0.27s | 0 tokens | $0.000000
-> Marie Curie was determined, patient and deeply curious, working for years in tough conditions.
She discovered polonium and radium and was the first person to win Nobel Prizes in two sciences.
[7/7] 'Albert Einstein'
[metric] embedding: 3 tokens, $0.0000001
[log] closest saved question: 'marie curie' (similarity 0.41)
[event] llm_call_started {'question': 'Albert Einstein'}
[metric] embedding: 3 tokens, $0.0000001
[event] answer_cached {'question': 'albert einstein', 'llm_seconds': 0.88}
[metric] FRESH | 1.49s | 71 tokens | $0.000025
-> Albert Einstein was imaginative and fiercely independent, famous for his "thought experiments".
He developed the theory of relativity and won the 1921 Nobel Prize in Physics.
=== SESSION METRICS ===
Questions : 7
Exact cache hits : 2
Semantic hits : 2
LLM calls : 3
Cache hit rate : 57%
LLM tokens : 207
LLM cost : $0.000071The whole run costs well under one US cent. Section 6 explains how to read every line.
What changed from the original, and why
Same idea, same three checkpoints, same seven-question demo. Here's everything that's different.
| # | Original | Now | Why |
|---|---|---|---|
| 1 | gpt-3.5-turbo with its old prices | gpt-6-luna, prices $0.10 / $0.50 per million tokens | OpenAI shut gpt-3.5-turbo down in October 2026, so every call failed. gpt-6-luna is OpenAI's current small, cheap model. |
| 2 | Keys copied into os.environ in code, using the old LANGCHAIN_* names | All settings in .env with the current LANGSMITH_* names | The old lines crashed with a TypeError whenever a key was missing. Settings belong in .env, not in code. |
| 3 | langsmith.run_helpers and tracing_v2_enabled() | from langsmith import traceable; tracing switched on by LANGSMITH_TRACING=true | The current, simpler way. |
| 4 | Prompts and answers not recorded | client = wrap_openai(OpenAI()) | One line adds the logs pillar: every prompt, answer, model and token count appears in the trace. |
| 5 | Every node always ran; each one checked "already answered? then do nothing" | Two small routers send the question straight to END on a hit | The trace now shows only the steps that really happened, which makes it easier to read. |
| 6 | @traceable on every graph node | Removed from the nodes | LangGraph already traces every node; the extra decorator created duplicate steps. |
| 7 | Similarity threshold 0.85; test questions "Tell me about Elon", "Info on Curie" | Threshold 0.70; "Who is Elon Musk?", "Tell me about Marie Curie" | With OpenAI's current embedding model, short rewordings usually score below 0.85, so the demo's "semantic hits" didn't happen. 0.70 shows the idea; tune it on your own data. |
| 8 | API errors returned the text "Error: …" as the answer | Errors are not caught | The original saved the error message in the cache and served it as the answer forever after. Now the error shows up red in the trace and nothing bad is cached. |
| 9 | scikit-learn's cosine_similarity | np.dot | OpenAI's embedding vectors already have length 1, so a dot product is the cosine similarity. One less heavy library to install. |
| 10 | "⚡ EXACT CACHE HIT:" glued to the front of the answer | The answer stays clean; the hit type is a separate field | A field you can filter and count is a metric; text glued to an answer is not. |
| 11 | lower().strip() | clean() also squeezes repeated spaces | "marie curie" and "marie curie" should be the same question. |
| 12 | time.sleep(1) between questions | Removed | It only made the demo slower. |
The code, step by step
Each block below is copied straight from the file, with its line numbers, so you can follow along in your editor.
Imports and settings
import time from typing import TypedDict import numpy as np from dotenv import load_dotenv from langgraph.graph import StateGraph, END from langsmith import traceable from langsmith.wrappers import wrap_openai from openai import OpenAI load_dotenv() # reads OPENAI_API_KEY and the LANGSMITH_* settings from .env CHAT_MODEL = "gpt-6-luna" # OpenAI's small, fast, cheap model EMBEDDING_MODEL = "text-embedding-3-small" # turns text into a list of numbers (a vector) # Prices in US$ per 1 million tokens (check OpenAI's pricing page, they change) PRICE_INPUT, PRICE_OUTPUT, PRICE_EMBEDDING = 0.10, 0.50, 0.02 SIMILARITY_THRESHOLD = 0.70 # how close (0 to 1) a new question must be to reuse an old answer # wrap_openai: one line, and every OpenAI call (prompt, answer, model, tokens, time) # is logged to LangSmith automatically. client = wrap_openai(OpenAI())
💡 What each part is for
- numpy: maths on the embedding vectors (the dot product).
- langgraph: builds the three-checkpoint graph.
- traceable: a decorator that turns any Python function into a step (span) in the trace.
- wrap_openai: wraps the OpenAI client so every chat call is logged automatically.
- Two models:
gpt-6-lunawrites answers;text-embedding-3-smallturns text into a list of numbers that captures its meaning. - Prices: used to compute the cost metric. Prices change, so they're kept in one easy-to-edit line.
- SIMILARITY_THRESHOLD: how alike two questions must be (0 to 1) before we reuse an answer.
🍛 Analogy: wrap_openai
Like putting a call recorder on the office phone. You don't change how anyone talks; every call is simply recorded with its time and length.
The State: what the graph knows about one question
class AgentState(TypedDict, total=False): query: str # the question, e.g. "Elon Musk" response: str # the answer cache_hit_type: str # "exact", "semantic", "fresh" (or "miss" while still looking) similarity: float # best similarity score found in the semantic cache cost: float # US$ spent on the LLM for this question tokens: int # LLM tokens used for this question
def clean(text: str) -> str: """' Marie Curie ' and 'marie curie' should count as the same question.""" return " ".join(text.lower().split())
💡 In plain words
The State is a small dictionary that travels through the graph. Each node reads it and returns only the fields it wants to change; LangGraph merges them in. total=False means a field can be missing until a node fills it in.
clean() makes the cache forgiving: " Marie Curie " → "marie curie".
🍛 Analogy
A token slip at a food court: it starts with just your order, and each counter writes on it ("not in fridge", "cooked fresh", "₹2 gas used") until it comes back to you.
The agent's four methods (each one becomes a step in the trace)
def __init__(self): self.cache = {} # cleaned question -> answer self.embeddings = {} # cleaned question -> its embedding vector
Two caches. cache maps a cleaned question to its answer. embeddings maps the same question to its meaning vector, for the semantic search.
2a · get_embedding: text → meaning vector
@traceable(name="get_embedding", run_type="embedding") def get_embedding(self, text: str) -> np.ndarray: response = client.embeddings.create(model=EMBEDDING_MODEL, input=text) tokens = response.usage.total_tokens print(f" [metric] embedding: {tokens} tokens, ${tokens / 1e6 * PRICE_EMBEDDING:.7f}") return np.array(response.data[0].embedding)
Sends the text to OpenAI's embedding model and gets back 1,536 numbers. Texts with similar meaning get similar numbers. It also prints a metric line: tokens and cost. Embeddings are extremely cheap: about $0.0000001 for a short question.
2b · find_semantic_match: the closest earlier question
@traceable(name="find_semantic_match", run_type="tool") def find_semantic_match(self, query: str): """Return (closest saved question, similarity score).""" if not self.embeddings: return None, 0.0 query_vector = self.get_embedding(clean(query)) best_key, best_score = None, -1.0 # start below any real score for key, vector in self.embeddings.items(): score = float(np.dot(query_vector, vector)) # OpenAI vectors have length 1, so dot = cosine similarity if score > best_score: best_key, best_score = key, score print(f" [log] closest saved question: '{best_key}' (similarity {best_score:.2f})") return best_key, best_score
💡 How "same meaning" is measured
Compare the new question's vector with every saved one. The dot product gives a score: about 1.0 for the same meaning, about 0 for unrelated. Typical scores you'll see:
| New question | Closest saved | Score | Result (threshold 0.70) |
|---|---|---|---|
| Who is Elon Musk? | elon musk | ≈ 0.84 | ✅ reuse |
| Tell me about Marie Curie | marie curie | ≈ 0.78 | ✅ reuse |
| Albert Einstein | marie curie | ≈ 0.41 | ❌ ask OpenAI |
Einstein and Curie score higher than Curie and Musk because both are physicists, but nowhere near "same question".
2c · call_openai_model: the paid step
@traceable(name="call_openai_model", run_type="chain") def call_openai_model(self, question: str): response = client.chat.completions.create( model=CHAT_MODEL, reasoning_effort="none", # answer straight away, no hidden "thinking" tokens messages=[ {"role": "system", "content": "Give exactly 2 short lines about this person's personality and achievements."}, {"role": "user", "content": f"Tell me about {question}"}, ], ) usage = response.usage cost = usage.prompt_tokens / 1e6 * PRICE_INPUT + usage.completion_tokens / 1e6 * PRICE_OUTPUT return response.choices[0].message.content.strip(), usage.total_tokens, cost
- Two messages: a system message with the rule ("exactly 2 short lines") and the user's question.
reasoning_effort="none":gpt-6-lunacan "think" before answering, which costs extra hidden tokens. For a two-line answer we switch that off.- Cost: input tokens × input price + output tokens × output price. For 27 tokens in and 40 out: 27 × $0.10/1M + 40 × $0.50/1M ≈ $0.000023.
2d · record_event: mark a meaningful moment
@traceable(name="record_event", run_type="tool") def record_event(self, event_name: str, details: dict): """An EVENT: a meaningful moment we want to find and count later.""" print(f" [event] {event_name} {details}")
It only prints, but because of @traceable every call becomes a named step in the trace, with its details attached. Later you can count them in LangSmith: "how many semantic hits today?"
⚠️ The run_type labels
run_type tells LangSmith what kind of step this is (embedding, tool, chain, llm), so it can show the right icon and let you filter by type. It doesn't change what the code does.
The graph: three nodes and two routers
def build_graph(agent: PersonalityAgent): def check_exact_cache(state: AgentState) -> dict: key = clean(state["query"]) if key in agent.cache: agent.record_event("cache_hit_exact", {"question": key}) return {"response": agent.cache[key], "cache_hit_type": "exact", "cost": 0.0, "tokens": 0} return {"cache_hit_type": "miss"} def check_semantic_cache(state: AgentState) -> dict: best_key, score = agent.find_semantic_match(state["query"]) if best_key and score >= SIMILARITY_THRESHOLD: agent.record_event("cache_hit_semantic", {"question": state["query"], "matched": best_key, "similarity": round(score, 2)}) # Only a tiny embedding cost was spent (printed above), no LLM cost return {"response": agent.cache[best_key], "cache_hit_type": "semantic", "similarity": score, "cost": 0.0, "tokens": 0} return {"cache_hit_type": "miss", "similarity": score} def call_llm(state: AgentState) -> dict: question = state["query"] agent.record_event("llm_call_started", {"question": question}) start = time.perf_counter() answer, tokens, cost = agent.call_openai_model(question) seconds = time.perf_counter() - start key = clean(question) # save for next time, in BOTH caches agent.cache[key] = answer agent.embeddings[key] = agent.get_embedding(key) agent.record_event("answer_cached", {"question": key, "llm_seconds": round(seconds, 2)}) return {"response": answer, "cache_hit_type": "fresh", "cost": cost, "tokens": tokens} def after_exact(state: AgentState) -> str: return END if state["cache_hit_type"] == "exact" else "check_semantic_cache" def after_semantic(state: AgentState) -> str: return END if state["cache_hit_type"] == "semantic" else "call_llm" graph = StateGraph(AgentState) graph.add_node("check_exact_cache", check_exact_cache) graph.add_node("check_semantic_cache", check_semantic_cache) graph.add_node("call_llm", call_llm) graph.set_entry_point("check_exact_cache") graph.add_conditional_edges("check_exact_cache", after_exact) graph.add_conditional_edges("check_semantic_cache", after_semantic) graph.add_edge("call_llm", END) return graph.compile()
💡 Read it in this order
- check_exact_cache: cleaned question in the cache? Return the saved answer, with cost 0. Otherwise mark it
"miss". - check_semantic_cache: find the closest saved question. Score at or above 0.70? Reuse its answer. Otherwise
"miss". - call_llm: ask OpenAI, time it, then save the answer and its embedding so future questions can match it.
- after_exact / after_semantic: the routers. They read
cache_hit_typeand return the name of the next node, orEND. - The wiring at the bottom: start at
check_exact_cache, use the routers after the first two nodes, and always end aftercall_llm.
🍛 Analogy
Three counters at a passport office: "already processed?" → "a very similar case on file?" → "process it fresh". At each counter an officer (the router) decides: done, or next counter.
⚠️ One small inefficiency to spot
For a new question, find_semantic_match computes its embedding, and then call_llm computes the same embedding again to save it. You can see the two embedding lines in the output for Marie Curie. It costs almost nothing, but it's a nice exercise to fix (see Exercises).
One question = one trace
@traceable(name="personality_query", run_type="chain", metadata={"app": "personality_bot", "version": "2.0"}) def run_query(graph, query: str) -> dict: start = time.perf_counter() result = graph.invoke({"query": query}) seconds = time.perf_counter() - start print(f" [metric] {result['cache_hit_type'].upper()} | {seconds:.2f}s | " f"{result.get('tokens', 0)} tokens | ${result.get('cost', 0.0):.6f}") print(f" -> {result['response']}") return result
This is the root of each trace. Everything that happens inside graph.invoke (nodes, embeddings, OpenAI calls, events) is nested under it. The metadata is attached to every trace, so in LangSmith you can filter "show me only version 2.0 of personality_bot". It also prints the summary metric line: hit type, seconds, tokens and cost.
The main block: seven questions, then session metrics
if __name__ == "__main__": agent = PersonalityAgent() graph = build_graph(agent) questions = [ "Elon Musk", # fresh: asked for the first time "Elon Musk", # exact hit: same text "Who is Elon Musk?", # semantic hit (if similarity >= threshold): same meaning "Marie Curie", # fresh " marie curie ", # exact hit after cleaning (lower case, extra spaces) "Tell me about Marie Curie", # semantic hit (if similarity >= threshold) "Albert Einstein", # fresh ] counts = {"exact": 0, "semantic": 0, "fresh": 0} total_cost, total_tokens = 0.0, 0 for i, question in enumerate(questions, 1): print(f"\n[{i}/{len(questions)}] {question!r}") result = run_query(graph, question) counts[result["cache_hit_type"]] += 1 total_cost += result.get("cost", 0.0) total_tokens += result.get("tokens", 0) print("\n=== SESSION METRICS ===") print(f"Questions : {len(questions)}") print(f"Exact cache hits : {counts['exact']}") print(f"Semantic hits : {counts['semantic']}") print(f"LLM calls : {counts['fresh']}") print(f"Cache hit rate : {100 * (counts['exact'] + counts['semantic']) / len(questions):.0f}%") print(f"LLM tokens : {total_tokens}") print(f"LLM cost : ${total_cost:.6f}")
The question list is designed to hit every path: fresh, exact, semantic, exact-after-cleaning. The loop adds up the counts, tokens and cost, and prints a session summary at the end: the kind of numbers you'd put on a dashboard.
Following one question
"Marie Curie" (question 4), as LangSmith shows it
Roughly what you see when you open the trace (times vary).
personality_query 1.56 s metadata: app=personality_bot, version=2.0
└─ LangGraph 1.56 s
├─ check_exact_cache 0.00 s -> cache_hit_type = "miss"
├─ check_semantic_cache 0.32 s
│ └─ find_semantic_match 0.32 s closest: 'elon musk' (0.29), below 0.70
│ └─ get_embedding 0.32 s "marie curie", 3 tokens
└─ call_llm 1.24 s
├─ record_event 0.00 s llm_call_started
├─ call_openai_model 0.91 s
│ └─ ChatOpenAI 0.91 s gpt-6-luna · 27 tokens in, 42 out
│ (click it: full system prompt, question and answer)
├─ get_embedding 0.33 s "marie curie", 3 tokens
└─ record_event 0.00 s answer_cached💡 How to read it
- The indentation shows what ran inside what. The exact-cache check took 0 s; the semantic search spent 0.32 s on one embedding; the model call took 0.91 s.
- Click ChatOpenAI and you see the logs: the full system prompt, the question, the answer, the model name and the token counts. That's
wrap_openaiat work. - The record_event steps are the events. They mark the moments that matter.
- An exact hit (question 5) shows just one short step under LangGraph:
check_exact_cache, then done.
Reading the terminal output
| Line starts with | Pillar | Example | Means |
|---|---|---|---|
[metric] | Metrics | FRESH | 1.56s | 69 tokens | $0.000024 | How this question was answered, how long it took, what it cost |
[event] | Events | cache_hit_semantic {... 'similarity': 0.78} | A meaningful moment, with details |
[log] | Logs | closest saved question: 'elon musk' (similarity 0.29) | Detail you'd want when debugging a bad cache match |
-> | (the answer) | "Marie Curie was determined…" | What the user sees |
🌍 What the session metrics tell a business
57% of questions were answered from the cache. At scale (say 1 lakh questions a day), that's 57,000 fewer model calls: lower cost and much faster answers for those users. This is exactly the kind of metric you put on a dashboard and watch over time.
⚠️ The risk of a semantic cache
Set the threshold too low and different questions get the same answer: "Marie Curie's daughter" might match "Marie Curie" and get the wrong person's story. That's why the [log] line prints the score. Watch these scores on real traffic before choosing a threshold.
Using this in class
Link to the Observability lecture
| Lecture idea | Where to point in this code |
|---|---|
| Monitoring vs observability | The session totals are monitoring ("57% hit rate"). The traces are observability: you can open any single question and see why it went the way it did. |
| MELT | Section 2's table: [metric], record_event, wrap_openai, @traceable |
| Traces and spans | The "Marie Curie" tree above: each line is a span |
| Instrumenting code | Step 0 (wrap_openai) and the @traceable decorators in steps 2 and 4 |
| LangSmith | The project observability_demo, seven personality_query runs |
Exercises for learners
1. Change the threshold to 0.90. Which questions change from SEMANTIC to FRESH, and how do the session metrics change?
Questions 3 and 6 (scores ≈ 0.84 and ≈ 0.78) become FRESH: 5 LLM calls instead of 3, hit rate drops from 57% to 29%, and cost goes up. Safer, but more expensive.
2. Remove the double embedding for new questions.
Have check_semantic_cache return the vector it computed (add a vector field to the State), and let call_llm save that vector instead of calling get_embedding again.
3. Add a new event, "slow_answer", when the LLM takes more than 2 seconds.
In call_llm, after measuring seconds: if seconds > 2: agent.record_event("slow_answer", {"question": question, "seconds": round(seconds, 2)}). Then filter for it in LangSmith.
4. Put a wrong API key in .env and run it. What does the trace show?
The ChatOpenAI step (and its parents) turns red with the authentication error, and nothing is cached. Compare with the original code, which would have cached the error text as the "answer".
5. Ask "Marie Curie's daughter". Does the semantic cache wrongly reuse the Marie Curie answer?
Look at the [log] line's score. If it's above the threshold, that's a false match: a good discussion of why semantic caches need careful tuning.
Glossary
- Cache
- A store of earlier answers, reused instead of recomputing.
- Exact cache
- Reuse only when the (cleaned) text is identical.
- Semantic cache
- Reuse when the meaning is close enough, measured with embeddings.
- Embedding
- A list of numbers representing the meaning of a text.
- Cosine similarity
- A 0-to-1 score for how alike two embeddings are.
- Threshold
- The minimum score needed to count as "the same question".
- Token
- A small chunk of text (about ¾ of a word); models charge per token.
- State
- The dictionary that travels through a LangGraph graph.
- Node / router
- A step in the graph / a function that picks the next step.
- Trace / span
- The full record of one request / one step inside it.
- @traceable
- LangSmith decorator that turns a function into a span.
- wrap_openai
- LangSmith helper that logs every OpenAI chat call.
- run_type
- The label LangSmith shows for a span: llm, chain, tool, embedding.
- reasoning_effort
- How much the model "thinks" before answering; "none" is fastest.
Full source
obs_demo_langsmith.py (complete file)
""" Observability demo with LangSmith - by Shivank Agarwal ========================================================= WHAT IT DOES A tiny "personality bot": you give it a famous person's name and it answers in 2 lines. Two caches make repeated questions free, and LangSmith records every step, so for each question you can open a TRACE and see exactly what happened, how long it took and what it cost. question | v [check_exact_cache] ----- hit ----> END (same question asked before: free, instant) | miss v [check_semantic_cache] -- hit ----> END (a question with the same MEANING: almost free) | miss v [call_llm] -----------------------> END (ask OpenAI, then save the answer in both caches) THE 4 MELT PILLARS, AND WHERE THEY ARE IN THIS FILE Metrics -> tokens, cost and time for every question, plus session totals at the end Events -> record_event("cache_hit_exact", ...) etc. appear as steps in the trace Logs -> wrap_openai() stores every prompt and every answer inside the trace Traces -> @traceable + LangGraph: one tree per question in LangSmith HOW TO RUN 1. pip install -r requirements.txt 2. Create a free LangSmith account at https://smith.langchain.com -> Settings -> API Keys 3. Copy .env.example to .env and fill in your two keys 4. python obs_demo_langsmith.py 5. Open https://smith.langchain.com -> Tracing Projects -> observability_demo """ import time from typing import TypedDict import numpy as np from dotenv import load_dotenv from langgraph.graph import StateGraph, END from langsmith import traceable from langsmith.wrappers import wrap_openai from openai import OpenAI load_dotenv() # reads OPENAI_API_KEY and the LANGSMITH_* settings from .env CHAT_MODEL = "gpt-6-luna" # OpenAI's small, fast, cheap model EMBEDDING_MODEL = "text-embedding-3-small" # turns text into a list of numbers (a vector) # Prices in US$ per 1 million tokens (check OpenAI's pricing page, they change) PRICE_INPUT, PRICE_OUTPUT, PRICE_EMBEDDING = 0.10, 0.50, 0.02 SIMILARITY_THRESHOLD = 0.70 # how close (0 to 1) a new question must be to reuse an old answer # wrap_openai: one line, and every OpenAI call (prompt, answer, model, tokens, time) # is logged to LangSmith automatically. client = wrap_openai(OpenAI()) # --------------------------------------------------------------------------- # The State: what the graph knows about ONE question # --------------------------------------------------------------------------- class AgentState(TypedDict, total=False): query: str # the question, e.g. "Elon Musk" response: str # the answer cache_hit_type: str # "exact", "semantic", "fresh" (or "miss" while still looking) similarity: float # best similarity score found in the semantic cache cost: float # US$ spent on the LLM for this question tokens: int # LLM tokens used for this question def clean(text: str) -> str: """' Marie Curie ' and 'marie curie' should count as the same question.""" return " ".join(text.lower().split()) # --------------------------------------------------------------------------- # The Agent: caches + the OpenAI calls, each one traced # --------------------------------------------------------------------------- class PersonalityAgent: def __init__(self): self.cache = {} # cleaned question -> answer self.embeddings = {} # cleaned question -> its embedding vector @traceable(name="get_embedding", run_type="embedding") def get_embedding(self, text: str) -> np.ndarray: response = client.embeddings.create(model=EMBEDDING_MODEL, input=text) tokens = response.usage.total_tokens print(f" [metric] embedding: {tokens} tokens, ${tokens / 1e6 * PRICE_EMBEDDING:.7f}") return np.array(response.data[0].embedding) @traceable(name="find_semantic_match", run_type="tool") def find_semantic_match(self, query: str): """Return (closest saved question, similarity score).""" if not self.embeddings: return None, 0.0 query_vector = self.get_embedding(clean(query)) best_key, best_score = None, -1.0 # start below any real score for key, vector in self.embeddings.items(): score = float(np.dot(query_vector, vector)) # OpenAI vectors have length 1, so dot = cosine similarity if score > best_score: best_key, best_score = key, score print(f" [log] closest saved question: '{best_key}' (similarity {best_score:.2f})") return best_key, best_score @traceable(name="call_openai_model", run_type="chain") def call_openai_model(self, question: str): response = client.chat.completions.create( model=CHAT_MODEL, reasoning_effort="none", # answer straight away, no hidden "thinking" tokens messages=[ {"role": "system", "content": "Give exactly 2 short lines about this person's personality and achievements."}, {"role": "user", "content": f"Tell me about {question}"}, ], ) usage = response.usage cost = usage.prompt_tokens / 1e6 * PRICE_INPUT + usage.completion_tokens / 1e6 * PRICE_OUTPUT return response.choices[0].message.content.strip(), usage.total_tokens, cost @traceable(name="record_event", run_type="tool") def record_event(self, event_name: str, details: dict): """An EVENT: a meaningful moment we want to find and count later.""" print(f" [event] {event_name} {details}") # --------------------------------------------------------------------------- # The graph: 3 nodes + 2 routers (LangGraph traces every node automatically) # --------------------------------------------------------------------------- def build_graph(agent: PersonalityAgent): def check_exact_cache(state: AgentState) -> dict: key = clean(state["query"]) if key in agent.cache: agent.record_event("cache_hit_exact", {"question": key}) return {"response": agent.cache[key], "cache_hit_type": "exact", "cost": 0.0, "tokens": 0} return {"cache_hit_type": "miss"} def check_semantic_cache(state: AgentState) -> dict: best_key, score = agent.find_semantic_match(state["query"]) if best_key and score >= SIMILARITY_THRESHOLD: agent.record_event("cache_hit_semantic", {"question": state["query"], "matched": best_key, "similarity": round(score, 2)}) # Only a tiny embedding cost was spent (printed above), no LLM cost return {"response": agent.cache[best_key], "cache_hit_type": "semantic", "similarity": score, "cost": 0.0, "tokens": 0} return {"cache_hit_type": "miss", "similarity": score} def call_llm(state: AgentState) -> dict: question = state["query"] agent.record_event("llm_call_started", {"question": question}) start = time.perf_counter() answer, tokens, cost = agent.call_openai_model(question) seconds = time.perf_counter() - start key = clean(question) # save for next time, in BOTH caches agent.cache[key] = answer agent.embeddings[key] = agent.get_embedding(key) agent.record_event("answer_cached", {"question": key, "llm_seconds": round(seconds, 2)}) return {"response": answer, "cache_hit_type": "fresh", "cost": cost, "tokens": tokens} def after_exact(state: AgentState) -> str: return END if state["cache_hit_type"] == "exact" else "check_semantic_cache" def after_semantic(state: AgentState) -> str: return END if state["cache_hit_type"] == "semantic" else "call_llm" graph = StateGraph(AgentState) graph.add_node("check_exact_cache", check_exact_cache) graph.add_node("check_semantic_cache", check_semantic_cache) graph.add_node("call_llm", call_llm) graph.set_entry_point("check_exact_cache") graph.add_conditional_edges("check_exact_cache", after_exact) graph.add_conditional_edges("check_semantic_cache", after_semantic) graph.add_edge("call_llm", END) return graph.compile() # --------------------------------------------------------------------------- # One question = one trace in LangSmith # --------------------------------------------------------------------------- @traceable(name="personality_query", run_type="chain", metadata={"app": "personality_bot", "version": "2.0"}) def run_query(graph, query: str) -> dict: start = time.perf_counter() result = graph.invoke({"query": query}) seconds = time.perf_counter() - start print(f" [metric] {result['cache_hit_type'].upper()} | {seconds:.2f}s | " f"{result.get('tokens', 0)} tokens | ${result.get('cost', 0.0):.6f}") print(f" -> {result['response']}") return result if __name__ == "__main__": agent = PersonalityAgent() graph = build_graph(agent) questions = [ "Elon Musk", # fresh: asked for the first time "Elon Musk", # exact hit: same text "Who is Elon Musk?", # semantic hit (if similarity >= threshold): same meaning "Marie Curie", # fresh " marie curie ", # exact hit after cleaning (lower case, extra spaces) "Tell me about Marie Curie", # semantic hit (if similarity >= threshold) "Albert Einstein", # fresh ] counts = {"exact": 0, "semantic": 0, "fresh": 0} total_cost, total_tokens = 0.0, 0 for i, question in enumerate(questions, 1): print(f"\n[{i}/{len(questions)}] {question!r}") result = run_query(graph, question) counts[result["cache_hit_type"]] += 1 total_cost += result.get("cost", 0.0) total_tokens += result.get("tokens", 0) print("\n=== SESSION METRICS ===") print(f"Questions : {len(questions)}") print(f"Exact cache hits : {counts['exact']}") print(f"Semantic hits : {counts['semantic']}") print(f"LLM calls : {counts['fresh']}") print(f"Cache hit rate : {100 * (counts['exact'] + counts['semantic']) / len(questions):.0f}%") print(f"LLM tokens : {total_tokens}") print(f"LLM cost : ${total_cost:.6f}")
requirements.txt
openai>=2.0 langsmith>=0.4 langgraph>=1.0 numpy python-dotenv
.env.example
# Copy this file to .env and fill in your keys. OPENAI_API_KEY=sk-your-openai-key # LangSmith (free account at https://smith.langchain.com -> Settings -> API Keys) LANGSMITH_TRACING=true LANGSMITH_API_KEY=lsv2_your-langsmith-key LANGSMITH_PROJECT=observability_demo