Build a tool with Python code
Now that your chatbot has the historical events and Wikipedia tools at its disposal, the school administration would also like you to add a grammar tool for the English curriculum. They've asked you to build a palindrome-checker that determines if an input phrase or word reads the same even when it is typed in reverse. The students should be able to use this tool to test different types of input strings to check if they are palindromes, such as "level" or "never odd or even", which both read the same when typed backwards.
This exercise is part of the course
Designing Agentic Systems with LangChain
Exercise instructions
- Specify the input type for the tool as a string.
- Convert the characters to lowercase using
.lower()
, removing any non-alphanumeric characters using.isalnum()
. - To determine if the text is a palindrome, check if the cleaned text matches its reversed version.
- Complete the placeholders of the
else
statement with the original input to return the appropriate message for non-palindromes.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
@tool
# Set input format to string
def palindrome_checker(text: ____) -> str:
"""Check if a word or phrase is a palindrome."""
# Remove non-alphanumeric characters and convert to lowercase
cleaned_text = ''.join(char.____() for char in ____ if char.____())
# Set up if-else block to check reversed text against original text
if cleaned_text == ____[::-1]:
return f"The phrase or word '{____}' is a palindrome."
else:
# Print an alternative statement if text is not a palindrome
____ f"The phrase or word '{____}' is not a palindrome."