Qlaudia

← All courses

Build an Agentic AI App with Hugging Face

  • Artificial Intelligence
  • Technology & Computing

Build a Python research assistant that executes a think-act-observe loop using smolagents, Claude, and Hugging Face tools to search the web, retrieve from private knowledge bases, and cite sources. Deploy the final agent as an interactive web application on Hugging Face Spaces, learning to implement custom tools, multi-agent delegation, retrieval-augmented generation, and observability along the way.

Sign in to enrollFree21 lessons

What you'll learn

  • Designing the Research Assistant Capstone AgentCombining web search, a webpage-reading tool, and a knowledge-base retrieval tool inside a single CodeAgent configured with instructions that favor the knowledge base and require cited sources, plus guard rails like max_steps and planning_interval.
  • CodeAgent and Python-Based Tool CallingHow smolagents' CodeAgent acts by generating and executing Python code rather than emitting JSON tool calls, allowing looping, branching, and combining tools within a single generated step for fewer steps and lower cost.
  • Centralized Model Configuration with common.pyHow the tutorial centralizes model selection and setup in common.py, including the MODEL_ID constant, the get_model() LiteLLMModel factory that exits if the API key is missing, the QUIET verbosity setting used across all agents, and quiet_hf_downloads() for silencing Hub download progress.
  • CodeAgent versus ToolCallingAgentThe practical differences between CodeAgent and ToolCallingAgent, including when to choose each, the code sandbox CodeAgent runs in, and why additional_authorized_imports only applies to CodeAgent since ToolCallingAgent has no interpreter to import into.
  • max_steps as a Runaway Guard RailUsing the max_steps parameter to cap how many think-act-observe iterations an agent can take, preventing infinite or runaway loops.
  • Loading Tools from an MCP ServerUsing ToolCollection.from_mcp to connect to a Model Context Protocol server and dynamically load externally defined tools into an agent, rather than writing them yourself.
  • The Think-Act-Observe Agent LoopThe core idea that distinguishes an agent from a one-shot chatbot: repeatedly thinking about what to do, acting by invoking a tool, and observing the result until a goal is satisfied.
  • Multi-Agent Systems with Manager and Worker AgentsBuilding a multi-agent system where a manager agent with no tools of its own delegates tasks to a named worker agent via managed_agents, receiving only the worker's final answer rather than its full transcript.
  • Agent Safety PracticesThe repository's own safety guidance for agents: applying least privilege in tool access, using max_steps, running code in sandboxed executors such as docker or e2b, and being cautious with trust_remote_code.
  • Instrumenting Agents with step_callbacksUsing step_callbacks to hook into each step of an agent's execution for custom logging or monitoring purposes.
  • Writing Custom Tools with the @tool DecoratorHow to define a custom tool function using the @tool decorator, and why the docstring — especially its Args section — is the literal contract the model reads to understand how to call the tool correctly.
  • Inspecting Agent MemoryUsing agent.memory.steps to inspect the recorded history of an agent's actions, observations, and reasoning after or during a run.
  • Monitoring Token UsageUsing agent.monitor.get_total_token_counts() to track cumulative token consumption across an agent's run for cost awareness.
  • Wrapping an Agent in a Gradio Web UIUsing GradioUI to expose an agent through a browser-based chat interface that streams each of the agent's steps live, including why the tutorial overrides the default share=True behavior to avoid a public tunnel.
  • Context Isolation and Token Cost TradeoffsThe tradeoff in multi-agent delegation between isolating a worker agent's context from the manager (reducing noise and coupling) and the token cost implications of running multiple agents versus a single agent.
  • Running the Capstone via CLI and GradioRunning the capstone research-assistant agent both from the command line via agent.py and through a Gradio web interface via app.py.
  • Project Setup and Dependency InstallationSetting up a Python 3.10+ virtual environment, installing pinned dependencies from requirements.txt (smolagents[toolkit], litellm, sentence-transformers, mcp, mcpadapt, gradio), and configuring environment variables such as ANTHROPIC_API_KEY via a .env file.
  • Retrieval-Augmented Generation as a ToolImplementing RAG by wrapping semantic search over embedded documents in a class-based Tool (KnowledgeBaseTool), using a Hub-hosted embedding model to perform in-memory similarity search over markdown knowledge files.
  • Deploying an Agent as a Hugging Face SpacePackaging and deploying the capstone application to a Hugging Face Space by copying the required files (app.py, agent.py, common.py, requirements.txt, data/) and setting the ANTHROPIC_API_KEY as a Space secret.
  • Hub-Hosted Embedding ModelsWhat a Hugging Face Hub-hosted embedding model like all-MiniLM-L6-v2 is, how it's downloaded and used locally via sentence-transformers to convert text into vectors for semantic search.
  • The trust_remote_code DecisionWhy loading tools or code from an external MCP server requires explicitly setting trust_remote_code=True, and how to reason about the trust and security implications of that decision.

About this course

What this course builds

You are going to build, module by module, a Python program that starts as a five-line agent and ends as a deployable web application: a "research assistant" that searches the open web, reads pages it finds, and answers questions from a private knowledge base — citing its sources — running as a Hugging Face Space anyone can visit in a browser.

