Lesson 6 of 6
Build your summariser tool
Combine the prompt, file handling and API call into a single script that takes a file path and prints a summary.
7 minClaude, Gemini and ChatGPT
After this lesson, you will be able to turn the script from the earlier lessons into a reusable command-line summariser tool. You will write one script that reads a text file, builds a prompt, calls the Claude API, and prints a summary. You will also add a simple way to change the output length from the command line.
Start from the script you have
In Lesson 5 you wrote a script that reads a file and sends its contents to Claude with a fixed prompt. That script already does most of the work. In this lesson you will clean it up, make the prompt a separate constant, and add a command-line option for the summary length. The result is a tool you can run on any text file.
Create a new file called summarise.py and copy the code below. It is the same as the script from Lesson 5, with two changes: the prompt is now a constant at the top, and the script prints a short usage message if you run it without a file path.
import os
import sys
from anthropic import Anthropic
from anthropic import AuthenticationError, RateLimitError
# Replace with a current model from the Anthropic model list
MODEL_NAME = "claude-3-5-sonnet-20241022"
PROMPT_TEMPLATE = """You are a patient teacher who explains technical ideas to beginners.
Explain the text below in simple words.
Write three bullet points. Each bullet point must be one sentence.
Text:
{text}"""
client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
temperature = 0.3
max_tokens = 200
if len(sys.argv) != 2:
print("Usage: python summarise.py <file_path>")
sys.exit(1)
file_path = sys.argv[1]
try:
with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
except FileNotFoundError:
print(f"File not found: {file_path}")
sys.exit(1)
prompt = PROMPT_TEMPLATE.format(text=text)
try:
message = client.messages.create(
model=MODEL_NAME,
max_tokens=max_tokens,
temperature=temperature,
messages=[
{"role": "user", "content": prompt}
]
)
print(message.content[0].text)
except AuthenticationError:
print("Authentication failed. Check your ANTHROPIC_API_KEY.")
except RateLimitError:
print("Rate limit exceeded. Wait a moment and try again.")Run the script on the pandas.txt file you used earlier. If you do not have that file, create it with the Pandas text from Lesson 2.
python summarise.py pandas.txtThe output should be three bullet points that explain Pandas in simple words. The prompt is now separate from the code, so you can change the instructions without touching the rest of the script.
Add a length option
The tool always asks for three bullet points. Sometimes you may want a shorter or longer summary. You can add an optional second command-line argument that sets the number of bullet points. The prompt will then ask for that many bullet points.
Change the top of summarise.py so that it reads an optional second argument. If the argument is missing, use three bullet points as the default. The code below shows the new parts. Replace the lines from if len(sys.argv) != 2: to the end of the file with this version.
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("Usage: python summarise.py <file_path> [num_bullets]")
sys.exit(1)
file_path = sys.argv[1]
if len(sys.argv) == 3:
try:
num_bullets = int(sys.argv[2])
except ValueError:
print("Number of bullet points must be an integer.")
sys.exit(1)
else:
num_bullets = 3
try:
with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
except FileNotFoundError:
print(f"File not found: {file_path}")
sys.exit(1)
prompt = PROMPT_TEMPLATE.format(text=text, num_bullets=num_bullets)Now update the PROMPT_TEMPLATE constant so that it includes the number of bullet points. Replace the constant at the top of the file with this version.
PROMPT_TEMPLATE = """You are a patient teacher who explains technical ideas to beginners.
Explain the text below in simple words.
Write {num_bullets} bullet points. Each bullet point must be one sentence.
Text:
{text}"""The full script now looks like this. Check that your file matches.
import os
import sys
from anthropic import Anthropic
from anthropic import AuthenticationError, RateLimitError
# Replace with a current model from the Anthropic model list
MODEL_NAME = "claude-3-5-sonnet-20241022"
PROMPT_TEMPLATE = """You are a patient teacher who explains technical ideas to beginners.
Explain the text below in simple words.
Write {num_bullets} bullet points. Each bullet point must be one sentence.
Text:
{text}"""
client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
temperature = 0.3
max_tokens = 200
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("Usage: python summarise.py <file_path> [num_bullets]")
sys.exit(1)
file_path = sys.argv[1]
if len(sys.argv) == 3:
try:
num_bullets = int(sys.argv[2])
except ValueError:
print("Number of bullet points must be an integer.")
sys.exit(1)
else:
num_bullets = 3
try:
with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
except FileNotFoundError:
print(f"File not found: {file_path}")
sys.exit(1)
prompt = PROMPT_TEMPLATE.format(text=text, num_bullets=num_bullets)
try:
message = client.messages.create(
model=MODEL_NAME,
max_tokens=max_tokens,
temperature=temperature,
messages=[
{"role": "user", "content": prompt}
]
)
print(message.content[0].text)
except AuthenticationError:
print("Authentication failed. Check your ANTHROPIC_API_KEY.")
except RateLimitError:
print("Rate limit exceeded. Wait a moment and try again.")Run the tool with a different number of bullet points.
python summarise.py pandas.txt 5The output should now have five bullet points. If you run it without the second argument, it still gives three.
Handle long files
The script reads the whole file into memory. For very large files this may cause an error or a slow request. A simple safeguard is to check the file size before reading. Add this check inside the try block, just after the with open(...) line and before text = file.read(). The os module is already imported at the top of the file, so you do not need to add a new import.
file_size = os.path.getsize(file_path)
if file_size > 100_000:
print("File is too large. Please use a file smaller than 100,000 bytes.")
sys.exit(1)The full script after this change is below. Replace your entire summarise.py with this version to avoid any missing import.
import os
import sys
from anthropic import Anthropic
from anthropic import AuthenticationError, RateLimitError
# Replace with a current model from the Anthropic model list
MODEL_NAME = "claude-3-5-sonnet-20241022"
PROMPT_TEMPLATE = """You are a patient teacher who explains technical ideas to beginners.
Explain the text below in simple words.
Write {num_bullets} bullet points. Each bullet point must be one sentence.
Text:
{text}"""
client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
temperature = 0.3
max_tokens = 200
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("Usage: python summarise.py <file_path> [num_bullets]")
sys.exit(1)
file_path = sys.argv[1]
if len(sys.argv) == 3:
try:
num_bullets = int(sys.argv[2])
except ValueError:
print("Number of bullet points must be an integer.")
sys.exit(1)
else:
num_bullets = 3
try:
with open(file_path, "r", encoding="utf-8") as file:
file_size = os.path.getsize(file_path)
if file_size > 100_000:
print("File is too large. Please use a file smaller than 100,000 bytes.")
sys.exit(1)
text = file.read()
except FileNotFoundError:
print(f"File not found: {file_path}")
sys.exit(1)
prompt = PROMPT_TEMPLATE.format(text=text, num_bullets=num_bullets)
try:
message = client.messages.create(
model=MODEL_NAME,
max_tokens=max_tokens,
temperature=temperature,
messages=[
{"role": "user", "content": prompt}
]
)
print(message.content[0].text)
except AuthenticationError:
print("Authentication failed. Check your ANTHROPIC_API_KEY.")
except RateLimitError:
print("Rate limit exceeded. Wait a moment and try again.")Now the tool refuses files larger than 100,000 bytes. You can adjust this limit to suit your needs.
Your summariser tool is ready
You now have a single script that takes a file path and prints a summary. The prompt is easy to change, the number of bullet points is adjustable, and the script handles missing files and large files. This is a solid base for further improvements, such as different summary styles or output formats.
Key takeaways
- A reusable tool keeps the prompt separate from the code so you can change instructions without touching the API call.
- Command-line arguments let you control the tool's behaviour without editing the script.
- Check user input and file conditions, such as missing files or very large files, to make the tool robust.
- The summariser script combines file reading, prompt building, and the Claude API call into one workflow.
Try it
Modify summarise.py so that the output format can be chosen with a third command-line argument. The argument should be either bullets or paragraph. If it is bullets, the prompt asks for bullet points as before. If it is paragraph, the prompt asks for a single paragraph summary. If the argument is missing, default to bullets. To allow the third argument, change the len(sys.argv) check to accept between two and four arguments (the script name, file path, optional number of bullets, optional output format). Update the prompt template to use this format choice. Run the script with python summarise.py pandas.txt 3 paragraph and check that the output is one paragraph, not bullet points. Then run python summarise.py pandas.txt and confirm it still gives three bullet points. A good result is a script that handles both formats and the default correctly.
Official documentation
Written with AI and checked automatically. Tools change, so a command may behave differently in the version you install. Spotted a mistake? Tell us.