### Run the development server Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/README.md Start the development server to choose between different course sections. ```bash pnpm dev ``` -------------------------------- ### Stream output chunks Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/99-reference/99.02-defining-tools/explainer/readme.md Shows the sequence of stream chunks when running the example, including tool input start, delta, available, output available, and finish events. ```txt { type: 'start' } { type: 'start-step' } { type: 'tool-input-start', toolCallId: 'B1iGVK2Sa3b0JRzJ', toolName: 'logToConsole', dynamic: false } { type: 'tool-input-delta', toolCallId: 'B1iGVK2Sa3b0JRzJ', inputTextDelta: '{"message":"Hello, world!"}' } Hello, world! { type: 'tool-input-available', toolCallId: 'B1iGVK2Sa3b0JRzJ', toolName: 'logToConsole', input: { message: 'Hello, world!' } } { type: 'tool-output-available', toolCallId: 'B1iGVK2Sa3b0JRzJ', output: 'Message logged to console' } { type: 'finish-step' } { type: 'finish' } ``` -------------------------------- ### Copy environment file Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/README.md Copy the example environment file to create your own .env file for API keys. ```bash cp .env.example .env ``` -------------------------------- ### Install dependencies with pnpm Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/README.md Install project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Basic ToolLoopAgent setup Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/plans/03.0x-tool-loop-agent-notes.md Creates a ToolLoopAgent with a model and a string instruction. Uses 'instructions' instead of 'system'. ```typescript import { ToolLoopAgent } from 'ai'; const agent = new ToolLoopAgent({ model: "anthropic/claude-sonnet-4.5", instructions: 'You are an expert software engineer.', }); ``` -------------------------------- ### Example query for testing Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/09-advanced-patterns/09.04-research-workflow/problem/readme.md An example query string used to test the implementation. It asks for a detailed comparison of gas, electric, or induction hobs. ```tsx const [input, setInput] = useState( `Which are better? Gas, electric, or induction hobs? Please provide a detailed answer.`, ); ``` -------------------------------- ### Write start message manually via writer.write Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/08-agents-and-workflows/08.02-streaming-custom-data-to-the-frontend/problem/readme.md Placeholder for writing a { type: 'start' } message manually using writer.write, as referenced by the TODO at the top of the execute function. ```typescript // TODO: write a { type: 'start' } message via writer.write TODO; ``` -------------------------------- ### Example UIMessageStream output objects Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/01-ai-sdk-basics/01.07-ui-message-streams/explainer/readme.md Shows the sequence of objects streamed by toUIMessageStream(), including start, start-step, text-start, text-delta, text-end, finish-step, and finish. The deltas contain the incremental text chunks. ```txt { type: 'start' } { type: 'start-step' } { type: 'text-start', id: '0' } { type: 'text-delta', id: '0', delta: 'A' } { type: 'text-delta', id: '0', delta: ' feline friend,' } // ... more deltas ... { type: 'text-end', id: '0' } { type: 'finish-step' } { type: 'finish' } ``` -------------------------------- ### Evalite basic setup with title 'Capitals' Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/06-evals/06.01-evalite-basics/problem/readme.md Initializes an Evalite eval with the title 'Capitals'. This is the starting point for defining an eval. ```typescript import { evalite } from 'evalite'; evalite('Capitals', { // Configuration goes here }); ``` -------------------------------- ### Status sequence example (Loading, Searching, Scraping, Summarizing) Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/99-reference/99.06-custom-data-parts-id-reconciliation/explainer/readme.md Shows the sequence of statuses that should be displayed as a single changing status rather than four separate elements. ```txt Loading... Searching the web... Scraping some pages... Summarizing... ``` -------------------------------- ### Run with simple mode for troubleshooting Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/01-ai-sdk-basics/01.02-how-to-take-this-course/explainer/readme.md Runs the exercise runner in a more robust mode, useful on unusual operating systems. Recommended if you encounter setup issues. ```bash pnpm dev --simple ``` -------------------------------- ### Example of creating a tool with AI SDK Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/03-agents/03.01-tool-calling/problem/readme.md Shows the structure for creating a tool using the tool function from 'ai' and zod for input schema. Includes description, inputSchema, and execute function. ```TypeScript // Example of creating a tool import { tool } from 'ai'; import { z } from 'zod'; // This is just an example of the tool structure const exampleTool = tool({ description: 'Description of what the tool does', inputSchema: z.object({ param1: z.string().describe('Description of parameter 1'), param2: z.number().describe('Description of parameter 2'), }), execute: async ({ param1, param2 }) => { // Implementation that uses the parameters return { result: 'some result' }; }, }); ``` -------------------------------- ### Example stream output with messageMetadata Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/99-reference/99.07-message-metadata/explainer/readme.md Shows the expected console output when logging the stream chunks, including the finish chunk with messageMetadata length 39. ```text { type: 'start' } { type: 'start-step' } { type: 'text-start', id: '0' } { type: 'text-delta', id: '0', delta: 'Hello' } { type: 'text-delta', id: '0', delta: ' there! How can I help you today?\n' } { type: 'text-end', id: '0' } { type: 'finish-step' } { type: 'finish', messageMetadata: { length: 39 } } ``` -------------------------------- ### Console output while generating answer Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/05-context-engineering/05.05-chain-of-thought/problem/readme.md Output shown when running the example: it prints 'Generating answer' followed by dots while the LLM generates the answer, then writes to an output.md file. ```txt Generating answer .................... ``` -------------------------------- ### Tool input start event Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/03-agents/03.02-message-parts/explainer/readme.md Shows the structure of a tool-input-start event, indicating the tool call ID and tool name. ```typescript { type: 'tool-input-start', toolCallId: 'mjDMqVhIzJMwcC22', toolName: 'writeFile', providerExecuted: undefined } ``` -------------------------------- ### Instantiate a model with openai() Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/01-ai-sdk-basics/01.04-choosing-your-model/explainer/readme.md Creates a model instance by calling the imported provider function with a model ID. The example uses 'gpt-4o-mini' and logs the model object to inspect its structure. ```TypeScript const model = openai('gpt-4o-mini'); console.dir(model, { depth: null }); ``` -------------------------------- ### Instructions array with system role Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/03-agents/03.04-tool-loop-agent/explainer/readme.md The 'instructions' parameter accepts an array of message parts, allowing structured system prompts with different roles. This example shows a system role message. ```TypeScript instructions: [ { role: 'system', content: 'You are a helpful assistant...', }, ], ``` -------------------------------- ### Configure first paragraph toUIMessageStream Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/99-reference/99.09-start-and-finish-parts/explainer/readme.md For the first paragraph, both sendStart and sendFinish are commented out to avoid sending start and finish parts, as the stream has already started and more content follows. ```TypeScript writer.merge( firstParagraphResult.toUIMessageStream({ // TODO: Try uncommenting these and see what happens // sendStart: false, // sendFinish: false, }), ); ``` -------------------------------- ### ModelMessage output example Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/99-reference/99.01-ui-messages-vs-model-messages/explainer/readme.md Shows the resulting ModelMessage array after conversion. Each message has role and content array, without IDs. ```TypeScript [ { role: 'user', content: [ { type: 'text', text: 'What is the capital of France?' }, ], }, { role: 'assistant', content: [ { type: 'text', text: 'The capital of France is Paris.' }, ], }, ]; ``` -------------------------------- ### useChat hook setup Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/plans/tool-approval-notes.md Configures the `useChat` hook with `sendAutomaticallyWhen` set to `lastAssistantMessageIsCompleteWithApprovalResponses` to automatically send messages when approval responses are complete. ```TypeScript import { useChat } from '@ai-sdk/react'; import { lastAssistantMessageIsCompleteWithApprovalResponses } from 'ai'; const { messages, addToolApprovalResponse } = useChat({ sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses, }); ``` -------------------------------- ### Data setup for Capitals evaluation Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/06-evals/06.02-deterministic-eval/problem/readme.md Defines a list of TypeScript release links and an evalite data function with two inputs asking about TypeScript 5.8 and 5.2 releases. This is the data used for the evaluation. ```typescript const links = [ { title: 'TypeScript 5.8', url: 'https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-8.html', }, // more links... ]; evalite('Capitals', { data: () => [ { input: 'Tell me about the TypeScript 5.8 release', }, { input: 'Tell me about the TypeScript 5.2 release', }, ], // ... }); ``` -------------------------------- ### Setup with two streamText calls using different models Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/09-advanced-patterns/09.03-comparing-multiple-outputs/problem/readme.md Creates a UI message stream with two streamText calls, each using a different Google model (gemini-2.5-flash-lite and gemini-2.5-flash) but the same messages. The TODO indicates using Promise.all to call streamModelText for each model. ```typescript const stream = createUIMessageStream({ execute: async ({ writer }) => { const firstStreamResult = streamText({ model: google('gemini-2.5-flash-lite'), messages: modelMessages, }); const secondStreamResult = streamText({ model: google('gemini-2.5-flash'), messages: modelMessages, }); // TODO: Using Promise.all, call streamModelText for each model // and pass in the appropriate model await Promise.all(TODO); }, }); ``` -------------------------------- ### Configure createMCPClient with HTTP transport Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/03-agents/03.06-mcp-via-http/explainer/readme.md Replace the transport property in createMCPClient to use HTTP. Set type to 'http', provide the remote server URL, and include authentication headers. This avoids running local code and simplifies setup. ```typescript import { experimental_createMCPClient as createMCPClient } from '@ai-sdk/mcp'; const mcpClient = await createMCPClient({ transport: { type: 'http', url: 'https://api.githubcopilot.com/mcp', headers: { Authorization: `Bearer ${process.env.GITHUB_PERSONAL_ACCESS_TOKEN}`, }, }, }); ``` -------------------------------- ### Implement onFinish callback to close MCP client Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/03-agents/03.05-mcp-via-stdio/problem/readme.md Placeholder for the onFinish callback where mcpClient.close() should be called to shut down the MCP server started by StdioMCPTransport. ```TypeScript onFinish: async () => { // Close the MCP client }, ``` -------------------------------- ### TypeScript: MORE_REALISTIC_TEMPLATE with career guidance context Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/05-context-engineering/05.01-the-template/explainer/readme.md The template is a realistic prompt for an AI career coach, reducing XML tags while achieving the same goals as the simpler template. It includes a career guidance document in a tag and mentions more sections follow. The template leverages the LLM's bias to position critical instructions at the end. ```typescript export const MORE_REALISTIC_TEMPLATE = (opts: { careerGuidanceDocument: string; conversationHistory: string; latestQuestion: string; }) => ` You will be acting as an AI career coach named Joe created by the company AdAstra Careers. Your goal is to give career advice to users. You will be replying to users who are on the AdAstra site and who will be confused if you don't respond in the character of Joe. You should maintain a friendly customer service tone. Here is the career guidance document you should reference when answering the user: ${opts.careerGuidanceDocument} // More sections follow... `; ``` -------------------------------- ### MyUIMessage with mixed parts (JSON blob example) Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/04-persistence/04.04-persistence-in-a-normalized-db/explainer/readme.md Shows a message object containing text, reasoning, and tool-getWeatherInformation parts. Used to illustrate the complexity of storing heterogeneous parts as a JSON blob in Postgres. ```typescript const message: MyUIMessage = { id: '123', role: 'user', parts: [ { type: 'text', text: 'Hello!', }, { type: 'reasoning', text: 'I am thinking...', }, { type: 'tool-getWeatherInformation', state: 'output-available', toolCallId: '123', input: { city: 'London', }, output: { city: 'London', weather: 'sunny', }, }, ], }; ``` -------------------------------- ### Configure second paragraph toUIMessageStream Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/99-reference/99.09-start-and-finish-parts/explainer/readme.md For the second paragraph, both sendStart and sendFinish are commented out to avoid sending start and finish parts, as the stream continues. ```TypeScript writer.merge( secondParagraphResult.toUIMessageStream({ // TODO: Try uncommenting these and see what happens // sendStart: false, // sendFinish: false, }), ); ``` -------------------------------- ### UIMessage array example Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/99-reference/99.01-ui-messages-vs-model-messages/explainer/readme.md Shows the structure of UIMessage with role, id, and parts array containing text parts. This is the format used for UI display and database persistence. ```TypeScript const messages: UIMessage[] = [ { role: 'user', id: '1', parts: [ { type: 'text', text: 'What is the capital of France?', }, ], }, // ... ``` -------------------------------- ### TypeScript: Define exemplars and streamText prompt with TODO Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/05-context-engineering/05.03-exemplars/problem/readme.md Defines an array of exemplar objects with input and expected fields, then calls `streamText` with a prompt containing a TODO comment to be replaced with XML-formatted exemplars. The prompt includes task context, rules, conversation history, ask, and output format. The TODO is intended to be replaced with `` tags containing `` and `` elements. ```typescript const exemplars = [ { input: `What's the difference between TypeScript and JavaScript? Should I learn TypeScript first or JavaScript?`, expected: 'TypeScript vs JavaScript Comparison', }, { input: `I want to start investing but I'm a complete beginner. What are the safest options for someone with $5000 to invest?`, expected: 'Beginner Investment Options', }, ]; const result = await streamText({ model: google('gemini-2.5-flash-lite'), prompt: ` You are a helpful assistant that can generate titles for conversations. Find the most concise title that captures the essence of the conversation. Titles should be at most 30 characters. Titles should be formatted in sentence case, with capital letters at the start of each word. Do not provide a period at the end. ${TODO /* TODO: Add the exemplars here, formatted with XML */} ${INPUT} Generate a title for the conversation. Return only the title. `, }); ``` -------------------------------- ### Baseline generateText call with google('gemini-2.5-flash-lite') Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/06-evals/06.05-chat-title-generation/problem/readme.md Initial prompt that generates a title from an input using the Gemini model. Used as a starting point for improvement. ```typescript const result = await generateText({ model: google('gemini-2.5-flash-lite'), prompt: ` Generate me a title: ${input} `, }); ``` -------------------------------- ### Example of final UIMessage parts array Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/03-agents/03.02-message-parts/explainer/readme.md Shows the final `UIMessage` structure with a `parts` array containing step-start, tool-writeFile, and text parts. The tool-writeFile part includes input and output for writing a file, and the text part contains the final response. ```typescript [ { id: '', metadata: undefined, role: 'assistant', parts: [ { type: 'step-start' }, { type: 'tool-writeFile', toolCallId: 'mjDMqVhIzJMwcC22', state: 'output-available', input: { path: 'pirate.md', content: '...', // The pirate poem content }, output: { success: true, message: 'File written successfully: pirate.md', path: 'pirate.md', }, // Other properties }, { type: 'step-start' }, { type: 'text', text: "I've written a poem about a pirate and saved it to a file named `pirate.md`.", state: 'done', }, ], }, ]; ``` -------------------------------- ### streamText with onFinish logging response.messages Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/04-persistence/04.01-on-finish/explainer/readme.md Shows the POST route setup using streamText with an onFinish callback that logs response.messages. This callback provides model messages (AssistantModelMessage or ToolModelMessage) which are not suitable for persisting UI data. ```typescript export const POST = async (req: Request): Promise => { const body: { messages: UIMessage[] } = await req.json(); const { messages } = body; const result = streamText({ model: google('gemini-2.5-flash'), messages: await convertToModelMessages(messages), onFinish: ({ response }) => { console.log('streamText.onFinish'); console.log(' response.messages'); console.dir(response.messages, { depth: null }); }, }); // More code... }; ``` -------------------------------- ### Call generateText to get the result Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/01-ai-sdk-basics/01.05-generating-text/problem/readme.md The TODO is to be replaced with await generateText({ model, prompt }) to obtain the result. ```TypeScript const result = TODO; // TODO: Use generateText to get the result ``` -------------------------------- ### IIMT with keyof SomeObject (repeated) Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/05-context-engineering/05.05-chain-of-thought/problem/iimt-article.md Repeats the IIMT example to illustrate the immediate indexing step. The mapped type is indexed with keyof SomeObject to produce a union of values. ```typescript /** * | { * key: 'a'; * } * | { * key: 'b'; * } */ export type Example = { [K in keyof SomeObject]: { key: K; }; }[keyof SomeObject]; ``` -------------------------------- ### Define structured output with Output.object and Zod schema Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/01-ai-sdk-basics/01.11-generating-objects-via-output/problem/readme.md Shows the output configuration for generateText: Output.object with a schema containing a facts array of strings, each described to guide the model. This is the spoiler solution for the structured output step. ```ts output: Output.object({ schema: z.object({ facts: z .array(z.string()) .describe( 'The facts about the imaginary planet. Write as if you are a scientist.', ), }), }); ``` -------------------------------- ### Configure third paragraph toUIMessageStream Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/99-reference/99.09-start-and-finish-parts/explainer/readme.md For the third paragraph, only sendStart is commented out to avoid sending a start part, but a finish part is desired at the end. ```TypeScript writer.merge( thirdParagraphResult.toUIMessageStream({ // TODO: Try uncommenting these and see what happens // sendStart: false, }), ); ``` -------------------------------- ### Example request payload with auto-generated ID Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/04-persistence/04.02-pass-chat-id-to-the-api/problem/readme.md Shows the structure of the request payload sent by the AI SDK, which includes an auto-generated UUID in the 'id' field. ```ts // Example request payload { messages: [...], id: "some-uuid-here" } ``` -------------------------------- ### streamText with for-await loop to consume stream (onFinish called) Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/99-reference/99.03-consume-stream/explainer.1/readme.md This example processes each chunk of the stream using a for-await loop over textStream. Consuming the stream ensures the onFinish callback is invoked, and the output includes the streamed response. ```TypeScript import { google } from '@ai-sdk/google'; import { streamText } from 'ai'; console.log('Process starting...'); const streamTextResult = streamText({ model: google('gemini-2.5-flash'), prompt: 'Hello, world!', onFinish: () => { console.log('Stream finished!'); }, }); // Process each chunk of the stream for await (const chunk of streamTextResult.textStream) { process.stdout.write(chunk); } console.log('Process exiting...'); ``` -------------------------------- ### Generate follow-up suggestion with streamText Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/07-streaming/07.01-custom-data-parts/problem/readme.md Calls `streamText` again to get a follow-up suggestion, using the model `google('gemini-2.5-flash')` and including the previous assistant response and a user prompt asking for the next question. ```TypeScript const followupSuggestionsResult = streamText({ model: google('gemini-2.5-flash'), messages: [ ...modelMessages, { role: 'assistant', content: await streamTextResult.text, }, { role: 'user', content: 'What question should I ask next? Return only the question text.', }, ], }); ``` -------------------------------- ### Calculate cached and uncached tokens Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/02-llm-fundamentals/02.05-prompt-caching/explainer.1/readme.md Logic that matches the prompt caching behavior: it counts matching tokens from the start, then splits the input into cached and uncached tokens and decodes them to text. ```TypeScript let numberOfMatchingTokens = 0; for (let i = 0; i < inputTokens.length; i++) { if (inputTokens[i] === tokensInCache[i]) { numberOfMatchingTokens++; } else { break; } } // The cached and uncached tokens const cachedTokens = tokensInCache.slice( 0, numberOfMatchingTokens, ); const uncachedTokens = inputTokens.slice(numberOfMatchingTokens); // The cached and uncached output text const cachedText = tokenizer.decode(cachedTokens); const uncachedText = tokenizer.decode(uncachedTokens); ``` -------------------------------- ### Uncomment start part writer.write Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/99-reference/99.09-start-and-finish-parts/explainer/readme.md Uncomment the writer.write call with type 'start' to ensure the stream starts correctly and prevents duplicate messages. This is the only change needed to fix the double message error. ```TypeScript // TODO: Try uncommenting this and see what happens // writer.write({ // type: 'start', // }); ``` -------------------------------- ### Clone the repository Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/README.md Clone the AI SDK v6 Crash Course repository and navigate into the project directory. ```bash git clone https://github.com/ai-hero-dev/ai-sdk-v6-crash-course.git cd ai-sdk-v6-crash-course ``` -------------------------------- ### Set up StdioMCPTransport for GitHub MCP server Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/03-agents/03.05-mcp-via-stdio/problem/readme.md Configures the transport to run the GitHub MCP server via Docker, passing the GITHUB_PERSONAL_ACCESS_TOKEN environment variable. Requires Docker Desktop and a GitHub personal access token in .env. ```TypeScript const myTransport = new StdioMCPTransport({ command: 'docker', args: [ 'run', '-i', '--rm', '-e', 'GITHUB_PERSONAL_ACCESS_TOKEN', 'ghcr.io/github/github-mcp-server', ], env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_PERSONAL_ACCESS_TOKEN!, }, }); ``` -------------------------------- ### streamText with tools and prompt Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/99-reference/99.02-defining-tools/explainer/readme.md Sets up a `streamText` call with a Google Gemini model and a prompt asking to log a message. The `tools` object is defined inline but can be moved to a separate file. ```ts const result = streamText({ model: google('gemini-2.5-flash'), prompt: 'Log the message "Hello, world!" to the console', tools: { // ...explained below }, }); ``` -------------------------------- ### Configure experimental_telemetry for AI SDK calls Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/06-evals/06.07-langfuse-basics/problem/readme.md Replace the experimental_telemetry TODO with an object that enables telemetry, sets a functionId, and includes metadata linking to the LangFuse trace ID. The functionId should describe the action being performed. ```ts // Replace this: experimental_telemetry: TODO, // With something like: experimental_telemetry: { isEnabled: true, functionId: 'your-name-here', metadata: { langfuseTraceId: trace.id, }, }, ``` -------------------------------- ### Import dependencies and define test cases Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/05-context-engineering/05.04-retrieval/problem/readme.md Imports Google AI SDK, AI SDK streamText, and Tavily core. Defines an array of test cases with questions and URLs to scrape. ```typescript import { google } from '@ai-sdk/google'; import { streamText } from 'ai'; import { tavily } from '@tavily/core'; const testCases = [ { input: 'What did Guillermo Rauch say about Matt Pocock?', url: 'https://www.aihero.dev/', }, { input: "What is Matt Pocock's open source background?", url: 'https://www.aihero.dev/', }, { input: 'Why is learning TypeScript important?', url: 'https://totaltypescript.com/', }, ] as const; ``` -------------------------------- ### Run a specific exercise Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/README.md Jump to a specific exercise by providing its number. ```bash pnpm exercise ``` -------------------------------- ### Wrap language model with devToolsMiddleware Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/01-ai-sdk-basics/01.13-devtools-basics/explainer/readme.md Imports google, devToolsMiddleware, and wrapLanguageModel, then wraps the gemini-2.5-flash model with the middleware to enable DevTools inspection. ```ts import { google } from '@ai-sdk/google'; import { devToolsMiddleware } from '@ai-sdk/devtools'; import { wrapLanguageModel } from 'ai'; const model = wrapLanguageModel({ model: google('gemini-2.5-flash'), middleware: devToolsMiddleware(), }); ``` -------------------------------- ### Stream text with Google model using streamText Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/01-ai-sdk-basics/01.06-stream-text-to-terminal/problem/readme.md Sets up a Google Gemini model and streams a story prompt to the terminal. Replace the TODO with streamText({ model, prompt }) to create the stream, then iterate over stream.textStream with a for await loop to write each chunk to stdout. ```ts import { google } from '@ai-sdk/google'; import { streamText } from 'ai'; const model = google('gemini-2.5-flash'); const prompt = 'Give me the first paragraph of a story about an imaginary planet.'; const stream = TODO; // TODO - stream some text with the model above. for await (const chunk of stream.textStream) { process.stdout.write(chunk); } ``` -------------------------------- ### GET handler for /api/chat Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/04-persistence/04.03-persistence/problem/readme.md Fetches a chat by chatId from the query parameters. Returns a 400 error if chatId is missing, otherwise returns the chat as JSON. ```TypeScript export const GET = async (req: Request): Promise => { const url = new URL(req.url); const chatId = url.searchParams.get('chatId'); if (!chatId) { return new Response('No chatId provided', { status: 400 }); } const chat = await getChat(chatId); return new Response(JSON.stringify(chat), { headers: { 'Content-Type': 'application/json', }, }); }; ``` -------------------------------- ### Get addToolApprovalResponse from useChat in client/root.tsx Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/03-agents/03.07-tool-approval/problem/readme.md Shows the useChat hook destructuring messages, sendMessage, and addToolApprovalResponse, with TODOs to add the sendAutomaticallyWhen option using lastAssistantMessageIsCompleteWithApprovalResponses. ```typescript const { messages, sendMessage, addToolApprovalResponse } = useChat({ // TODO: Get addToolApprovalResponse from useChat // TODO: Add sendAutomaticallyWhen option using // lastAssistantMessageIsCompleteWithApprovalResponses }); ``` -------------------------------- ### Extract chatId from search params using useSearchParams Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/04-persistence/04.02-pass-chat-id-to-the-api/problem/readme.md Uses React Router's useSearchParams hook to get the chatId from the URL and log it to the console. ```tsx // Inside client/root.tsx import { useSearchParams } from 'react-router'; const App = () => { const [searchParams, setSearchParams] = useSearchParams(); console.log(searchParams.get('chatId')); // Rest of component... }; ``` -------------------------------- ### Import dependencies in chat.ts Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/03-agents/03.01-tool-calling/problem/readme.md Import the required dependencies for the tool-calling exercise: tool and stepCountIs from 'ai', z from 'zod', and file system tools from './file-system-functionality.ts'. ```TypeScript import { tool, stepCountIs } from 'ai'; import { z } from 'zod'; import * as fsTools from './file-system-functionality.ts'; ``` -------------------------------- ### Define a Basic Object Type Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/05-context-engineering/05.05-chain-of-thought/solution/output.md Demonstrates the syntax for defining a simple object type with specific property types. ```typescript type MyObjectType = { name: string; age: number; }; ``` -------------------------------- ### Implement messageMetadata function in toUIMessageStreamResponse Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/07-streaming/07.03-message-metadata/problem/readme.md Capture start time with Date.now() and implement messageMetadata callback to return duration when encountering a 'finish' part. The callback is called on every text part. ```typescript // TODO: Calculate the start time of the stream const startTime = TODO; return result.toUIMessageStreamResponse({ // TODO: Add the messageMetadata function here // If it encounters a 'finish' part, it should return the duration // of the stream in milliseconds messageMetadata: TODO, }); ``` -------------------------------- ### Simulate caching in a conversation Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/02-llm-fundamentals/02.05-prompt-caching/explainer.1/readme.md Sets up a conversation format for the cache and input tokens. The cache contains a user and assistant message, and the input adds a new user question. This shows how previous conversation turns are cached. ```TypeScript const tokensInCache = tokenize( // NOTE: Change this to change what's in the cache [ 'User: What is the capital of France?', 'Assistant: Paris', ].join('\n'), ); const inputTokens = tokenize( // NOTE: Change this to change what the input is [ 'User: What is the capital of France?', 'Assistant: Paris', 'User: What is the capital of Germany?', ].join('\n'), ); ``` -------------------------------- ### Import AI SDK model providers Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/01-ai-sdk-basics/01.04-choosing-your-model/explainer/readme.md Imports the OpenAI, Google, and Anthropic providers from their respective packages. Each import requires a corresponding environment variable to be set in the .env file. ```TypeScript // Requires an OPENAI_API_KEY environment variable in .env import { openai } from '@ai-sdk/openai'; // Requires a GOOGLE_GENERATIVE_AI_API_KEY environment variable in .env import { google } from '@ai-sdk/google'; // Requires an ANTHROPIC_API_KEY environment variable in .env import { anthropic } from '@ai-sdk/anthropic'; ``` -------------------------------- ### Import and instantiate Google Gemini model Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/01-ai-sdk-basics/01.05-generating-text/problem/readme.md Imports the google function from @ai-sdk/google and generateText from ai. The TODO is to be replaced with google('gemini-2.5-flash') to choose the model. ```TypeScript // Import the necessary functions import { google } from '@ai-sdk/google'; import { generateText } from 'ai'; // TODO: Choose a model. I recommend using the Google Gemini model: // gemini-2.5-flash const model = TODO; ``` -------------------------------- ### Merge final Slack attempt into writer with sendStart: false Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/08-agents-and-workflows/08.02-streaming-custom-data-to-the-frontend/problem/readme.md The finalSlackAttempt is a streamText call that needs to be merged into the writer. Pass sendStart: false to avoid sending the start part again, as the message has already begun. ```typescript const finalSlackAttempt = streamText({ model: google('gemini-2.5-flash'), system: WRITE_SLACK_MESSAGE_FINAL_SYSTEM, prompt: ` Conversation history: ${formatMessageHistory(messages)} First draft: ${writeSlackResult.text} Previous feedback: ${evaluateSlackResult.text} `, }); // TODO: merge the final slack attempt into the stream, // sending sendStart: false writer.TODO; ``` -------------------------------- ### streamText without consuming the stream (onFinish not called) Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/99-reference/99.03-consume-stream/explainer.1/readme.md This example calls streamText with an onFinish callback but does not consume the stream. As a result, the callback is never invoked, and the process exits without logging 'Stream finished!'. ```TypeScript import { google } from '@ai-sdk/google'; import { streamText } from 'ai'; console.log('Process starting...'); const streamTextResult = streamText({ model: google('gemini-2.5-flash'), prompt: 'Hello, world!', onFinish: () => { console.log('Stream finished!'); }, }); // No consumption of the stream here console.log('Process exiting...'); ``` -------------------------------- ### streamText with Gemini for TypeScript explanation Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/05-context-engineering/05.05-chain-of-thought/problem/readme.md Uses the AI SDK's streamText with Google's gemini-2.5-flash-lite model to generate an explanation of complex TypeScript code. The prompt includes task context, background data with the code and an article, rules, and the ask. The result is streamed and eventually written to an output.md file. ```typescript const result = streamText({ model: google('gemini-2.5-flash-lite'), prompt: ` You are a helpful TypeScript expert that can explain complex TypeScript code for beginner TypeScript developers. You will be given a complex TypeScript code and you will need to explain it in a way that is easy to understand. Here is the complex TypeScript code: ${COMPLEX_TS_CODE} And here is an article about the IIMT pattern:
${IIMT_ARTICLE}
- Do not let the user know that you are using the article as a reference. Refer to the concepts as if you are an expert. - Use section headers to organize the explanation. Explain the code, using the article as a reference. `, }); ``` -------------------------------- ### Simulate prompt caching with tokenized input Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/02-llm-fundamentals/02.05-prompt-caching/explainer.1/readme.md Defines the tokens in cache and the input tokens for the playground. The input tokens include the cached text plus additional text. Change the input to see how caching changes. ```TypeScript const tokensInCache = tokenize( `The quick brown fox jumps over the lazy dog`, ); const inputTokens = tokenize( // NOTE: Change this to change what the input is `The quick brown fox jumps over the lazy dog. What a brilliant story.`, ); ``` -------------------------------- ### Frontend: useChat hook in App component (client/root.tsx) Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/01-ai-sdk-basics/01.08-stream-text-to-ui/problem/readme.md Use the useChat hook from @ai-sdk/react to get messages and sendMessage. Replace the TODO with useChat({}). Complete the onSubmit handler to call sendMessage with the input text. ```tsx import { useChat } from '@ai-sdk/react'; const App = () => { // TODO: use the useChat hook to get the messages and sendMessage function const { messages, sendMessage } = TODO; const [input, setInput] = useState( `What's the capital of France?`, ); return ( {messages.map((message) => ( ))} setInput(e.target.value)} onSubmit={(e) => { e.preventDefault(); // TODO: send the message }} /> ); }; ``` -------------------------------- ### Define logToConsole tool with Zod inputSchema Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/99-reference/99.02-defining-tools/explainer/readme.md Defines a `logToConsole` tool using the `tool` function. The `inputSchema` uses Zod to describe a `message` string property, which is validated against LLM output. ```ts tools: { logToConsole: tool({ description: 'Log a message to the console', inputSchema: z.object({ message: z .string() .describe('The message to log to the console'), }), // execute function will go here }), } ``` -------------------------------- ### displayQueriesInFrontend - Stream queries and plan to frontend Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/09-advanced-patterns/09.04-research-workflow/problem/readme.md Implement this function to stream partial objects from the queriesResult to the frontend using the writer. The function is async and uses a for-await loop over queriesResult.partialObjectStream. The TODO placeholder indicates where to add the streaming logic. ```TypeScript const displayQueriesInFrontend = async ( queriesResult: ReturnType, writer: UIMessageStreamWriter, ) => { const queriesPartId = crypto.randomUUID(); const planPartId = crypto.randomUUID(); for await (const part of queriesResult.partialObjectStream) { // TODO: Stream the queries and plan to the frontend TODO; } }; ``` -------------------------------- ### Course modules directory structure Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/README.md Shows the directory layout of the exercises folder, including the main modules and subfolders. ```text exercises/ ├── 01-basics/ # AI SDK v6 fundamentals │ ├── 01.1-what-is-the-ai-sdk/ │ ├── 01.2-choosing-a-model/ │ ├── 01.3-stream-text-to-terminal/ │ ├── 01.4-ui-message-streams/ │ ├── 01.5-stream-text-to-ui/ │ └── 01.6-system-prompts/ ├── 02-agents/ # Tool calling & agents ├── 03-advanced/ # Advanced patterns └── 99-reference/ # Material reference ``` -------------------------------- ### Call generateText with structured output (TODO placeholder) Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/01-ai-sdk-basics/01.11-generating-objects-via-output/problem/readme.md Placeholder for calling generateText with Output.object and a Zod schema for facts. The TODO comment indicates the required parameters: model, prompt using finalText, and output with schema. ```ts // TODO: Replace this with a call to generateText, passing: // - The model, same as above // - The prompt, asking for facts about the imaginary planet, // passing in the finalText as the story // - The output, which should be Output.object({}), passing // the schema: z.object({ // facts: z.array(z.string()).describe('The facts about the imaginary planet. Write as if you are a scientist.'), // }) const factsResult = TODO; ``` -------------------------------- ### Polymorphic instructions with providerOptions Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/plans/03.0x-tool-loop-agent-notes.md Shows ToolLoopAgent accepting an array of instruction parts, each with providerOptions for caching. This allows different provider-specific cache options per instruction part. ```typescript const agent = new ToolLoopAgent({ model: "anthropic/claude-sonnet-4.5", instructions: [ { text: 'You are an expert software engineer.', providerOptions: { /* cache options */ } }, { text: 'Additional context here.', providerOptions: { /* different cache */ } }, ], }); ``` -------------------------------- ### Define SYSTEM_PROMPT constant for pirate behavior Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/01-ai-sdk-basics/01.09-system-prompts/explainer/readme.md Defines a system prompt that instructs the LLM to always reply in pirate language, refer to the pirate code as guidelines, and decline requests to use other languages. This is used to customize the LLM's behavior. ```TypeScript const SYSTEM_PROMPT = ` ALWAYS reply in Pirate language. ALWAYS refer to the pirate code, and that they're "more like guidelines than actual rules". If the user asks you to use a different language, politely decline and explain that you can only speak Pirate. `; ``` -------------------------------- ### Drizzle ORM schema for parts table with check constraints Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/04-persistence/04.04-persistence-in-a-normalized-db/explainer/readme.md Defines a dedicated parts table with fields for each part type and SQL check constraints to enforce that required fields exist per type. The example shows a text_text constraint and notes that more constraints exist. ```typescript export const parts = pgTable( 'parts', { id: varchar() .primaryKey() .$defaultFn(() => generateId()), messageId: varchar() .references(() => messages.id, { onDelete: 'cascade' }) .notNull(), type: varchar().$type().notNull(), createdAt: timestamp().defaultNow().notNull(), order: integer().notNull().default(0), // Text fields text_text: text(), // Reasoning fields reasoning_text: text(), // Many more fields for different part types... }, (t) => [ // Check constraints for each part type check( 'text_text_required_if_type_is_text', sql`CASE WHEN ${t.type} = 'text' THEN ${t.text_text} IS NOT NULL ELSE TRUE END`, ), // More constraints... ], ); ``` -------------------------------- ### callTavilyToGetSearchResults - Fetch search results from Tavily Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/09-advanced-patterns/09.04-research-workflow/problem/readme.md This function is already implemented and calls the Tavily API to get search results for each query. It uses the tavily client with an API key from environment variables, and fetches up to 5 results per query. The function returns an array of objects containing the query and the response. ```TypeScript const callTavilyToGetSearchResults = async ( queries: string[], ) => { const tavilyClient = tavily({ apiKey: process.env.TAVILY_API_KEY, }); const searchResults = await Promise.all( queries.map(async (query) => { const response = await tavilyClient.search(query, { maxResults: 5, }); return { query, response, }; }), ); return searchResults; }; ``` -------------------------------- ### Stream text and print usage with AI SDK Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/02-llm-fundamentals/02.02-usage/problem/readme.md Streams a response from Google's Gemini 2.5 Flash Lite model and prints the streamed text. The usage property is available on the output object and may be a promise that needs to be awaited. The TODO line indicates where to print the usage. ```typescript import { google } from '@ai-sdk/google'; import { streamText } from 'ai'; const output = streamText({ model: google('gemini-2.5-flash-lite'), prompt: `Which country makes the best sausages? Answer in a single paragraph.`, }); for await (const chunk of output.textStream) { process.stdout.write(chunk); } console.log(); // Empty log to separate the output from the usage // TODO: Print the usage to the console TODO; ``` -------------------------------- ### Define sample data array with URLs and titles Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/02-llm-fundamentals/02.03-data-represented-as-tokens/explainer/readme.md Defines an array of objects containing URLs and titles, used as the base data for all format conversions. ```TypeScript const DATA = [ { url: 'https://aihero.dev', title: 'AI Hero', }, { url: 'https://totaltypescript.com', title: 'Total TypeScript', }, { url: 'https://mattpocock.com', title: 'Matt Pocock', }, { url: 'https://twitter.com/mattpocockuk', title: 'Twitter', }, ]; ``` -------------------------------- ### Import AI SDK components Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/06-evals/06.01-evalite-basics/problem/readme.md Imports the Google provider and generateText from the AI SDK, required for implementing the task function. ```typescript import { google } from '@ai-sdk/google'; import { generateText } from 'ai'; ``` -------------------------------- ### System prompt template to update Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/06-evals/06.02-deterministic-eval/problem/readme.md The current system prompt template that needs to be updated to pass the links data and instruct the model to include markdown links and be succinct. ```typescript prompt: ` You are a helpful assistant that can answer questions about TypeScript releases. Question: ${input} `, ``` -------------------------------- ### Implement task function with AI SDK Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/06-evals/06.01-evalite-basics/problem/readme.md Shows the task function structure with a placeholder for calling generateText. The prompt should instruct the model to answer questions about capitals. ```typescript task: async (input) => { const capitalResult = // Call generateText with appropriate model and prompt return capitalResult.text; }, ``` -------------------------------- ### Define the prompt Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/01-ai-sdk-basics/01.05-generating-text/problem/readme.md A simple prompt asking for the capital of France. ```TypeScript const prompt = 'What is the capital of France?'; ``` -------------------------------- ### Undesired output: multiple title options Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/05-context-engineering/05.02-basic-prompting/problem/readme.md Observed output from the current prompt: multiple title options with explanations instead of a single title. The desired output is just a short title like "Induction Hobs versus Aga Cookers". ```text Here are a few title options, ranging from informative to more click-baity: **Informative & Direct:** * Replacing an AGA with Induction: A Guide to 100cm Range Cookers * AGA to Induction: Comparing Range Cookers for Size and Performance ... ``` -------------------------------- ### Basic IIMT with keyof SomeObject Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/05-context-engineering/05.05-chain-of-thought/problem/iimt-article.md Creates a union of object types for each key of SomeObject by immediately indexing a mapped type with keyof SomeObject. The resulting type is a union of { key: 'a' } and { key: 'b' }. ```typescript type SomeObject = { a: string; b: number; }; /** * | { * key: 'a'; * } * | { * key: 'b'; * } */ export type Example = { [K in keyof SomeObject]: { key: K; }; }[keyof SomeObject]; ``` -------------------------------- ### Background Data XML Block Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/05-context-engineering/05.01-the-template/explainer/readme.md Use this XML-tagged block to include background information, such as a career guidance document, in the prompt. Each document is wrapped in XML tags to help the LLM recognize document boundaries. ```typescript Here is the career guidance document you should reference when answering the user: ${opts.careerGuidanceDocument} ``` -------------------------------- ### Execute function for logToConsole Source: https://github.com/ai-hero-dev/ai-sdk-v6-crash-course/blob/main/exercises/99-reference/99.02-defining-tools/explainer/readme.md The `execute` function logs the message with green bold styling and returns a string report that is passed back to the LLM. ```ts execute: async ({ message }) => { console.log(styleText(['green', 'bold'], message)); return 'Message logged to console'; }; ```