Every module adds one capability to the same underlying idea. By the end you will be able to explain, and not just recite, why each design choice in the finished agent is there.

The central idea: an agent is a loop, not a single call

A chatbot answers a prompt once and stops. An agent is different: it repeats a loop —

THINK→ACT→OBSERVE→THINK→⋯\text{THINK} \rightarrow \text{ACT} \rightarrow \text{OBSERVE} \rightarrow \text{THINK} \rightarrow \cdots

until it decides it has enough information to give a final answer. "Think" is the language model reasoning about what to do next. "Act" is running a tool — a function the model chooses to call, such as a web search or a lookup in a knowledge base. "Observe" is feeding the tool's result back to the model so it can decide the next step.

THINK ACT (run tool) OBSERVE repeat until final answer is ready

The think-act-observe loop: the model reasons, chooses and runs a tool, reads the result, and repeats until it can answer.

Everything in this course is a variation on that loop: which tools are available, how many agents share the work, how the loop is instrumented, and how it is exposed to a user.

smolagents: the agent framework

smolagents is Hugging Face's open-source Python library for building agents like the one above. It is deliberately small — its core logic is on the order of a thousand lines — which matters for you as a learner: you can read and reason about what it does rather than treating it as a black box.

Its signature idea is the CodeAgent. Many agent frameworks have the model emit a tool call as a block of JSON, which a runtime then parses and executes. CodeAgent instead has the model write and execute actual Python code to call its tools. This means the model can use loops, conditionals, and variables to combine tools within a single step, instead of being limited to one tool call per round trip — which tends to mean fewer steps and lower cost for multi-tool tasks. You will meet CodeAgent's alternative, ToolCallingAgent, which does use the more conventional JSON-call approach, and see concretely where each one is the better fit.

Claude as the reasoning model, reached through LiteLLM

The "think" step needs a language model to do the reasoning. This course uses Anthropic's Claude Sonnet as that model. smolagents does not talk to Anthropic directly; it goes through an adapter called LiteLLMModel, which gives smolagents a uniform way to call many different model providers. Hugging Face's role in this course is not to host the reasoning model — it is the agent framework (smolagents), a Hub-hosted embedding model you will use for retrieval, tool loading over MCP, the Gradio UI library, and Spaces as the deployment target.

You will need an Anthropic API key to run any of the agents in this course, and Anthropic bills per token — running the exercises will incur small, usage-based charges on your account.

What each module adds

Working through the course in order, you will layer in:

  • Custom tools — writing your own Python functions decorated with @tool, and learning that the function's docstring, especially its Args: section, is not documentation for humans but the literal contract the model reads to decide how to call it.
  • CodeAgent vs. ToolCallingAgent — running the same task through both, and seeing how CodeAgent's Python sandbox and its additional_authorized_imports setting (which has no equivalent for ToolCallingAgent, since there is no code interpreter to import into) shape what each agent can safely do.
  • Retrieval-augmented generation (RAG) as a tool — building a tool that embeds a set of documents using a Hugging Face Hub-hosted embedding model and performs semantic search over them, so the agent can answer from a private knowledge base rather than only from what it already knows or can find on the web.
  • Multi-agent delegation — a manager agent with no tools of its own that delegates subtasks to named worker agents, and the tradeoff this creates: the manager sees only a worker's final answer, not its full working, which isolates context but costs tokens to re-establish.
  • Model Context Protocol (MCP) — loading tools you did not write from an external MCP server via ToolCollection.from_mcp, and the explicit trust decision (trust_remote_code) that loading someone else's code requires.
  • A Gradio web UI — wrapping an agent in GradioUI so its steps stream live to a browser instead of only printing to a terminal.
  • Observability — using step_callbacks, the agent's memory, and its monitor's token counts to see what an agent actually did and what it cost, plus max_steps as a guard rail against runaway loops.

The course closes with the capstone: a single agent combining web search, a webpage-reading tool, and retrieval over a private knowledge base, instructed to prefer the knowledge base and always cite its sources — deployed as a working Hugging Face Space.

What you need before starting

  • Python 3.10 or later, installed and runnable from your terminal.
  • An Anthropic API key (create one if you don't have it), since the reasoning model is Claude Sonnet reached through Anthropic's API.
  • A free Hugging Face account, used for downloading a Hub-hosted embedding model and for deploying the capstone as a Space.
  • Comfort with basic Python, pip, virtual environments, and running scripts from the command line. No prior experience with agent frameworks, smolagents, MCP, or Gradio is assumed — each of those is introduced from scratch as you reach it.

How this course relates to the reference repository

The finished, working version of everything you will build lives at https://github.com/ChuckIrvine/hf_agent_tutorial. You do not need to clone it or browse its source to follow this course — every file a lesson needs is pulled from that repository and given to you directly at the point you need it. Instead, you will create your own project directory on your machine and build up the same modules yourself, file by file, running each one from your terminal as you go. If you want to explore beyond what a lesson covers, the repository is there and freely licensed (Apache-2.0) for you to read.

Build an Agentic AI App with Hugging Face — Qlaudia