共用方式為


建立 AI 代理程式及其工具

重要

這項功能處於公開預覽狀態

本文說明如何使用 Mosaic AI 代理程式架構來建立 AI 代理程式和工具。

了解如何使用 AI 遊樂場快速建立工具呼叫代理程式的原型,並將其匯出至 Mosaic AI 代理程式架構。

需求

建立 AI 代理程式工具

AI 代理程式會使用工具來執行語言產生以外的動作,例如擷取結構化或非結構化資料、執行程式碼,或與遠端服務對話 (例如傳送電子郵件或 Slack 訊息)。

若要使用 Mosaic AI 代理程式架構將工具提供給代理程式,您可以使用下列方法的任何組合:

  1. 建立或使用現有的 Unity 目錄函式作為工具,讓您輕鬆探索、治理及共用工具。
  2. 在本機將工具定義為代理程式程式碼中的 Python 函式。

不論您的代理程式是以自訂 Python 程式碼撰寫,還是使用 LangGraph 之類的代理程式撰寫,兩種方法都能運作。

定義工具時,請確定工具、其參數及其傳回值都已妥善記載,讓代理程式 LLM 可以了解工具的使用時機和方式。

使用 Unity 目錄函式來建立代理程式工具

這些範例會使用以筆記本環境或 SQL 編輯器撰寫的 Unity 目錄函式來建立 AI 代理程式工具。

在筆記本儲存格中執行以下程式碼。 它會使用 %sql 筆記本 magic 來建立名為 python_exec 的 Unity 目錄函式。

LLM 可以使用此工具執行由使用者提供給它們的 Python 程式碼。

%sql
CREATE OR REPLACE FUNCTION
main.default.python_exec (
 code STRING COMMENT 'Python code to execute. Remember to print the final result to stdout.'
)
RETURNS STRING
LANGUAGE PYTHON
DETERMINISTIC
COMMENT 'Executes Python code in the sandboxed environment and returns its stdout. The runtime is stateless and you can not read output of the previous tool executions. i.e. No such variables "rows", "observation" defined. Calling another tool inside a Python code is NOT allowed. Use standard python libraries only.'
AS $$
 import sys
 from io import StringIO
 sys_stdout = sys.stdout
 redirected_output = StringIO()
 sys.stdout = redirected_output
 exec(code)
 sys.stdout = sys_stdout
 return redirected_output.getvalue()
$$

在 SQL 編輯器中執行下列程式碼。

它會建立稱為 lookup_customer_info 的 Unity 目錄函式,LLM 可用來從假設 customer_data 資料表擷取結構化資料:

CREATE OR REPLACE FUNCTION main.default.lookup_customer_info(
  customer_name STRING COMMENT 'Name of the customer whose info to look up'
)
RETURNS STRING
COMMENT 'Returns metadata about a particular customer given the customer name, including the customer email and ID. The
customer ID can be used for other queries.'
RETURN SELECT CONCAT(
    'Customer ID: ', customer_id, ', ',
    'Customer Email: ', customer_email
  )
  FROM main.default.customer_data
  WHERE customer_name = customer_name
  LIMIT 1;

AI 遊樂場中的原型工具呼叫代理程式

建立 Unity 目錄函式之後,可以使用 AI 遊樂場將其提供給 LLM 並測試代理程式。 AI 遊樂場提供沙箱以建立工具呼叫代理程式的原型。

一旦您滿意 AI 代理程式,就可以匯出,以在 Python 中進一步開發,或將其部署為模型服務端點。

注意

Unity 目錄無伺服器計算、Mosaic AI 代理程式架構,以及每個權杖的付費基礎模型外部模型,都必須在目前的工作區中取得,才能在 AI 遊樂場中建立代理程式的原型。

建立工具呼叫端點的原型。

  1. 從遊樂場中,選取具有函式呼叫標籤的模型。

    選取工具呼叫 LLM

  2. 選取 [工具],然後在下拉式清單中指定您的 Unity 目錄函式名稱:

    選取工具

  3. 聊天以測試 LLM、工具和系統提示的目前組合,並嘗試各種變化。

    建立 LLM 原型

匯出與部署 AI 遊樂場代理程式

新增工具和測試代理程式之後,將遊樂場代理程式匯出至 Python 筆記本:

  1. 按下 [匯出代理程式程式碼] 以產生 Python 筆記本,協助您開發和部署 AI 代理程式。

    匯出代理程式程式碼之後,您會看到儲存至工作區的三個檔案:

    • agent 筆記本:包含使用 LangChain 定義代理程式的 Python 程式碼。
    • driver 筆記本:包含 Python 程式碼,可使用 Mosaic AI 代理程式架構來記錄、追蹤、註冊及部署 AI 代理程式。
    • config.yml:包含代理程式的組態資訊,包括工具定義。
  2. 開啟 agent 筆記本以查看定義代理程式的 LangChain 程式碼,使用此筆記本以程式設計方式測試並逐一查看代理程式,例如定義更多工具或調整代理程式的參數

    注意

    匯出的程式碼可能會有不同於 AI 遊樂場工作階段的行為。 Databricks 建議您執行匯出的筆記本,以進一步逐一查看和偵錯、評估代理程式品質,然後部署代理程式以與他人共用。

  3. 一旦您滿意代理程式的輸出,可以執行 driver 筆記本來記錄代理程式,並將代理程式部署至模型服務端點。

在程式碼中定義代理程式

除了從 AI 遊樂場產生代理程式程式碼之外,您也可以使用 LangChain 或 Python 程式碼等架構,自行在程式碼中定義代理程式。 若要使用代理程式架構部署代理程式,其輸入必須符合其中支援的輸入和輸出格式之一。

