Ai Interview Questions
40 curated ai interview questions with detailed answers and examples.
← Browse all interview questionsStart from requirements, not popularity: list what you need (streaming to a React UI, tool calling, memory, human approval, durable long-running runs, tracing) and check which you can already do with a lightweight SDK. Many teams can start with the Vercel AI SDK and plain TypeScript, and adopt a heavier framework such as Mastra, LangGraph.js or the OpenAI Agents SDK only when they need its specific features. Build the same small agent as a spike in your top two options, and keep the framework behind your own interface so you can switch later.
Make every run replayable: record one trace per run with a span per step, holding what the model saw, which tools it chose with what arguments, what the tools returned, the finish reason, tokens and timings. Then debug from the trace like a Redux DevTools timeline: find the first step where things went wrong and ask whether the cause was missing context, a vague tool description, a bad tool result or the model's reasoning. Turn each confirmed failure into a test case so the fix stays fixed.
A model has no memory of its own: every call only sees what you send in that request. Agent "memory" is your app deciding what to put back into the context: short-term memory is the current conversation (message history for one thread), working memory is a small set of key facts kept in the prompt, and long-term memory is data stored in a database across sessions and pulled in when relevant, often by semantic search. Each type trades accuracy against tokens, cost and privacy.
Multiple agents pay off when a task splits into independent pieces that can run in parallel, each needing its own large context, such as broad research across many sources. They are a poor fit when the pieces depend on each other or must share the same decisions, like most UI and coding tasks, because subagents lose context and make conflicting choices. Default to one agent with good tools, and split only when you have measured that one context window or one sequential loop is the bottleneck.
A workflow is LLM calls and tools wired together by your code along a path you decided in advance. An agent is a model running in a loop that decides its own next step and which tools to call. Use a workflow when the steps are known and you need predictable cost and latency, and reach for an agent only when the number and order of steps genuinely depend on the input.
An agent loop keeps calling the model, running the tools it asks for and feeding results back. It stops naturally when the model finishes without requesting a tool, when it calls a tool that has no server-side execute (so the client or a human must act), or when a call needs approval. On top of that you add hard limits: a maximum step count, a stop-on-specific-tool rule, and custom conditions such as a token budget, because the model deciding to stop is not a guarantee.
Classify each tool by risk on the server, run safe reads automatically, and mark risky calls as needing user approval so the loop pauses and returns an approval request instead of running the tool. The UI shows exactly what will happen (amount, order, reason) with Approve and Deny buttons, sends the decision back, and the server only executes after an approved response, still re-checking permissions inside execute. Decide approval rules in server code from the tool input, never from the model or the browser alone.
Render the assistant message as a list of parts, and give each tool part its own small component that switches on its state: input-streaming, input-available, approval-requested, output-available, output-error or output-denied. Show a short human label while the tool runs, the result in a compact card when it finishes, and a clear error or denial message when it fails. Announce changes politely to screen readers and keep raw JSON out of the main view.
Once a model can call tools, anything that can influence its input (a user message, a web page, an email, a document) can try to steer it into calling tools you did not intend, which is prompt injection turned into real actions. The main risks are excessive agency (too many tools, too much permission, too little oversight), data exfiltration through tool arguments, unvalidated input and output, and runaway cost. Reduce them with narrow tools, least-privilege credentials scoped to the current user, server-side authorisation in every tool, approval for high-impact actions, and limits and logs on every loop.
Tool calling lets a model ask your app to run a function: you describe each tool with a name, a description and an input schema, and the model replies with a structured request (tool name plus JSON arguments) instead of plain text. The model never runs anything itself. Your code validates the arguments, runs the function, sends the result back, and the model uses it to continue; the exception is provider-executed tools like hosted web search, which run on the provider side.
useChat keeps an array of UIMessage objects, each with an id, a role and a list of parts. sendMessage adds your message right away, sets status to submitted, posts the conversation through a transport and then applies each streamed chunk to the assistant message, moving status to streaming and finally to ready or error. Helpers like stop, regenerate and setMessages change that same array, and the throttle option limits how often React re-renders.
First treat the key as leaked: rotate it in the provider dashboard, because NEXT_PUBLIC_ values are inlined into the JavaScript bundle at build time. Then move the model call into a Route Handler, store the key in a variable without the NEXT_PUBLIC_ prefix, and import "server-only" in the module that uses it so a Client Component import fails the build. The browser only talks to your route, which adds auth and limits before calling the provider.
The server owns everything that must be trusted: the API key, the model choice, the system instructions, tool execution, auth, input validation, rate limits and saving the conversation. The client owns everything the user touches: the input box, the message list, rendering streamed parts, the stop button and loading or error states. In the App Router that usually means a Route Handler that returns a UI message stream and a Client Component that uses useChat.
Limit in layers, inside the Route Handler and before the model call. Identify the caller by user id (IP only as a fallback), apply a request limit such as a sliding window in Redis, and add a daily token budget per user because one request can cost far more than another. Cap input size and maxOutputTokens, return 429 with a Retry-After header when a limit is hit, and show a calm message in the UI.
An AI SDK gives you one API (generateText, streamText, tools, structured output and a UI message stream) on top of a shared language model specification, so switching providers is mostly a change to the model argument. What stays provider-specific is capability and behaviour: which models support tools, images or reasoning, how they tokenize and price, features like prompt caching, and extra settings you pass through providerOptions keyed by provider name.
The context window is the maximum number of tokens a model can work with in one request: system prompt, chat history, documents, tools and the answer it generates. The model has no memory between calls, so your app resends the history every turn and it keeps growing. When the input is too large the API rejects the request, so the app must trim, summarize or compact older turns before that happens.
Input tokens are everything you send; output tokens are what the model generates. Output is priced higher per token (Anthropic currently lists it at 5x input for its Claude models), and it is generated one token at a time, so long answers dominate total response time. Long inputs cost more and delay the first token, but caching repeated prefixes can make that input much cheaper.
LLMs sample each next token from a probability distribution, so two runs of the same prompt can take different paths, and even temperature 0 is not fully deterministic. Model updates and changes to the hidden context (system prompt, history, retrieved data) change answers too. The UI should treat every response as a unique record: store what the user saw, offer regenerate instead of hiding variation, and validate anything the app depends on.
At each step the model produces a probability for every possible next token, and temperature reshapes that distribution before one token is sampled. Lower temperature makes the likeliest tokens even more likely, so output is more focused and repeatable; higher temperature flattens it, so output is more varied. Lower it for extraction, classification and code, but check your model first: several newer models only accept the default value.
A token is the unit of text a model reads and writes: usually a word, part of a word, a punctuation mark or a space-plus-word chunk. Providers bill and rate-limit by tokens, not characters or words, so the same text can cost different amounts on models with different tokenizers. Count tokens with the provider's tokenizer or counting API instead of guessing from string length.
Test it in layers: unit test the business logic inside each handler, then drive the whole server through a real MCP client in-process so you test listing, schemas, results and errors exactly as a host sees them. Add a smoke test that spawns the real stdio or HTTP server, use the MCP Inspector for manual and scripted checks, and keep a separate eval for whether models actually pick your tools correctly.
An MCP server runs real code with real permissions on behalf of a model, so treat every tool call like an untrusted API request. Authenticate every HTTP request with tokens issued for your server (never pass client tokens through), validate inputs, enforce per-user access checks, rate limit and sanitise outputs. Also plan for prompt injection through tool results, minimal OAuth scopes, and human approval for destructive actions.
All three are things an MCP server exposes, but they differ in who decides when they are used. Tools are model-controlled actions the model can ask to run, resources are read-only context the host application chooses to include, and prompts are templates the user explicitly picks, often as a slash command. Picking the right primitive decides who is in control, which matters for safety, cost and UX.
MCP is an open protocol that standardises how an AI application connects to external tools and data, so one server can work with many AI apps instead of every app writing its own integration. It has three roles: a host (the AI app), a client inside the host that talks to exactly one server, and a server that exposes tools, resources and prompts. Messages are JSON-RPC, sent over stdio for local servers or Streamable HTTP for remote ones.
Define tools directly when one app owns the feature, the tool needs tight access to your app state, and you want the simplest, fastest path. Reach for MCP when the same capability should work across several AI hosts or teams, when another team or vendor already ships an MCP server, or when you want the tool to live and deploy separately. MCP adds a process, a protocol and a security surface, so it should earn its place.
Create an AbortController per request, pass controller.signal to fetch, and call controller.abort() from the Stop button or a useEffect cleanup. The fetch promise or the pending reader.read() then rejects with an AbortError, which you catch and treat as a normal stop, keeping the text already shown. On the server, pass the incoming request signal on to the upstream LLM call so the model actually stops generating and billing.
Start the upstream request, then hand its body stream straight to your response instead of awaiting text() or json(). In a Next.js Route Handler that means returning new Response(upstream.body); in Express, pipe Readable.fromWeb(upstream.body) into res. Then remove hidden buffers along the path (compression middleware, nginx proxy buffering, caches) and abort the upstream call when the client disconnects.
response.body is a ReadableStream of Uint8Array chunks. Get a reader with getReader(), call read() in a loop until done is true, and turn each chunk into text with a single TextDecoder using decode(chunk, { stream: true }). Then buffer the text and parse only complete lines or events, because network chunks do not line up with tokens or messages.
UTF-8 encodes many characters in 2 to 4 bytes, and the network can split a stream anywhere, including in the middle of one character. If you decode each chunk on its own, the incomplete bytes become the replacement character U+FFFD. Use one TextDecoder for the whole stream with decode(chunk, { stream: true }) (or TextDecoderStream), and flush it at the end, so incomplete bytes wait for the next chunk.
For a normal chat completion, Server-Sent Events (SSE) over HTTP is the better fit: the client sends one request, the server pushes tokens back in one direction, and it works with ordinary HTTP infrastructure, auth and serverless functions. The major LLM APIs stream over SSE for exactly this reason. WebSockets make sense when both sides need to keep sending data over one long-lived connection, such as realtime voice or a persistent agent session.
Do not let the screen reader announce the answer token by token. Keep the streaming text out of an active live region, and use a separate, visually hidden polite status region to announce short lifecycle messages such as "Generating response" and "Response complete". Keep focus in the input, give each message a clear structure the user can navigate, and test with real screen readers because live region support varies.
Follow the stream only while the user is already at the bottom. Track a "stick to bottom" flag from scroll position, turn it off as soon as the user scrolls up, and show a "Jump to latest" button instead of pulling them back down. Scroll when the content actually grows (a ResizeObserver on the message container works well), and turn sticking back on when the user sends a new message or clicks the button.
Keep finished messages stable and isolate the one that is still streaming, so only that bubble re-renders. Wrap message rows in React.memo with stable keys and unchanged object references, and batch incoming chunks so you update state at most once per animation frame instead of once per token.
Render markdown to React elements with a library like react-markdown, which escapes raw HTML by default, instead of piping parsed HTML into dangerouslySetInnerHTML. To avoid flicker and wasted work, split the text into blocks and memoize finished blocks so only the last one re-parses, and handle unclosed syntax such as an open code fence, either yourself or with a streaming-aware renderer like Streamdown.
Model each assistant reply as a message with a status (streaming, done, stopped or error) and a list of versions. Stop aborts the request and marks the current version as stopped while keeping its text. Regenerate rebuilds the history up to the user message before that reply, streams a new version into the same message slot, and keeps older versions available so nothing the user saw is silently lost.
Design the schema like a form for a new teammate: clear key names with units, a short description on every field, enums instead of free text where the values are known, and an explicit null or "not found" option so the model never has to invent data. Keep it shallow, order fields so context comes before conclusions, and stay inside the schema features your provider supports. Then measure it with a small set of test inputs instead of guessing.
You have four main options: wait for the full text, repair the partial text on every chunk (close open strings and brackets, then parse), stream complete elements one at a time, or switch the wire format to one object per line. The AI SDK gives you the repair approach as partialOutputStream on the server and useObject on the client, and elementStream for arrays. Partial objects cannot be schema-validated, so treat every field as possibly missing and validate once at the end.
Decide by the kind of failure. Retry transient errors like timeouts, 429s and 5xx with backoff, because the same request can succeed next time. Repair when the content is close: fix small problems in code first, then re-ask the model once with the validation errors. Fall back when retrying cannot help, such as a refusal, a content filter or repeated failures, and always cap attempts because every retry costs tokens and time.
JSON mode only promises that the reply parses as JSON, not that it has the fields you need. Structured output goes further and constrains the reply to a JSON Schema you send, so the shape is enforced at generation time. Function calling uses the same schema machinery for a different job: the model asks your code to run a tool with typed arguments, instead of answering the user in a fixed shape.
Treat model output like any untrusted API response: parse it against a Zod schema at the server boundary before it reaches React. Use safeParse so a failure becomes a value you can branch on, log the raw text and the Zod issues, and return a typed error state the UI knows how to render. With the AI SDK, Output.object runs this validation for you and throws NoObjectGeneratedError when the object does not match.