Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 15

Building an AI-Powered Educational Summarizer with Claude

Recommended resources

Welcome to the final lesson of our introductory module on the Anthropic Claude API. We've journeyed from understanding the fundamentals of LLMs and the Claude API, to controlling model outputs, and most recently, to building resilient API calls that can withstand real-world network issues. Now, we'll bring all these skills together to achieve our first major project milestone.

Today's objective is to build a complete Python script that accepts a learning topic from a user and leverages the Claude API to generate a structured, educational summary. This is the first "end-to-end" feature of our grasp.study clone, transforming a simple topic into a tangible piece of educational content. This process of creating a core functional unit should feel familiar from your experience building full-stack applications.

1. Designing an Effective Prompt

The quality of our educational summary hinges entirely on the quality of the instructions we give to Claude. This is the essence of prompt engineering. We need to craft a prompt that is clear, specific, and guides the model to produce output in a consistent, structured format that our application can reliably use.

The Anthropic team provides excellent guidance on structuring prompts. The video below, "Prompting 101," breaks down the key components of a great prompt.

Prompting 101 | Code w/ Claude

This official video from Anthropic, "Prompting 101", is an essential guide to effective prompt design. It explains how to structure your instructions to get the best results from Claude.

As you watch, focus on these core principles: Overall Structure: Watch the section on great prompt structure to understand the recommended sequence: task description, content, instructions, and examples. Task and Tone: Pay attention to how to define the model's role and desired tone. This is crucial for making Claude act as an expert educator, not just a generic chatbot. Providing Stable Context: The discussion on using the system prompt for background details is key. We will use this to tell Claude the structure we want for our summary. Enforcing Output Format: See how you can ask for a specific format using XML tags or JSON. This is vital for making the LLM's output programmatically useful.

Applying these principles, let's design a prompt to generate our educational summary. We want the summary to have a clear, repeatable structure. For our purposes, a good structure would be:

  • <title>: A concise title for the summary.
  • <introduction>: A brief paragraph introducing the topic.
  • <key_concepts>: A bulleted list of the most important concepts.
  • <analogy>: A simple analogy to help understand the core idea.
  • <summary>: A concluding paragraph to wrap up.

We can create a prompt template that incorporates this structure. Notice the use of XML tags, which, as the video explained, is a powerful technique for guiding Claude's output.

Here is a Python function that builds our prompt. It uses an f-string to insert the user-provided topic into the template.

def create_summary_prompt(topic: str) -> str:
    """Creates a structured prompt for generating an educational summary."""
    
    prompt = f"""
    Your role is an expert educator and content creator. You are tasked with creating a concise, easy-to-understand educational summary about a given topic.

    The topic is: {topic}

    Please generate the summary and structure your response using the following XML tags. Do not include any other text or preamble outside of these tags.

    <response>
        <title>A Clear and Concise Title About the Topic</title>
        <introduction>
            A brief, one-paragraph introduction to the topic, explaining what it is and why it's important.
        </introduction>
        <key_concepts>
            - A bullet point for the first key concept.
            - A bullet point for the second key concept.
            - A bullet point for the third key concept.
        </key_concepts>
        <analogy>
            A simple, relatable analogy to explain the core idea of the topic.
        </analogy>
        <summary>
            A short concluding paragraph that summarizes the main points.
        </summary>
    </response>
    """
    return prompt

This prompt clearly defines the role, provides the context (the topic), and gives explicit instructions on the output format.


2. Building the Python Script

Now, let's integrate this prompt into a complete Python script. This script will combine everything we've learned: setting up the client, managing the API key, making a resilient API call with tenacity, and processing the response.

Before we write the final script, let's quickly review the mechanics of a basic API call and how we can instruct Claude to generate specific artifacts, like a file or, in our case, structured text.

Claude 3.5 API in Python • Explore AWESOME Use Cases!

The video "Claude 3.5 API in Python" by pixegami provides a practical walkthrough of making API calls.

First, review the basics of a simple API call from this section. It covers the client, model, max_tokens, temperature, system prompt, and messages. Next, watch the demonstration starting at this point, where the user instructs Claude to write a Python program and save it to a file. This is a powerful parallel to our goal. We are similarly instructing Claude to generate a specific "artifact"—our structured XML summary—which our program will then receive and display.

With that context, let's assemble our final script for this module. Make sure you have the anthropic, python-dotenv, and tenacity libraries installed (pip install anthropic python-dotenv tenacity).

Create a file named .env in your project directory and add your API key to it:

ANTHROPIC_API_KEY="your_api_key_here"