使用參數來設定代理程式

在代理程式架構,您可以使用參數來控制代理程式的執行方式。 這可讓您透過變更代理程式的不同特性來快速迭代,而無需更改程式碼。 參數是您在 Python 字典或 .yaml 檔案定義的索引鍵/值組。

若要設定程式碼,可以建立 ModelConfig,即一組索引鍵/值參數。 ModelConfig 是 Python 字典或 .yaml 檔案。 例如,您可以在開發期間使用字典,然後將其轉換成生產部署及 CI/CD 的 .yaml 檔案。 如需 ModelConfig 的詳細資訊,請參閱 MLflow 文件

範例 ModelConfig 如下所示。

llm_parameters:
  max_tokens: 500
  temperature: 0.01
model_serving_endpoint: databricks-dbrx-instruct
vector_search_index: ml.docs.databricks_docs_index
prompt_template: 'You are a hello world bot. Respond with a reply to the user''s
  question that indicates your prompt template came from a YAML file. Your response
  must use the word "YAML" somewhere. User''s question: {question}'
prompt_template_input_vars:
- question

若要從程式碼呼叫組態,請使用下列其中一項:

# Example for loading from a .yml file
config_file = "configs/hello_world_config.yml"
model_config = mlflow.models.ModelConfig(development_config=config_file)

# Example of using a dictionary
config_dict = {
    "prompt_template": "You are a hello world bot. Respond with a reply to the user's question that is fun and interesting to the user. User's question: {question}",
    "prompt_template_input_vars": ["question"],
    "model_serving_endpoint": "databricks-dbrx-instruct",
    "llm_parameters": {"temperature": 0.01, "max_tokens": 500},
}

model_config = mlflow.models.ModelConfig(development_config=config_dict)

# Use model_config.get() to retrieve a parameter value
value = model_config.get('sample_param')

支援的輸入格式

以下是代理程式支援的輸入格式。

  • 建議)使用 OpenAI 聊天完成結構描述的查詢。 其應具物件陣列做為 messages 參數。 此格式最適合用於 RAG 應用程式。

    question = {
        "messages": [
            {
                "role": "user",
                "content": "What is Retrieval-Augmented Generation?",
            },
            {
                "role": "assistant",
                "content": "RAG, or Retrieval Augmented Generation, is a generative AI design pattern that combines a large language model (LLM) with external knowledge retrieval. This approach allows for real-time data connection to generative AI applications, improving their accuracy and quality by providing context from your data to the LLM during inference. Databricks offers integrated tools that support various RAG scenarios, such as unstructured data, structured data, tools & function calling, and agents.",
            },
            {
                "role": "user",
                "content": "How to build RAG for unstructured data",
            },
        ]
    }
    
  • SplitChatMessagesRequest. 建議用於多回合聊天應用程式,特別是當您想要個別管理目前查詢及歷程記錄時。

    question = {
        "query": "What is MLflow",
        "history": [
            {
                "role": "user",
                "content": "What is Retrieval-augmented Generation?"
            },
            {
                "role": "assistant",
                "content": "RAG is"
            }
        ]
    }
    

針對 LangChain,Databricks 建議使用 LangChain 運算式語言來撰寫鏈。 在鏈定義程式碼,您可以使用 itemgetter 來取得訊息或 queryhistory 物件,視您使用的輸入格式而定。

支援的輸出格式

您的代理程式必須具有下列其中一種支援的輸出格式:

  • 建議)ChatCompletionResponse。 對於具有 OpenAI 回應格式互通性的客戶,建議使用此格式。
  • StringObjectResponse。 此格式是最簡單且最簡易的解譯格式。

針對 LangChain,請使用 MLflow 的 StringResponseOutputParser()ChatCompletionsOutputParser() 作為最後鏈步驟。 這麼做會將 LangChain AI 訊息格式化為代理程式相容格式。


  from mlflow.langchain.output_parsers import StringResponseOutputParser, ChatCompletionsOutputParser

  chain = (
      {
          "user_query": itemgetter("messages")
          | RunnableLambda(extract_user_query_string),
          "chat_history": itemgetter("messages") | RunnableLambda(extract_chat_history),
      }
      | RunnableLambda(fake_model)
      | StringResponseOutputParser() # use this for StringObjectResponse
      # ChatCompletionsOutputParser() # or use this for ChatCompletionResponse
  )

如果您使用 PyFunc,Databricks 建議使用類型提示來註記 predict() 函數的輸入與輸出資料類別,這些類別是 mlflow.models.rag_signatures 所定義類別的子類別。

您可以從 predict() 內的資料類別建構輸出物件,以確保遵循格式。 傳回的物件必須轉換成字典表示法,以確保其可序列化。


  from mlflow.models.rag_signatures import ChatCompletionRequest, ChatCompletionResponse, ChainCompletionChoice, Message

  class RAGModel(PythonModel):
    ...
      def predict(self, context, model_input: ChatCompletionRequest) -> ChatCompletionResponse:
        ...
        return asdict(ChatCompletionResponse(
            choices=[ChainCompletionChoice(message=Message(content=text))]
        ))

範例筆記本

這些筆記本會建立簡單的「Hello, world」鏈,說明如何在 Databricks 建立鏈應用程式。 第一個範例建立簡單的鏈。 第二個範例筆記本說明如何在開發期間使用參數來最小化程式碼變更。

簡單鏈筆記本

取得筆記本

簡單鏈驅動程式筆記本

取得筆記本

參數化鏈筆記本

取得筆記本

參數化鏈驅動程式筆記本

取得筆記本

下一步