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.
Deze oefening maakt deel uit van de cursus
Designing Agentic Systems with LangChain
Oefeninstructies
- 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
elsestatement with the original input to return the appropriate message for non-palindromes.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
@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."