評估你的 AI 代理(預覽)(經典版)

僅適用於:Foundry(經典)入口。 這篇文章無法在新的 Foundry 入口網站中提供。 了解更多關於新入口網站的資訊。

本文中的連結可能會開啟新版 Microsoft Foundry 文件的內容,而非您目前正在瀏覽的 Foundry(經典版)文件。

重要

本文中標示為(預覽)的項目目前正處於公開預覽階段。 此預覽版未簽訂服務水準協議,且不建議用於生產工作負載。 某些功能可能不被支援或功能受限。 欲了解更多資訊,請參閱Microsoft Azure預覽補充使用條款

AI 代理是強大的生產力助理,能為企業需求創造工作流程。 然而,由於其複雜的互動模式,可觀測性具有挑戰性。 在本文中,您將學習如何利用內建的評估器評估 Microsoft Foundry 代理或其他代理程式。

為了建立生產環境就緒的代理應用程式並確保可觀察性與透明度,開發者需要工具不僅評估代理工作流程的最終輸出,也評估工作流程的品質與效率。

像是使用者查詢「weather tomorrow」這類事件會觸發代理式工作流程。 為了產生最終回應,工作流程包括透過使用者意圖推理、呼叫工具,以及使用檢索增強生成。

Microsoft Foundry SDK 用於評估與 Foundry 入口網站目前處於公開預覽階段,但 API 通常可用於模型與資料集評估(代理評估仍處於公開預覽階段)。 本文中標示為(預覽)的 Azure AI 評估 SDK 及評估器目前已在各處公開預覽。

在此過程中,評估工作流程的每個步驟以及最終成果的品質與安全性至關重要。 這些評估面向被具體化為以下代理人的評估器:

  • 意圖解析:衡量代理人是否正確識別使用者意圖。
  • 工具呼叫準確度:衡量代理人是否正確地對使用者請求執行工具呼叫。
  • 任務依從性:衡量代理人的最終回應是否符合其系統訊息及先前步驟所指派的任務。

利用內建的完整評估器套件,評估您代理工作流程的其他品質與安全面向。 一般來說,代理會發出代理訊息。 將代理訊息轉換為評估人員所需的正確評估資料可能具有挑戰性。 如果您使用 Foundry Agent Service 建立您的代理,您可以透過我們的轉換支持無縫地評估它。 如果你是在 Foundry Agent Service 之外建置代理,仍可依照你的代理工作流程使用評估器,將代理訊息解析成 所需的資料格式。 請參考 評估其他代理人的範例。

開始

安裝 Azure AI 評估 SDK 中的 evaluators 套件:

pip install azure-ai-evaluation

評估 Microsoft Foundry 代理程式

如果您使用 Foundry Agent Service,您可以透過我們為 Microsoft Foundry 及 語意核心 代理人提供的轉換支援,無縫評估您的代理人。 以下評估器支援轉換器回傳的評估資料:IntentResolutionToolCallAccuracyTaskAdherenceRelevanceGroundedness和 。

如果你要建置其他輸出不同架構的代理,就把它們轉換成通用的 OpenAI 風格 代理訊息架構 ,並使用前面的評估器。 更一般來說,如果你能將客服訊息解析成 所需的資料格式,你也可以使用我們所有的評估工具。

AI 輔助評估者的模型支援

AzureOpenAI 與 OpenAI 推理模型 與非推理模型會依評估者不同而支援 LLM-judge:

評估員 作為評審的推理模型(範例:來自 Azure OpenAI / OpenAI 的 o 系列模型) 非推理模型作為評測者(例如:gpt-4.1、gpt-4o 等) 啟用
IntentResolutionTaskAdherenceToolCallAccuracyResponseCompletenessCoherenceFluencySimilarityGroundednessRetrievalRelevance 支援 支援 初始化評估器時設定 is_reasoning_model=True 額外參數
其他評估者 不支援 支援 --

對於需要精細推理的複雜評估,請使用強有力的推理模型,以 4.1-mini 平衡推理效能與成本效益。

工具呼叫評估支援

