Skip to content
C.W.K.
Lesson 02 of 04 · published

Gradio: ML Demos in 10 Lines

~26 min · spaces, gradio

Level 0Scout
0 XP0/50 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Gradio's signature: a Python function becomes a UI

Define a function. Wrap it with gr.Interface or compose with gr.Blocks. Gradio inspects the signature, auto-builds inputs/outputs, and serves a web UI. demo.launch() starts the server, locally and on Spaces alike: the Space just runs your app.py, so the file must call launch() itself.

Two layouts

  • gr.Interface(fn, inputs, outputs) — one function, one UI. Best for single-task demos.
  • gr.Blocks() — explicit layout. Multiple inputs/outputs, tabs, custom CSS, conditional visibility. Use when Interface is too rigid.

Streaming and ChatInterface

For chat models, gr.ChatInterface handles message history and streaming with a generator-based handler. The same pattern works with InferenceClient or local models.

Code

10-line Gradio demo of a HF model·python
import gradio as gr
from transformers import pipeline

pipe = pipeline("sentiment-analysis")

def classify(text):
    out = pipe(text)[0]
    return f"{out['label']} ({out['score']:.2f})"

demo = gr.Interface(fn=classify, inputs=gr.Textbox(label="Review"), outputs="text")
demo.launch()
Streaming chat with InferenceClient·python
import gradio as gr
from huggingface_hub import InferenceClient

client = InferenceClient(model="meta-llama/Llama-3.1-8B-Instruct", provider="auto")

def chat(message, history):
    # In Gradio 6, history is a list of {"role", "content"} dicts,
    # and content is a list of {"type": "text", "text": ...} parts
    messages = [
        {"role": h["role"], "content": "".join(c["text"] for c in h["content"] if c.get("type") == "text")}
        for h in history
    ]
    messages.append({"role": "user", "content": message})
    stream = client.chat_completion(messages=messages, max_tokens=500, stream=True)
    answer = ""
    for chunk in stream:
        answer += chunk.choices[0].delta.content or ""
        yield answer

gr.ChatInterface(chat, title="Llama Chat").launch()

External links

Exercise

Build a Gradio Space that wraps a small HF model (e.g. text classification or whisper-tiny). Test locally first. Push to a Space (on a free personal account, create it on ZeroGPU hardware). Then add a second tab that demos a different model. Verify both work side by side.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign in — Please sign in to comment.

No comments yet — be the first.