開始使用免費開始

用 Python 程式碼建立一個工具

你的聊天機器人已經能使用歷史事件與 Wikipedia 工具,學校行政單位也希望你為英語課程新增一個文法工具。他們要求你建立一個回文(palindrome)檢查器,用來判斷輸入的片語或單字在反向輸入時是否與原本相同。學生應該可以用這個工具測試不同型態的輸入字串,看看是否為回文,例如「level」或「never odd or even」,這兩個在倒著輸入時讀起來都一樣。

本練習屬於課程

Designing Agentic Systems with LangChain

檢視課程

練習說明

  • 將此工具的輸入型別指定為字串。
  • 使用 .lower() 將字元轉為小寫,並用 .isalnum() 移除所有非英數字元。
  • 若要判斷文字是否為回文,檢查清理後的文字是否與其反轉版本相同。
  • else 陳述的占位符中填入原始輸入,為非回文的情況回傳適當的訊息。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

@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."
編輯並執行程式碼