ToolCallAccuracyEvaluator 支援於 Microsoft Foundry 代理程式中對以下工具進行評估:

  • 檔案搜尋
  • Azure AI 搜尋服務
  • Bing 基礎
  • Bing 自訂搜尋
  • SharePoint 基礎設置
  • 程式碼直譯器
  • Fabric 資料代理
  • OpenAPI
  • 功能工具(使用者自訂工具)

然而,如果你在代理執行中使用非支援工具,評估器會輸出「通過」並說明不支援評估所調用工具的理由,方便過濾這些案例。 為了啟用評估,將非支援工具包裝為使用者自訂工具。

這個範例展示了如何建置並評估 Microsoft Foundry 代理程式。 除了評估之外,Foundry Agent Service 還需要pip install azure-ai-projects azure-identity、Foundry 專案的連接字串以及支援的模型。

建立代理程式執行緒與執行操作

經紀人可以使用工具。 以下是一個為代理建立自訂工具的範例(以模擬天氣函數為例):

from azure.ai.projects.models import FunctionTool, ToolSet
from typing import Set, Callable, Any
import json

# Define a custom Python function.
def fetch_weather(location: str) -> str:
    """
    Fetches the weather information for the specified location.

    :param location (str): The location to fetch weather for.
    :return: Weather information as a JSON string.
    :rtype: str
    """
    # In a real-world scenario, you'd integrate with a weather API.
    # In the following code snippet, we mock the response.
    mock_weather_data = {"Seattle": "Sunny, 25°C", "London": "Cloudy, 18°C", "Tokyo": "Rainy, 22°C"}
    weather = mock_weather_data.get(location, "Weather data not available for this location.")
    weather_json = json.dumps({"weather": weather})
    return weather_json

user_functions: Set[Callable[..., Any]] = {
    fetch_weather,
}

# Add tools that the agent will use. 
functions = FunctionTool(user_functions)

toolset = ToolSet()
toolset.add(functions)

AGENT_NAME = "Seattle Tourist Assistant"

如果你使用Foundry(非 Hub)專案,請使用以下工具組建立代理程式:

如果你使用的是基於 Foundry Hub 的專案(只支援較低版本的 azure-ai-projects<1.0.0b10azure-ai-agents<1.0.0b10),請遷移到 最新的 Foundry Agent Service SDK Python客戶端庫。 欲了解更多資訊,請參閱 用於記錄批次評估結果的 Foundry 專案設定。

請用以下工具組建立一個代理:

import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from dotenv import load_dotenv

load_dotenv()

# Create an Azure AI Client from an endpoint, copied from your Foundry project.
# You need to login to Azure subscription via Azure CLI and set the environment variables
# Foundry project endpoint, example: AZURE_AI_PROJECT=https://your-account.services.ai.azure.com/api/projects/your-project
project_endpoint = os.environ["AZURE_AI_PROJECT"]  # Ensure the PROJECT_ENDPOINT environment variable is set

# Create an AIProjectClient instance
project_client = AIProjectClient(
    endpoint=project_endpoint,
    credential=DefaultAzureCredential(),  # Use Azure Default Credential for authentication
)

# Create an agent with the toolset 
agent = project_client.agents.create_agent(
    model=os.environ["MODEL_DEPLOYMENT_NAME"],  # Model deployment name
    name="my-agent",  # Name of the agent
    instructions="You are a helpful agent",  # Instructions for the agent
    toolset=toolset
)
print(f"Created agent, ID: {agent.id}")

# Create a thread for communication
thread = project_client.agents.threads.create()
print(f"Created thread, ID: {thread.id}")

# Add a message to the thread
message = project_client.agents.messages.create(
    thread_id=thread.id,
    role="user",  # Role of the message sender
    content="What is the weather in Seattle today?",  # Message content
)
print(f"Created message, ID: {message.id}")

# Create and process an agent run
run = project_client.agents.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)
print(f"Run finished with status: {run.status}")

# Check if the run failed
if run.status == "failed":
    print(f"Run failed: {run.last_error}")

# Fetch and log all messages
messages = project_client.agents.messages.list(thread_id=thread.id)
for message in messages:
    print(f"Role: {message.role}, Content: {message.content}")
    

