LangSmith in Practice: Tracing, Evals and Prompts for LLM Apps
By · · 8 min read · AI Development
#python #typescript #langsmith #langchain #langgraph #openai #ai-observability
What LangSmith actually gives you once an LLM app leaves the notebook: traces you can read, evals you can rerun, and prompts with a history.
On this page
Getting an LLM app to work once is easy. Getting it to work the same way next Tuesday, after someone “slightly improved” the prompt, is the hard part.
With normal code, a bug usually leaves a stack trace. With an LLM app you get a wrong answer and a shrug. Was it the retrieval step? The prompt? The model having a bad day? Without some tooling you end up adding print statements and reading raw JSON, which gets old fast.
LangSmith is the tool I’d reach for here. This post covers the three things it does, with enough code to get each one running.
What LangSmith is
LangSmith is a hosted platform from the LangChain team. It does three jobs:
- Tracing. Records every step of a request so you can see what went in and what came out.
- Evaluation. Runs your app against a dataset and scores the results.
- Prompt management. Keeps prompts versioned and editable outside your codebase.
One thing people often miss: you don’t need LangChain to use it. It works with plain OpenAI calls, your own framework, anything. If you do use langchain or langgraph, you get tracing almost for free, but it isn’t a requirement.
Why bother
A small prompt change can fix one case and quietly break five others. You won’t notice, because you only tested the one case you were looking at. That’s the whole problem in one sentence.
So you need two things. First, a way to look inside a single request when it goes wrong. Second, a way to check many requests at once whenever you change something. Tracing gives you the first, evals give you the second. Prompt versioning is what makes the two usable together, because you can tell which prompt produced which result.
Tracing
Start here. It takes about five minutes and pays off the same day.
Install the SDK:
pip install -U langsmith openaiSet the environment variables:
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY="<your-langsmith-api-key>"
export OPENAI_API_KEY="<your-openai-api-key>"Now take a small RAG function and add @traceable to the parts you care about:
from openai import OpenAI
from langsmith import traceable
from langsmith.wrappers import wrap_openai
# wrap_openai makes the model call itself show up in the trace,
# with token counts and latency
openai_client = wrap_openai(OpenAI())
@traceable(run_type="retriever")
def retriever(query: str) -> list[str]:
# Fake retriever. Swap in your vector store here.
return ["Harrison worked at Kensho", "He was a software engineer"]
@traceable
def rag(question: str) -> str:
docs = retriever(question)
context = "\n".join(docs)
system_message = (
"Answer the user's question using only the information below:\n"
f"{context}"
)
response = openai_client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": system_message},
{"role": "user", "content": question},
],
)
return response.choices[0].message.content
print(rag("Where did Harrison work?"))Run it, open the LangSmith UI, and you’ll see one trace with three nested steps: rag, then retriever, then the OpenAI call. Each step shows its inputs, outputs, how long it took, and any error it raised.
That nesting is the useful bit. When an answer is wrong, you click into the retriever step and check what it returned. If the documents are wrong, it’s a retrieval problem. If the documents are right and the answer is still wrong, it’s a prompt or model problem. That question used to take twenty minutes to answer. Now it takes one click.
Adding tags and metadata
Once real users are involved, you’ll want to filter traces. Tags and metadata handle that:
@traceable(tags=["rag", "production"])
def rag(question: str) -> str:
...
# Per-request metadata, passed at call time
rag(
"Where did Harrison work?",
langsmith_extra={"metadata": {"user_id": "u_123", "plan": "free"}},
)Now “show me failed requests from free-plan users this week” is a filter in the UI, not a log-parsing script. You can also build dashboards and alerts on top of the same data, for things like latency, error rate and cost.
Evaluation
Tracing tells you what happened in one request. Evaluation tells you whether your app is getting better or worse overall.
An eval has three parts:
- A dataset. Inputs, and usually the outputs you expect.
- A target. The function you’re testing. It can be one LLM call or the whole app.
- Evaluators. Functions that look at the output and return a score.
Create a dataset
from langsmith import Client
client = Client()
dataset = client.create_dataset(
dataset_name="rag_qa_dataset",
description="Questions and answers for RAG evaluation",
)
client.create_examples(
dataset_id=dataset.id,
inputs=[
{"question": "Where did Harrison work?"},
{"question": "What was Harrison's role?"},
],
outputs=[
{"answer": "Harrison worked at Kensho"},
{"answer": "Harrison was a software engineer"},
],
)Two examples is obviously too few. In practice, start with ten or twenty real questions, and every time you find a bad answer in production, add it. LangSmith lets you send a trace straight into a dataset from the UI, which makes this habit easy to keep.
Write an evaluator and run it
def target(inputs: dict) -> dict:
return {"answer": rag(inputs["question"])}
def contains_answer(outputs: dict, reference_outputs: dict) -> bool:
"""Crude check: does the response contain the expected answer?"""
return reference_outputs["answer"].lower() in outputs["answer"].lower()
results = client.evaluate(
target,
data="rag_qa_dataset",
evaluators=[contains_answer],
experiment_prefix="rag-baseline",
)Each run becomes an “experiment” in the UI. Change your prompt, run it again, and you can put the two experiments side by side and see exactly which examples got better and which got worse.
LLM-as-judge evaluators
String matching breaks down quickly. “Harrison was employed by Kensho” is correct but fails the check above. For cases like this you can have another model do the grading. The openevals package has ready-made judges:
from openevals.llm import create_llm_as_judge
from openevals.prompts import CORRECTNESS_PROMPT
judge = create_llm_as_judge(
prompt=CORRECTNESS_PROMPT,
model="openai:gpt-4o-mini",
feedback_key="correctness",
)
def correctness(inputs: dict, outputs: dict, reference_outputs: dict):
return judge(
inputs=inputs,
outputs=outputs,
reference_outputs=reference_outputs,
)
client.evaluate(
target,
data="rag_qa_dataset",
evaluators=[correctness],
experiment_prefix="rag-llm-judge",
)A word of caution: an LLM judge is also an LLM. It will be wrong sometimes. Read a sample of its verdicts before you trust the score, and keep the cheap deterministic checks where they work.
Prompt management
The third piece is less exciting but saves real pain. Prompts usually start as strings in the code. Then someone who isn’t a developer wants to tweak the wording, and now every comma change needs a pull request and a deploy.
LangSmith lets you keep prompts on the platform instead:
- Edit and test them in a playground, against real examples from your datasets
- Every save creates a new version, so you can see what changed and roll back
- Pull a prompt into your code by name, optionally pinned to a specific version
The flow that works well: edit the prompt in the playground, run it against your dataset, compare with the previous experiment, and only then move the production tag to the new version. It’s the same idea as a staging environment, applied to prompts.
With LangChain and LangGraph
If you’re already on LangChain, there’s nothing to decorate. Set the environment variables and every chain is traced:
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
llm = ChatOpenAI(model="gpt-4o-mini")
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
("user", "{input}"),
])
chain = prompt | llm | StrOutputParser()
# Traced automatically because LANGSMITH_TRACING=true
chain.invoke({"input": "What is LangSmith?"})Same story for LangGraph. Each node shows up as its own step, which is where tracing really earns its keep, since graphs with loops and branches are hard to follow from logs alone:
from langgraph.graph import StateGraph, MessagesState, START, END
def chatbot(state: MessagesState):
return {"messages": [llm.invoke(state["messages"])]}
builder = StateGraph(MessagesState)
builder.add_node("chatbot", chatbot)
builder.add_edge(START, "chatbot")
builder.add_edge("chatbot", END)
app = builder.compile()
app.invoke({"messages": [("user", "Hello!")]})A few things worth knowing before production
Decide what you send. Traces contain your users’ inputs. If that includes personal data, look at the SDK’s options for masking inputs and outputs before you turn tracing on everywhere.
Sample if volume is high. You don’t need every trace from a high-traffic endpoint. A sampling rate keeps cost down and still shows you the patterns.
Don’t swallow errors. If you catch an exception and return a polite fallback message, the trace looks like a success. Let the error surface in the traced function, and handle the fallback one level up.
Name your experiments. rag-baseline and rag-shorter-prompt are useful six weeks later. test2-final is not.
Where to start
If you only do one thing after reading this, turn on tracing. It’s two environment variables and one decorator, and it changes how you debug straight away.
Then, the next time you find a bad answer, save it to a dataset instead of just fixing it. After a couple of weeks you’ll have a small test set built from real failures, and running evals before each prompt change will feel natural, not like extra process.
The official docs are good and go deeper on all three areas.