Build a Titanic Data Analyst Agent with smolagents

October 18, 2026 • guides
Hugging FaceMachine Learning

This guide is adapted from Hugging Face Cookbook's agent_data_analyst.ipynb, used under the Apache-2.0 licence.

A data analyst agent built with smolagents can inspect a raw CSV, generate its own analytical questions, produce summary statistics and plots, and then train a baseline machine-learning model — all from a single natural-language instruction. Instead of writing a bespoke Jupyter workflow, you hand the agent a dataframe and a goal; it writes and executes Python directly. This is useful for data scientists and ML engineers who want fast exploratory analysis, Kaggle competitors who need a baseline submission in minutes, or anyone prototyping an autonomous analytics pipeline.

The main cost is not local compute. The source uses meta-llama/Llama-3.1-70B-Instruct served through Hugging Face Inference Providers, so you need an internet connection and a Hugging Face account, but no local GPU. You also need a Python environment with the required libraries installed locally because the agent executes code on your machine.

Prerequisites

The source establishes these requirements:

  • Python 3 with pip.
  • seaborn, smolagents, and transformers installed via pip.
  • A Hugging Face account and an API token, available as the environment variable HUGGINGFACEHUB_API_TOKEN.
  • The Titanic dataset files titanic/train.csv and titanic/test.csv in your working directory. The notebook does not download them for you.
  • For the prediction step, scikit-learn must also be installed in the same Python environment, even though the initial install command does not include it.

The agent runs remotely through Hugging Face Inference Providers with the Llama model. If you want a single-GPU open-weights alternative for local execution, see our coverage of NVIDIA Nemotron 3.5 Super VL 120B.

Step 1: Install the required Python packages

Run this in your environment. In a Jupyter notebook the leading ! executes a shell command; in a terminal, omit the !.

!pip install seaborn smolagents transformers -q -U

This brings in the agent framework, the inference client, and the plotting and data libraries the agent will later use.

Step 2: Initialise the model and the CodeAgent

The agent uses InferenceClientModel to call a hosted Llama model, and CodeAgent to execute generated Python. The additional_authorized_imports argument whitelists the libraries the agent may import while working. Keeping this list tight reduces the attack surface, but every listed library must already be installed locally or the agent will fail at import time.

from smolagents import InferenceClientModel, CodeAgent
from huggingface_hub import login
import os

login(os.getenv("HUGGINGFACEHUB_API_TOKEN"))

model = InferenceClientModel("meta-llama/Llama-3.1-70B-Instruct")

agent = CodeAgent(
    tools=[],
    model=model,
    additional_authorized_imports=["numpy", "pandas", "matplotlib.pyplot", "seaborn"],
    max_iterations=10,
)

max_iterations=10 bounds how many reasoning and code-execution steps the agent can take before stopping. Ten is usually enough for an exploratory analysis pass, but too low for the later training step.

Step 3: Create the output directory

The agent will save figures into ./figures/. The directory must exist before the run begins because the agent is not instructed to create it:

import os

os.mkdir("./figures")

If the directory already exists, this raises an error. Run it once at the start of a fresh session.

Step 4: Run the analyst prompt

The prompt instructs the agent to load titanic/train.csv, formulate three questions, answer them numerically, and save plots. The additional_notes argument passes domain knowledge from the competition — such as the meaning of pclass, sibsp, and parch — directly into the agent's context.

additional_notes = """
### Variable Notes
pclass: A proxy for socio-economic status (SES)
1st = Upper
2nd = Middle
3rd = Lower
age: Age is fractional if less than 1. If the age is estimated, is it in the form of xx.5
sibsp: The dataset defines family relations in this way...
Sibling = brother, sister, stepbrother, stepsister
Spouse = husband, wife (mistresses and fiancés were ignored)
parch: The dataset defines family relations in this way...
Parent = mother, father
Child = daughter, son, stepdaughter, stepson
Some children travelled only with a nanny, therefore parch=0 for them.
"""

analysis = agent.run(
    """You are an expert data analyst.
Please load the source file and analyze its content.
According to the variables you have, begin by listing 3 interesting questions that could be asked on this data, for instance about specific correlations with survival rate.
Then answer these questions one by one, by finding the relevant numbers.
Meanwhile, plot some figures using matplotlib/seaborn and save them to the (already existing) folder './figures/': take care to clear each figure with plt.clf() before doing another plot.

In your final answer: summarize these correlations and trends
After each number derive real worlds insights, for instance: "Correlation between is_december and boredness is 1.3453, which suggest people are more bored in winter".
Your final answer should have at least 3 numbered and detailed parts.
""",
    additional_args=dict(
        additional_notes=additional_notes,
        source_file="titanic/train.csv"
    )
)

Two details matter. First, plt.clf() is required between plots because the agent may reuse the same figure object and accidentally layer multiple charts. Second, because the agent is an LLM, the exact questions it asks and the figures it creates will vary from run to run.

Step 5: Inspect the generated analysis

Print the final response to see the trends the agent extracted and the file names of the saved figures:

print(analysis)

The output is the agent's final synthesis, not a raw dataframe dump. It typically contains the three numbered answers and references to the saved matplotlib or seaborn figures. If the result is thin, raise max_iterations rather than assuming the prompt failed.

Step 6: Switch to a prediction agent

