
Mini lesson · English
How to add an AI chatbot to your website
Run a ready private chatbot with a coding assistant and test whether a follow-up uses the conversation and survives a failed request.
Who is this for?
People adding a conversational assistant to a small website. The project is supplied; you direct its behavior and test it rather than writing message-handling code.
Before you start
Your own Google AI Studio API access and the supplied separate server-function project. The API-key lesson explains private setup if needed. Confirm available model access, usage limits and possible charges first. Use synthetic messages and an owner-held practice code; authentication, durable usage limits and budget monitoring are needed before public use.
Estimated time: 20–32 min
Estimates for the supplied starter files with prerequisite accounts and tools ready. Setup, deployment queues and delivery/DNS waits take additional time. Real requests use your configured account quota. Public authentication, durable limits and privacy review are separate work.
What you will learn
- Run a first real AI reply.
- Check a follow-up that depends on the previous message.
- Keep a failed message available for retry.
Step 1
Choose a small conversation to test
The second message should depend on the first.
Open the ready chatbot project with your assistant. Choose a simple synthetic topic and a follow-up referring to its previous answer, so you can judge whether the conversation is carried forward.
An isolated good answer does not establish a working conversation. Plan to inspect both messages and the relationship between them.
A concrete example
Ask for a short explanation, then request a simpler version of that same explanation.
Use the supplied chatbot project and guide the private setup in run-locally.txt. Keep credentials and model instructions on the server. Help me ask an initial question, follow up about the same topic and test a failed request without losing the typed message. Do not rebuild the site or claim the conversation works from only the first answer.Files for this step
Open or download the files below. When saving a project, keep the folder paths shown in the filenames.
How it works (optional)
Add a chatbot that can continue a conversation
A useful chat integration must read the student's latest message and its context.
This lesson builds a small website tutor. A visitor can ask a question, read the answer and ask a follow-up. The browser sends the accepted conversation with each new message; the server calls Gemini and returns a genuine model response.
A model does not automatically remember your previous HTTP request. We keep a short in-memory history in this tab. Reload clears it, and the workshop stops after four successful exchanges to keep the practice bounded.
Worked example
Ask “What is DNS?” then “Explain that using a street-address example.” The second request needs both the earlier question and answer to establish what “that” means.
Extra implementation exercise
Why might a second-turn answer sound unrelated even when the API call succeeds?
Show a worked solution
The integration may have sent only a generic prompt or omitted history. Inspect the outgoing messages array and confirm it contains the previous accepted turns and the new question in order.
- Checks whether prior messages were included.
- Checks whether the latest user message was preserved.
Common mistake
Calling a sequence of unrelated canned responses a conversation.
Step 2
Start the supplied chatbot
Have the assistant handle private server configuration.
Follow run-locally.txt with your assistant. Confirm the account/model and usage terms, set private server values from server-env.example.txt, then open the app URL printed by the local proxy. Enter the separate practice code in the form, never the provider key. This setup is required; writing the server code is optional.
The provider key and governing instructions stay on the server. If your account/model is unavailable, report that exact stage rather than filling the page with a fake reply.
A concrete example
A website field should not let a visitor choose your private provider credentials.
Gemini generateContent API · Gemini API keys · Gemini: current model IDs and capabilities · Node.js: supported release status
Try it yourself
Did the running app produce a real first answer, or where did setup stop?
Discuss your answer with the lesson tutor
Show a worked solution
Illustrative first-call record: “The complete app opened at the proxy URL. I entered the separate practice code and received an explanation from the configured provider model. The Google key stayed in the private server environment.”
A blocked example is “The local page opened, but the server could not obtain a model reply.” Record the actual configuration/access/quota stage, and review account costs before retrying. A static file preview cannot establish a live reply.
- Identifies the local proxy app and an actual provider-backed first response or exact blocker.
- Separates the practice code from the private provider key and checks account/model usage limits.
Files for this step
Open or download the files below. When saving a project, keep the folder paths shown in the filenames.
How it works (optional)
Connect the browser to a bounded server function
Keep credentials and the tutor's role server-owned.
Deploy the supplied folders and configure the variables in START-HERE.txt. public/app.js posts user/assistant messages to your own mini-chat function. The function accepts only alternating roles, bounded text and a small history.
The server maps assistant to Gemini's model role and supplies a separate system instruction. A caller cannot choose a provider URL or replace that instruction with a client-supplied system role. The owner code restricts this lab; it does not replace public authentication and durable spending controls.
The generate function is a local helper inside netlify/functions/mini-chat.mjs, not another deployed service. To change the tutor's role for the assignment, edit the instruction string passed to generate in this server file. Setting a frontend .env variable is not an alternative: a value substituted into browser code becomes public.
For the complete local sequence, open run-locally.txt: prepare the private root environment, link only the practice project and start the Netlify function proxy. server-env.example.txt lists variable names without real secrets. Opening only the HTML cannot run the server.
Use the current model guide below, or run list-text-models.mjs from the private workshop root with your own environment. It lists account-visible generateContent candidates without printing the key. Choose a supported text model, check its terms/quota, then copy its exact API ID into the server GEMINI_MODEL setting.
Worked example
The history validator rejects an injected system-role message before calling the provider. It cannot make model output infallible, but it keeps the request shape and privileged configuration under your control.
Gemini generateContent API · Gemini API keys · Gemini: current model IDs and capabilities · Node.js: supported release status
Extra implementation exercise
Should the browser choose GEMINI_API_KEY or send a system message to override the tutor?
Show a worked solution
Neither. Configure the key and role on the server. Validate client roles and sizes; model responses still require evaluation for correctness.
- Keeps provider secrets on the server.
- Treats client messages as untrusted conversation input.
Common mistake
Trusting client-supplied roles because the normal UI does not expose them.
Step 3
Continue the conversation and try failure
Keep a typed message safe when the request fails.
Send the dependent follow-up and compare its answer with the earlier exchange. Ask your assistant to help simulate or reproduce one failed request in the disposable project.
The follow-up should remain about your conversation, and a failed send should preserve the draft and previous messages for retry.
A concrete example
A second-turn failure should not erase the question you just typed.
Try it yourself
What happened on the follow-up and on the failed-send/retry path?
Discuss your answer with the lesson tutor
Show a worked solution
Illustrative conversation record: “After the server explanation, my simpler-version request stayed about that explanation. I then deliberately used a wrong practice code for a send; the draft and earlier messages remained visible. Restoring the valid code let me retry.”
The wrong-code rejection is an intentional local test, not a provider outage. If the draft disappears or a successful turn is duplicated during retry, the conversation is not yet ready.
- Compares the follow-up answer with the previous exchange for topic continuity.
- Tests a clearly labeled failure and checks that the draft and earlier messages survive for retry.
Files for this step
Open or download the files below. When saving a project, keep the folder paths shown in the filenames.
How it works (optional)
Test continuation and failure
Make the second turn part of your completion test.
Ask the DNS example, then a follow-up referring to it. Inspect the request body in browser tools and compare the answer against the actual last question. A long fluent response is not evidence of relevance.
Try a wrong access code for the next submission. The draft stays in the textarea and no failed exchange is appended to accepted history. After correcting access, retry. Enter sends; Shift+Enter creates a new line. The button is disabled while waiting.
Worked example
A timeout or incomplete provider response yields a visible failure. The browser does not add an empty assistant message and pretend the conversation continued.
Extra implementation exercise
Your first answer is good but the second request fails. What should happen to the typed message and history?
Show a worked solution
Keep the draft and the previously accepted turns. Show the failure honestly, restore sending controls and append the new pair only after a valid answer arrives.
- Preserves the draft for retry.
- Does not record a fabricated assistant reply.
Common mistake
Testing only “hello” and declaring the whole conversation functional.
Step 4
Hand over the conversation behavior
Use several exchanges rather than one attractive answer.
Complete a three-exchange test with your synthetic topic and keep a redacted transcript. Repeat the failed-send recovery after any repair.
Check that retry does not lose a draft or duplicate a successful exchange. Record unavailable tests as not run. This example does not retrieve trusted website notes or guarantee factual answers; the next content-chatbot lesson adds a supplied source-and-check task.
A concrete example
Your evidence should show what the visitor asked, what came back and how a failed request recovered.
Try it yourself
Start with these materials
The starter files and test content are supplied. A live verification still requires your own permitted provider account, inbox or domain as listed under prerequisites. Local inspection is possible without them; record the live step as not tested until you actually perform it.
Provide the transcript and the actual failure/retry observation.
What to produce A short multi-turn transcript and an observed failure/retry result, with secrets removed.
Discuss your answer with the lesson tutor
Show a worked solution
Illustrative three-exchange outline: “1. Explain a website server. 2. Make that answer simpler. 3. Give one example of that server helping this site.” A completed record would include the actual replies beside those questions so their relationship can be judged.
Illustrative recovery note: “A deliberately rejected send kept its draft; retry added one successful exchange, not two.” Before public use, this owner-restricted example still needs authentication, durable usage controls and cost monitoring; it is not a source-grounded answer system.
- Includes three related exchanges and enough context to judge the replies.
- Records failed-send recovery without a lost draft or duplicated successful exchange.
Files for this step
Open or download the files below. When saving a project, keep the folder paths shown in the filenames.
How it works (optional)
Your assignment: make a tutor worth continuing
Evaluate relevance instead of merely counting successful requests.
Change the server instruction to a concise HTML/CSS tutor. Run three exchanges: ask about a broken anchor, propose an incorrect href/id pair and ask why it fails. Use synthetic code, not private source.
Keep a redacted transcript and annotate whether the answer addresses each latest message. Repeat one failed submission and demonstrate that retry keeps the conversation coherent. Before public access, plan actual authentication, persistent per-user quotas and an explanation of where messages are sent.
Worked example
A useful tutor says which href/id disagree. Generic advice about naming variables would miss the specific student answer, even if technically true.
The complete reference walkthrough is available in reference/assignment-walkthrough.txt. Compare its steps with your own result; fill the test record from observations in your own project.
Extra implementation exercise
Produce a three-exchange transcript and one failure/retry observation.
Show a worked solution
Edit the instruction string in the server function to a concise HTML/CSS tutor. Do not change a frontend variable or move generate into the public folder. The reference function is a complete version with the changed instruction.
Sample evaluation: user asks why <a href='#work'> fails to reach <section id='projects'>. A relevant response names that href/id mismatch. The next user proposes href='#projects'; a relevant follow-up checks that specific correction. Generic variable-naming advice would fail this test even if HTTP status is 200.
Submit with a wrong practice code on a later turn. The accepted conversation must stay intact and the textarea must keep the unsent draft. Correct access and retry; append a new user/assistant pair only after a valid reply. This sample transcript is an evaluation guide, not a claim of a live generated result.
- Follow-ups respond to the actual previous messages.
- Failure preserves draft/history and the provider key stays private.
Common mistake
Scoring an AI integration by HTTP success alone.
Was this lesson useful?
Leave a like, or share it with someone who could use it.
Continue learning
- How to build your first personal website
- How to publish your website from GitHub
- How to connect a custom domain to your website
- How to set up email on your own domain
- How to make your website usable on phones
- How to make website images load faster
- How to get website feedback in your inbox
- How to add email subscriptions to your website
- How to send automated emails from your website
- How to save form submissions in a database
- How to let people sign in to your website
- How to keep a page private
- How to let users edit their profile information
- How to let users upload images
- How to keep API keys out of your frontend
- How to show data from an external API on your website
- How to make a chatbot answer from your own content
- How to add a blog to your website
- How to add search to your website
- How to add another language to your website
- How to help Google find your website
- How to fix your website preview when sharing a link
- How to measure visits and useful actions on your website
- How to let visitors book an appointment
- How to accept a payment on your website
- How to preview website changes before publishing
- How to undo a broken website deployment
- How to back up and restore your website data
- How to find and fix errors on your live website