Skip to article content
FrontendXLesson 01 / 20

Anatomy of a model API call

Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.

beginner · about 35 minutes · 4 exercises

  • Predict
  • Explain
  • Implement

What you will be able to do

#
  • Construct a well-formed chat-style request object and explain the purpose of every top-level field.
  • Trace a deterministic mock client to predict the exact response content for a given request.
  • Explain why model APIs are stateless and what that implies for multi-turn conversation code.

Overview

#

What a model API call actually is

A large language model (LLM) API is an HTTP endpoint that accepts a description of a conversation and returns generated text. Despite the marketing word "chat", the transport is boring and testable: you send JSON, you receive JSON. Everything an AI feature does sits on top of that exchange, so the fastest way to learn AI engineering is to treat the call like any other I/O boundary in your system: explicit inputs, explicit outputs, explicit failure modes.

This course never calls a real provider. Every example uses a deterministic local mock, a plain JavaScript function that returns fixed outputs for fixed inputs. That gives you three benefits: no API keys exist anywhere in this course, no network is touched, and every exercise result can be verified by hand-tracing the code.

The request object, field by field

A chat-style request has a small number of fields that matter in practice:

FieldPurposeExample
modelWhich model serves the request"mock-mini"
messagesThe full conversation so fararray of { role, content }
temperatureSampling randomness, 0 to 20 for extraction tasks
streamWhether tokens arrive incrementallyfalse
maxOutputTokensCap on generated length300

The messages array is the heart of the request. Each entry has a role and a content:

  • system: persistent instructions that set behavior for the whole conversation ("You are a concise support assistant. Answer only from provided documents.").
  • user: the end user's input, plus any data you attach for the model to work on.
  • assistant: previous model replies. Including them is how multi-turn conversation works.
snippet.javascript
function buildChatRequest(system, user) {
  return {
    model: "mock-mini",
    temperature: 0,
    stream: false,
    messages: [
      { role: "system", content: system },
      { role: "user", content: user }
    ]
  };
}

const request = buildChatRequest("You are concise.", "Summarize this invoice.");
// JSON.stringify(request) produces:
// {"model":"mock-mini","temperature":0,"stream":false,"messages":[
//   {"role":"system","content":"You are concise."},
//   {"role":"user","content":"Summarize this invoice."}]}

The response object

A non-streaming response typically contains the generated message, a finish reason, and a usage block:

snippet.javascript
function mockChat(request) {
  const replies = {
    "Summarize this invoice.": "Invoice 1042 totals 120 USD.",
    "default": "I did not understand the request."
  };
  const last = request.messages[request.messages.length - 1];
  return {
    model: request.model,
    content: replies[last.content] || replies["default"],
    finishReason: "stop",
    usage: { inputTokens: 21, outputTokens: 8 }
  };
}

console.log(mockChat(request).content);
// Simulated output: Invoice 1042 totals 120 USD.

The mock maps the last user message to a fixed reply, so the output above is deterministic: you can trace it line by line. Real providers add the same three ideas, generated content, a stop reason, and token usage, under provider-specific field names. When you later read a real provider's reference, map each field back to these three concepts instead of memorizing their JSON paths.

Statelessness changes how you build chat

The single most important operational fact: the model does not remember previous calls. Each request is complete and independent. If the user says "make it shorter" in turn three, that instruction only works if turn three's messages array still contains enough earlier context to know what "it" refers to.

snippet.javascript
const turn1 = buildChatRequest("You are concise.", "Summarize this invoice.");
const reply1 = mockChat(turn1).content;

// Wrong: the second call has no memory of the first.
const turn2 = buildChatRequest("You are concise.", "Now make it shorter.");

// Right: resend the exchange, then ask.
const turn2b = buildChatRequest("You are concise.", "Summarize this invoice.");
turn2b.messages.push({ role: "assistant", content: reply1 });
turn2b.messages.push({ role: "user", content: "Now make it shorter." });

Resending history has a cost consequence: every turn makes the next request larger, which is why token budgeting gets its own lesson later in this course.

Why mock-first is the professional workflow

Real calls are slow, billed, nondeterministic at nonzero temperature, and rate limited. A deterministic mock is none of those things, which makes it the right substrate for learning and for unit tests. The professional pattern you will practice throughout this course: define the boundary (request and response shapes), implement business logic against the mock, and swap the transport later without touching the logic. When you eventually wire a real provider, the only new code should be an adapter that speaks the provider's JSON dialect.

One caution before moving on: a passing mock proves your logic, never model quality. The difference between a demo and an evaluation is a central theme of this course, and it starts here: the mock always cooperates, real models do not.