評估單一代理運行實例

建立代理執行後,使用轉換器將 Microsoft Foundry 代理執行緒資料轉換成評估人員能理解的必要評估資料。

import json, os
from azure.ai.evaluation import AIAgentConverter, IntentResolutionEvaluator

# Initialize the converter for Microsoft Foundry agents.
converter = AIAgentConverter(project_client)

# Specify the thread and run ID.
thread_id = thread.id
run_id = run.id

converted_data = converter.convert(thread_id, run_id)

就是這樣! converted_data 包含這些評估器所需的所有輸入。 你不需要閱讀每個評估者的輸入需求,也不需要花時間解析這些輸入。 選擇你的評估器,並在這次運行中調用評估器。 根據評審不同,我們支援Azure OpenAI 或 OpenAI 推理模型,以及非推理模型供評審使用:

評估員 作為評審的推理模型(範例:來自 Azure OpenAI / OpenAI 的 o 系列模型) 非推理模型作為評審(例如:gpt-4.1、gpt-4o 等) 啟用
GroundednessProEvaluator之外的所有品質評估員 支援 支援 初始化評估器時設定 is_reasoning_model=True 額外參數
GroundednessProEvaluator 使用者不需要支援模型 使用者不需要支援模型 --

對於需要精細推理的複雜任務,建議使用強力推理模型 o3-mini ,或後續推出的 o 系列迷你模型,以平衡推理效能與成本效益。

你在quality_evaluatorssafety_evaluators中建立一份品質與安全評估員名單。 你會在 評估多次代理執行或執行緒時參考它們

# This is specific to agentic workflows.
from azure.ai.evaluation import IntentResolutionEvaluator, TaskAdherenceEvaluator, ToolCallAccuracyEvaluator 
# Other quality, risk, and safety metrics:
from azure.ai.evaluation import RelevanceEvaluator, CoherenceEvaluator, CodeVulnerabilityEvaluator, ContentSafetyEvaluator, IndirectAttackEvaluator, FluencyEvaluator
from azure.identity import DefaultAzureCredential

import os
from dotenv import load_dotenv
load_dotenv()

model_config = {
    "azure_deployment": os.getenv("AZURE_DEPLOYMENT_NAME"),
    "api_key": os.getenv("AZURE_OPENAI_API_KEY"),
    "azure_endpoint": os.getenv("AZURE_OPENAI_ENDPOINT"),
    "api_version": os.getenv("AZURE_API_VERSION"),
}

# example config for a reasoning model
reasoning_model_config = {
    "azure_deployment": "o4-mini",
    "api_key": os.getenv("AZURE_OPENAI_API_KEY"),
    "azure_endpoint": os.getenv("AZURE_OPENAI_ENDPOINT"),
    "api_version": os.getenv("AZURE_API_VERSION"),
}

# Evaluators you might want to use with reasoning models 
quality_evaluators = {evaluator.__name__: evaluator(model_config=reasoning_model_config, is_reasoning_model=True) for evaluator in [IntentResolutionEvaluator, TaskAdherenceEvaluator, ToolCallAccuracyEvaluator]}

# Other evaluators you might NOT want to use with reasoning models 
quality_evaluators.update({ evaluator.__name__: evaluator(model_config=model_config) for evaluator in [CoherenceEvaluator, FluencyEvaluator, RelevanceEvaluator]})

## Using Foundry (non-Hub) project endpoint, example: AZURE_AI_PROJECT=https://your-account.services.ai.azure.com/api/projects/your-project
azure_ai_project = os.environ.get("AZURE_AI_PROJECT")

safety_evaluators = {evaluator.__name__: evaluator(azure_ai_project=azure_ai_project, credential=DefaultAzureCredential()) for evaluator in [ContentSafetyEvaluator, IndirectAttackEvaluator, CodeVulnerabilityEvaluator]}

# Reference the quality and safety evaluator list above.
quality_and_safety_evaluators = {**quality_evaluators, **safety_evaluators}

for name, evaluator in quality_and_safety_evaluators.items():
    result = evaluator(**converted_data)
    print(name)
    print(json.dumps(result, indent=4)) 

