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 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
|
# pylint: disable=too-many-lines,line-too-long,useless-suppression
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
# cSpell:disable# cSpell:disable
import pytest
import os
from typing import Optional
from azure.ai.projects.telemetry import AIProjectInstrumentor, _utils
from azure.core.settings import settings
from gen_ai_trace_verifier import GenAiTraceVerifier
from azure.ai.projects.models import PromptAgentDefinition, PromptAgentDefinitionText
from azure.ai.projects.models import (
Reasoning,
FunctionTool,
ResponseTextFormatConfigurationText,
)
from devtools_testutils import (
recorded_by_proxy,
)
from test_base import servicePreparer
from test_ai_instrumentor_base import TestAiAgentsInstrumentorBase, MessageCreationMode, CONTENT_TRACING_ENV_VARIABLE
settings.tracing_implementation = "OpenTelemetry"
_utils._span_impl_type = settings.tracing_implementation()
class TestAiAgentsInstrumentor(TestAiAgentsInstrumentorBase):
"""Tests for AI agents instrumentor."""
@pytest.fixture(scope="function")
def instrument_with_content(self):
os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True"})
self.setup_telemetry()
yield
self.cleanup()
@pytest.fixture(scope="function")
def instrument_without_content(self):
os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "False"})
self.setup_telemetry()
yield
self.cleanup()
def test_instrumentation(self, **kwargs):
# Make sure code is not instrumented due to a previous test exception
AIProjectInstrumentor().uninstrument()
exception_caught = False
try:
assert AIProjectInstrumentor().is_instrumented() == False
AIProjectInstrumentor().instrument()
assert AIProjectInstrumentor().is_instrumented() == True
AIProjectInstrumentor().uninstrument()
assert AIProjectInstrumentor().is_instrumented() == False
except RuntimeError as e:
exception_caught = True
print(e)
assert exception_caught == False
def test_instrumenting_twice_does_not_cause_exception(self, **kwargs):
# Make sure code is not instrumented due to a previous test exception
AIProjectInstrumentor().uninstrument()
exception_caught = False
try:
AIProjectInstrumentor().instrument()
AIProjectInstrumentor().instrument()
except RuntimeError as e:
exception_caught = True
print(e)
AIProjectInstrumentor().uninstrument()
assert exception_caught == False
def test_uninstrumenting_uninstrumented_does_not_cause_exception(self, **kwargs):
# Make sure code is not instrumented due to a previous test exception
AIProjectInstrumentor().uninstrument()
exception_caught = False
try:
AIProjectInstrumentor().uninstrument()
except RuntimeError as e:
exception_caught = True
print(e)
assert exception_caught == False
def test_uninstrumenting_twice_does_not_cause_exception(self, **kwargs):
# Make sure code is not instrumented due to a previous test exception
AIProjectInstrumentor().uninstrument()
exception_caught = False
try:
AIProjectInstrumentor().instrument()
AIProjectInstrumentor().uninstrument()
AIProjectInstrumentor().uninstrument()
except RuntimeError as e:
exception_caught = True
print(e)
assert exception_caught == False
@pytest.mark.parametrize(
"env1, env2, expected",
[
(None, None, False),
(None, False, False),
(None, True, False),
(False, None, False),
(False, False, False),
(False, True, False),
(True, None, True),
(True, False, True),
(True, True, True),
],
)
def test_content_recording_verify_old_env_variable_ignored(
self, env1: Optional[bool], env2: Optional[bool], expected: bool
):
"""
Test content recording enablement with both old and new environment variables.
This test verifies the behavior of content recording when both the current
and legacy environment variables are set to different combinations of values.
The method tests all possible combinations of None, True, and False for both
environment variables to ensure the old one is no longer having impact, since
support for it has been dropped.
Args:
env1: Value for the current content tracing environment variable.
Can be None (unset), True, or False.
env2: Value for the old/legacy content tracing environment variable.
Can be None (unset), True, or False.
expected: The expected result of is_content_recording_enabled() given
the environment variable combination.
The test ensures that only if one or both of the environment variables are
defined and set to "true" content recording is enabled.
"""
OLD_CONTENT_TRACING_ENV_VARIABLE = "AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED" # Deprecated, undocumented.
def set_env_var(var_name, value):
if value is None:
os.environ.pop(var_name, None)
else:
os.environ[var_name] = "true" if value else "false"
set_env_var(CONTENT_TRACING_ENV_VARIABLE, env1)
set_env_var(OLD_CONTENT_TRACING_ENV_VARIABLE, env2)
self.setup_telemetry()
try:
assert AIProjectInstrumentor().is_content_recording_enabled() == expected
finally:
self.cleanup() # This also undefines CONTENT_TRACING_ENV_VARIABLE
os.environ.pop(OLD_CONTENT_TRACING_ENV_VARIABLE, None)
@pytest.mark.usefixtures("instrument_with_content")
@servicePreparer()
@recorded_by_proxy
def test_agent_creation_with_tracing_content_recording_enabled(self, **kwargs):
self.cleanup()
os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True"})
self.setup_telemetry()
assert True == AIProjectInstrumentor().is_content_recording_enabled()
assert True == AIProjectInstrumentor().is_instrumented()
with self.create_client(operation_group="tracing", **kwargs) as project_client:
model = self.test_agents_params["model_deployment_name"]
print(f"Using model deployment: {model}")
agent_definition = PromptAgentDefinition(
# Required parameter
model=model,
# Optional parameters
instructions="You are a helpful AI assistant. Be polite and provide accurate information.",
# temperature=0.7,
# top_p=0.9,
# # Reasoning configuration
# reasoning=Reasoning(
# effort="medium",
# summary="auto",
# ),
# # Tools that the model can use
# tools=[
# # Function tool for custom functions
# FunctionTool(
# name="get_weather",
# description="Get the current weather for a location",
# parameters={
# "type": "object",
# "properties": {
# "location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"},
# "unit": {
# "type": "string",
# "enum": ["celsius", "fahrenheit"],
# "description": "The temperature unit",
# },
# },
# "required": ["location"],
# },
# strict=True, # Enforce strict parameter validation
# ),
# ],
# # Text response configuration
# text=PromptAgentDefinitionText(format=ResponseTextFormatConfigurationText()),
)
agent = project_client.agents.create_version(agent_name="myagent", definition=agent_definition)
version = agent.version
# delete agent and close client
project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
print("Deleted agent")
# ------------------------- Validate "create_agent" span ---------------------------------
self.exporter.force_flush()
spans = self.exporter.get_spans_by_name("create_agent myagent")
assert len(spans) == 1
span = spans[0]
expected_attributes = [
("gen_ai.system", "az.ai.agents"),
("gen_ai.provider.name", "azure.ai.agents"),
("gen_ai.operation.name", "create_agent"),
("server.address", ""),
("gen_ai.request.model", model),
# ("gen_ai.request.temperature", "0.7"),
# ("gen_ai.request.top_p", "0.9"),
# ("gen_ai.request.response_format", "text"),
# ("gen_ai.request.reasoning.effort", "medium"),
# ("gen_ai.request.reasoning.summary", "auto"),
("gen_ai.agent.name", "myagent"),
("gen_ai.agent.id", "myagent:" + str(version)),
("gen_ai.agent.version", str(version)),
("gen_ai.agent.type", "prompt"),
]
attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes)
assert attributes_match == True
expected_events = [
{
"name": "gen_ai.system.instruction",
"attributes": {
"gen_ai.system": "az.ai.agents",
"gen_ai.event.content": '{"content": [{"type": "text", "text": "You are a helpful AI assistant. Be polite and provide accurate information."}]}',
},
}
]
events_match = GenAiTraceVerifier().check_span_events(span, expected_events)
assert events_match == True
@pytest.mark.usefixtures("instrument_without_content")
@servicePreparer()
@recorded_by_proxy
def test_agent_creation_with_tracing_content_recording_disabled(self, **kwargs):
self.cleanup()
os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "False"})
self.setup_telemetry()
assert False == AIProjectInstrumentor().is_content_recording_enabled()
assert True == AIProjectInstrumentor().is_instrumented()
with self.create_client(operation_group="agents", **kwargs) as project_client:
model = self.test_agents_params["model_deployment_name"]
agent_definition = PromptAgentDefinition(
# Required parameter
model=model,
# Optional parameters
instructions="You are a helpful AI assistant. Always be polite and provide accurate information.",
# temperature=0.7,
# top_p=0.9,
# # Reasoning configuration
# reasoning=Reasoning(
# effort="medium",
# summary="auto",
# ),
# # Tools that the model can use
# tools=[
# # Function tool for custom functions
# FunctionTool(
# name="get_weather",
# description="Get the current weather for a location",
# parameters={
# "type": "object",
# "properties": {
# "location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"},
# "unit": {
# "type": "string",
# "enum": ["celsius", "fahrenheit"],
# "description": "The temperature unit",
# },
# },
# "required": ["location"],
# },
# strict=True, # Enforce strict parameter validation
# ),
# ],
# Text response configuration
# text=PromptAgentDefinitionText(format=ResponseTextFormatConfigurationText()),
)
agent = project_client.agents.create_version(agent_name="myagent", definition=agent_definition)
version = agent.version
# delete agent and close client
project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
print("Deleted agent")
# ------------------------- Validate "create_agent" span ---------------------------------
self.exporter.force_flush()
spans = self.exporter.get_spans_by_name("create_agent myagent")
assert len(spans) == 1
span = spans[0]
expected_attributes = [
("gen_ai.system", "az.ai.agents"),
("gen_ai.provider.name", "azure.ai.agents"),
("gen_ai.operation.name", "create_agent"),
("server.address", ""),
("gen_ai.request.model", model),
# ("gen_ai.request.temperature", "0.7"),
# ("gen_ai.request.top_p", "0.9"),
# ("gen_ai.request.response_format", "text"),
# ("gen_ai.request.reasoning.effort", "medium"),
# ("gen_ai.request.reasoning.summary", "auto"),
("gen_ai.agent.name", "myagent"),
("gen_ai.agent.id", "myagent:" + str(version)),
("gen_ai.agent.version", str(version)),
("gen_ai.agent.type", "prompt"),
]
attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes)
assert attributes_match == True
expected_events = [
{
"name": "gen_ai.system.instruction",
"attributes": {
"gen_ai.system": "az.ai.agents",
"gen_ai.event.content": "{}",
},
}
]
events_match = GenAiTraceVerifier().check_span_events(span, expected_events)
assert events_match == True
@pytest.mark.usefixtures("instrument_with_content")
@servicePreparer()
@recorded_by_proxy
def test_workflow_agent_creation_with_tracing_content_recording_enabled(self, **kwargs):
"""Test workflow agent creation with content recording enabled."""
self.cleanup()
os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "True"})
self.setup_telemetry()
assert True == AIProjectInstrumentor().is_content_recording_enabled()
assert True == AIProjectInstrumentor().is_instrumented()
from azure.ai.projects.models import WorkflowAgentDefinition
with self.create_client(operation_group="tracing", **kwargs) as project_client:
workflow_yaml = """
kind: workflow
trigger:
kind: OnConversationStart
id: test_workflow
actions:
- kind: SetVariable
id: set_variable
variable: Local.TestVar
value: "test"
"""
agent = project_client.agents.create_version(
agent_name="test-workflow-agent",
definition=WorkflowAgentDefinition(workflow=workflow_yaml),
)
version = agent.version
# delete agent
project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
print("Deleted workflow agent")
# ------------------------- Validate "create_agent" span ---------------------------------
self.exporter.force_flush()
spans = self.exporter.get_spans_by_name("create_agent test-workflow-agent")
assert len(spans) == 1
span = spans[0]
expected_attributes = [
("gen_ai.system", "az.ai.agents"),
("gen_ai.provider.name", "azure.ai.agents"),
("gen_ai.operation.name", "create_agent"),
("server.address", ""),
("gen_ai.agent.name", "test-workflow-agent"),
("gen_ai.agent.id", "test-workflow-agent:" + str(version)),
("gen_ai.agent.version", str(version)),
("gen_ai.agent.type", "workflow"),
]
attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes)
assert attributes_match == True
# Verify workflow event with standard content format
events = span.events
assert len(events) == 1
workflow_event = events[0]
assert workflow_event.name == "gen_ai.agent.workflow"
import json
event_content = json.loads(workflow_event.attributes["gen_ai.event.content"])
assert "content" in event_content
assert len(event_content["content"]) == 1
assert event_content["content"][0]["type"] == "workflow"
assert "workflow" in event_content["content"][0]
assert "kind: workflow" in event_content["content"][0]["workflow"]
@pytest.mark.usefixtures("instrument_without_content")
@servicePreparer()
@recorded_by_proxy
def test_workflow_agent_creation_with_tracing_content_recording_disabled(self, **kwargs):
"""Test workflow agent creation with content recording disabled."""
self.cleanup()
os.environ.update({CONTENT_TRACING_ENV_VARIABLE: "False"})
self.setup_telemetry()
assert False == AIProjectInstrumentor().is_content_recording_enabled()
assert True == AIProjectInstrumentor().is_instrumented()
from azure.ai.projects.models import WorkflowAgentDefinition
with self.create_client(operation_group="agents", **kwargs) as project_client:
workflow_yaml = """
kind: workflow
trigger:
kind: OnConversationStart
id: test_workflow
actions:
- kind: SetVariable
id: set_variable
variable: Local.TestVar
value: "test"
"""
agent = project_client.agents.create_version(
agent_name="test-workflow-agent",
definition=WorkflowAgentDefinition(workflow=workflow_yaml),
)
version = agent.version
# delete agent
project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
print("Deleted workflow agent")
# ------------------------- Validate "create_agent" span ---------------------------------
self.exporter.force_flush()
spans = self.exporter.get_spans_by_name("create_agent test-workflow-agent")
assert len(spans) == 1
span = spans[0]
expected_attributes = [
("gen_ai.system", "az.ai.agents"),
("gen_ai.provider.name", "azure.ai.agents"),
("gen_ai.operation.name", "create_agent"),
("server.address", ""),
("gen_ai.agent.name", "test-workflow-agent"),
("gen_ai.agent.id", "test-workflow-agent:" + str(version)),
("gen_ai.agent.version", str(version)),
("gen_ai.agent.type", "workflow"),
]
attributes_match = GenAiTraceVerifier().check_span_attributes(span, expected_attributes)
assert attributes_match == True
# Verify no workflow event when content recording is disabled
events = span.events
assert len(events) == 0
|