Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

feat: add Smolagents Code Agent using HuggingFace smolagents and Mistral

Tiioluwani230869b179fd
diff --git a/ai_agents/smolagents_code_agent/.env.example b/ai_agents/smolagents_code_agent/.env.example
new file mode 100644
index 0000000..7023412
--- /dev/null
+++ b/ai_agents/smolagents_code_agent/.env.example
@@ -0,0 +1,2 @@
+# Get your key at https://console.mistral.ai/
+MISTRAL_API_KEY=your_mistral_api_key_here
diff --git a/ai_agents/smolagents_code_agent/README.md b/ai_agents/smolagents_code_agent/README.md
new file mode 100644
index 0000000..c98eb5a
--- /dev/null
+++ b/ai_agents/smolagents_code_agent/README.md
@@ -0,0 +1,111 @@
+# Smolagents Code Agent
+
+> A real-time AI agent that takes any natural language task, reasons through it with a think-act-observe loop, and streams every step live in a Gradio UI.
+
+## Overview
+
+Smolagents Code Agent wires together HuggingFace's **smolagents** `CodeAgent` and **Mistral Small** (via LiteLLM) into a Gradio web app. You type a task, the agent writes and executes Python code using DuckDuckGo and Wikipedia, and every reasoning step appears in the UI as it happens — no waiting for a final answer to see what the model was thinking.
+
+## Demo
+
+![Demo](assets/demo.png)
+
+## Features
+
+- **Real-time trace streaming** — every Think, Act, and Observe step appears in the UI as the agent works, powered by `step_callbacks` and a background thread queue
+- **Code-first reasoning** — the agent writes and executes Python code at each step rather than calling fixed tool APIs
+- **Two built-in tools** — `DuckDuckGoSearchTool` for live web search and a custom `WikipediaTool` that fetches 5-sentence article summaries
+- **Clean final answer** — the agent's conclusion is extracted and displayed separately from the full reasoning trace
+- **Swappable LLM** — change one line in `app.py` to switch from Mistral Small to DeepSeek V3 Flash via OpenRouter (see [Usage](#usage))
+- **Run/Clear controls** — a spinner confirms the agent is active; Clear resets all outputs instantly
+
+## Tech Stack
+
+| Layer | Technology |
+|---|---|
+| Agent framework | [HuggingFace smolagents](https://github.com/huggingface/smolagents) — `CodeAgent` |
+| LLM | Mistral Small 4 (`mistral-small-latest`) via `LiteLLMModel` |
+| Web search | `DuckDuckGoSearchTool` (bundled with smolagents) |
+| Knowledge tool | Custom `WikipediaTool` using the `wikipedia` package |
+| UI | [Gradio](https://www.gradio.app/) |
+
+## Prerequisites
+
+- Python 3.10 or later
+- A Mistral API key — get one at [platform.mistral.ai](https://platform.mistral.ai)
+
+## Installation
+
+**Clone the repository**
+
+```bash
+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git
+cd Hands-On-AI-Engineering/ai_agents/smolagents_code_agent
+```
+
+**Create and activate a virtual environment**
+
+*Windows*
+```bash
+python -m venv .venv
+.venv\Scripts\activate
+```
+
+*macOS / Linux*
+```bash
+python -m venv .venv
+source .venv/bin/activate
+```
+
+**Install dependencies**
+
+```bash
+pip install -r requirements.txt
+```
+
+**Set up environment variables**
+
+```bash
+cp .env.example .env
+```
+
+Open `.env` and paste your Mistral API key (see [Environment Variables](#environment-variables)).
+
+## Usage
+
+```bash
+python app.py
+```
+
+Open `http://127.0.0.1:7860` in your browser, type a task, and click **Run Agent**.
+
+**Example task**
+
+```text
+Find the latest news about AI agents and summarize the top 3 stories.
+```
+
+## Environment Variables
+
+| Variable | Description | Where to get it |
+|---|---|---|
+| `MISTRAL_API_KEY` | Authenticates requests to Mistral's API | [platform.mistral.ai](https://platform.mistral.ai) |
+
+`.env.example`:
+
+```env
+MISTRAL_API_KEY=your_mistral_api_key_here
+```
+
+## Project Structure
+
+```text
+smolagents-code-agent/
+├── app.py # Gradio UI, agent runner, step formatter
+├── tools.py # Custom WikipediaTool
+├── requirements.txt # Python dependencies
+├── .env # Your secrets (git-ignored)
+├── .env.example # Template for .env
+└── assets/
+ └── demo.png # Screenshot used in README
+```
diff --git a/ai_agents/smolagents_code_agent/app.py b/ai_agents/smolagents_code_agent/app.py
new file mode 100644
index 0000000..b4a63e0
--- /dev/null
+++ b/ai_agents/smolagents_code_agent/app.py
@@ -0,0 +1,194 @@
+import os
+import queue
+import threading
+import gradio as gr
+from dotenv import load_dotenv
+from smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel
+
+from tools import WikipediaTool
+
+load_dotenv()
+
+MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY")
+
+
+# -- Formatting ----------------------------------------------------------------
+
+def format_step(step_log) -> str:
+ """Convert a smolagents step log object into a human-readable trace block."""
+ parts = []
+ step_num = getattr(step_log, "step_number", None)
+ step_type = type(step_log).__name__
+
+ header_label = f"STEP {step_num}" if step_num is not None else step_type.upper()
+ parts.append(f"\n{'-' * 60}")
+ parts.append(header_label)
+ parts.append("-" * 60)
+
+ # Planning text (PlanningStep)
+ plan = getattr(step_log, "plan", None)
+ if plan:
+ parts.append(f"\n[PLAN]\n{plan.strip()}")
+
+ # LLM output -- contains the agent's reasoning and generated code
+ llm_output = getattr(step_log, "llm_output", None)
+ if llm_output:
+ parts.append(f"\n[THINK / ACT]\n{llm_output.strip()}")
+
+ # Explicit tool calls (non-code agents)
+ tool_calls = getattr(step_log, "tool_calls", None)
+ if tool_calls:
+ for tc in tool_calls:
+ name = getattr(tc, "name", "?")
+ args = getattr(tc, "arguments", None)
+ parts.append(f"\n[TOOL CALL] {name}")
+ if args:
+ parts.append(f"Arguments: {args}")
+
+ # Observations -- execution result / tool output
+ observations = getattr(step_log, "observations", None)
+ if observations:
+ parts.append(f"\n[OBSERVE]\n{str(observations).strip()}")
+
+ # Error
+ error = getattr(step_log, "error", None)
+ if error:
+ parts.append(f"\n[ERROR]\n{error}")
+
+ return "\n".join(parts) + "\n"
+
+
+# -- Agent runner --------------------------------------------------------------
+
+def run_agent(task: str):
+ """
+ Gradio generator: yields (trace, final_answer, spinner_update) after every
+ agent step so the UI updates in real time.
+ """
+ if not task.strip():
+ yield "Please enter a task.", "", gr.update(visible=False)
+ return
+
+ step_queue: queue.Queue = queue.Queue()
+ result_container: list = []
+ error_container: list = []
+
+ def _step_callback(step_log):
+ step_queue.put(("step", step_log))
+
+ def _run():
+ try:
+ agent = CodeAgent(
+ tools=[DuckDuckGoSearchTool(), WikipediaTool()],
+ model=LiteLLMModel(
+ model_id="mistral/mistral-small-latest",
+ api_key=MISTRAL_API_KEY,
+ ),
+ step_callbacks=[_step_callback],
+ max_steps=10,
+ verbosity_level=0,
+ )
+ result = agent.run(task)
+ result_container.append(result)
+ except Exception as exc:
+ error_container.append(str(exc))
+ finally:
+ step_queue.put(("done", None))
+
+ thread = threading.Thread(target=_run, daemon=True)
+ thread.start()
+
+ trace = f"Task: {task}\n\nStarting agent...\n"
+ final_answer = ""
+
+ # Show spinner immediately
+ yield trace, final_answer, gr.update(visible=True)
+
+ while True:
+ try:
+ msg_type, step_log = step_queue.get(timeout=120)
+ except queue.Empty:
+ trace += "\n[TIMEOUT] Agent did not respond within 120 s.\n"
+ yield trace, final_answer, gr.update(visible=False)
+ return
+
+ if msg_type == "done":
+ break
+
+ trace += format_step(step_log)
+ yield trace, final_answer, gr.update(visible=True)
+
+ thread.join(timeout=5)
+
+ if error_container:
+ trace += f"\n[ERROR]\n{error_container[0]}\n"
+ yield trace, final_answer, gr.update(visible=False)
+ return
+
+ if result_container:
+ final_answer = str(result_container[0])
+
+ trace += "\n" + "-" * 60 + "\nAgent finished.\n"
+ yield trace, final_answer, gr.update(visible=False)
+
+
+# -- Gradio UI -----------------------------------------------------------------
+
+with gr.Blocks(title="Smolagents Code Agent") as demo:
+ gr.Markdown(
+ """
+# Smolagents Code Agent
+Powered by **Mistral Small** via LiteLLM and **HuggingFace smolagents**.
+Enter a task in plain English and watch the agent reason through it step by step.
+ """
+ )
+
+ with gr.Row():
+ with gr.Column(scale=4):
+ task_input = gr.Textbox(
+ label="Task",
+ placeholder=(
+ 'e.g. "Find the latest news about AI agents and summarize the top 3 stories"'
+ ),
+ lines=3,
+ )
+ with gr.Column(scale=1, min_width=140):
+ run_btn = gr.Button("Run Agent", variant="primary")
+ clear_btn = gr.Button("Clear", variant="secondary")
+
+ spinner = gr.HTML(
+ value=(
+ '<div style="text-align:center;padding:10px;background:#eef2ff;'
+ 'border-radius:8px;font-weight:600;color:#4338ca;">'
+ "Agent is running...</div>"
+ ),
+ visible=False,
+ )
+
+ trace_output = gr.Textbox(
+ label="Reasoning Trace (Think -> Act -> Observe)",
+ lines=20,
+ max_lines=40,
+ interactive=False,
+ )
+
+ final_output = gr.Textbox(
+ label="Final Answer",
+ lines=6,
+ interactive=False,
+ )
+
+ run_btn.click(
+ fn=run_agent,
+ inputs=[task_input],
+ outputs=[trace_output, final_output, spinner],
+ )
+
+ clear_btn.click(
+ fn=lambda: ("", "", gr.update(visible=False)),
+ inputs=[],
+ outputs=[trace_output, final_output, spinner],
+ )
+
+if __name__ == "__main__":
+ demo.launch(theme=gr.themes.Soft())
diff --git a/ai_agents/smolagents_code_agent/assets/demo.png b/ai_agents/smolagents_code_agent/assets/demo.png
new file mode 100644
index 0000000..6793b65
Binary files /dev/null and b/ai_agents/smolagents_code_agent/assets/demo.png differ
diff --git a/ai_agents/smolagents_code_agent/requirements.txt b/ai_agents/smolagents_code_agent/requirements.txt
new file mode 100644
index 0000000..619fd9d
--- /dev/null
+++ b/ai_agents/smolagents_code_agent/requirements.txt
@@ -0,0 +1,6 @@
+smolagents[litellm]>=1.0.0
+gradio>=4.44.0
+python-dotenv>=1.0.0
+duckduckgo-search>=6.0.0
+wikipedia>=1.4.0
+ddgs
diff --git a/ai_agents/smolagents_code_agent/tools.py b/ai_agents/smolagents_code_agent/tools.py
new file mode 100644
index 0000000..1113870
--- /dev/null
+++ b/ai_agents/smolagents_code_agent/tools.py
@@ -0,0 +1,46 @@
+import wikipedia
+from smolagents import Tool
+
+
+class WikipediaTool(Tool):
+ name = "wikipedia"
+ description = (
+ "Searches Wikipedia and returns a summary of the most relevant article "
+ "for the given query. Use this for factual questions about people, places, "
+ "events, concepts, or any topic likely to have a Wikipedia page."
+ )
+ inputs = {
+ "query": {
+ "type": "string",
+ "description": "The topic or question to look up on Wikipedia.",
+ }
+ }
+ output_type = "string"
+
+ def forward(self, query: str) -> str:
+ try:
+ results = wikipedia.search(query, results=3)
+ if not results:
+ return f"No Wikipedia results found for '{query}'."
+
+ try:
+ page = wikipedia.page(results[0], auto_suggest=False)
+ summary = wikipedia.summary(results[0], sentences=5, auto_suggest=False)
+ return f"Title: {page.title}\n\n{summary}\n\nURL: {page.url}"
+
+ except wikipedia.exceptions.DisambiguationError as e:
+ if e.options:
+ try:
+ summary = wikipedia.summary(e.options[0], sentences=5, auto_suggest=False)
+ return f"Title: {e.options[0]}\n\n{summary}"
+ except Exception:
+ pass
+ return (
+ f"'{query}' is ambiguous. Possible topics: "
+ + ", ".join(e.options[:5])
+ )
+
+ except wikipedia.exceptions.PageError:
+ return f"No Wikipedia page found for '{query}'."
+ except Exception as e:
+ return f"Wikipedia lookup error: {e}"