輸出格式

AI輔助品質評估器會對查詢和回應配對返回結果。 結果是一本包含以下內容的字典:

  • {metric_name}:提供一個數值分數,可以是李克特量表上的整數(1到5),或是一個介於0到1之間的浮點數。
  • {metric_name}_label:若指標自然輸出二進位分數,則提供二元標籤。
  • {metric_name}_reason:解釋為何每個資料點會給出特定的分數或標籤。
  • details: 包含單一代理執行品質的除錯資訊的可選輸出。

為了更清楚,所有評估器都接受一個二進位閾值(除非其輸出本身就是二進位),並產生兩個新的鍵值。 對於二元化閾值,系統會預設一個值,使用者可以修改該閾值。 這兩個新鑰匙是:

  • {metric_name}_result:基於二元化閾值的「通過」或「失敗」字串。
  • {metric_name}_threshold:由預設或使用者設定的數值二元化閾值。

請看以下部分評估器的範例輸出:

{
    "intent_resolution": 5.0, # likert scale: 1-5 integer 
    "intent_resolution_threshold": 3,
    "intent_resolution_result": "pass", # pass because 5 > 3 the threshold
    "intent_resolution_reason": "The assistant correctly understood the user's request to fetch the weather in Seattle. It used the appropriate tool to get the weather information and provided a clear and accurate response with the current weather conditions in Seattle. The response fully resolves the user's query with all necessary information."
}
{
    "task_adherence": 5.0, # likert scale: 1-5 integer 
    "task_adherence_threshold": 3,
    "task_adherence_result": "pass", # pass because 5 > 3 the threshold
    "task_adherence_reason": "The response accurately follows the instructions, fetches the correct weather information, and relays it back to the user without any errors or omissions."
}
{
    "tool_call_accuracy": 5,  # a score between 1-5, higher is better
    "tool_call_accuracy_threshold": 3,
    "tool_call_accuracy_result": "pass", # pass because 5 > 3 the threshold
    "details": { ... } # helpful details for debugging the tool calls made by the agent
}

評估多個代理程式運行或執行緒

若要評估多個代理執行或執行緒,請使用批次 evaluate() API 進行非同步評估。 首先,利用轉換器支援將代理執行緒資料轉換成檔案:

import json
from azure.ai.evaluation import AIAgentConverter

# Initialize the converter.
converter = AIAgentConverter(project_client)

# Specify a file path to save the agent output (evaluation input data) to.
filename = os.path.join(os.getcwd(), "evaluation_input_data.jsonl")

evaluation_data = converter.prepare_evaluation_data(thread_ids=thread_id, filename=filename) 

print(f"Evaluation data saved to {filename}")

透過一行程式碼完成評估資料,您可以選擇評估人員來評估代理人的品質,並提交批次評估。 以下範例中,請參考「 評估單一代理執行quality_and_safety_evaluators」節中相同的品質與安全評估員名單:

import os
from dotenv import load_dotenv
load_dotenv()

# Batch evaluation API (local):
from azure.ai.evaluation import evaluate

response = evaluate(
    data=filename,
    evaluation_name="agent demo - batch run",
    evaluators=quality_and_safety_evaluators,
    # optionally, log your results to your Foundry project for rich visualization 
    azure_ai_project=os.environ.get("AZURE_AI_PROJECT"),  # example: https://your-account.services.ai.azure.com/api/projects/your-project
)
# Inspect the average scores at a high level.
print(response["metrics"])
# Use the URL to inspect the results on the UI.
print(f'Foundry URL: {response.get("studio_url")}')

選擇網址後,你會被導向 Foundry。 查看您在 Foundry 專案中的評估結果,並除錯您的應用程式。 利用理由欄位和通過/不通過結果來評估申請的品質與安全性。 你可以執行多次並對其進行比較,以測試是否有回歸或進步。

使用 Azure AI 評估 SDK 用戶端函式庫,評估您的 Microsoft Foundry 代理,並支援轉換器,實現代理工作流程的可觀察性與透明度。

評估其他代理人

即使你使用客服服務以外的客服人員,仍可透過準備正確的資料來評估他們,供你選擇的評估者使用。

