Use a system prompt to define a model's role, boundaries, and response style.

Download the runnable notebook

This complete lesson was converted from the matching notebook stored locally in the TechClub repository. Outputs are cleared; never add API keys or private data.

Goal, prerequisites, and setup

Learn how system instructions differ from user messages and how to test a behavioral constraint. Complete the requests lesson first; know Python functions and message lists. Install anthropic and python-dotenv, set ANTHROPIC_API_KEY and ANTHROPIC_MODEL, and verify the notebook kernel.

Run the tutor example unchanged, then vary one instruction at a time. Record whether the response follows the constraint, where it is ambiguous, and what a safer fallback would be.

# Load environment variables
from dotenv import load_dotenv

load_dotenv()
# Create an API client
import os
from anthropic import Anthropic

client = Anthropic()

model = os.getenv("ANTHROPIC_MODEL")
# Helpers
def add_message(messages, content, role):
    message = {"role": role, "content": content}
    messages.append(message)

def chat(messages, system=None):
    params = {
        "model": model,
        "max_tokens": 1000,
        "messages": messages,
    }

    if system:
        params["system"] = system

    message = client.messages.create(**params)

    return message.content[0].text
messages = []

system_prompt = """
You are a patient math tutor.
Do not directly answer a student's question.
Guide them to a solution step by step.
"""

add_message(messages, "How do I solve 5x+3=2 for x?", "user")
answer = chat(messages, system=system_prompt)

print(answer)

Evidence and references