# Anthropic Prompt Engineering Interactive Tutorial This project is a comprehensive educational resource designed to teach developers how to engineer effective prompts for Claude, Anthropic's AI assistant. The tutorial provides hands-on learning through interactive Jupyter notebooks with practical exercises covering fundamental to advanced prompting techniques. It offers two implementations: one using Anthropic's direct API and another using Amazon Bedrock, making it accessible for different deployment scenarios. The course is structured as a progressive learning path with 9 core chapters and an appendix covering advanced topics. Each chapter includes detailed lessons, graded exercises with automatic validation, and example playgrounds for experimentation. The tutorial teaches essential skills like basic prompt structure, role assignment, data separation, output formatting, few-shot learning, hallucination prevention, and building complex industry-specific prompts. It uses Claude 3 Haiku as the default model for cost-effectiveness while demonstrating techniques applicable across all Claude model variants. ## Basic Prompt Structure with Messages API Send messages to Claude using the Messages API with proper user/assistant role formatting. ```python import anthropic client = anthropic.Anthropic(api_key="your-api-key") def get_completion(prompt: str, system_prompt=""): message = client.messages.create( model="claude-3-haiku-20240307", max_tokens=2000, temperature=0.0, system=system_prompt, messages=[ {"role": "user", "content": prompt} ] ) return message.content[0].text # Simple question response = get_completion("What year was Celine Dion born in?") print(response) # Output: Celine Dion was born in 1968. # With system prompt system = "Your answer should always be a series of critical thinking questions that further the conversation (do not provide answers to your questions)." response = get_completion("Why is the sky blue?", system) print(response) # Output: What is it about the Earth's atmosphere that causes the sky to appear blue? What role do light waves play in this phenomenon? ``` ## Amazon Bedrock Integration Connect to Claude through AWS Bedrock for enterprise deployments with regional compliance. ```python from anthropic import AnthropicBedrock client = AnthropicBedrock(aws_region="us-west-2") def get_completion(prompt, system=''): message = client.messages.create( model="anthropic.claude-3-haiku-20240307-v1:0", max_tokens=2000, temperature=0.0, messages=[ {"role": "user", "content": prompt} ], system=system ) return message.content[0].text # Query Claude through Bedrock response = get_completion("Hi Claude, how are you?") print(response) # Output: Hello! As an AI assistant, I don't have feelings, but I'm functioning well and ready to help you. ``` ## Multi-turn Conversation Pattern Simulate conversational context by alternating user and assistant messages. ```python import anthropic client = anthropic.Anthropic(api_key="your-api-key") # Multi-turn conversation requires alternating roles response = client.messages.create( model="claude-3-haiku-20240307", max_tokens=2000, temperature=0.0, messages=[ {"role": "user", "content": "What year was Celine Dion born in?"}, {"role": "assistant", "content": "Celine Dion was born in 1968."}, {"role": "user", "content": "Can you tell me some other facts about her?"} ] ) print(response.content[0].text) # Output: Celine Dion is a Canadian singer known for powerful vocals. She gained international fame with "My Heart Will Go On" from Titanic. She has sold over 200 million records worldwide... ``` ## Email Classification with Categories Classify user emails into predefined categories with structured output using prefilling. ```python def classify_email(email_text): prompt = f"""Please classify this email into the following categories: {email_text} Do not include any extra words except the category. (A) Pre-sale question (B) Broken or defective item (C) Billing question (D) Other (please explain) """ # Prefill assistant response to control output format message = client.messages.create( model="claude-3-haiku-20240307", max_tokens=100, temperature=0.0, messages=[ {"role": "user", "content": prompt}, {"role": "assistant", "content": "("} ] ) return "(" + message.content[0].text # Test with sample email email = "How much does the Mixmaster4000 cost and when will it be back in stock?" result = classify_email(email) print(result) # Output: (A) Pre-sale question ``` ## Few-Shot Learning with Examples Provide example inputs and outputs to guide Claude's response format and accuracy. ```python def classify_email_with_examples(email_text): prompt = f"""Please classify emails into the following categories, and do not include explanations: (A) Pre-sale question (B) Broken or defective item (C) Billing question (D) Other (please explain) Here are a few examples of correct answer formatting: Q: How much does it cost to buy a Mixmaster4000? A: The correct category is: A Q: My Mixmaster won't turn on. A: The correct category is: B Q: Please remove me from your mailing list. A: The correct category is: D Here is the email for you to categorize: {email_text}""" message = client.messages.create( model="claude-3-haiku-20240307", max_tokens=100, temperature=0.0, messages=[ {"role": "user", "content": prompt}, {"role": "assistant", "content": "The correct category is:"} ] ) return "The correct category is:" + message.content[0].text # Test classification email = "I was charged twice for my last order." result = classify_email_with_examples(email) print(result) # Output: The correct category is: C ``` ## Document-Based Q&A with Quote Extraction Answer questions based on provided documents using quote extraction to prevent hallucinations. ```python def answer_with_quotes(question, tax_code): prompt = f"""You are a master tax accountant. Your task is to answer user questions using any provided reference documentation. Here is the material you should use to answer the user's question: {tax_code} Here is an example of how to respond: What defines a "qualified" employee? For purposes of this subsection— (A)In general The term "qualified employee" means any individual who— (i)is not an excluded employee, and (ii)agrees in the election made under this subsection to meet such requirements as are determined by the Secretary. According to the provided documentation, a "qualified employee" is defined as an individual who: 1. Is not an "excluded employee" as defined in the documentation. 2. Agrees to meet the requirements determined by the Secretary to ensure the corporation's withholding requirements under Chapter 24 are met with respect to the qualified stock. First, gather quotes in tags that are relevant to answering the user's question. If there are no quotes, write "no relevant quotes found". Then insert two paragraph breaks before answering the user question within tags. Only answer the user's question if you are confident that the quotes in tags support your answer. If not, tell the user that you unfortunately do not have enough information to answer the user's question. Here is the user question: {question}""" return get_completion(prompt) # Example usage tax_document = "Section 1202: Capital gains from qualified small business stock held for more than 5 years may be excluded from taxable income..." response = answer_with_quotes("What is Section 1202?", tax_document) print(response) ``` ## Socratic Tutoring for Code Review Guide learners through code issues using Socratic questioning rather than direct answers. ```python def code_tutor(code_snippet): prompt = f"""You are Codebot, a helpful AI assistant who finds issues with code and suggests possible improvements. Act as a Socratic tutor who helps the user learn. You will be given some code from a user. Please do the following: 1. Identify any issues in the code. Put each issue inside separate tags. 2. Invite the user to write a revised version of the code to fix the issue. Here's an example: def calculate_circle_area(radius): return (3.14 * radius) ** 2 3.14 is being squared when it's actually only the radius that should be squared> That's almost right, but there's an issue related to order of operations. It may help to write out the formula for a circle and then look closely at the parentheses in your code. Here is the code you are to analyze: {code_snippet} Find the relevant issues and write the Socratic tutor-style response. Do not give the user too much help! Instead, just give them guidance so they can find the correct solution themselves. Put each issue in tags and put your final response in tags.""" return get_completion(prompt) # Example usage buggy_code = """ def calculate_average(numbers): total = 0 for num in numbers: total += num return total / len(numbers) """ feedback = code_tutor(buggy_code) print(feedback) ``` ## Tool Use with Function Calling Define tools that Claude can call to retrieve data or perform actions. ```python system_prompt = """Here are the functions available in JSONSchema format: get_user Retrieves a user from the database by their user ID. user_id int The ID of the user to retrieve. get_product Retrieves a product from the database by its product ID. product_id int The ID of the product to retrieve. add_user Adds a new user to the database. name str The name of the user. email str The email address of the user. """ # Use the system prompt with tool definitions response = get_completion("Add a new user named John Doe with email john@example.com", system_prompt) print(response) # Claude will respond with tool call format indicating which function to call with which parameters ``` ## Exercise Validation with Regex Patterns Automatically grade exercises using pattern matching and validation functions. ```python import re def grade_counting_exercise(text): """Check if response contains numbers 1, 2, and 3""" pattern = re.compile(r'^(?=.*1)(?=.*2)(?=.*3).*$', re.DOTALL) return bool(pattern.match(text)) def grade_spanish_exercise(text): """Check if response includes Spanish greeting""" return bool(re.search(r"hola", text, re.IGNORECASE)) def grade_name_exercise(text): """Check for exact match of name""" return text.strip() == "Michael Jordan" # Test student response student_prompt = "Count to three" response = get_completion(student_prompt) print(f"Response: {response}") print(f"Grade: {'PASS' if grade_counting_exercise(response) else 'FAIL'}") # Output: # Response: 1, 2, 3 # Grade: PASS ``` ## Summary This interactive tutorial serves as a complete learning resource for anyone wanting to master prompt engineering with Claude. The main use cases include onboarding new developers to Claude API, training teams on best practices for AI integration, prototyping conversational AI applications, and building production-ready prompt templates for specific industries. The course covers essential patterns like role-based prompting, XML tag usage for structured data, prefilling for output control, and multi-turn conversations that maintain context. Integration patterns demonstrated include direct API usage through the Anthropic Python SDK, AWS Bedrock integration for enterprise deployments, automatic exercise validation for learning platforms, and reusable helper functions that abstract common operations. The tutorial's modular structure allows developers to extract specific techniques—such as quote-based QA systems, few-shot classifiers, or Socratic tutoring patterns—and adapt them to their own applications. Whether building chatbots, document analysis systems, code review tools, or customer support automation, this tutorial provides battle-tested prompt patterns with working code examples that can be immediately deployed in production environments.