davidberenstein1957 HF staff MJannik commited on
Commit
866abdc
·
verified ·
1 Parent(s): c187244

add notebook for bonus unit 2 - agent evaluation (#62)

Browse files

- add notebook for bonus unit 2 - agent evaluation (d29ce2619de5c91c4b5e580df7f5be7bc5961019)


Co-authored-by: Jannik <[email protected]>

bonus-unit2/monitoring-and-evaluating-agents.ipynb ADDED
@@ -0,0 +1,647 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Bonus Unit 1: Observability and Evaluation of Agents\n",
8
+ "\n",
9
+ "In this tutorial, we will learn how to **monitor the internal steps (traces) of our AI agent** and **evaluate its performance** using open-source observability tools.\n",
10
+ "\n",
11
+ "The ability to observe and evaluate an agent’s behavior is essential for:\n",
12
+ "- Debugging issues when tasks fail or produce suboptimal results\n",
13
+ "- Monitoring costs and performance in real-time\n",
14
+ "- Improving reliability and safety through continuous feedback\n",
15
+ "\n",
16
+ "This notebook is part of the [Hugging Face Agents Course](https://www.hf.co/learn/agents-course/unit1/introduction)."
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "markdown",
21
+ "metadata": {},
22
+ "source": [
23
+ "## Exercise Prerequisites 🏗️\n",
24
+ "\n",
25
+ "Before running this notebook, please be sure you have:\n",
26
+ "\n",
27
+ "🔲 📚 **Studied** [Introduction to Agents](https://huggingface.co/learn/agents-course/unit1/introduction)\n",
28
+ "\n",
29
+ "🔲 📚 **Studied** [The smolagents framework](https://huggingface.co/learn/agents-course/unit2/smolagents/introduction)"
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "markdown",
34
+ "metadata": {},
35
+ "source": [
36
+ "## Step 0: Install the Required Libraries\n",
37
+ "\n",
38
+ "We will need a few libraries that allow us to run, monitor, and evaluate our agents:"
39
+ ]
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "execution_count": null,
44
+ "metadata": {},
45
+ "outputs": [],
46
+ "source": [
47
+ "%pip install 'smolagents[telemetry]'\n",
48
+ "%pip install opentelemetry-sdk opentelemetry-exporter-otlp openinference-instrumentation-smolagents\n",
49
+ "%pip install langfuse datasets 'smolagents[gradio]' gradio"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "markdown",
54
+ "metadata": {},
55
+ "source": [
56
+ "## Step 1: Instrument Your Agent\n",
57
+ "\n",
58
+ "In this notebook, we will use [Langfuse](https://langfuse.com/) as our observability tool, but you can use **any other OpenTelemetry-compatible service**. The code below shows how to set environment variables for Langfuse (or any OTel endpoint) and how to instrument your smolagent.\n",
59
+ "\n",
60
+ "**Note:** If you are using LlamaIndex or LangGraph, you can find documentation on instrumenting them [here](https://langfuse.com/docs/integrations/llama-index/workflows) and [here](https://langfuse.com/docs/integrations/langchain/example-python-langgraph). "
61
+ ]
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "execution_count": null,
66
+ "metadata": {},
67
+ "outputs": [],
68
+ "source": [
69
+ "import os\n",
70
+ "import base64\n",
71
+ "\n",
72
+ "# Get your own keys from https://cloud.langfuse.com\n",
73
+ "os.environ[\"LANGFUSE_PUBLIC_KEY\"] = \"pk-lf-...\" \n",
74
+ "os.environ[\"LANGFUSE_SECRET_KEY\"] = \"sk-lf-...\" \n",
75
+ "os.environ[\"LANGFUSE_HOST\"] = \"https://cloud.langfuse.com\" # 🇪🇺 EU region example\n",
76
+ "# os.environ[\"LANGFUSE_HOST\"] = \"https://us.cloud.langfuse.com\" # 🇺🇸 US region example\n",
77
+ "\n",
78
+ "LANGFUSE_AUTH = base64.b64encode(\n",
79
+ " f\"{os.environ.get('LANGFUSE_PUBLIC_KEY')}:{os.environ.get('LANGFUSE_SECRET_KEY')}\".encode()\n",
80
+ ").decode()\n",
81
+ "\n",
82
+ "os.environ[\"OTEL_EXPORTER_OTLP_ENDPOINT\"] = os.environ.get(\"LANGFUSE_HOST\") + \"/api/public/otel\"\n",
83
+ "os.environ[\"OTEL_EXPORTER_OTLP_HEADERS\"] = f\"Authorization=Basic {LANGFUSE_AUTH}\""
84
+ ]
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "execution_count": null,
89
+ "metadata": {},
90
+ "outputs": [],
91
+ "source": [
92
+ "# Set your Hugging Face and other tokens/secrets as environment variable\n",
93
+ "os.environ[\"HF_TOKEN\"] = \"hf_...\" "
94
+ ]
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "execution_count": null,
99
+ "metadata": {},
100
+ "outputs": [],
101
+ "source": [
102
+ "from opentelemetry.sdk.trace import TracerProvider\n",
103
+ "from openinference.instrumentation.smolagents import SmolagentsInstrumentor\n",
104
+ "from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter\n",
105
+ "from opentelemetry.sdk.trace.export import SimpleSpanProcessor\n",
106
+ " \n",
107
+ "# Create a TracerProvider for OpenTelemetry\n",
108
+ "trace_provider = TracerProvider()\n",
109
+ "\n",
110
+ "# Add a SimpleSpanProcessor with the OTLPSpanExporter to send traces\n",
111
+ "trace_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter()))\n",
112
+ "\n",
113
+ "# Set the global default tracer provider\n",
114
+ "from opentelemetry import trace\n",
115
+ "trace.set_tracer_provider(trace_provider)\n",
116
+ "tracer = trace.get_tracer(__name__)\n",
117
+ "\n",
118
+ "# Instrument smolagents with the configured provider\n",
119
+ "SmolagentsInstrumentor().instrument(tracer_provider=trace_provider)\n"
120
+ ]
121
+ },
122
+ {
123
+ "cell_type": "markdown",
124
+ "metadata": {},
125
+ "source": [
126
+ "## Step 2: Test Your Instrumentation\n",
127
+ "\n",
128
+ "Here is a simple CodeAgent from smolagents that calculates `1+1`. We run it to confirm that the instrumentation is working correctly. If everything is set up correctly, you will see logs/spans in your observability dashboard."
129
+ ]
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "execution_count": null,
134
+ "metadata": {},
135
+ "outputs": [],
136
+ "source": [
137
+ "from smolagents import HfApiModel, CodeAgent\n",
138
+ "\n",
139
+ "# Create a simple agent to test instrumentation\n",
140
+ "agent = CodeAgent(\n",
141
+ " tools=[],\n",
142
+ " model=HfApiModel()\n",
143
+ ")\n",
144
+ "\n",
145
+ "agent.run(\"1+1=\")"
146
+ ]
147
+ },
148
+ {
149
+ "cell_type": "markdown",
150
+ "metadata": {},
151
+ "source": [
152
+ "Check your [Langfuse Traces Dashboard](https://cloud.langfuse.com/traces) (or your chosen observability tool) to confirm that the spans and logs have been recorded.\n",
153
+ "\n",
154
+ "Example screenshot from Langfuse:\n",
155
+ "\n",
156
+ "![Example trace in Langfuse](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/first-example-trace.png)\n",
157
+ "\n",
158
+ "_[Link to the trace](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1b94d6888258e0998329cdb72a371155?timestamp=2025-03-10T11%3A59%3A41.743Z)_"
159
+ ]
160
+ },
161
+ {
162
+ "cell_type": "markdown",
163
+ "metadata": {},
164
+ "source": [
165
+ "## Step 3: Observe and Evaluate a More Complex Agent\n",
166
+ "\n",
167
+ "Now that you have confirmed your instrumentation works, let's try a more complex query so we can see how advanced metrics (token usage, latency, costs, etc.) are tracked."
168
+ ]
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "execution_count": null,
173
+ "metadata": {},
174
+ "outputs": [],
175
+ "source": [
176
+ "from smolagents import (CodeAgent, DuckDuckGoSearchTool, HfApiModel)\n",
177
+ "\n",
178
+ "search_tool = DuckDuckGoSearchTool()\n",
179
+ "agent = CodeAgent(tools=[search_tool], model=HfApiModel())\n",
180
+ "\n",
181
+ "agent.run(\"How many Rubik's Cubes could you fit inside the Notre Dame Cathedral?\")"
182
+ ]
183
+ },
184
+ {
185
+ "cell_type": "markdown",
186
+ "metadata": {},
187
+ "source": [
188
+ "### Trace Structure\n",
189
+ "\n",
190
+ "Most observability tools record a **trace** that contains **spans**, which represent each step of your agent’s logic. Here, the trace contains the overall agent run and sub-spans for:\n",
191
+ "- The tool calls (DuckDuckGoSearchTool)\n",
192
+ "- The LLM calls (HfApiModel)\n",
193
+ "\n",
194
+ "You can inspect these to see precisely where time is spent, how many tokens are used, and so on:\n",
195
+ "\n",
196
+ "![Trace tree in Langfuse](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/trace-tree.png)\n",
197
+ "\n",
198
+ "_[Link to the trace](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1ac33b89ffd5e75d4265b62900c348ed?timestamp=2025-03-07T13%3A45%3A09.149Z&display=preview)_"
199
+ ]
200
+ },
201
+ {
202
+ "cell_type": "markdown",
203
+ "metadata": {},
204
+ "source": [
205
+ "## Online Evaluation\n",
206
+ "\n",
207
+ "In the previous section, we learned about the difference between online and offline evaluation. Now, we will see how to monitor your agent in production and evaluate it live.\n",
208
+ "\n",
209
+ "### Common Metrics to Track in Production\n",
210
+ "\n",
211
+ "1. **Costs** — The smolagents instrumentation captures token usage, which you can transform into approximate costs by assigning a price per token.\n",
212
+ "2. **Latency** — Observe the time it takes to complete each step, or the entire run.\n",
213
+ "3. **User Feedback** — Users can provide direct feedback (thumbs up/down) to help refine or correct the agent.\n",
214
+ "4. **LLM-as-a-Judge** — Use a separate LLM to evaluate your agent’s output in near real-time (e.g., checking for toxicity or correctness).\n",
215
+ "\n",
216
+ "Below, we show examples of these metrics."
217
+ ]
218
+ },
219
+ {
220
+ "cell_type": "markdown",
221
+ "metadata": {},
222
+ "source": [
223
+ "#### 1. Costs\n",
224
+ "\n",
225
+ "Below is a screenshot showing usage for `Qwen2.5-Coder-32B-Instruct` calls. This is useful to see costly steps and optimize your agent. \n",
226
+ "\n",
227
+ "![Costs](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/smolagents-costs.png)\n",
228
+ "\n",
229
+ "_[Link to the trace](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1ac33b89ffd5e75d4265b62900c348ed?timestamp=2025-03-07T13%3A45%3A09.149Z&display=preview)_"
230
+ ]
231
+ },
232
+ {
233
+ "cell_type": "markdown",
234
+ "metadata": {},
235
+ "source": [
236
+ "#### 2. Latency\n",
237
+ "\n",
238
+ "We can also see how long it took to complete each step. In the example below, the entire conversation took 32 seconds, which you can break down by step. This helps you identify bottlenecks and optimize your agent.\n",
239
+ "\n",
240
+ "![Latency](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/smolagents-latency.png)\n",
241
+ "\n",
242
+ "_[Link to the trace](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1ac33b89ffd5e75d4265b62900c348ed?timestamp=2025-03-07T13%3A45%3A09.149Z&display=preview)_"
243
+ ]
244
+ },
245
+ {
246
+ "cell_type": "markdown",
247
+ "metadata": {},
248
+ "source": [
249
+ "#### 3. Additional Attributes\n",
250
+ "\n",
251
+ "You may also pass additional attributes—such as user IDs, session IDs, or tags—by setting them on the spans. For example, smolagents instrumentation uses OpenTelemetry to attach attributes like `langfuse.user.id` or custom tags."
252
+ ]
253
+ },
254
+ {
255
+ "cell_type": "code",
256
+ "execution_count": null,
257
+ "metadata": {},
258
+ "outputs": [],
259
+ "source": [
260
+ "from smolagents import (CodeAgent, DuckDuckGoSearchTool, HfApiModel)\n",
261
+ "from opentelemetry import trace\n",
262
+ "\n",
263
+ "search_tool = DuckDuckGoSearchTool()\n",
264
+ "agent = CodeAgent(\n",
265
+ " tools=[search_tool],\n",
266
+ " model=HfApiModel()\n",
267
+ ")\n",
268
+ "\n",
269
+ "with tracer.start_as_current_span(\"Smolagent-Trace\") as span:\n",
270
+ " span.set_attribute(\"langfuse.user.id\", \"smolagent-user-123\")\n",
271
+ " span.set_attribute(\"langfuse.session.id\", \"smolagent-session-123456789\")\n",
272
+ " span.set_attribute(\"langfuse.tags\", [\"city-question\", \"testing-agents\"])\n",
273
+ "\n",
274
+ " agent.run(\"What is the capital of Germany?\")"
275
+ ]
276
+ },
277
+ {
278
+ "cell_type": "markdown",
279
+ "metadata": {},
280
+ "source": [
281
+ "![Enhancing agent runs with additional metrics](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/smolagents-attributes.png)"
282
+ ]
283
+ },
284
+ {
285
+ "cell_type": "markdown",
286
+ "metadata": {},
287
+ "source": [
288
+ "#### 4. User Feedback\n",
289
+ "\n",
290
+ "If your agent is embedded into a user interface, you can record direct user feedback (like a thumbs-up/down in a chat UI). Below is an example using [Gradio](https://gradio.app/) to embed a chat with a simple feedback mechanism.\n",
291
+ "\n",
292
+ "In the code snippet below, when a user sends a chat message, we capture the OpenTelemetry trace ID. If the user likes/dislikes the last answer, we attach a score to the trace."
293
+ ]
294
+ },
295
+ {
296
+ "cell_type": "code",
297
+ "execution_count": null,
298
+ "metadata": {},
299
+ "outputs": [],
300
+ "source": [
301
+ "import gradio as gr\n",
302
+ "from opentelemetry.trace import format_trace_id\n",
303
+ "from smolagents import (CodeAgent, HfApiModel)\n",
304
+ "from langfuse import Langfuse\n",
305
+ "\n",
306
+ "langfuse = Langfuse()\n",
307
+ "model = HfApiModel()\n",
308
+ "agent = CodeAgent(tools=[], model=model, add_base_tools=True)\n",
309
+ "\n",
310
+ "formatted_trace_id = None # We'll store the current trace_id globally for demonstration\n",
311
+ "\n",
312
+ "def respond(prompt, history):\n",
313
+ " with trace.get_tracer(__name__).start_as_current_span(\"Smolagent-Trace\") as span:\n",
314
+ " output = agent.run(prompt)\n",
315
+ "\n",
316
+ " current_span = trace.get_current_span()\n",
317
+ " span_context = current_span.get_span_context()\n",
318
+ " trace_id = span_context.trace_id\n",
319
+ " global formatted_trace_id\n",
320
+ " formatted_trace_id = str(format_trace_id(trace_id))\n",
321
+ " langfuse.trace(id=formatted_trace_id, input=prompt, output=output)\n",
322
+ "\n",
323
+ " history.append({\"role\": \"assistant\", \"content\": str(output)})\n",
324
+ " return history\n",
325
+ "\n",
326
+ "def handle_like(data: gr.LikeData):\n",
327
+ " # For demonstration, we map user feedback to a 1 (like) or 0 (dislike)\n",
328
+ " if data.liked:\n",
329
+ " langfuse.score(\n",
330
+ " value=1,\n",
331
+ " name=\"user-feedback\",\n",
332
+ " trace_id=formatted_trace_id\n",
333
+ " )\n",
334
+ " else:\n",
335
+ " langfuse.score(\n",
336
+ " value=0,\n",
337
+ " name=\"user-feedback\",\n",
338
+ " trace_id=formatted_trace_id\n",
339
+ " )\n",
340
+ "\n",
341
+ "with gr.Blocks() as demo:\n",
342
+ " chatbot = gr.Chatbot(label=\"Chat\", type=\"messages\")\n",
343
+ " prompt_box = gr.Textbox(placeholder=\"Type your message...\", label=\"Your message\")\n",
344
+ "\n",
345
+ " # When the user presses 'Enter' on the prompt, we run 'respond'\n",
346
+ " prompt_box.submit(\n",
347
+ " fn=respond,\n",
348
+ " inputs=[prompt_box, chatbot],\n",
349
+ " outputs=chatbot\n",
350
+ " )\n",
351
+ "\n",
352
+ " # When the user clicks a 'like' button on a message, we run 'handle_like'\n",
353
+ " chatbot.like(handle_like, None, None)\n",
354
+ "\n",
355
+ "demo.launch()\n"
356
+ ]
357
+ },
358
+ {
359
+ "cell_type": "markdown",
360
+ "metadata": {},
361
+ "source": [
362
+ "User feedback is then captured in your observability tool:\n",
363
+ "\n",
364
+ "![User feedback is being captured in Langfuse](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/user-feedback-gradio.png)"
365
+ ]
366
+ },
367
+ {
368
+ "cell_type": "markdown",
369
+ "metadata": {},
370
+ "source": [
371
+ "#### 5. LLM-as-a-Judge\n",
372
+ "\n",
373
+ "LLM-as-a-Judge is another way to automatically evaluate your agent's output. You can set up a separate LLM call to gauge the output’s correctness, toxicity, style, or any other criteria you care about.\n",
374
+ "\n",
375
+ "**Workflow**:\n",
376
+ "1. You define an **Evaluation Template**, e.g., \"Check if the text is toxic.\"\n",
377
+ "2. Each time your agent generates output, you pass that output to your \"judge\" LLM with the template.\n",
378
+ "3. The judge LLM responds with a rating or label that you log to your observability tool.\n",
379
+ "\n",
380
+ "Example from Langfuse:\n",
381
+ "\n",
382
+ "![LLM-as-a-Judge Evaluation Template](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/evaluator-template.png)\n",
383
+ "![LLM-as-a-Judge Evaluator](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/evaluator.png)"
384
+ ]
385
+ },
386
+ {
387
+ "cell_type": "code",
388
+ "execution_count": null,
389
+ "metadata": {},
390
+ "outputs": [],
391
+ "source": [
392
+ "# Example: Checking if the agent’s output is toxic or not.\n",
393
+ "from smolagents import (CodeAgent, DuckDuckGoSearchTool, HfApiModel)\n",
394
+ "\n",
395
+ "search_tool = DuckDuckGoSearchTool()\n",
396
+ "agent = CodeAgent(tools=[search_tool], model=HfApiModel())\n",
397
+ "\n",
398
+ "agent.run(\"Can eating carrots improve your vision?\")"
399
+ ]
400
+ },
401
+ {
402
+ "cell_type": "markdown",
403
+ "metadata": {},
404
+ "source": [
405
+ "You can see that the answer of this example is judged as \"not toxic\".\n",
406
+ "\n",
407
+ "![LLM-as-a-Judge Evaluation Score](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/llm-as-a-judge-score.png)"
408
+ ]
409
+ },
410
+ {
411
+ "cell_type": "markdown",
412
+ "metadata": {},
413
+ "source": [
414
+ "#### 6. Observability Metrics Overview\n",
415
+ "\n",
416
+ "All of these metrics can be visualized together in dashboards. This enables you to quickly see how your agent performs across many sessions and helps you to track quality metrics over time.\n",
417
+ "\n",
418
+ "![Observability metrics overview](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/langfuse-dashboard.png)"
419
+ ]
420
+ },
421
+ {
422
+ "cell_type": "markdown",
423
+ "metadata": {},
424
+ "source": [
425
+ "## Offline Evaluation\n",
426
+ "\n",
427
+ "Online evaluation is essential for live feedback, but you also need **offline evaluation**—systematic checks before or during development. This helps maintain quality and reliability before rolling changes into production."
428
+ ]
429
+ },
430
+ {
431
+ "cell_type": "markdown",
432
+ "metadata": {},
433
+ "source": [
434
+ "### Dataset Evaluation\n",
435
+ "\n",
436
+ "In offline evaluation, you typically:\n",
437
+ "1. Have a benchmark dataset (with prompt and expected output pairs)\n",
438
+ "2. Run your agent on that dataset\n",
439
+ "3. Compare outputs to the expected results or use an additional scoring mechanism\n",
440
+ "\n",
441
+ "Below, we demonstrate this approach with the [GSM8K dataset](https://huggingface.co/datasets/gsm8k), which contains math questions and solutions."
442
+ ]
443
+ },
444
+ {
445
+ "cell_type": "code",
446
+ "execution_count": null,
447
+ "metadata": {},
448
+ "outputs": [],
449
+ "source": [
450
+ "import pandas as pd\n",
451
+ "from datasets import load_dataset\n",
452
+ "\n",
453
+ "# Fetch GSM8K from Hugging Face\n",
454
+ "dataset = load_dataset(\"openai/gsm8k\", 'main', split='train')\n",
455
+ "df = pd.DataFrame(dataset)\n",
456
+ "print(\"First few rows of GSM8K dataset:\")\n",
457
+ "print(df.head())"
458
+ ]
459
+ },
460
+ {
461
+ "cell_type": "markdown",
462
+ "metadata": {},
463
+ "source": [
464
+ "Next, we create a dataset entity in Langfuse to track the runs. Then, we add each item from the dataset to the system. (If you’re not using Langfuse, you might simply store these in your own database or local file for analysis.)"
465
+ ]
466
+ },
467
+ {
468
+ "cell_type": "code",
469
+ "execution_count": null,
470
+ "metadata": {},
471
+ "outputs": [],
472
+ "source": [
473
+ "from langfuse import Langfuse\n",
474
+ "langfuse = Langfuse()\n",
475
+ "\n",
476
+ "langfuse_dataset_name = \"gsm8k_dataset_huggingface\"\n",
477
+ "\n",
478
+ "# Create a dataset in Langfuse\n",
479
+ "langfuse.create_dataset(\n",
480
+ " name=langfuse_dataset_name,\n",
481
+ " description=\"GSM8K benchmark dataset uploaded from Huggingface\",\n",
482
+ " metadata={\n",
483
+ " \"date\": \"2025-03-10\", \n",
484
+ " \"type\": \"benchmark\"\n",
485
+ " }\n",
486
+ ")"
487
+ ]
488
+ },
489
+ {
490
+ "cell_type": "code",
491
+ "execution_count": null,
492
+ "metadata": {},
493
+ "outputs": [],
494
+ "source": [
495
+ "for idx, row in df.iterrows():\n",
496
+ " langfuse.create_dataset_item(\n",
497
+ " dataset_name=langfuse_dataset_name,\n",
498
+ " input={\"text\": row[\"question\"]},\n",
499
+ " expected_output={\"text\": row[\"answer\"]},\n",
500
+ " metadata={\"source_index\": idx}\n",
501
+ " )\n",
502
+ " if idx >= 9: # Upload only the first 10 items for demonstration\n",
503
+ " break"
504
+ ]
505
+ },
506
+ {
507
+ "cell_type": "markdown",
508
+ "metadata": {},
509
+ "source": [
510
+ "![Dataset items in Langfuse](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/example-dataset.png)"
511
+ ]
512
+ },
513
+ {
514
+ "cell_type": "markdown",
515
+ "metadata": {},
516
+ "source": [
517
+ "#### Running the Agent on the Dataset\n",
518
+ "\n",
519
+ "We define a helper function `run_smolagent()` that:\n",
520
+ "1. Starts an OpenTelemetry span\n",
521
+ "2. Runs our agent on the prompt\n",
522
+ "3. Records the trace ID in Langfuse\n",
523
+ "\n",
524
+ "Then, we loop over each dataset item, run the agent, and link the trace to the dataset item. We can also attach a quick evaluation score if desired."
525
+ ]
526
+ },
527
+ {
528
+ "cell_type": "code",
529
+ "execution_count": null,
530
+ "metadata": {},
531
+ "outputs": [],
532
+ "source": [
533
+ "from opentelemetry.trace import format_trace_id\n",
534
+ "from smolagents import (CodeAgent, HfApiModel, LiteLLMModel)\n",
535
+ "\n",
536
+ "# Example: using HfApiModel or LiteLLMModel to access openai, anthropic, gemini, etc. models:\n",
537
+ "model = HfApiModel()\n",
538
+ "\n",
539
+ "agent = CodeAgent(\n",
540
+ " tools=[],\n",
541
+ " model=model,\n",
542
+ " add_base_tools=True\n",
543
+ ")\n",
544
+ "\n",
545
+ "def run_smolagent(question):\n",
546
+ " with tracer.start_as_current_span(\"Smolagent-Trace\") as span:\n",
547
+ " span.set_attribute(\"langfuse.tag\", \"dataset-run\")\n",
548
+ " output = agent.run(question)\n",
549
+ "\n",
550
+ " current_span = trace.get_current_span()\n",
551
+ " span_context = current_span.get_span_context()\n",
552
+ " trace_id = span_context.trace_id\n",
553
+ " formatted_trace_id = format_trace_id(trace_id)\n",
554
+ "\n",
555
+ " langfuse_trace = langfuse.trace(\n",
556
+ " id=formatted_trace_id, \n",
557
+ " input=question, \n",
558
+ " output=output\n",
559
+ " )\n",
560
+ " return langfuse_trace, output"
561
+ ]
562
+ },
563
+ {
564
+ "cell_type": "code",
565
+ "execution_count": null,
566
+ "metadata": {},
567
+ "outputs": [],
568
+ "source": [
569
+ "dataset = langfuse.get_dataset(langfuse_dataset_name)\n",
570
+ "\n",
571
+ "# Run our agent against each dataset item (limited to first 10 above)\n",
572
+ "for item in dataset.items:\n",
573
+ " langfuse_trace, output = run_smolagent(item.input[\"text\"])\n",
574
+ "\n",
575
+ " # Link the trace to the dataset item for analysis\n",
576
+ " item.link(\n",
577
+ " langfuse_trace,\n",
578
+ " run_name=\"smolagent-notebook-run-01\",\n",
579
+ " run_metadata={ \"model\": model.model_id }\n",
580
+ " )\n",
581
+ "\n",
582
+ " # Optionally, store a quick evaluation score for demonstration\n",
583
+ " langfuse_trace.score(\n",
584
+ " name=\"<example_eval>\",\n",
585
+ " value=1,\n",
586
+ " comment=\"This is a comment\"\n",
587
+ " )\n",
588
+ "\n",
589
+ "# Flush data to ensure all telemetry is sent\n",
590
+ "langfuse.flush()"
591
+ ]
592
+ },
593
+ {
594
+ "cell_type": "markdown",
595
+ "metadata": {},
596
+ "source": [
597
+ "You can repeat this process with different:\n",
598
+ "- Models (OpenAI GPT, local LLM, etc.)\n",
599
+ "- Tools (search vs. no search)\n",
600
+ "- Prompts (different system messages)\n",
601
+ "\n",
602
+ "Then compare them side-by-side in your observability tool:\n",
603
+ "\n",
604
+ "![Dataset run overview](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/dataset_runs.png)\n",
605
+ "![Dataset run comparison](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/dataset-run-comparison.png)\n"
606
+ ]
607
+ },
608
+ {
609
+ "cell_type": "markdown",
610
+ "metadata": {},
611
+ "source": [
612
+ "## Final Thoughts\n",
613
+ "\n",
614
+ "In this notebook, we covered how to:\n",
615
+ "1. **Set up Observability** using smolagents + OpenTelemetry exporters\n",
616
+ "2. **Check Instrumentation** by running a simple agent\n",
617
+ "3. **Capture Detailed Metrics** (cost, latency, etc.) through an observability tools\n",
618
+ "4. **Collect User Feedback** via a Gradio interface\n",
619
+ "5. **Use LLM-as-a-Judge** to automatically evaluate outputs\n",
620
+ "6. **Perform Offline Evaluation** with a benchmark dataset\n",
621
+ "\n",
622
+ "🤗 Happy coding!"
623
+ ]
624
+ }
625
+ ],
626
+ "metadata": {
627
+ "kernelspec": {
628
+ "display_name": "Python 3",
629
+ "language": "python",
630
+ "name": "python3"
631
+ },
632
+ "language_info": {
633
+ "codemirror_mode": {
634
+ "name": "ipython",
635
+ "version": 3
636
+ },
637
+ "file_extension": ".py",
638
+ "mimetype": "text/x-python",
639
+ "name": "python",
640
+ "nbconvert_exporter": "python",
641
+ "pygments_lexer": "ipython3",
642
+ "version": "3.13.2"
643
+ }
644
+ },
645
+ "nbformat": 4,
646
+ "nbformat_minor": 2
647
+ }