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.

Start the interactive lessonRead the lesson below

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.

Workshop files

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

Start hereWorkshop files

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.

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

Files for this step

Start hereWorkshop files

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.

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.

Files for this step

Start hereWorkshop files

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.

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.

Files for this step

Start hereWorkshop files

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.

Was this lesson useful?

Leave a like, or share it with someone who could use it.

Continue learning

Explore the other lessons