1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
|
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
from unittest.mock import MagicMock
import pytest
from azure.ai.evaluation._evaluators._task_completion import _TaskCompletionEvaluator
from azure.ai.evaluation._exceptions import EvaluationException
# Mock flow side effect that mimics the output of the prompty (the _flow call)
async def flow_side_effect(timeout, **kwargs):
query = kwargs.get("query", "")
response = kwargs.get("response", "")
# Simple logic to determine success based on keywords in query and response
if "complete" in str(response).lower() or "done" in str(response).lower():
success = 1
explanation = "Task was completed successfully with all requirements met."
details = {
"task_requirements": "The requirements for the task.",
"delivered_outcome": "The final deliverable of the task.",
"completion_gaps": "complete",
}
elif "partial" in str(response).lower():
success = 0
explanation = "Task was only partially completed, missing key requirements."
details = {
"task_requirements": "The requirements for the task.",
"delivered_outcome": "The final deliverable of the task.",
"completion_gaps": "incomplete",
}
elif "invalid" in str(response).lower():
# Return invalid output to test error handling
success = "invalid_value"
explanation = "This is an invalid response."
details = {}
else:
success = 0
explanation = "Task was not completed."
details = {
"task_requirements": "The requirements for the task.",
"delivered_outcome": "none",
"completion_gaps": "failed",
}
return {
"llm_output": {
"success": success,
"explanation": explanation,
"details": details,
},
}
@pytest.mark.usefixtures("mock_model_config")
@pytest.mark.unittest
class TestTaskCompletionEvaluator:
def test_task_completed_successfully(self, mock_model_config):
"""Test when task is completed successfully"""
evaluator = _TaskCompletionEvaluator(model_config=mock_model_config)
evaluator._flow = MagicMock(side_effect=flow_side_effect)
query = "Plan a 3-day itinerary for Paris with cultural landmarks and local cuisine."
response = "I have completed a comprehensive 3-day Paris itinerary with cultural landmarks and local cuisine recommendations."
result = evaluator(query=query, response=response)
key = _TaskCompletionEvaluator._RESULT_KEY
assert result is not None
assert key in result
assert result[key] == 1
assert result[f"{key}_result"] == "pass"
assert f"{key}_reason" in result
assert "completed successfully" in result[f"{key}_reason"]
assert f"{key}_details" in result
assert isinstance(result[f"{key}_details"], dict)
def test_task_not_completed(self, mock_model_config):
"""Test when task is not completed"""
evaluator = _TaskCompletionEvaluator(model_config=mock_model_config)
evaluator._flow = MagicMock(side_effect=flow_side_effect)
query = "Write a detailed analysis of market trends."
response = "I cannot provide this analysis at the moment."
result = evaluator(query=query, response=response)
key = _TaskCompletionEvaluator._RESULT_KEY
assert result is not None
assert key in result
assert result[key] == 0
assert result[f"{key}_result"] == "fail"
assert f"{key}_reason" in result
assert f"{key}_details" in result
def test_task_partially_completed(self, mock_model_config):
"""Test when task is only partially completed"""
evaluator = _TaskCompletionEvaluator(model_config=mock_model_config)
evaluator._flow = MagicMock(side_effect=flow_side_effect)
query = "Create a budget plan with income, expenses, and savings goals."
response = "I have provided a partial budget plan with income and expenses only."
result = evaluator(query=query, response=response)
key = _TaskCompletionEvaluator._RESULT_KEY
assert result is not None
assert key in result
assert result[key] == 0
assert result[f"{key}_result"] == "fail"
assert "partial" in result[f"{key}_reason"].lower()
assert f"{key}_details" in result
def test_with_tool_definitions(self, mock_model_config):
"""Test evaluation with tool definitions provided"""
evaluator = _TaskCompletionEvaluator(model_config=mock_model_config)
evaluator._flow = MagicMock(side_effect=flow_side_effect)
query = [{"role": "user", "content": "Find hotels in Paris and book the cheapest one"}]
response = [
{"role": "assistant", "content": "Task is complete. I found hotels and booked the cheapest option."}
]
tool_definitions = [
{
"name": "search_hotels",
"description": "Search for hotels in a location",
"parameters": {
"type": "object",
"properties": {"location": {"type": "string", "description": "City name"}},
},
},
{
"name": "book_hotel",
"description": "Book a hotel",
"parameters": {
"type": "object",
"properties": {"hotel_id": {"type": "string", "description": "Hotel identifier"}},
},
},
]
result = evaluator(query=query, response=response, tool_definitions=tool_definitions)
key = _TaskCompletionEvaluator._RESULT_KEY
assert result is not None
assert key in result
assert result[key] == 1
assert result[f"{key}_result"] == "pass"
def test_with_conversation_history(self, mock_model_config):
"""Test evaluation with conversation history as list of messages"""
evaluator = _TaskCompletionEvaluator(model_config=mock_model_config)
evaluator._flow = MagicMock(side_effect=flow_side_effect)
query = [
{"role": "system", "content": "You are a helpful travel assistant."},
{"role": "user", "content": "I need to book a flight to Tokyo."},
{"role": "assistant", "content": "I can help you with that. What dates?"},
{"role": "user", "content": "December 15-22, 2025"},
]
response = [
{"role": "assistant", "content": "Done! I have booked your flight to Tokyo for December 15-22, 2025."}
]
result = evaluator(query=query, response=response)
key = _TaskCompletionEvaluator._RESULT_KEY
assert result is not None
assert key in result
assert result[key] == 1
assert result[f"{key}_result"] == "pass"
def test_missing_query_and_response(self, mock_model_config):
"""Test that missing both query and response raises an exception"""
evaluator = _TaskCompletionEvaluator(model_config=mock_model_config)
evaluator._flow = MagicMock(side_effect=flow_side_effect)
with pytest.raises(EvaluationException) as exc_info:
evaluator()
assert "Either 'conversation' or individual inputs must be provided" in str(exc_info.value)
def test_string_success_value_true(self, mock_model_config):
"""Test handling of string 'TRUE' as success value"""
evaluator = _TaskCompletionEvaluator(model_config=mock_model_config)
async def string_true_flow(timeout, **kwargs):
return {
"llm_output": {
"success": "TRUE",
"explanation": "Task completed",
"details": {},
}
}
evaluator._flow = MagicMock(side_effect=string_true_flow)
query = "Complete this task"
response = "Task is complete"
result = evaluator(query=query, response=response)
key = _TaskCompletionEvaluator._RESULT_KEY
assert result[key] == 1
assert result[f"{key}_result"] == "pass"
def test_string_success_value_false(self, mock_model_config):
"""Test handling of string 'FALSE' as success value"""
evaluator = _TaskCompletionEvaluator(model_config=mock_model_config)
async def string_false_flow(timeout, **kwargs):
return {
"llm_output": {
"success": "FALSE",
"explanation": "Task not completed",
"details": {},
}
}
evaluator._flow = MagicMock(side_effect=string_false_flow)
query = "Complete this task"
response = "Could not complete"
result = evaluator(query=query, response=response)
key = _TaskCompletionEvaluator._RESULT_KEY
assert result[key] == 0
assert result[f"{key}_result"] == "fail"
def test_invalid_llm_output_format(self, mock_model_config):
"""Test handling when LLM output is not a dictionary"""
evaluator = _TaskCompletionEvaluator(model_config=mock_model_config)
async def invalid_output_flow(timeout, **kwargs):
return {"llm_output": "This is a string, not a dictionary"}
evaluator._flow = MagicMock(side_effect=invalid_output_flow)
query = "Complete this task"
response = "Done"
result = evaluator(query=query, response=response)
key = _TaskCompletionEvaluator._RESULT_KEY
assert result[key] == 0
def test_default_success_value(self, mock_model_config):
"""Test that default success value is 0 when not provided"""
evaluator = _TaskCompletionEvaluator(model_config=mock_model_config)
async def no_success_flow(timeout, **kwargs):
return {
"llm_output": {
"explanation": "No success field provided",
"details": {},
}
}
evaluator._flow = MagicMock(side_effect=no_success_flow)
query = "Complete this task"
response = "Task response"
result = evaluator(query=query, response=response)
key = _TaskCompletionEvaluator._RESULT_KEY
assert result[key] == 0
assert result[f"{key}_result"] == "fail"
def test_complex_response_with_tool_calls(self, mock_model_config):
"""Test evaluation with response containing tool calls"""
evaluator = _TaskCompletionEvaluator(model_config=mock_model_config)
evaluator._flow = MagicMock(side_effect=flow_side_effect)
query = "Search for restaurants and make a reservation"
response = [
{
"role": "assistant",
"content": [{"type": "text", "text": "Let me search for restaurants."}],
"tool_calls": [
{
"type": "function",
"id": "call_1",
"function": {
"name": "search_restaurants",
"arguments": '{"location": "downtown", "cuisine": "Italian"}',
},
}
],
},
{"role": "tool", "tool_call_id": "call_1", "content": "Found 5 Italian restaurants downtown."},
{"role": "assistant", "content": "Task complete! I found restaurants and made a reservation."},
]
tool_definitions = [
{
"name": "search_restaurants",
"type": "function",
"description": "Search for restaurants",
"parameters": {"type": "object", "properties": {}},
}
]
result = evaluator(query=query, response=response, tool_definitions=tool_definitions)
key = _TaskCompletionEvaluator._RESULT_KEY
assert result is not None
assert key in result
assert result[key] == 1
assert result[f"{key}_result"] == "pass"
def test_numeric_success_values(self, mock_model_config):
"""Test that numeric 0 and 1 values work correctly"""
evaluator = _TaskCompletionEvaluator(model_config=mock_model_config)
async def numeric_success_flow(timeout, **kwargs):
# Return 1 for success
return {
"llm_output": {
"success": 1,
"explanation": "Task completed",
"details": {},
}
}
evaluator._flow = MagicMock(side_effect=numeric_success_flow)
query = "Complete this task"
response = "Done"
result = evaluator(query=query, response=response)
key = _TaskCompletionEvaluator._RESULT_KEY
assert result[key] == 1
assert result[f"{key}_result"] == "pass"
def test_empty_details(self, mock_model_config):
"""Test handling of empty details field"""
evaluator = _TaskCompletionEvaluator(model_config=mock_model_config)
async def empty_details_flow(timeout, **kwargs):
return {
"llm_output": {
"success": 1,
"explanation": "Task completed",
# No details field
}
}
evaluator._flow = MagicMock(side_effect=empty_details_flow)
query = "Test"
response = "Complete"
result = evaluator(query=query, response=response)
key = _TaskCompletionEvaluator._RESULT_KEY
assert f"{key}_details" in result
assert result[f"{key}_details"] == ""
def test_empty_explanation(self, mock_model_config):
"""Test handling of missing explanation field"""
evaluator = _TaskCompletionEvaluator(model_config=mock_model_config)
async def no_explanation_flow(timeout, **kwargs):
return {
"llm_output": {
"success": 1,
"details": {},
# No explanation field
}
}
evaluator._flow = MagicMock(side_effect=no_explanation_flow)
query = "Test"
response = "Complete"
result = evaluator(query=query, response=response)
key = _TaskCompletionEvaluator._RESULT_KEY
assert f"{key}_reason" in result
assert result[f"{key}_reason"] == ""
|