AI Campus • Supporting resources

Build a local web app with an explicit tool API

Connect a real browser form to a Python API and an allowlisted tool before adding an AI agent.

Beginner · 60–120 minutes

Before you start

  • Python 3.10+ and a desktop browser.
  • A free local port, 8766 by default. Use fictional or non-sensitive text.

Cost: Python standard library only. Runs locally without API keys or cloud hosting.

Download a complete free starter

The ZIP includes the Python code, a README, sample files where needed, and a check you can run. No API key or paid service is needed for this baseline.

Download starter ZIP

Extract the ZIP, open its folder in a terminal and follow README.md. Start with python test_starter.py.

Step-by-step walkthrough

  1. 1. Save the starter

    Download tool_web_app.py and save it in a new project folder. No pip installation or API key is needed.

  2. 2. Run locally

    Run python tool_web_app.py. Open http://127.0.0.1:8766 in your browser; do not open the Python file itself in the browser.

  3. 3. Trace the full stack

    Choose Word count and submit “hello AI campus”. Expect words=3 and a trace naming count_words. Follow the fetch request in the browser Network panel and inspect the JSON response.

  4. 4. Test the failure states

    Submit empty text: expect an error. Change the action to First sentence: the output should identify a different tool. Only the two defined tools are allowed.

  5. 5. Add an agent deliberately

    Once the UI/API baseline works, optionally connect an explicitly local model or an official LangGraph template. Keep tool selection validated on the server and label model errors clearly.

  6. 6. Prepare a showcase

    Record a screen demo and commit the source and README. This loopback development server is not a production host; use a framework deployment guide before making a public service.

Complete code: tool_web_app.py

Download Python file
import argparse
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

HTML = """<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Local tool web app</title>
<main style="max-width:650px;margin:3rem auto;padding:1rem;font:18px system-ui"><h1>Local tool web app</h1><p>A deterministic tool baseline, without a model or API key.</p>
<form id="form"><label for="action">Tool</label><select id="action"><option value="count_words">Word count</option><option value="first_sentence">First sentence</option></select>
<p><label for="text">Your text</label><br><textarea id="text" required rows="6" style="width:100%"></textarea></p><button>Run tool</button></form><pre id="output" role="status" style="white-space:pre-wrap"></pre></main>
<script>document.querySelector('#form').addEventListener('submit',async event=>{event.preventDefault();const output=document.querySelector('#output');output.textContent='Running…';try{const response=await fetch('/api/run',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action:document.querySelector('#action').value,text:document.querySelector('#text').value})});output.textContent=JSON.stringify(await response.json(),null,2);}catch{output.textContent='Request failed. Check that the local Python server is running.';}});</script>"""

def run_tool(action, text):
    if not isinstance(text, str) or not text.strip() or len(text) > 2000:
        raise ValueError("Enter 1–2000 characters of text.")
    tools = {"count_words": lambda value: {"words": len(value.split())}, "first_sentence": lambda value: {"sentence": value.strip().split(".")[0]}}
    if action not in tools:
        raise ValueError("Choose an allowed tool.")
    return {"tool": action, "result": tools[action](text), "trace": ["validated input", action, "returned result"]}

class Handler(BaseHTTPRequestHandler):
    def reply(self, status, data):
        body = json.dumps(data).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)
    def do_GET(self):
        if self.path != "/":
            return self.reply(404, {"error": "Not found"})
        body = HTML.encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)
    def do_POST(self):
        if self.path != "/api/run":
            return self.reply(404, {"error": "Not found"})
        try:
            length = int(self.headers.get("Content-Length", "0"))
            if not 0 < length <= 8192:
                raise ValueError("Request must be 1–8192 bytes.")
            data = json.loads(self.rfile.read(length))
            if not isinstance(data, dict):
                raise ValueError("Send a JSON object.")
            return self.reply(200, run_tool(data.get("action"), data.get("text")))
        except (ValueError, TypeError, UnicodeError):
            return self.reply(400, {"error": "Check the JSON, allowed tool and non-empty text (up to 2000 characters)."})

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--port", type=int, default=8766)
    args = parser.parse_args()
    print(f"Open http://127.0.0.1:{args.port}", flush=True)
    try:
        ThreadingHTTPServer(("127.0.0.1", args.port), Handler).serve_forever()
    except KeyboardInterrupt:
        print("Server stopped.")

Run and verify

python tool_web_app.py
# Open http://127.0.0.1:8766 in your browser

A working form sends JSON to /api/run and displays the selected tool, result and trace. “hello AI campus” returns words=3.

Understand the limits

This is a deterministic UI/API/tool baseline, not an autonomous or LLM-powered agent. The development server is local only; production hosting, authentication and model access are separate extensions.

Official references

AI Campus Weekly Dispatch

Keep learning with AI Campus

Get AI news, tools, skills and opportunities in the weekly dispatch.

Get a welcome AI briefing and weekly Sunday updates. Unsubscribe anytime in 1 click.

Learn and build with BrandMint AI

Learning opportunities with BrandMint AI

Explore AI news, tools and skills on AI Campus. When you want to learn further, choose BrandMint AI courses, mentoring or learning apps below.

AI Campus guides are free. Check each platform for course fees and availability.

Courses and mentoring

Learn AI foundations or develop practical software skills.

Learning apps

Practise AI skills or explore CBSE learning support.

Marketing and filmmaking

Build a portfolio through creative and practical learning.

Essential cookies keep the site working. Language and subscription preferences stay on your device. We do not currently use optional analytics or advertising cookies.

Details and settings