The same CodeAgent class can train a model. This time the authorized imports include sklearn, and max_iterations is increased to 12 because training requires more attempts, error recovery, and CSV writes. The previous analysis is appended to the notes so the ML prompt can benefit from the patterns the analyst already found.

agent = CodeAgent(
    tools=[],
    model=model,
    additional_authorized_imports=[
        "numpy",
        "pandas",
        "matplotlib.pyplot",
        "seaborn",
        "sklearn",
    ],
    max_iterations=12,
)

output = agent.run(
    """You are an expert machine learning engineer.
Please train a ML model on "titanic/train.csv" to predict the survival for rows of "titanic/test.csv".
Output the results under './output.csv'.
Take care to import functions and modules before using them!
""",
    additional_args=dict(additional_notes=additional_notes + "\n" + analysis)
)

The two passes are similar but have different risk profiles:

Aspect Analyst pass Prediction pass
Primary goal Summarise trends, answer questions, save figures Train a model, generate output.csv
Authorized imports numpy, pandas, matplotlib.pyplot, seaborn Same plus sklearn
max_iterations 10 12
Context augmentation Competition variable notes only Variable notes plus the full analyst response
Typical failure Incomplete plot cleanup or shallow questions Import errors, missed train/test splits, malformed CSV output

The generated output.csv can be submitted to the Titanic competition for evaluation. Your exact score will vary because the model, sampling, and generated feature engineering are nondeterministic.

What to watch out for

The local environment must match the authorized imports. The initial install command does not include scikit-learn, so the prediction step fails unless you install it separately. The agent cannot install packages itself; it can only import what already exists.

CodeAgent runs Python on your machine. The additional_authorized_imports whitelist prevents arbitrary imports, but authorized libraries like pandas and sklearn can still read, write, and potentially overwrite files. For untrusted datasets, run the agent inside a container or sandbox rather than in your main development environment.

LLM nondeterminism changes results. The same prompt can produce different questions, plots, and model architectures. Treat the generated output.csv as a baseline, not a reproducible pipeline. If you need consistent evaluation, pin the model and use low sampling temperature where supported.

Hosted model calls can consume tokens and may hit rate limits. A 70B model generating long Python blocks and retrying errors may need many iterations. Start with a low max_iterations, and monitor your Hugging Face provider plan if a run stops unexpectedly.

os.mkdir("./figures") fails on reruns. Either create the directory only once, check for existence, or clear old figures before a new run. Old images can easily be mistaken for fresh output.

Prompt injection is real in data files. Titanic is benign, but if you point the agent at user-supplied or web-scraped data, rows containing instructions can influence the generated code or final answer. Sanitise field names and string content before passing them as additional_notes.

The agent may stop before finishing. Ten or twelve iterations is a hard ceiling. If the analysis is shallow or the training loop fails repeatedly, increase max_iterations, but expect the run to cost more and take longer.

Where to go next

The source is deliberately a minimal start. You can extend it by adding a visualizer tool so the agent can inspect its own plots, by using a larger or local model for more reliable code generation, or by replacing the prompt with a structured schema for your own datasets. Read the official smolagents documentation and the secure code execution tutorial before deploying this pattern against untrusted inputs. For production analytics agents, also look at managed evaluation and monitoring options rather than relying on a single LLM pass.

Frequently asked questions

What does the Hugging Face smolagents Titanic analyst agent do?

It uses a CodeAgent with the hosted model `meta-llama/Llama-3.1-70B-Instruct` to load `titanic/train.csv`, ask three analytical questions, compute answers, save matplotlib or seaborn figures to `./figures/`, and then train an sklearn baseline model in a second pass. The agent generates and executes Python code locally, with imports limited by `additional_authorized_imports`. The second pass writes survival predictions for `titanic/test.csv` to `output.csv`.

What Python packages do I need to run the smolagents Titanic agent?

Install `seaborn`, `smolagents`, and `transformers` with pip; the source install command is `!pip install seaborn smolagents transformers -q -U`. Before the prediction step, install `scikit-learn` separately, because the initial command does not include it. You also need a Hugging Face account and a token in the environment variable `HUGGINGFACEHUB_API_TOKEN`.

Why does the agent require `os.mkdir('./figures')`?

The analyst prompt tells the agent to save plots to an already existing `./figures/` folder, but the agent is not instructed to create that directory. Running `os.mkdir('./figures')` creates it before the agent starts. If the directory already exists, the command raises `FileExistsError`, so it should be run once for a fresh session.

Can I run the smolagents Titanic agent without a local GPU?

Yes. The source uses `InferenceClientModel` with `meta-llama/Llama-3.1-70B-Instruct` served through Hugging Face Inference Providers, so model inference runs remotely. You still need a local Python environment with the required libraries because the agent executes generated Python code on your machine. No local GPU is required for the hosted model.

How do I keep the generated agent code from importing arbitrary Python modules?

The `CodeAgent` constructor accepts `additional_authorized_imports`, which is the whitelist of modules the generated code may import. The analyst pass whitelists `numpy`, `pandas`, `matplotlib.pyplot`, and `seaborn`; the prediction pass adds `sklearn`. For untrusted datasets, run the agent in a container or sandbox because authorized libraries can still read, write, or overwrite files.

Related Guides