建立代理應用程式

本指南將逐步說明如何建立基本的代理應用程式,可回答使用者關於天氣的查詢。

事前準備

請務必先完成設定操作說明,再按照本指南操作。

建立代理應用程式

建立代理應用程式和根代理:

  1. 開啟 CX Agent Studio 控制台。
  2. 選取或建立專案。
  3. 點選「建立您的第一個 AI 代理」或「建立代理」。
  4. 提供「weather app」做為代理名稱。
  5. 點選「建立」。 如果這是您為專案建立的第一個代理應用程式,可能需要 1 到 2 分鐘才能完成。系統會顯示代理建構工具,並為您建立根層級代理。

建立代理階層

這個代理應用程式會使用三個代理:

  • 根層級代理,負責向使用者致意,並委派工作給其他子代理。
  • 天氣代理,可回答天氣相關問題。
  • 結束對話的代理。

根代理已建立,但您應更新這個代理的設定:

  1. 按一下根代理的標題列。
  2. 您可以視需要變更代理名稱。
  3. 輸入說明:「Handles simple greetings and delegates to other agents」。
  4. 按一下「儲存」,然後關閉設定面板。

建立天氣代理:

  1. 點選根代理底部的「+」按鈕。
  2. 按一下「Add new sub-agent」(新增子代理)。
  3. 按一下新代理的標題列。
  4. 將名稱變更為「Weather agent」。
  5. 輸入說明:「Handles any weather related questions from the user」。
  6. 按一下「儲存」,然後關閉設定面板。

以類似方式,建立根層級代理的另一個子代理,名為「Farewell agent」,說明為「Handles user farewells and goodbyes」。

代理階層的螢幕截圖

建立天氣工具

工具用於將代理連結至外部系統,或提供給代理的內嵌程式碼。有了工具,代理就能與其他系統互動,進而擷取、更新、格式化或分析資訊。

在這個步驟中,您將建立天氣工具,用於擷取天氣資訊。在本指南中,這項工具會向使用者傳送模擬回覆。在實際的天氣應用程式中,這項工具會存取外部伺服器來取得資訊。

建立天氣工具:

  1. 按一下代理建構工具右側的工具按鈕。
  2. 點選「+」,為代理應用程式建立新工具。
  3. 按一下「Python code」。
  4. 貼上下列程式碼:

    def get_weather(city: str) -> dict:
      """Retrieves the current weather report for a specified city.
    
      Args:
        city (str): The name of the city.
    
      Returns:
        dict: A dictionary containing the weather information.
              Includes a 'status' key ('success' or 'error').
              If 'success', includes a 'report' key with weather details.
              If 'error', includes an 'error_message' key.
      """
      city_normalized = city.lower().replace(" ", "")
    
      mock_weather_db = {
        "newyork": {"status": "success",
          "report": "The weather in New York is sunny and 25°C."},
        "london": {"status": "success",
          "report": "It's cloudy in London and  15°C."},
        "tokyo": {"status": "success",
          "report": "Tokyo is experiencing light rain and 18°C."},
      }
      if city_normalized in mock_weather_db:
        return mock_weather_db[city_normalized]
      else:
        return {"status": "error",
          "error_message": f"No weather information for '{city}'."}
    
  5. 點選「建立」。

現在,您需要將這項工具新增至天氣代理:

  1. 在天氣代理的標題列中,按一下「+」按鈕。
  2. 按一下「新增工具」。
  3. 選取天氣工具。

建立代理指令

每個代理都有一組指令,定義代理應執行的操作。

提供參照代理的指令時,請使用 {@AGENT: Agent name} 語法。如要參照工具,請使用 {@TOOL: tool_name}。

為每個代理建立指令:

  1. 按一下根代理標題列中的「+」按鈕。
  2. 按一下「新增操作說明」。
  3. 輸入下列指示:

    You are a helpful weather application.
    Your job is to greet the user and delegate to other sub-agents as needed.
    When greeting the user, describe how you can help them.
    When the user asks for the weather, delegate to {@AGENT: Weather agent}.
    When the user is ending the conversation,
    delegate to {@AGENT: Farewell agent}.
    Handle only weather requests, greetings, and farewells.
    
  4. 點選「建立」。

  5. 以類似方式,為天氣代理新增下列指令:

    You are a helpful weather agent.
    When the user asks for the weather in a specific city,
    use {@TOOL: get_weather} to find the information.
    If the tool returns an error, inform the user politely.
    If the tool is successful, present the weather report clearly.
    
  6. 以類似方式,為道別代理新增下列指令:

    You are the Farewell Agent.
    Your ONLY task is to provide a polite goodbye message.
    

