forked from Azure/azure-functions-durable-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Emit OpenAI Agents SDK integration usage telemetry #14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
# Copyright (c) Microsoft Corporation. All rights reserved. | ||
# Licensed under the MIT License. | ||
|
||
|
||
class UsageTelemetry: | ||
"""Handles telemetry logging for OpenAI Agents SDK integration usage.""" | ||
|
||
# Class-level flag to ensure logging happens only once across all instances | ||
_usage_logged = False | ||
|
||
@classmethod | ||
def log_usage_once(cls): | ||
"""Log OpenAI Agents SDK integration usage exactly once. | ||
|
||
Fails gracefully if metadata cannot be retrieved. | ||
""" | ||
if cls._usage_logged: | ||
return | ||
|
||
# NOTE: Any log line beginning with the special prefix defined below will be | ||
# captured by the Azure Functions host as a Language Worker console log and | ||
# forwarded to internal telemetry pipelines. | ||
# Do not change this constant value without coordinating with the Functions | ||
# host team. | ||
LANGUAGE_WORKER_CONSOLE_LOG_PREFIX = "LanguageWorkerConsoleLog" | ||
|
||
package_versions = cls._collect_openai_agent_package_versions() | ||
msg = ( | ||
f"{LANGUAGE_WORKER_CONSOLE_LOG_PREFIX}" # Prefix captured by Azure Functions host | ||
"Detected OpenAI Agents SDK integration with Durable Functions. " | ||
f"Package versions: {package_versions}" | ||
) | ||
print(msg) | ||
|
||
cls._usage_logged = True | ||
|
||
@classmethod | ||
def _collect_openai_agent_package_versions(cls) -> str: | ||
"""Collect versions of relevant packages for telemetry logging. | ||
|
||
Returns | ||
------- | ||
str | ||
Comma-separated list of name=version entries or "(unavailable)" if | ||
versions could not be determined. | ||
""" | ||
try: | ||
try: | ||
from importlib import metadata # Python 3.8+ | ||
except ImportError: # pragma: no cover - legacy fallback | ||
import importlib_metadata as metadata # type: ignore | ||
|
||
package_names = [ | ||
"azure-functions-durable", | ||
"openai", | ||
"openai-agents", | ||
] | ||
|
||
versions = [] | ||
for package_name in package_names: | ||
try: | ||
ver = metadata.version(package_name) | ||
versions.append(f"{package_name}={ver}") | ||
except Exception: # noqa: BLE001 - swallow and continue | ||
versions.append(f"{package_name}=(not installed)") | ||
|
||
return ", ".join(versions) if versions else "(unavailable)" | ||
except Exception: # noqa: BLE001 - never let version gathering break user code | ||
return "(unavailable)" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
import unittest.mock | ||
|
||
|
||
class TestUsageTelemetry: | ||
"""Test cases for the UsageTelemetry class.""" | ||
|
||
def test_log_usage_once_logs_message_on_first_call(self, capsys): | ||
"""Test that log_usage_once logs the telemetry message.""" | ||
# Reset any previous state by creating a fresh import | ||
import importlib | ||
from azure.durable_functions.openai_agents import usage_telemetry | ||
importlib.reload(usage_telemetry) | ||
UsageTelemetryFresh = usage_telemetry.UsageTelemetry | ||
|
||
def mock_version(package_name): | ||
if package_name == "azure-functions-durable": | ||
return "1.3.4" | ||
elif package_name == "openai": | ||
return "1.98.0" | ||
elif package_name == "openai-agents": | ||
return "0.2.5" | ||
return "unknown" | ||
|
||
with unittest.mock.patch('importlib.metadata.version', side_effect=mock_version): | ||
UsageTelemetryFresh.log_usage_once() | ||
|
||
captured = capsys.readouterr() | ||
assert captured.out.startswith("LanguageWorkerConsoleLog") | ||
assert "Detected OpenAI Agents SDK integration with Durable Functions." in captured.out | ||
assert "azure-functions-durable=1.3.4" in captured.out | ||
assert "openai=1.98.0" in captured.out | ||
assert "openai-agents=0.2.5" in captured.out | ||
|
||
def test_log_usage_handles_package_version_errors(self, capsys): | ||
"""Test that log_usage_once handles package version lookup errors gracefully.""" | ||
# Reset any previous state by creating a fresh import | ||
import importlib | ||
from azure.durable_functions.openai_agents import usage_telemetry | ||
importlib.reload(usage_telemetry) | ||
UsageTelemetryFresh = usage_telemetry.UsageTelemetry | ||
|
||
# Test with mixed success/failure scenario: some packages work, others fail | ||
def mock_version(package_name): | ||
if package_name == "azure-functions-durable": | ||
return "1.3.4" | ||
elif package_name == "openai": | ||
raise Exception("Package not found") | ||
elif package_name == "openai-agents": | ||
return "0.2.5" | ||
return "unknown" | ||
|
||
with unittest.mock.patch('importlib.metadata.version', side_effect=mock_version): | ||
UsageTelemetryFresh.log_usage_once() | ||
|
||
captured = capsys.readouterr() | ||
assert captured.out.startswith("LanguageWorkerConsoleLog") | ||
assert "Detected OpenAI Agents SDK integration with Durable Functions." in captured.out | ||
# Should handle errors gracefully: successful packages show versions, failed ones show "(not installed)" | ||
assert "azure-functions-durable=1.3.4" in captured.out | ||
assert "openai=(not installed)" in captured.out | ||
assert "openai-agents=0.2.5" in captured.out | ||
|
||
def test_log_usage_works_with_real_packages(self, capsys): | ||
"""Test that log_usage_once works with real package versions.""" | ||
# Reset any previous state by creating a fresh import | ||
import importlib | ||
from azure.durable_functions.openai_agents import usage_telemetry | ||
importlib.reload(usage_telemetry) | ||
UsageTelemetryFresh = usage_telemetry.UsageTelemetry | ||
|
||
# Test without mocking to see the real behavior | ||
UsageTelemetryFresh.log_usage_once() | ||
|
||
captured = capsys.readouterr() | ||
assert captured.out.startswith("LanguageWorkerConsoleLog") | ||
assert "Detected OpenAI Agents SDK integration with Durable Functions." in captured.out | ||
# Should contain some version information or (unavailable) | ||
assert ("azure-functions-durable=" in captured.out or "(unavailable)" in captured.out) | ||
|
||
def test_log_usage_once_is_idempotent(self, capsys): | ||
"""Test that multiple calls to log_usage_once only log once.""" | ||
# Reset any previous state by creating a fresh import | ||
import importlib | ||
from azure.durable_functions.openai_agents import usage_telemetry | ||
importlib.reload(usage_telemetry) | ||
UsageTelemetryFresh = usage_telemetry.UsageTelemetry | ||
|
||
with unittest.mock.patch('importlib.metadata.version', return_value="1.0.0"): | ||
# Call multiple times | ||
UsageTelemetryFresh.log_usage_once() | ||
UsageTelemetryFresh.log_usage_once() | ||
UsageTelemetryFresh.log_usage_once() | ||
|
||
captured = capsys.readouterr() | ||
# Should only see one log message despite multiple calls | ||
log_count = captured.out.count("LanguageWorkerConsoleLogDetected OpenAI Agents SDK integration") | ||
assert log_count == 1 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's fine to enable by default, but we should add a means to disable the logging.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@philliphoff Let me clarify though: this data will be propagated to internal Functions telemetry only for apps that are actually deployed to the public Azure Functions service. For these apps, there is already quite a lot of data collected without the customer having any opportunity to opt out (e.g. module usage stats, feature usage stats, and even specific app configurations). I don't feel we have enough reason to make an exception in this case.
For apps running locally or hosted on customer's own infrastructure, these logs will not be collected by the Azure Functions service in any case.