We will start by generating the boilerplate and installing the required dependencies.
1. Create the Next.js Project Run this command to create a modern Next.js application
1npx create-next-app@latest2. Install AI SDK Dependencies Move into the directory and install the Vercel AI SDK (Beta v6) and Zod.
1cd my-ai-agent2pnpm add ai@beta @ai-sdk/react@beta zodyou can also do this in your Terminal within Visual Studio Code Insider
Create a file named chatbot-prd.md in the root of your project. You can copy the content below and paste it directly into the file. This document contains the context an Github Copilot needs to write the code for you.
1# Product Spec: Weather Agent Chatbot2
3## References 4
5Learn from the following links 6https://v6.ai-sdk.dev/docs/ai-sdk-ui/chatbot7https://v6.ai-sdk.dev/docs/ai-sdk-ui/overview8https://v6.ai-sdk.dev/docs/ai-sdk-ui/chatbot9https://v6.ai-sdk.dev/docs/ai-sdk-ui/chatbot-tool-usage10https://v6.ai-sdk.dev/docs/ai-sdk-ui/generative-user-interfaces11
12## 1. Overview13Build a "Weather Agent" chatbot using **Next.js 16+ (App Router)** and the **Vercel AI SDK 6 (Beta)**. The chatbot must be able to answer general questions and autonomously fetch weather data for specific locations using a server-side tool.14
15## 2. Tech Stack16- **Framework:** Next.js 22+ (App Router)17- **Language:** TypeScript18- **Package Manager:** pnpm19- **AI SDK Core:** `ai` (v6 beta) for server-side streaming and tool execution.20- **AI SDK UI:** `@ai-sdk/react` (v6 beta) for client-side chat state management.21- **Validation:** `zod` for defining tool schemas.22- **Styling:** Tailwind CSS.23
24## 3. Core Features25
26
27### A. Server-Side Logic (`app/api/chat/route.ts`)281. **Route Handler:** Create a POST endpoint using standard Next.js conventions.29
302. **Model Configuration:**31 - Use `anthropic/claude-sonnet-4.5` (or a similar compatible model string).32 - Use `streamText` from the `ai` package.333. **Tool Definition:**34 - Define a tool named `weather` inside `streamText`.35 - **Description:** "Get the weather in a location (Celcius)".36 - **Schema:** Use `zod` to define an object with a `location` (string) field.37 - **Execution:** Implement an async `execute` function that returns mock weather data (e.g., a random temperature).384. **Agentic Loop (Multi-Step Calls):**39 - **Requirement:** The model must be able to call the tool, receive the result, and *then* generate a final text answer in a single request loop.40 - **Implementation:** Set `stopWhen: stepCountIs(5)` in the `streamText` options. This allows up to 5 steps of tool-use reasoning.41
42### B. Client-Side UI (`app/page.tsx`)431. **State Management:** Use the `useChat` hook from `@ai-sdk/react`.442. **Rendering Message Parts:**45 - Do not just render `message.content`.46 - Iterate over `message.parts` to handle different content types.47 - **Text Parts:** Render standard text.48 - **Tool Invocation Parts:** Detect parts with type `tool-invocation` (or specific types like `tool-weather` if strict typing is enabled). Render a code block showing the tool usage (e.g., `JSON.stringify(part, null, 2)`).493. **User Input:** A simple form fixed at the bottom of the screen to submit text messages.50
51## 4. Environment Variables52- The app requires an API key.53- Variable Name: `AI_GATEWAY_API_KEY` (or `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` depending on the provider used).54- Load this from `.env.local`.55
56## 5. Success Criteria57- A user asks "What is the weather in Sydney?".58- The UI displays the tool call (JSON) showing the "Sydney" parameter.59- The UI immediately updates with the final answer: "The weather in Sydney is 35°C," derived from the tool's output.Here is how the architecture defined in your spec works:
If you prefer to build it manually instead of using the Spec with an AI builder, follow these steps.
Create an .env.local file in your project root:
1AI_GATEWAY_API_KEY=your_api_key_hereThis file handles the agent logic. We import stepCountIs to enable the multi-step loop.
1import { streamText, tool, convertToModelMessages, stepCountIs } from 'ai';2import { z } from 'zod';3
4export const maxDuration = 30;5
6export async function POST(req: Request) {7 const { messages } = await req.json();8
9 const result = streamText({10 model: 'anthropic/claude-sonnet-4.5', // or 'openai/gpt-4o'11 messages: convertToModelMessages(messages),12
13 // 1. Define the tools14 tools: {15 weather: tool({16 description: 'Get the weather in a location (fahrenheit)',17 inputSchema: z.object({18 location: z.string().describe('The location to get the weather for'),19 }),20 execute: async ({ location }) => {21 // Simulate API call22 const temperature = Math.round(Math.random() * (90 - 32) + 32);23 return { location, temperature };24 },25 }),26 },27
28 // 2. Enable Multi-Step Calls (The "Agent" Logic)29 // This allows the model to see the tool result and generate a follow-up answer.30 stopWhen: stepCountIs(5),31 });32
33 return result.toUIMessageStreamResponse();34}We use useChat and map over message.parts to display the conversation.
1'use client';2
3import { useChat } from '@ai-sdk/react';4import { useState } from 'react';5
6export default function Chat() {7 const { messages, sendMessage } = useChat();8 const [input, setInput] = useState('');9
10 return (11 <div className="flex flex-col w-full max-w-md py-24 mx-auto stretch">12 {messages.map(message => (13 <div key={message.id} className="whitespace-pre-wrap mb-4">14 <strong>{message.role === 'user' ? 'User: ' : 'AI: '}</strong>15
16 {/* Render specific parts of the message */}17 {message.parts.map((part, i) => {18 switch (part.type) {19 case 'text':20 return <span key={i}>{part.text}</span>;21
22 // Handle tool invocations specifically23 case 'tool-invocation':24 const toolName = part.toolInvocation.toolName;25 return (26 <div key={i} className="bg-gray-100 p-2 rounded mt-2 text-sm font-mono">27 Using tool: {toolName}28 <pre>{JSON.stringify(part.toolInvocation.args, null, 2)}</pre>29 </div>30 );31
32 default:33 return null;34 }35 })}36 </div>37 ))}38
39 <form40 className="fixed bottom-0 w-full max-w-md p-2 mb-8 bg-white border-t"41 onSubmit={e => {42 e.preventDefault();43 sendMessage({ text: input });44 setInput('');45 }}46 >47 <input48 className="w-full p-2 border border-gray-300 rounded shadow-xl"49 value={input}50 placeholder="Ask about the weather..."51 onChange={e => setInput(e.currentTarget.value)}52 />53 </form>54 </div>55 );56}You've successfully completed all 30 chapters of this course.
Hack me if you can! Your portfolio is no longer just a showcase of your achievements — it is now an active target. Every professional Web application backed by a database of users is a potential entry point for attackers, and the developers who succeed are those who can defend, monitor, and continuously harden their systems. Digital Twin III challenges you to transform your personal portfolio into a cyber-secured, intelligence-driven digital asset — one that not only looks impressive, but proves its resilience under real-world conditions. This is where your skills move beyond basic deployment. You will implement a secure content management system, protect private user data, integrate defensive controls like WAF and firewalls, and design visible countermeasures against threats such as: * SQL injection * Prompt injection * Authentication/authorization failures * Broken access control * Malicious payloads * Automated bot attacks Your portfolio becomes a live cyber lab — built to be tested, attacked, and improved through real telemetry. You will upload evidence of each security layer: logs, attack statistics, CVSS scoring, risk reports, penetration test results, remediation notes, and resilience patterns. Your Digital Twin doesn’t claim to be secure — it demonstrates it. By the end of this course, your public website will: * Host your professional identity & project content * Detect and block real cyber threats in real-time * Analyse attacker behaviours * Communicate your cyber maturity to employers * Show your ability to manage security as a lifecycle — not a checkbox This is your opportunity to build something professionally defensible — a deployable, auditable case study that proves you understand the realities of modern cyber security. Welcome to Digital Twin III — the version of you that cannot be exploited.
Digital Twin II is a hands-on, full-stack AI engineering project focused on turning you into a web-accessible and voice-accessible AI persona. The goal is to build a fully functional chat- or voice-enabled Digital Twin that lives on the web and can autonomously communicate with visitors — particularly recruiters, hiring managers, and potential collaborators — while reflecting your personality, skills, and professional brand. You will build a production-style application that: • Has a real frontend and user experience • Stores and tracks conversations and leads • Handles scheduling and CTAs (Call-To-Action actions) • Optionally supports phone calls and voice-driven interactions This course is specifically designed for developers who already possess: ✔Modern web development knowledge (React, Next.js, TypeScript) ✔ Experience with CRUD, authentication, and full-stack workflows ✔ Understanding of spec-driven development and GitHub workflows ✔ Familiarity with agentic coding tools (Copilot, Claude Opus 4.5+) If Digital Twin I defined the intelligence, Digital Twin II defines the presence.
This course centres on a live industry project where you design and deploy a "Digital Twin"—a personal AI agent capable of autonomously representing its creator in professional job interviews. By leveraging Retrieval-Augmented Generation (RAG) and the Model Context Protocol (MCP), you will build a system that can semantically search its own professional history to provide factual, context-aware answers to recruiters and hiring managers. You will move from theory to application by mastering the following technical domains: • RAG Architecture: Implementing semantic search using vector databases to ground AI responses in factual studies and professional experiences. • MCP Server Development: Building Model Context Protocol servers (using Next.js/TypeScript) to integrate local data with AI agents. • Data Pipeline Engineering: Annotating, enriching, and embedding professional profiles (JSON) into vector storage. • AI-Powered Workflow: Utilising VS Code Insiders and GitHub Copilot to drive development and simulate agentic behaviours. • Team Collaboration: Managing a software lifecycle using GitHub for version control (Pull Requests, branches) and ClickUp for project management