代理通常發送訊息以與使用者或其他代理互動。 內建的評估器可接受簡單的資料型別,例如 queryresponseground_truth 中的字串,並根據 單次資料輸入需求進行。 然而,由於代理間複雜的互動模式及框架差異,從代理訊息中提取這些簡單資料型態具有挑戰性。 例如,單一使用者查詢可能觸發一長串代理訊息,通常會呼叫多個工具。

如以下範例所示,你可以啟用以下內建評估器的代理訊息支援,以評估代理工作流程的這些面向。 這些評估者在評估代理人時,可能會採用 tool_callstool_definitions 作為代理人獨有的參數。

評估員 query response tool_calls tool_definitions
IntentResolutionEvaluator 必修條件: Union[str, list[Message]] 必要條件: Union[str, list[Message]] 不適用 可選: list[ToolCall]
ToolCallAccuracyEvaluator 必修條件: Union[str, list[Message]] 可選: Union[str, list[Message]] 可選: Union[dict, list[ToolCall]] 必要條件: list[ToolDefinition]
TaskAdherenceEvaluator 必須:Union[str, list[Message]] 必修條件: Union[str, list[Message]] 不適用 可選: list[ToolCall]
GroundednessEvaluator 必修條件: Union[str, list[Message]] 必要條件: Union[str, list[Message]] 不適用 必要條件:list[ToolCall]
  • Messagedict OpenAI 風格的訊息描述客服與使用者的互動, query 且必須包含系統訊息作為第一則訊息。
  • ToolCalldict 指定在代理與使用者互動時所呼叫的工具。
  • ToolDefinitiondict 描述代理人可用的工具。

對於 ToolCallAccuracyEvaluator,你必須提供其中之一 responsetool_calls

GroundednessEvaluator 需要 tool_definitions 評估代理人回應與其接收的工具輸出是否具有理據性。

以下範例展示了兩種資料格式:簡單代理資料與代理訊息。 然而,由於這些評估者有獨特的需求,請參考 範例筆記本,該筆記本說明了每位評估者的可能輸入路徑。

所有 內建的 AI 輔助品質評估器都會 對每個輸入輸出通過或不通過的結果。

簡單代理資料

在簡單的代理資料格式中,queryresponse 是簡單的 Python 字串。 例如:

import os
import json
from azure.ai.evaluation import AzureOpenAIModelConfiguration
from azure.identity import DefaultAzureCredential
from azure.ai.evaluation import IntentResolutionEvaluator, ResponseCompletenessEvaluator
  
model_config = AzureOpenAIModelConfiguration(
    azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
    api_key=os.environ["AZURE_OPENAI_API_KEY"],
    api_version=os.environ["AZURE_OPENAI_API_VERSION"],
    azure_deployment=os.environ["MODEL_DEPLOYMENT_NAME"],
)
 
intent_resolution_evaluator = IntentResolutionEvaluator(model_config)

# Evaluate the query and response as strings.
# The following is a positive example. Intent is identified and understood and the response correctly resolves user intent.
result = intent_resolution_evaluator(
    query="What are the opening hours of the Eiffel Tower?",
    response="Opening hours of the Eiffel Tower are 9:00 AM to 11:00 PM.",
)
print(json.dumps(result, indent=4))
 

請參考以下輸出(詳情請參見 輸出格式 ):

{
    "intent_resolution": 5.0,
    "intent_resolution_result": "pass",
    "intent_resolution_threshold": 3,
    "intent_resolution_reason": "The response provides the opening hours of the Eiffel Tower, which directly addresses the user's query. The information is clear, accurate, and complete, fully resolving the user's intent.",
}

代理工具呼叫與定義

請參考以下 ToolCallAccuracyEvaluatortool_callstool_definitions 例子:

import json 

query = "How is the weather in Seattle?"
tool_calls = [{
                    "type": "tool_call",
                    "tool_call_id": "call_CUdbkBfvVBla2YP3p24uhElJ",
                    "name": "fetch_weather",
                    "arguments": {
                        "location": "Seattle"
                    }
            },
            {
                    "type": "tool_call",
                    "tool_call_id": "call_CUdbkBfvVBla2YP3p24uhElJ",
                    "name": "fetch_weather",
                    "arguments": {
                        "location": "London"
                    }
            }]

