Meeting 4: Building a ChatGPT-Powered Chatbot for Canvas
Goals
- Understand how to use OpenAIβs API
- Create a Python wrapper for a chatbot
- Serve the chatbot with a Flask web app
- Add a simple browser UI for interaction
- Explore Canvas integration options
Codespace Setup
You can use this Codespace template to quickly set up your development environment.
Project Layout
canvas-chatbot/
βββ .env
βββ app.py
βββ chatbot.py
βββ requirements.txt
βββ templates/
β βββ index.html
βββ .devcontainer/
βββ devcontainer.json
Chatbot Wrapper (Python)
chatbot.py
:
import openai, os
= "You are a helpful teaching assistant for an Intro to Python course..."
system_prompt = os.getenv("OPENAI_API_KEY")
openai.api_key
def ask_chatbot(prompt, system_role=system_prompt):
= openai.ChatCompletion.create(
response ="gpt-4o",
model=[
messages"role": "system", "content": system_role},
{"role": "user", "content": prompt}
{
]
)return response['choices'][0]['message']['content']
Flask API + Web UI
app.py
:
from flask import Flask, request, jsonify, render_template
@app.route("/")
def home():
return render_template("index.html")
@app.route("/chat", methods=["POST"])
def chat():
= request.json.get("message", "")
user_input = ask_chatbot(user_input)
response return jsonify({"response": response})
Simple Web Interface
templates/index.html
:
<textarea id="question"></textarea>
<button onclick="askBot()">Ask</button>
<div id="response"></div>
<script>
async function askBot() {
const res = await fetch("/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: document.getElementById("question").value })
;
})const data = await res.json();
document.getElementById("response").innerText = data.response;
}</script>
Run & Test
Open in browser:
Ask questions like: - βHow do I print Hello World 100 times?β
Canvas Integration
Embed via iframe or page
You can embed this tool in a Canvas Page using an <iframe>
if hosted publicly. We will need to investigate the best method to do this or look at Canvas LTI integrations.
<iframe src="LINK" width="100%" height="500"></iframe>
π‘ Use Case Ideas
- Answer syllabus questions
- Give Canvas navigation help
- Explain assignment expectations
- Act as a Python tutor
Summary
You created a Codespaces-ready project for deployment or Canvas use.