為 Bob Shell 撰寫有效的提示詞

透過加入角色、情境和範例,為 Bob Shell 撰寫有效的提示詞,然後將模糊的請求改進為帶有錯誤處理且有良好文件說明的 Python 程式碼。

當你的提示詞指明任務、角色、情境和範例時,IBM Bob Shell 會產生更準確的程式碼。在本教學中,將一個模糊的請求重寫為結構化的提示詞,然後比較兩者的結果。

前提條件

若要確認已安裝 Bob Shell,請開啟終端機並檢查版本:

bob --version

什麼是提示詞?

提示詞是你給 Bob 的問題、請求或命令,以獲得你想要的輸出。模糊的提示詞會得到模糊的回答。一個好的提示詞清晰、具體,並提供足夠的情境,以便 Bob 理解你想要什麼。

提示詞的組成部分

有效的提示詞結合了以下組成部分:

組成部分用途範例
指令 (Instruction)告知 Bob 要執行的任務。清晰的指令可減少歧義。"Generate a software bill of materials (SBOM) for this API."
角色 (Role)指派人格,以便 Bob 根據該角色的視角調整其回答。"You are a senior software engineer with expertise in Python."
情境 (Context)新增背景資訊,例如情況、受眾、語氣或限制。"The function runs in a production service and must include error handling."
範例 (Example)顯示你希望 Bob 遵循的模式、格式或風格。"Follow the structure of @src/api/users.py."
提示 (Cue)引導至你想要的回答類型,通常放在提示詞的結尾。"Return only the function, starting with def."

你可以將提示詞儲存為 自訂斜線命令, 以便重複使用並與團隊共享。

什麼讓提示詞更有效?

以下最佳實踐可以幫助你為 Bob 撰寫有效的提示詞。

  • 具體說明: 你的提示詞越具體,Bob 就越能理解你想要什麼。 與其問「如何撰寫 Python 函式?」,不如問「如何撰寫一個 接受數字清單並傳回平均值的 Python 函式?」
  • 提供情境: 如果你的提示詞涉及特定的專案或程式碼庫, 請提供一些相關背景。這有助於 Bob 產生與你的情況相關的回答。 使用 @ 參照(例如 @src/main.py)引導 Bob 查看 特定檔案。
  • 拆解任務: 就像你在 backlog 中細化任務時一樣, 將複雜任務拆解為更小、更易管理的步驟。這可以幫助 Bob 產生更準確、更有針對性的回答。
  • 包含範例: 如果你在新增新的 API,可以指導 Bob 查看程式碼庫中 寫得好的 API 作為範例。你也可以在提示詞中包含範例, 向 Bob 展示你想要的格式或風格。

改進模糊的提示詞

在本節中,你將為 Bob 撰寫一個模糊的提示詞並查看輸出結果。 然後你將根據最佳實踐改進提示詞,以提高回答的品質。

目標是讓 Bob 產生一個以 UTC 格式列印目前日期和時間的 Python 函式。 該函式應有良好的文件說明並包含錯誤處理。

開啟終端機並在 Agent 模式 中啟動互動式工作階段:

bob chat --mode agent

輸入以下提示詞:

Write a Python function that prints the date and time.

Bob 將產生一個回答,但它可能無法滿足你的所有需求。

from datetime import datetime

def print_datetime():
    now = datetime.now()
    print(now.strftime("%Y-%m-%d %H:%M:%S"))

該函式沒有錯誤處理,且列印的是本機時間,而非 UTC 時間。

輸入 /clear 以重設對話歷程記錄,這樣第一個回答就不會影響下一個回答:

/clear

使用 提示詞組成部分 來改進你的提示詞:

  • 角色: "You are a senior software engineer with expertise in Python 3."
  • 指令: "Write a Python 3 function that prints the current date and time in UTC format."
  • 情境: "The function should be well documented and include error handling."
  • 範例: 引導 Bob 查看權威來源,例如 Real Python 異常處理最佳實踐。

輸入改進後的提示詞:

You are a senior software engineer with expertise in Python 3. 
Write a Python 3 function that prints the current date and time in UTC format. 
The function should be well documented and include error handling, 
modeled after https://realpython.com/ref/best-practices/exception-handling/.
"""
utc_datetime.py — Utility for printing the current UTC date and time.
"""

from datetime import datetime, timezone

def print_utc_datetime() -> None:
    """Print the current date and time in UTC (ISO 8601 format).

    Retrieves the current moment from the system clock, attaches UTC timezone
    info, formats it as an ISO 8601 string, and writes it to stdout.

    Returns:
        None

    Raises:
        OSError: If the system clock cannot be read (e.g., hardware failure or
            OS-level permission restrictions).
        ValueError: If datetime formatting unexpectedly fails (e.g., year out
            of the supported range).

    Example:
        >>> print_utc_datetime()
        Current UTC date and time: 2025-07-15T13:42:00.123456+00:00
    """
    try:
        now_utc: datetime = datetime.now(tz=timezone.utc)
    except OSError as exc:
        # System clock is unavailable or inaccessible.
        raise OSError("Failed to read the system clock.") from exc

    try:
        formatted: str = now_utc.isoformat()
    except ValueError as exc:
        # Extremely unlikely, but guard against out-of-range datetime values.
        raise ValueError(
            f"Failed to format the datetime object: {now_utc!r}"
        ) from exc

    print(f"Current UTC date and time: {formatted}")


if __name__ == "__main__":
    print_utc_datetime()

改進後的提示詞產生的函式使用 UTC 格式、包含 docstring 且進行了異常處理。

IBM SkillsBuild

IBM SkillsBuild 是一個免費的線上學習平台,提供與為 Bob 等 AI 助理撰寫有效提示詞相關的課程。

若要了解更多關於如何撰寫優質提示詞的資訊,請學習 Craft Precise Prompts for AI Models 課程。

後續步驟

在本教學中,你學習了有效提示詞的組成部分,並將一個模糊的提示詞改進為能夠可靠地產生所需輸出的提示詞。

前進至 建立和使用技能,將一個寫得好的提示詞轉化為 Bob 可以自動應用的可重複使用、可重複執行的工作流程。

這個主題如何?