Module 1, Lesson 2: Basic Chat with Anthropic

A multi-turn terminal chat with a system prompt, using the Anthropic Messages API.

Published: 11/22/2026

Lesson 2: Basic chat

Create src/anthropic/config.ts:

export const model = "claude-sonnet-5-5";

Then src/anthropic/basic-chat.ts:

import Anthropic from "@anthropic-ai/sdk";
import dotenv from "dotenv";
import { createInterface } from "node:readline/promises";
import { basicTravelSystemPrompt } from "../common/prompt-ref.js";
import { model } from "./config.js";

dotenv.config();

const client = new Anthropic();
const messages: Anthropic.MessageParam[] = [];
const rl = createInterface({ input: process.stdin, output: process.stdout });

try {
  while (true) {
    const input = (await rl.question("You (return to exit): ")).trim();
    if (!input) break;
    messages.push({ role: "user", content: input });

    const response = await client.messages.create({
      model: model,
      max_tokens: 4000,
      messages,
      system: basicTravelSystemPrompt,
    });
    messages.push({ role: "assistant", content: response.content });

    for (const block of response.content) {
      if (block.type === "text") console.log(`\n${block.text}\n`);
    }
  }
} finally {
  rl.close();
}

Run it with pnpm tsx src/anthropic/basic-chat.ts, ask for a holiday idea, then ask a follow-up such as "and how far is it from the airport?". The follow-up works because the first exchange is still in messages.

How it works

  • The loop. readline asks for input. An empty line breaks out of the loop, and the finally block closes the interface.
  • system. The system prompt is a separate parameter, not a message. It is sent with every request.
  • max_tokens. Required on the Messages API. It is the ceiling on the reply length.
  • The assistant turn. response.content is an array of blocks. It is pushed back whole, as the assistant's message, so the next request sees exactly what Claude said.
  • Printing. Only blocks with type === "text" are printed. In the next lesson other block types appear.

Try it

  • Change the system prompt in prompt-ref.ts to "reply in one sentence" and see how the answers change.
  • Lower max_tokens to 50 and notice the reply is cut off. In the next lesson you'll detect that with the stop reason.

👉 Continue to Lesson 3: Chat with tools