{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"a-web-interface-with-gradio","title":"A web interface in twenty lines: Gradio, and what launch() actually starts","url":"https://addaly.com/learn/python-for-ai/a-web-interface-with-gradio","position":86,"of":89,"minutes":8,"answer":"gr.ChatInterface wraps a function that takes a message and history and returns text (or yields it for streaming) and launch() starts a local web server on port 7860; share=True opens a temporary public tunnel.","keyIdea":"gr.ChatInterface wraps a function that takes a message and history and returns text (or yields it for streaming) and launch() starts a local web server on port 7860; share=True opens a temporary public tunnel, and Hugging Face Spaces hosts the same file for free."},"body":{"format":"markdown","text":"## From a terminal to a page\n\nThe chat loop from earlier in this module reads with `input()` and writes with `print()`. Replacing those two with a web page is what Gradio (free, `pip install gradio`) does:\n\n```python\nimport gradio as gr\n\ndef respond(message, history):\n    messages = [{\"role\": \"system\", \"content\": SYSTEM}]\n    for turn in history:\n        content = turn[\"content\"]\n        if isinstance(content, list):    # Gradio 6 sends a list of parts: [{\"type\": \"text\", \"text\": ...}]\n            content = \"\".join(p.get(\"text\", \"\") for p in content if p.get(\"type\") == \"text\")\n        messages.append({\"role\": turn[\"role\"], \"content\": content})\n    messages.append({\"role\": \"user\", \"content\": message})\n    return provider.complete(trim(messages, 4000, count))\n\ndemo = gr.ChatInterface(respond, title=\"Notes assistant\")\ndemo.launch()\n```\n\nRun it and a browser opens at `http://127.0.0.1:7860` with a chat box. `ChatInterface` calls `respond` with the new message and the conversation so far, and displays what comes back. The history is kept by Gradio in the browser session; your function is stateless, which is why the `messages` list is rebuilt every call, and why `trim` from the chat-loop lesson is still needed.\n\nEverything you already built plugs in unchanged: the provider, the template, the cache, the search.\n\n## Streaming\n\nA reply that takes eight seconds to arrive whole feels broken; the same reply streaming feels alive. Make `respond` a generator and Gradio streams it:\n\n```python\ndef respond(message, history):\n    messages = build(message, history)\n    partial = \"\"\n    for piece in provider.stream(messages):      # module 6's stream_text, behind the provider\n        partial += piece\n        yield partial\n```\n\nYield the accumulated text each time, not the fragment: the interface displays what you yield as the whole current reply. The `+=` on a string is fine here; the pieces are few and the response short. For a very long reply, collect in a list and `\"\".join` as module 6 advised.\n\n## Other inputs\n\n`ChatInterface` is one preset. `gr.Interface` wraps any function with declared inputs and outputs:\n\n```python\ndemo = gr.Interface(\n    fn=search_notes,\n    inputs=[gr.Textbox(label=\"Question\"), gr.Slider(1, 10, value=5, step=1, label=\"Results\")],\n    outputs=gr.Markdown(),\n)\n```\n\nText boxes, sliders, file uploads, images, audio, dropdowns: each is a component, and the function receives their values as arguments in order. A `gr.File` input hands you a path; a `gr.Image` hands you a NumPy array of pixels, which module 8 taught you to read. `gr.Blocks` lets you lay out several components and wire them by hand when the presets do not fit.\n\n## What `launch()` starts\n\n`launch()` starts a web server (FastAPI and uvicorn underneath, which the next lesson covers) inside your Python process, on port 7860, listening on `127.0.0.1` only. That last part matters: nobody on your network can reach it. `launch(server_name=\"0.0.0.0\")` listens on all interfaces, which makes it reachable from a phone on the same Wi-Fi and from anyone else on that network, so do it only where you would be comfortable with that.\n\nThe process stays alive serving requests until you stop it. Every request runs your function on a worker; two people sending at once run concurrently, which is fine for a function that calls an API and dangerous for one that writes to a shared file without a lock, per module 6.\n\n## Sharing\n\n```python\ndemo.launch(share=True)\n```\n\nprints a `https://xxxx.gradio.live` link that anyone can open for 72 hours. It works by opening a tunnel from Gradio's servers to your laptop: requests arrive at the public address and are forwarded to the process on your machine. Nothing is uploaded. Which means the link works exactly as long as your laptop is awake and the process is running, and dies when either stops. It is for showing a friend, not for hosting.\n\n## Hosting for free\n\nHugging Face Spaces runs a Gradio app from a repository. The CPU Basic tier requires a subscription: PRO for personal accounts, or Team or Enterprise for organisations. Eligible free personal accounts in good standing, with a verified email and more than 30 days old, can host up to two Gradio Spaces on ZeroGPU hardware. Check the current [Space hardware rules](https://huggingface.co/docs/huggingface_hub/guides/manage-spaces) and [ZeroGPU eligibility](https://huggingface.co/docs/hub/spaces-zerogpu) before choosing hardware.\n\n1. Create a Space, choose Gradio, and on an eligible free account choose ZeroGPU as the hardware.\n2. Push `app.py` and a `requirements.txt` (module 5's pins).\n3. Put the API key in the Space's **Secrets** settings, never in the file; read it with `os.environ` as always.\n\nThe Space builds, starts, and gives you a permanent public URL. Free Spaces sleep after inactivity and wake on the next visit, which takes a few seconds. A local model through Ollama will not run there (there is no Ollama on a Space), but `sentence-transformers` and small `transformers` models do, so the notes search runs entirely on free hardware.\n\nStreamlit is the other common choice and also has free hosting; it re-runs your whole script on every interaction, which is a different mental model, better for dashboards than chat.\n\n## Keep the interface thin\n\n`app.py` should contain the Gradio wiring and nothing else. The provider, the search, the templates and the cache live in your package and are imported, exactly as the notebook lesson said of notebooks. Then the same functions serve the CLI, the web page and next lesson's API, and the tests cover all three.\n\n## Try this now\n\nWrap your chat loop's `respond` in `ChatInterface` against Ollama and open it on your phone using `server_name=\"0.0.0.0\"` and your laptop's IP. Add streaming. Then push the notes search as a Space with a `sentence-transformers` model and send someone the link."},"check":{"question":"A learner runs `demo.launch(share=True)`, sends the printed `*.gradio.live` link to a friend, and closes the laptop. The friend reports the link is dead. What happened?","options":[{"text":"Gradio share links are single-use and expire after the first person opens them.","correct":false,"tempting":"Share links serve any number of visitors while they are alive; the limit is on lifetime, not visitors."},{"text":"The friend's browser blocked the link because Gradio serves over plain HTTP, which modern browsers refuse for external hosts.","correct":false,"tempting":"Share links are served over HTTPS by the tunnel; browsers open them normally."},{"text":"The tunnel only forwards traffic to the process on the laptop, so when the laptop slept the link had nothing behind it.","correct":true},{"text":"Gradio uploads the model and the code to its servers on `share=True`, and the upload was interrupted when the laptop closed, so the hosted copy was never completed.","correct":false,"tempting":"Nothing is uploaded; the code and model stay on the laptop, and only requests are forwarded to it."}]},"prev":{"slug":"a-local-model-from-python","title":"A free model on your own machine, called from Python","url":"https://addaly.com/learn/python-for-ai/a-local-model-from-python"},"next":{"slug":"an-endpoint-with-fastapi","title":"An HTTP endpoint with FastAPI: your function, callable by any program","url":"https://addaly.com/learn/python-for-ai/an-endpoint-with-fastapi"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'A web interface in twenty lines: Gradio, and what launch() actually starts', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/a-web-interface-with-gradio (Accessed: 21 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"A web interface in twenty lines: Gradio, and what launch() actually starts","courseTitle":"Python, from Zero, for AI","module":{"index":9,"slug":"building-the-thing","title":"Building the thing: a small AI program, end to end"},"answer":null,"keyIdea":"gr.ChatInterface wraps a function that takes a message and history and returns text (or yields it for streaming) and launch() starts a local web server on port 7860; share=True opens a temporary public tunnel, and Hugging Face Spaces hosts the same file for free.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"from-a-terminal-to-a-page","runs":[{"text":"From a terminal to a page"}]},{"t":"p","runs":[{"text":"The chat loop from earlier in this module reads with "},{"text":"input()","code":true},{"text":" and writes with "},{"text":"print()","code":true},{"text":". Replacing those two with a web page is what Gradio (free, "},{"text":"pip install gradio","code":true},{"text":") does:"}]},{"t":"code","lang":"python","label":"Python","text":"import gradio as gr\n\ndef respond(message, history):\n    messages = [{\"role\": \"system\", \"content\": SYSTEM}]\n    for turn in history:\n        content = turn[\"content\"]\n        if isinstance(content, list):    # Gradio 6 sends a list of parts: [{\"type\": \"text\", \"text\": ...}]\n            content = \"\".join(p.get(\"text\", \"\") for p in content if p.get(\"type\") == \"text\")\n        messages.append({\"role\": turn[\"role\"], \"content\": content})\n    messages.append({\"role\": \"user\", \"content\": message})\n    return provider.complete(trim(messages, 4000, count))\n\ndemo = gr.ChatInterface(respond, title=\"Notes assistant\")\ndemo.launch()"},{"t":"p","runs":[{"text":"Run it and a browser opens at "},{"text":"http://127.0.0.1:7860","code":true},{"text":" with a chat box. "},{"text":"ChatInterface","code":true},{"text":" calls "},{"text":"respond","code":true},{"text":" with the new message and the conversation so far, and displays what comes back. The history is kept by Gradio in the browser session; your function is stateless, which is why the "},{"text":"messages","code":true},{"text":" list is rebuilt every call, and why "},{"text":"trim","code":true},{"text":" from the chat-loop lesson is still needed."}]},{"t":"p","runs":[{"text":"Everything you already built plugs in unchanged: the provider, the template, the cache, the search."}]},{"t":"h2","id":"streaming","runs":[{"text":"Streaming"}]},{"t":"p","runs":[{"text":"A reply that takes eight seconds to arrive whole feels broken; the same reply streaming feels alive. Make "},{"text":"respond","code":true},{"text":" a generator and Gradio streams it:"}]},{"t":"code","lang":"python","label":"Python","text":"def respond(message, history):\n    messages = build(message, history)\n    partial = \"\"\n    for piece in provider.stream(messages):      # module 6's stream_text, behind the provider\n        partial += piece\n        yield partial"},{"t":"p","runs":[{"text":"Yield the accumulated text each time, not the fragment: the interface displays what you yield as the whole current reply. The "},{"text":"+=","code":true},{"text":" on a string is fine here; the pieces are few and the response short. For a very long reply, collect in a list and "},{"text":"\"\".join","code":true},{"text":" as module 6 advised."}]},{"t":"h2","id":"other-inputs","runs":[{"text":"Other inputs"}]},{"t":"p","runs":[{"text":"ChatInterface","code":true},{"text":" is one preset. "},{"text":"gr.Interface","code":true},{"text":" wraps any function with declared inputs and outputs:"}]},{"t":"code","lang":"python","label":"Python","text":"demo = gr.Interface(\n    fn=search_notes,\n    inputs=[gr.Textbox(label=\"Question\"), gr.Slider(1, 10, value=5, step=1, label=\"Results\")],\n    outputs=gr.Markdown(),\n)"},{"t":"p","runs":[{"text":"Text boxes, sliders, file uploads, images, audio, dropdowns: each is a component, and the function receives their values as arguments in order. A "},{"text":"gr.File","code":true},{"text":" input hands you a path; a "},{"text":"gr.Image","code":true},{"text":" hands you a NumPy array of pixels, which module 8 taught you to read. "},{"text":"gr.Blocks","code":true},{"text":" lets you lay out several components and wire them by hand when the presets do not fit."}]},{"t":"h2","id":"what-launch-starts","runs":[{"text":"What "},{"text":"launch()","code":true},{"text":" starts"}]},{"t":"p","runs":[{"text":"launch()","code":true},{"text":" starts a web server (FastAPI and uvicorn underneath, which the next lesson covers) inside your Python process, on port 7860, listening on "},{"text":"127.0.0.1","code":true},{"text":" only. That last part matters: nobody on your network can reach it. "},{"text":"launch(server_name=\"0.0.0.0\")","code":true},{"text":" listens on all interfaces, which makes it reachable from a phone on the same Wi-Fi and from anyone else on that network, so do it only where you would be comfortable with that."}]},{"t":"p","runs":[{"text":"The process stays alive serving requests until you stop it. Every request runs your function on a worker; two people sending at once run concurrently, which is fine for a function that calls an API and dangerous for one that writes to a shared file without a lock, per module 6."}]},{"t":"h2","id":"sharing","runs":[{"text":"Sharing"}]},{"t":"code","lang":"python","label":"Python","text":"demo.launch(share=True)"},{"t":"p","runs":[{"text":"prints a "},{"text":"https://xxxx.gradio.live","code":true},{"text":" link that anyone can open for 72 hours. It works by opening a tunnel from Gradio’s servers to your laptop: requests arrive at the public address and are forwarded to the process on your machine. Nothing is uploaded. Which means the link works exactly as long as your laptop is awake and the process is running, and dies when either stops. It is for showing a friend, not for hosting."}]},{"t":"h2","id":"hosting-for-free","runs":[{"text":"Hosting for free"}]},{"t":"p","runs":[{"text":"Hugging Face Spaces runs a Gradio app from a repository. The CPU Basic tier requires a subscription: PRO for personal accounts, or Team or Enterprise for organisations. Eligible free personal accounts in good standing, with a verified email and more than 30 days old, can host up to two Gradio Spaces on ZeroGPU hardware. Check the current "},{"text":"Space hardware rules","href":"https://huggingface.co/docs/huggingface_hub/guides/manage-spaces"},{"text":" and "},{"text":"ZeroGPU eligibility","href":"https://huggingface.co/docs/hub/spaces-zerogpu"},{"text":" before choosing hardware."}]},{"t":"ol","start":1,"items":[[{"text":"Create a Space, choose Gradio, and on an eligible free account choose ZeroGPU as the hardware."}],[{"text":"Push "},{"text":"app.py","code":true},{"text":" and a "},{"text":"requirements.txt","code":true},{"text":" (module 5’s pins)."}],[{"text":"Put the API key in the Space’s "},{"text":"Secrets","b":true},{"text":" settings, never in the file; read it with "},{"text":"os.environ","code":true},{"text":" as always."}]]},{"t":"p","runs":[{"text":"The Space builds, starts, and gives you a permanent public URL. Free Spaces sleep after inactivity and wake on the next visit, which takes a few seconds. A local model through Ollama will not run there (there is no Ollama on a Space), but "},{"text":"sentence-transformers","code":true},{"text":" and small "},{"text":"transformers","code":true},{"text":" models do, so the notes search runs entirely on free hardware."}]},{"t":"p","runs":[{"text":"Streamlit is the other common choice and also has free hosting; it re-runs your whole script on every interaction, which is a different mental model, better for dashboards than chat."}]},{"t":"h2","id":"keep-the-interface-thin","runs":[{"text":"Keep the interface thin"}]},{"t":"p","runs":[{"text":"app.py","code":true},{"text":" should contain the Gradio wiring and nothing else. The provider, the search, the templates and the cache live in your package and are imported, exactly as the notebook lesson said of notebooks. Then the same functions serve the CLI, the web page and next lesson’s API, and the tests cover all three."}]},{"t":"h2","id":"try-this-now","runs":[{"text":"Try this now"}],"role":"try"},{"t":"p","runs":[{"text":"Wrap your chat loop’s "},{"text":"respond","code":true},{"text":" in "},{"text":"ChatInterface","code":true},{"text":" against Ollama and open it on your phone using "},{"text":"server_name=\"0.0.0.0\"","code":true},{"text":" and your laptop’s IP. Add streaming. Then push the notes search as a Space with a "},{"text":"sentence-transformers","code":true},{"text":" model and send someone the link."}]}],"check":{"question":[{"text":"A learner runs "},{"text":"demo.launch(share=True)","code":true},{"text":", sends the printed "},{"text":"*.gradio.live","code":true},{"text":" link to a friend, and closes the laptop. The friend reports the link is dead. What happened?"}],"options":[{"text":[{"text":"Gradio share links are single-use and expire after the first person opens them."}],"correct":false,"tempting":[{"text":"Share links serve any number of visitors while they are alive; the limit is on lifetime, not visitors."}]},{"text":[{"text":"The friend’s browser blocked the link because Gradio serves over plain HTTP, which modern browsers refuse for external hosts."}],"correct":false,"tempting":[{"text":"Share links are served over HTTPS by the tunnel; browsers open them normally."}]},{"text":[{"text":"The tunnel only forwards traffic to the process on the laptop, so when the laptop slept the link had nothing behind it."}],"correct":true,"tempting":null},{"text":[{"text":"Gradio uploads the model and the code to its servers on "},{"text":"share=True","code":true},{"text":", and the upload was interrupted when the laptop closed, so the hosted copy was never completed."}],"correct":false,"tempting":[{"text":"Nothing is uploaded; the code and model stay on the laptop, and only requests are forwarded to it."}]}],"order":[0,1,3,2],"why":null},"prev":{"slug":"a-local-model-from-python","title":"A free model on your own machine, called from Python","minutes":9},"next":{"slug":"an-endpoint-with-fastapi","title":"An HTTP endpoint with FastAPI: your function, callable by any program","minutes":9}}}