Continue with ai-engineering-prompt-structure-and-roles to design the messages array deliberately instead of defaulting to one blob of text.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Implement

    Implement buildChatRequest(system, user) so it returns an object with exactly the fields model: "mock-mini", temperature: 0, stream: false, and messages: a system message followed by a user message. Verify by comparing JSON.stringify(request) with the expected output.

    starter.javascript
    function buildChatRequest(system, user) {
      // Return an object with exactly these fields, in this order:
      // model: "mock-mini", temperature: 0, stream: false,
      // messages: [ { role: "system", content: system },
      //             { role: "user", content: user } ]
    }

    Reveal the reference answer
    reference.javascript
    function buildChatRequest(system, user) {
      return {
        model: "mock-mini",
        temperature: 0,
        stream: false,
        messages: [
          { role: "system", content: system },
          { role: "user", content: user }
        ]
      };
    }

    Authored expected output: {"model":"mock-mini","temperature":0,"stream":false,"messages":[{"role":"system","content":"You are concise."},{"role":"user","content":"Summarize this invoice."}]}

    The request is plain data. System instructions go in a system-role message, the user input in a user-role message, and transport options such as temperature and stream live at the top level, not inside messages.

  2. Exercise 2Predict

    Using the mockChat function and the request from ex1, predict the exact value logged by console.log(mockChat(request).content). Trace the lookup: the last message content is used as the key into the replies table.

    starter.javascript
    function mockChat(request) {
      const replies = {
        "Summarize this invoice.": "Invoice 1042 totals 120 USD.",
        "default": "I did not understand the request."
      };
      const last = request.messages[request.messages.length - 1];
      return {
        model: request.model,
        content: replies[last.content] || replies["default"],
        finishReason: "stop",
        usage: { inputTokens: 21, outputTokens: 8 }
      };
    }
    
    const request = buildChatRequest("You are concise.", "Summarize this invoice.");
    console.log(mockChat(request).content);

    Reveal the reference answer
    reference.javascript
    // Predicted output of console.log(mockChat(request).content):
    //
    // Invoice 1042 totals 120 USD.
    //
    // Trace: request.messages has two entries, so the last one is the user
    // message with content "Summarize this invoice.". That string is an exact
    // key in the replies table, so mockChat returns its mapped value. The
    // usage and finishReason fields exist in the response but are not logged.

    Authored expected output: Invoice 1042 totals 120 USD.

    mockChat reads the last message, finds the exact key "Summarize this invoice." in its fixed table, and returns the mapped reply. Deterministic mocks make this traceable by hand with no execution needed.

  3. Exercise 3Explain

    turn2 in the body calls buildChatRequest("You are concise.", "Now make it shorter.") as the second turn of a conversation. Explain what the model can and cannot know in that call, and what a correct second request must contain.

    starter.text
    const turn1 = buildChatRequest("You are concise.", "Summarize this invoice.");
    const reply1 = mockChat(turn1).content;
    
    // Second turn, written as if the server remembered turn one.
    const turn2 = buildChatRequest("You are concise.", "Now make it shorter.");

    Reveal the reference answer
    reference.text
    The model can only know what is in the messages array of the current request. In turn2 the array contains just the system instruction and the text "Now make it shorter.", so the referent of "it" is unknown and any reply is a guess. A correct second request resends the prior exchange: the original user message, the assistant reply produced in turn one, and then the new user message. This is the statelessness rule: history is data your code owns and re-sends, not server-side memory.

    Authored expected output: A written explanation stating that the model sees only the current messages array, that "it" has no referent without history, and that the fix is resending the prior user and assistant messages before the new user message.

    Statelessness is the reason conversation code is really context-management code. It also drives cost: every turn re-sends and re-bills the whole history.

  4. Exercise 4Explain

    Knowledge check: which message role carries persistent behavior instructions that apply to the whole conversation?

    starter.text
    // Choose the correct option.

    Reveal the reference answer
    reference.text
    The system role. System messages set durable behavior for the conversation, user messages carry per-turn input and data, and assistant messages record previous replies.

    Authored expected output: system

    Roles are a convention the model is trained to follow: system for behavior, user for input, assistant for prior replies. Lesson 2 builds on this to separate instructions from data.

Common misconceptions

#
  • Myth: the model remembers earlier calls on the server. Fact: each request is independent, so your code must resend the conversation history every turn.
  • Myth: the response is just a string. Fact: responses carry generated content, a finish reason and a token usage block, and production code should read all three.
  • Myth: a mock that returns a good answer proves the feature works. Fact: a mock proves your logic, never model quality; that distinction is what separates a demo from an evaluation.

Follow-up practice

#
  • ai-engineering-prompt-structure-and-roles

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.