Skip to content

Commit f32244d

Browse files
M-Hietalajhakulinnick863howieleungglharper
authored
M hietala/merge remove enable telemetry function (Azure#41009)
* init agents v1 with new operations * update * add samples * aio * update * update * updates * update * update * update * update * update * add create_thread_and_run * create thread and process run * add tests and update README (Azure#40760) * update README * update tests * fix sample * adding tracing (Azure#40769) * Fix unit tests (Azure#40783) * Fix unit tests * Record instrumentor tests * modifying multiagent sample (Azure#40799) * Jhakulin/azure sdk review fixes (Azure#40795) Fix static analysis, updates from azure sdk reviews. --------- Co-authored-by: nick863 <[email protected]> * run black, fix some readme update snip issue (Azure#40815) * Howie/ffix toolcall (Azure#40750) * max retry and tests * fix test * Update samples csv data (Azure#40821) * update samples csv data * add cspell * Add ew artifact to list (Azure#40833) * [AI] [Agents] tool schema updates (Azure#40841) * [AI] [Agents] tool changes for Bing tools and Azure AI Search * add implementation for abstract tool methods * Remove packages not handled in the branch from the CI (Azure#40842) * Jhakulin/agents naming changes (Azure#40845) * naming changes * update tests * Record the tests and disable azue functions for now (Azure#40852) * Nirovins/record tests (Azure#40854) * Record the tests and disable azue functions for now * Add recordings for azure functions * Record instrumentation tests --------- Co-authored-by: Jarno Hakulinen <[email protected]> --------- Co-authored-by: Nikolay Rovinskiy <[email protected]> * bring tests README back (Azure#40858) * Uncomment function tests (Azure#40855) * naming changes * update names * update * update tests * update * Record the tests and disable azue functions for now (Azure#40852) * Nirovins/record tests (Azure#40854) * Record the tests and disable azue functions for now * Add recordings for azure functions * Record instrumentation tests --------- Co-authored-by: Jarno Hakulinen <[email protected]> * Uncomment function tests * Fix --------- Co-authored-by: jhakulin <[email protected]> * Jhakulin/list op update (Azure#40871) * update list operations * update tests * update README * update * Fix the instrumentation tests (Azure#40877) * Fix the instrumentation tests * Better instrumentation handling * pylint --------- Co-authored-by: Nikolay Rovinskiy <[email protected]> * Howie/poll timeout (Azure#40825) * add timeout for polling * fix merge * fix merge * fix merge * fixed merge * enable_auto_function_calls param changes (Azure#40820) * get CI green (Azure#40884) * fix logic app sample (Azure#40883) * agent azure monitor tracing sample updates (Azure#40865) * agent azure monitor tracing sample updates * disable pylint for global statement * agent tracing runid to feature branch (Azure#40888) * omit azure-ai-agents from pypy compatibility map * [AI] [Agents] write initial CHANGELOG and add missing samples (Azure#40891) * [AI] [Agents] write initial CHANGELOG * add sample for multiple connected agents * add sample for connected agents * update snippets * try get green pipeline (Azure#40914) * resolved comments (Azure#40922) * update code owner (Azure#40933) * Howie/toolcall fix (Azure#40939) * update code owner * fix tool call for async to be same as sync * fix test * Resolved Johan comments (Azure#40943) * resolved comments * resolved comments * Resolved comments * change project label * Hide the hack to use connection string. (Azure#40945) * FIx for function name changes (Azure#40951) * Remove Key Authentication (Azure#40954) * Remove Key Authentication * Exclude samples * Fix linter * Fixed logger (Azure#40957) * clean up py (Azure#40959) * removing enable_trace function from agents telemetry * removing an import of the removed function * redoing change that was incorrectly merged * removing one remaining enable_telemetry import * adding instrumentor call to azure monitor tracing samples * fixing multiagent sample trace configurator * updating tracing snippet in readme --------- Co-authored-by: jhakulin <[email protected]> Co-authored-by: Nikolay Rovinskiy <[email protected]> Co-authored-by: Howie Leung <[email protected]> Co-authored-by: Glenn Harper <[email protected]> Co-authored-by: Scott Beddall <[email protected]>
1 parent 459ac58 commit f32244d

10 files changed

+58
-179
lines changed

sdk/ai/azure-ai-agents/README.md

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1172,10 +1172,13 @@ from azure.monitor.opentelemetry import configure_azure_monitor
11721172
application_insights_connection_string = os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
11731173
configure_azure_monitor(connection_string=application_insights_connection_string)
11741174

1175-
# enable additional instrumentations
1176-
from azure.ai.agents.telemetry import enable_telemetry
1177-
1178-
enable_telemetry()
1175+
try:
1176+
from azure.ai.agents.telemetry import AIAgentsInstrumentor
1177+
agents_instrumentor = AIAgentsInstrumentor()
1178+
if not agents_instrumentor.is_instrumented():
1179+
agents_instrumentor.instrument()
1180+
except Exception as exc: # pylint: disable=broad-exception-caught
1181+
print(f"Could not call `AIAgentsInstrumentor().instrument()`. Exception: {exc}")
11791182

11801183
scenario = os.path.basename(__file__)
11811184
tracer = trace.get_tracer(__name__)

sdk/ai/azure-ai-agents/azure/ai/agents/telemetry/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@
77
# --------------------------------------------------------------------------
88

99
from ._ai_agents_instrumentor import AIAgentsInstrumentor
10-
from ._utils import enable_telemetry
1110
from ._trace_function import trace_function
1211

1312

14-
__all__ = ["AIAgentsInstrumentor", "enable_telemetry", "trace_function"]
13+
__all__ = ["AIAgentsInstrumentor", "trace_function"]

sdk/ai/azure-ai-agents/azure/ai/agents/telemetry/_utils.py

Lines changed: 1 addition & 152 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,8 @@
33
# Copyright (c) Microsoft Corporation.
44
# Licensed under the MIT License.
55
# ------------------------------------
6-
from typing import Any, Optional, TextIO, Union, cast
7-
8-
import io
6+
from typing import Optional
97
import logging
10-
import sys
11-
128
from enum import Enum
139

1410
from azure.core.tracing import AbstractSpan, SpanKind # type: ignore
@@ -157,150 +153,3 @@ def start_span(
157153
span.add_attribute(GEN_AI_REQUEST_RESPONSE_FORMAT, response_format)
158154

159155
return span
160-
161-
162-
# Internal helper functions to enable OpenTelemetry, used by both sync and async clients
163-
def _get_trace_exporter(destination: Union[TextIO, str, None]) -> Any:
164-
if isinstance(destination, str):
165-
# `destination` is the OTLP endpoint
166-
# See: https://opentelemetry-python.readthedocs.io/en/latest/exporter/otlp/otlp.html#usage
167-
try:
168-
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter # type: ignore
169-
except ModuleNotFoundError as e:
170-
raise ModuleNotFoundError(
171-
"OpenTelemetry OTLP exporter is not installed. "
172-
+ "Please install it using 'pip install opentelemetry-exporter-otlp-proto-grpc'"
173-
) from e
174-
return OTLPSpanExporter(endpoint=destination)
175-
176-
if isinstance(destination, io.TextIOWrapper):
177-
if destination is sys.stdout:
178-
# See: https://opentelemetry-python.readthedocs.io/en/latest/sdk/trace.export.html#opentelemetry.sdk.trace.export.ConsoleSpanExporter # pylint: disable=line-too-long
179-
try:
180-
from opentelemetry.sdk.trace.export import ConsoleSpanExporter
181-
except ModuleNotFoundError as e:
182-
raise ModuleNotFoundError(
183-
"OpenTelemetry SDK is not installed. Please install it using 'pip install opentelemetry-sdk'"
184-
) from e
185-
186-
return ConsoleSpanExporter()
187-
raise ValueError("Only `sys.stdout` is supported at the moment for type `TextIO`")
188-
189-
return None
190-
191-
192-
def _get_log_exporter(destination: Union[TextIO, str, None]) -> Any:
193-
if isinstance(destination, str):
194-
# `destination` is the OTLP endpoint
195-
# See: https://opentelemetry-python.readthedocs.io/en/latest/exporter/otlp/otlp.html#usage
196-
try:
197-
# _logs are considered beta (not internal) in OpenTelemetry Python API/SDK.
198-
# So it's ok to use it for local development, but we'll swallow
199-
# any errors in case of any breaking changes on OTel side.
200-
from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter # type: ignore # pylint: disable=import-error,no-name-in-module
201-
except Exception as ex: # pylint: disable=broad-exception-caught
202-
# since OTel logging is still in beta in Python, we're going to swallow any errors
203-
# and just warn about them.
204-
logger.warning("Failed to configure OpenTelemetry logging.", exc_info=ex)
205-
return None
206-
207-
return OTLPLogExporter(endpoint=destination)
208-
209-
if isinstance(destination, io.TextIOWrapper):
210-
if destination is sys.stdout:
211-
# See: https://opentelemetry-python.readthedocs.io/en/latest/sdk/trace.export.html#opentelemetry.sdk.trace.export.ConsoleSpanExporter # pylint: disable=line-too-long
212-
try:
213-
from opentelemetry.sdk._logs.export import ConsoleLogExporter
214-
215-
return ConsoleLogExporter()
216-
except ModuleNotFoundError as ex:
217-
# since OTel logging is still in beta in Python, we're going to swallow any errors
218-
# and just warn about them.
219-
logger.warning("Failed to configure OpenTelemetry logging.", exc_info=ex)
220-
return None
221-
raise ValueError("Only `sys.stdout` is supported at the moment for type `TextIO`")
222-
223-
return None
224-
225-
226-
def _configure_tracing(span_exporter: Any) -> None:
227-
if span_exporter is None:
228-
return
229-
230-
try:
231-
from opentelemetry import trace
232-
from opentelemetry.sdk.trace import TracerProvider
233-
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
234-
except ModuleNotFoundError as e:
235-
raise ModuleNotFoundError(
236-
"OpenTelemetry SDK is not installed. Please install it using 'pip install opentelemetry-sdk'"
237-
) from e
238-
239-
# if tracing was not setup before, we need to create a new TracerProvider
240-
if not isinstance(trace.get_tracer_provider(), TracerProvider):
241-
# If the provider is NoOpTracerProvider, we need to create a new TracerProvider
242-
provider = TracerProvider()
243-
trace.set_tracer_provider(provider)
244-
245-
# get_tracer_provider returns opentelemetry.trace.TracerProvider
246-
# however, we have opentelemetry.sdk.trace.TracerProvider, which implements
247-
# add_span_processor method, though we need to cast it to fix type checking.
248-
provider = cast(TracerProvider, trace.get_tracer_provider())
249-
provider.add_span_processor(SimpleSpanProcessor(span_exporter))
250-
251-
252-
def _configure_logging(log_exporter: Any) -> None:
253-
if log_exporter is None:
254-
return
255-
256-
try:
257-
# _events and _logs are considered beta (not internal) in
258-
# OpenTelemetry Python API/SDK.
259-
# So it's ok to use them for local development, but we'll swallow
260-
# any errors in case of any breaking changes on OTel side.
261-
from opentelemetry import _logs, _events
262-
from opentelemetry.sdk._logs import LoggerProvider # pylint: disable=import-error,no-name-in-module
263-
from opentelemetry.sdk._events import EventLoggerProvider # pylint: disable=import-error,no-name-in-module
264-
from opentelemetry.sdk._logs.export import (
265-
SimpleLogRecordProcessor,
266-
) # pylint: disable=import-error,no-name-in-module
267-
268-
if not isinstance(_logs.get_logger_provider(), LoggerProvider):
269-
logger_provider = LoggerProvider()
270-
_logs.set_logger_provider(logger_provider)
271-
272-
# get_logger_provider returns opentelemetry._logs.LoggerProvider
273-
# however, we have opentelemetry.sdk._logs.LoggerProvider, which implements
274-
# add_log_record_processor method, though we need to cast it to fix type checking.
275-
logger_provider = cast(LoggerProvider, _logs.get_logger_provider())
276-
logger_provider.add_log_record_processor(SimpleLogRecordProcessor(log_exporter))
277-
_events.set_event_logger_provider(EventLoggerProvider(logger_provider))
278-
except Exception as ex: # pylint: disable=broad-exception-caught
279-
# since OTel logging is still in beta in Python, we're going to swallow any errors
280-
# and just warn about them.
281-
logger.warning("Failed to configure OpenTelemetry logging.", exc_info=ex)
282-
283-
284-
def enable_telemetry(destination: Union[TextIO, str, None] = None, **kwargs) -> None: # pylint: disable=unused-argument
285-
"""Enable tracing and logging to console (sys.stdout), or to an OpenTelemetry Protocol (OTLP) endpoint.
286-
287-
:param destination: `sys.stdout` to print telemetry to console or a string holding the
288-
OpenTelemetry protocol (OTLP) endpoint.
289-
If not provided, this method enables instrumentation, but does not configure OpenTelemetry
290-
SDK to export traces and logs.
291-
:type destination: Union[TextIO, str, None]
292-
"""
293-
span_exporter = _get_trace_exporter(destination)
294-
_configure_tracing(span_exporter)
295-
296-
log_exporter = _get_log_exporter(destination)
297-
_configure_logging(log_exporter)
298-
299-
try:
300-
from azure.ai.agents.telemetry import AIAgentsInstrumentor
301-
302-
agents_instrumentor = AIAgentsInstrumentor()
303-
if not agents_instrumentor.is_instrumented():
304-
agents_instrumentor.instrument()
305-
except Exception as exc: # pylint: disable=broad-exception-caught
306-
logger.warning("Could not call `AIAgentsInstrumentor().instrument()`", exc_info=exc)

sdk/ai/azure-ai-agents/samples/agents_multiagent/utils/agent_trace_configurator.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
from opentelemetry.sdk.trace import TracerProvider
1010
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, ConsoleSpanExporter
1111
from azure.ai.agents import AgentsClient
12-
from azure.ai.agents.telemetry import enable_telemetry
1312
from azure.monitor.opentelemetry import configure_azure_monitor
1413

1514

@@ -26,7 +25,13 @@ def enable_azure_monitor_tracing(self):
2625
print("Enable it via the 'Tracing' tab in your AI Foundry project page.")
2726
exit()
2827
configure_azure_monitor(connection_string=application_insights_connection_string)
29-
enable_telemetry()
28+
try:
29+
from azure.ai.agents.telemetry import AIAgentsInstrumentor
30+
agents_instrumentor = AIAgentsInstrumentor()
31+
if not agents_instrumentor.is_instrumented():
32+
agents_instrumentor.instrument()
33+
except Exception as exc: # pylint: disable=broad-exception-caught
34+
print(f"Could not call `AIAgentsInstrumentor().instrument()`. Exception: {exc}")
3035

3136
def enable_console_tracing_without_genai(self):
3237
exporter = ConsoleSpanExporter()
@@ -37,7 +42,18 @@ def enable_console_tracing_without_genai(self):
3742
print("Console tracing enabled without agent traces.")
3843

3944
def enable_console_tracing_with_agent(self):
40-
enable_telemetry(destination=sys.stdout)
45+
span_exporter = ConsoleSpanExporter()
46+
tracer_provider = TracerProvider()
47+
tracer_provider.add_span_processor(SimpleSpanProcessor(span_exporter))
48+
trace.set_tracer_provider(tracer_provider)
49+
tracer = trace.get_tracer(__name__)
50+
try:
51+
from azure.ai.agents.telemetry import AIAgentsInstrumentor
52+
agents_instrumentor = AIAgentsInstrumentor()
53+
if not agents_instrumentor.is_instrumented():
54+
agents_instrumentor.instrument()
55+
except Exception as exc: # pylint: disable=broad-exception-caught
56+
print(f"Could not call `AIAgentsInstrumentor().instrument()`. Exception: {exc}")
4157
print("Console tracing enabled with agent traces.")
4258

4359
def display_menu(self):

sdk/ai/azure-ai-agents/samples/agents_telemetry/sample_agents_basics_async_with_azure_monitor_tracing.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,13 @@ async def main() -> None:
5252
application_insights_connection_string = os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
5353
configure_azure_monitor(connection_string=application_insights_connection_string)
5454

55-
# enable additional instrumentations
56-
from azure.ai.agents.telemetry import enable_telemetry
57-
58-
enable_telemetry()
55+
try:
56+
from azure.ai.agents.telemetry import AIAgentsInstrumentor
57+
agents_instrumentor = AIAgentsInstrumentor()
58+
if not agents_instrumentor.is_instrumented():
59+
agents_instrumentor.instrument()
60+
except Exception as exc: # pylint: disable=broad-exception-caught
61+
print(f"Could not call `AIAgentsInstrumentor().instrument()`. Exception: {exc}")
5962

6063
with tracer.start_as_current_span(scenario):
6164
async with agents_client:

sdk/ai/azure-ai-agents/samples/agents_telemetry/sample_agents_basics_async_with_console_tracing.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@
3737
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, ConsoleSpanExporter
3838
from azure.ai.agents.aio import AgentsClient
3939
from azure.ai.agents.models import ListSortOrder, MessageTextContent
40-
from azure.ai.agents.telemetry import enable_telemetry
4140
from azure.identity.aio import DefaultAzureCredential
4241
from opentelemetry import trace
4342
import os

sdk/ai/azure-ai-agents/samples/agents_telemetry/sample_agents_basics_with_azure_monitor_tracing.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,13 @@
4646
application_insights_connection_string = os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
4747
configure_azure_monitor(connection_string=application_insights_connection_string)
4848

49-
# enable additional instrumentations
50-
from azure.ai.agents.telemetry import enable_telemetry
51-
52-
enable_telemetry()
49+
try:
50+
from azure.ai.agents.telemetry import AIAgentsInstrumentor
51+
agents_instrumentor = AIAgentsInstrumentor()
52+
if not agents_instrumentor.is_instrumented():
53+
agents_instrumentor.instrument()
54+
except Exception as exc: # pylint: disable=broad-exception-caught
55+
print(f"Could not call `AIAgentsInstrumentor().instrument()`. Exception: {exc}")
5356

5457
scenario = os.path.basename(__file__)
5558
tracer = trace.get_tracer(__name__)

sdk/ai/azure-ai-agents/samples/agents_telemetry/sample_agents_stream_eventhandler_with_azure_monitor_tracing.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -82,14 +82,17 @@ def on_unhandled_event(self, event_type: str, event_data: Any) -> None:
8282
application_insights_connection_string = os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
8383
configure_azure_monitor(connection_string=application_insights_connection_string)
8484

85+
try:
86+
from azure.ai.agents.telemetry import AIAgentsInstrumentor
87+
agents_instrumentor = AIAgentsInstrumentor()
88+
if not agents_instrumentor.is_instrumented():
89+
agents_instrumentor.instrument()
90+
except Exception as exc: # pylint: disable=broad-exception-caught
91+
print(f"Could not call `AIAgentsInstrumentor().instrument()`. Exception: {exc}")
92+
8593
scenario = os.path.basename(__file__)
8694
tracer = trace.get_tracer(__name__)
8795

88-
# enable additional instrumentations
89-
from azure.ai.agents.telemetry import enable_telemetry
90-
91-
enable_telemetry()
92-
9396
with tracer.start_as_current_span(scenario):
9497
with agents_client:
9598
# Create an agent and run stream with event handler

sdk/ai/azure-ai-agents/samples/agents_telemetry/sample_agents_stream_eventhandler_with_console_tracing.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@
4646
ThreadRun,
4747
RunStep,
4848
)
49-
from azure.ai.agents.telemetry import enable_telemetry
5049
from typing import Any
5150
from azure.ai.agents.telemetry import AIAgentsInstrumentor
5251

sdk/ai/azure-ai-agents/samples/agents_telemetry/sample_agents_toolset_with_azure_monitor_tracing.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
)
4040
from opentelemetry import trace
4141
from azure.monitor.opentelemetry import configure_azure_monitor
42-
from azure.ai.agents.telemetry import trace_function, enable_telemetry
42+
from azure.ai.agents.telemetry import trace_function
4343

4444
agents_client = AgentsClient(
4545
endpoint=os.environ["PROJECT_ENDPOINT"],
@@ -50,8 +50,13 @@
5050
application_insights_connection_string = os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
5151
configure_azure_monitor(connection_string=application_insights_connection_string)
5252

53-
# enable additional instrumentations if needed
54-
enable_telemetry()
53+
try:
54+
from azure.ai.agents.telemetry import AIAgentsInstrumentor
55+
agents_instrumentor = AIAgentsInstrumentor()
56+
if not agents_instrumentor.is_instrumented():
57+
agents_instrumentor.instrument()
58+
except Exception as exc: # pylint: disable=broad-exception-caught
59+
print(f"Could not call `AIAgentsInstrumentor().instrument()`. Exception: {exc}")
5560

5661
scenario = os.path.basename(__file__)
5762
tracer = trace.get_tracer(__name__)

0 commit comments

Comments
 (0)