tool_definitions = [{
                    "name": "fetch_weather",
                    "description": "Fetches the weather information for the specified location.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "location": {
                                "type": "string",
                                "description": "The location to fetch weather for."
                            }
                        }
                    }
                }]

from azure.ai.evaluation import ToolCallAccuracyEvaluator

tool_call_accuracy = ToolCallAccuracyEvaluator(model_config) # reuse the config defined above
response = tool_call_accuracy(query=query, tool_calls=tool_calls, tool_definitions=tool_definitions)
print(json.dumps(response, indent=4))

請參考以下輸出(詳細參考 輸出格式 ):

{
    "tool_call_accuracy": 3,  # a score between 1-5, higher is better
    "tool_call_accuracy_result": "fail",
    "tool_call_accuracy_threshold": 4,
    "details": { ... } # helpful details for debugging the tool calls made by the agent
}

代理訊息結構

以代理訊息格式, queryresponse 是 OpenAI 風格的訊息列表。 具體來說,query 包含過去發生在代理與使用者之間,直到最近一次使用者查詢前的所有互動紀錄,並要求代理的系統訊息位於清單頂端。 response 傳送代理對最後使用者查詢的最後訊息。

評估者預期的輸入格式為 Python 訊息清單,如下:

[
  {
    "role": "system" | "user" | "assistant" | "tool",
    "createdAt": "ISO 8601 timestamp",     // Optional for 'system'
    "run_id": "string",                    // Optional, only for assistant/tool in tool call context
    "tool_call_id": "string",              // Optional, only for tool/tool_result
    "name": "string",                      // Present if it's a tool call
    "arguments": { ... },                  // Parameters passed to the tool (if tool call)
    "content": [
      {
        "type": "text" | "tool_call" | "tool_result",
        "text": "string",                  // if type == text
        "tool_call_id": "string",         // if type == tool_call
        "name": "string",                 // tool name if type == tool_call
        "arguments": { ... },             // tool args if type == tool_call
        "tool_result": { ... }            // result if type == tool_result
      }
    ]
  }
]

範例查詢與回應物件:

query = [
    {
        "role": "system",
        "content": "You are an AI assistant interacting with Azure Maps services to serve user requests."
    },
    {
        "createdAt": "2025-04-25T23:55:43Z",
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "Find the address for coordinates 41.8781,-87.6298."
            }
        ]
    },
    {
        "createdAt": "2025-04-25T23:55:45Z",
        "run_id": "run_DGE8RWPS8A9SmfCg61waRx9u",
        "role": "assistant",
        "content": [
            {
                "type": "tool_call",
                "tool_call_id": "call_nqNyhOFRw4FmF50jaCCq2rDa",
                "name": "azure_maps_reverse_address_search",
                "arguments": {
                    "lat": "41.8781",
                    "lon": "-87.6298"
                }
            }
        ]
    },
    {
        "createdAt": "2025-04-25T23:55:47Z",
        "run_id": "run_DGE8RWPS8A9SmfCg61waRx9u",
        "tool_call_id": "call_nqNyhOFRw4FmF50jaCCq2rDa",
        "role": "tool",
        "content": [
            {
                "type": "tool_result",
                "tool_result": {
                    "address": "300 South Federal Street, Chicago, IL 60604",
                    "position": {
                        "lat": "41.8781",
                        "lon": "-87.6298"
                    }
                }
            }
        ]
    },
    {
        "createdAt": "2025-04-25T23:55:48Z",
        "run_id": "run_DGE8RWPS8A9SmfCg61waRx9u",
        "role": "assistant",
        "content": [
            {
                "type": "text",
                "text": "The address for the coordinates 41.8781, -87.6298 is 300 South Federal Street, Chicago, IL 60604."
            }
        ]
    },
    {
        "createdAt": "2025-04-25T23:55:50Z",
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "What timezone corresponds to 41.8781,-87.6298?"
            }
        ]
    },
]