測試代理

現在可以使用模擬器與代理應用程式互動:

  1. 在控制台畫面左下角,按一下「預覽代理」列,展開視窗 (如果尚未展開)。
  2. 輸入「hello」,然後按下 Enter 鍵。 代理會回覆一般問候語。
  3. 輸入「what is the weather in new york?」,然後按下 Enter 鍵。 代理會回覆天氣資訊。
  4. 輸入「goodbye」,然後按下 Enter 鍵。 服務專員結束對話。

使用變數

變數可用來儲存及擷取執行階段的對話資料。這樣一來,代理就能在多輪對話之間記住資訊,提供更符合脈絡的互動體驗。您將為這個代理建立變數,擷取使用者名稱。

如要建立變數,請按照下列步驟操作:

  1. 按一下代理建構工具右側的變數按鈕。
  2. 按一下「建立變數」或「+」。
  3. 輸入「username」做為變數名稱。
  4. 將類型保留為「Text」。
  5. 點選「建立」。

定義變數後,您需要定義工具,讓代理更新變數:

  1. 按一下代理建構工具右側的工具按鈕。
  2. 點選「+」,為代理應用程式建立新工具。
  3. 按一下「Python code」。
  4. 貼上下列程式碼:

    from typing import Optional
    
    def update_username(username: str) -> Optional[str]:
      """Updates the current user's name"""
      set_variable("username", username)
    
  5. 點選「建立」。

將這項工具新增至根代理:

  1. 按一下根代理標題列中的「+」按鈕。
  2. 按一下「新增工具」。
  3. 選取 update_username 工具。

在根代理指示中加入下列句子,使用 {variable_name} 語法參照變數:

If provided, the current user is {username},
and you should address them with this name.
You can use {@TOOL: update_username} to update the user's name if they provide
it.

您可以再次測試代理,確認變數使用情形:

  1. 按一下模擬器標題列中的「Start new conversation」。
  2. 輸入「Hello, my name is Frank」。
  3. 輸入「你的資訊有多準確?」。

請注意,代理現在會使用您的名稱回覆。您也可以展開模擬器對話的「Steps」(步驟) 部分,驗證工具執行情形等。

控管結束工作階段的方式

根據預設,每個代理都會設為使用 end_session系統工具,但您可以建立明確的操作說明,提高結束工作階段的可靠性和控制能力。

在根代理和天氣代理中,點選工具旁的「x」x,移除 end_session 工具。這樣一來,就只有道別代理會結束工作階段。

在道別代理的指令中,新增下列內容:

After providing the goodbye message and confirming the user has no more
questions, execute the tool {@TOOL: end_session}(reason="success").

使用回呼,在工作階段結束時強制顯示靜態訊息

回呼提供一種機制,可使用 Python 程式碼,掛接到特定代理的執行程序。您可以在預先定義的特定時間點,觀察、自訂,甚至控制代理的行為。

您可以運用多種回呼類型,每種回呼類型都會在對話回合的特定時間點執行。

在本教學課程中,請在結束工作階段時,將靜態訊息附加至模型回覆:

  1. 按一下 farewell 代理的標題列。
  2. 按一下「Add callback」。
  3. 選取「After LLM」。
  4. 請輸入以下程式碼:

    SURVEY_MESSAGE = "Click here to take our post call survey."
    
    def after_model_callback(
        callback_context: CallbackContext,
        llm_response: LlmResponse
    ) -> Optional[LlmResponse]:
      for index, part in enumerate(llm_response.content.parts):
        if part.has_function_call('end_session'):
          return LlmResponse.from_parts(parts=[
            *llm_response.content.parts,
            Part.from_text(SURVEY_MESSAGE)
    
        ])
      return None
    
  5. 按一下「完成」。

  6. 按一下「儲存」。

您可以再次測試代理,確認工作階段結束行為:

  1. 按一下模擬器標題列中的「Start new conversation」。
  2. 輸入「Hello」。
  3. 輸入「Goodbye」。

請注意,代理現在會使用您附加的訊息回覆。

調整指令結構

如要改善代理行為,可以採用最適合模型處理的任意形式 XML 格式,建構所有代理指令。請為每個代理執行下列操作:

  1. 開啟代理的「指令」面板。
  2. 按一下右上方的「結構」按鈕。
  3. 按一下「儲存」。

部署

代理運作後,您有多種部署選項。