Now, create a Python file, let's call it summary_generator.py, and add the following code. I've included detailed comments to explain each part of the script.

import os
import anthropic
from dotenv import load_dotenv
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type

# --- 1. Setup and Configuration ---

# Load environment variables from .env file (for the API key)
load_dotenv()

# Check if the API key is set
api_key = os.getenv("ANTHROPIC_API_KEY")
if not api_key:
    raise ValueError("ANTHROPIC_API_KEY environment variable not set!")

# Initialize the Anthropic client
client = anthropic.Anthropic(api_key=api_key)


# --- 2. Prompt Design ---

def create_summary_prompt(topic: str) -> str:
    """Creates a structured prompt for generating an educational summary."""
    # This is the same function we designed earlier.
    prompt = f"""
    Your role is an expert educator and content creator. You are tasked with creating a concise, easy-to-understand educational summary about a given topic.

    The topic is: {topic}

    Please generate the summary and structure your response using the following XML tags. Do not include any other text or preamble outside of these tags.

    <response>
        <title>A Clear and Concise Title About the Topic</title>
        <introduction>
            A brief, one-paragraph introduction to the topic, explaining what it is and why it's important.
        </introduction>
        <key_concepts>
            - A bullet point for the first key concept.
            - A bullet point for the second key concept.
            - A bullet point for the third key concept.
        </key_concepts>
        <analogy>
            A simple, relatable analogy to explain the core idea of the topic.
        </analogy>
        <summary>
            A short concluding paragraph that summarizes the main points.
        </summary>
    </response>
    """
    return prompt


# --- 3. Resilient API Call ---

# Apply the retry decorator from the previous lesson!
@retry(
    wait=wait_exponential(multiplier=1, min=2, max=30),
    stop=stop_after_attempt(5),
    retry=retry_if_exception_type((anthropic.RateLimitError, anthropic.APIStatusError))
)
def generate_summary(topic: str) -> str:
    """
    Generates an educational summary for a given topic using the Claude API.
    This function is decorated to be resilient to transient API errors.
    """
    print(f"\nGenerating summary for '{topic}'...")
    
    system_prompt = "You are an expert educator. Follow the user's instructions precisely to generate a structured educational summary."
    user_prompt = create_summary_prompt(topic)

    try:
        response = client.messages.create(
            model="claude-3-sonnet-20240229", # You can also try "claude-3-haiku-20240307"
            max_tokens=1024,
            temperature=0.2, # Lower temperature for more consistent, factual output
            system=system_prompt,
            messages=[
                {"role": "user", "content": user_prompt}
            ]
        )
        
        # The response content is a list; we are interested in the first text block.
        summary_text = response.content[0].text
        print("Summary generated successfully!")
        return summary_text

    except anthropic.APIError as e:
        print(f"An API error occurred: {e}")
        raise # Re-raise the exception to allow tenacity to handle retries


# --- 4. Main Execution Block ---

if __name__ == "__main__":
    print("--- Educational Summary Generator ---")
    
    try:
        # Get topic from user input
        user_topic = input("Enter a topic you want to learn about: ")
        
        # Generate the summary
        educational_summary = generate_summary(user_topic)
        
        # Print the final, structured output
        print("\n--- Here is your summary ---")
        print(educational_summary)

    except Exception as e:
        print(f"\nAn unexpected error occurred: {e}")
        print("The program could not complete the request.")

To run your script, open a terminal in your project directory and execute:
python summary_generator.py

When prompted, enter a topic like "Python Dictionaries", "API Rate Limiting", or "React State Management" and watch as Claude generates a structured summary for you.


Conclusion

Congratulations on completing the first project milestone! You have successfully built a Python script that integrates all the concepts from this module into a single, functional tool. This script is not just an exercise; it's the foundational block for the educational content engine of our grasp.study clone.

Key Takeaways:

  • Prompt Engineering is Key: The structure and clarity of your prompt directly determine the quality and consistency of the LLM's output.
  • Structure for Programmatic Use: Using techniques like XML tagging in your prompts forces the LLM to return data in a predictable format that your code can easily parse and use later.
  • Synthesizing Skills: Real-world applications are built by combining individual skills. We integrated environment management, prompt design, API communication, and error handling into one cohesive script.
  • Building Incrementally: We now have a tangible asset—a summary generator. This is a core component that we will build upon in the upcoming modules.

In the next module, Core Prompt Engineering Techniques, we will move beyond single-shot summaries. You'll learn advanced prompting strategies like few-shot learning, chain-of-thought, and how to reliably request JSON output. These skills will enable us to build the next major feature: the syllabus generation engine.