response = [
    {
        "createdAt": "2025-04-25T23:55:52Z",
        "run_id": "run_DmnhUGqYd1vCBolcjjODVitB",
        "role": "assistant",
        "content": [
            {
                "type": "tool_call",
                "tool_call_id": "call_qi2ug31JqzDuLy7zF5uiMbGU",
                "name": "azure_maps_timezone",
                "arguments": {
                    "lat": 41.878100000000003,
                    "lon": -87.629800000000003
                }
            }
        ]
    },
    {
        "createdAt": "2025-04-25T23:55:54Z",
        "run_id": "run_DmnhUGqYd1vCBolcjjODVitB",
        "tool_call_id": "call_qi2ug31JqzDuLy7zF5uiMbGU",
        "role": "tool",
        "content": [
            {
                "type": "tool_result",
                "tool_result": {
                    "ianaId": "America/Chicago",
                    "utcOffset": None,
                    "abbreviation": None,
                    "isDaylightSavingTime": None
                }
            }
        ]
    },
    {
        "createdAt": "2025-04-25T23:55:55Z",
        "run_id": "run_DmnhUGqYd1vCBolcjjODVitB",
        "role": "assistant",
        "content": [
            {
                "type": "text",
                "text": "The timezone for the coordinates 41.8781, -87.6298 is America/Chicago."
            }
        ]
    }
]

如果查詢請求(截至目前執行的對話紀錄)或代理反應(對查詢的回應)的格式不符,評估器就會顯示警告。

關於利用ToolCallAccuracyEvaluator來評估代理訊息的範例,請參見:

import json

# The user asked a question.
query = [
    {
        "role": "system",
        "content": "You are a friendly and helpful customer service agent."
    },
    # Past interactions are omitted. 
    # ...
    {
        "createdAt": "2025-03-14T06:14:20Z",
        "role": "user",
        "content": [
            {
                "type": "text",
                "text": "Hi, I need help with the last 2 orders on my account #888. Could you please update me on their status?"
            }
        ]
    }
]
# The agent emits multiple messages to fulfill the request.
response = [
    {
        "createdAt": "2025-03-14T06:14:30Z",
        "run_id": "0",
        "role": "assistant",
        "content": [
            {
                "type": "text",
                "text": "Hello! Let me quickly look up your account details."
            }
        ]
    },
    {
        "createdAt": "2025-03-14T06:14:35Z",
        "run_id": "0",
        "role": "assistant",
        "content": [
            {
                "type": "tool_call",
                "tool_call_id": "tool_call_20250310_001",
                "name": "get_orders",
                "arguments": {
                    "account_number": "888"
                }
            }
        ]
    },
    # Many more messages are omitted. 
    # ...
    # Here is the agent's final response:
    {
        "createdAt": "2025-03-14T06:15:05Z",
        "run_id": "0",
        "role": "assistant",
        "content": [
            {
                "type": "text",
                "text": "The order with ID 123 has been shipped and is expected to be delivered on March 15, 2025. However, the order with ID 124 is delayed and should now arrive by March 20, 2025. Is there anything else I can help you with?"
            }
        ]
    }
]

# An example of tool definitions available to the agent:
tool_definitions = [
    {
        "name": "get_orders",
        "description": "Get the list of orders for a given account number.",
        "parameters": {
            "type": "object",
            "properties": {
                "account_number": {
                    "type": "string",
                    "description": "The account number to get the orders for."
                }
            }
        }
    },
    # Other tool definitions are omitted. 
    # ...
]

result = tool_call_accuracy(
    query=query,
    response=response,
    tool_definitions=tool_definitions 
)
print(json.dumps(result, indent=4))

請參考以下輸出(詳細參考 輸出格式 ):

{
    "tool_call_accuracy": 2,  # a score between 1-5, higher is better
    "tool_call_accuracy_result": "fail",
    "tool_call_accuracy_threshold": 3,
    "details": { ... } # helpful details for debugging the tool calls made by the agent
}

此評估架構有助於解析代理服務外的資料,使內建評估器能支援代理工作流程中的可觀察性。

範例筆記本

請為每位評估者嘗試一個範例。