Add autogen user agent to azure openai requests (#6124)

This commit is contained in:
Jack Gerrits 2025-03-26 19:01:42 -04:00 committed by GitHub
parent ce92926e78
commit 8a5ee3de6a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 32 additions and 1 deletions

View File

@ -1,4 +1,9 @@
from ._openai_client import AzureOpenAIChatCompletionClient, BaseOpenAIChatCompletionClient, OpenAIChatCompletionClient
from ._openai_client import (
AzureOpenAIChatCompletionClient,
BaseOpenAIChatCompletionClient,
OpenAIChatCompletionClient,
AZURE_OPENAI_USER_AGENT,
)
from .config import (
AzureOpenAIClientConfigurationConfigModel,
BaseOpenAIClientConfigurationConfigModel,
@ -14,4 +19,5 @@ __all__ = [
"OpenAIClientConfigurationConfigModel",
"BaseOpenAIClientConfigurationConfigModel",
"CreateArgumentsConfigModel",
"AZURE_OPENAI_USER_AGENT",
]

View File

@ -87,6 +87,8 @@ from .config import (
OpenAIClientConfiguration,
OpenAIClientConfigurationConfigModel,
)
from importlib.metadata import PackageNotFoundError, version
logger = logging.getLogger(EVENT_LOGGER_NAME)
trace_logger = logging.getLogger(TRACE_LOGGER_NAME)
@ -101,12 +103,31 @@ create_kwargs = set(completion_create_params.CompletionCreateParamsBase.__annota
disallowed_create_args = set(["stream", "messages", "function_call", "functions", "n"])
required_create_args: Set[str] = set(["model"])
USER_AGENT_HEADER_NAME = "User-Agent"
try:
version_info = version("autogen-ext")
except PackageNotFoundError:
version_info = "dev"
AZURE_OPENAI_USER_AGENT = f"autogen-python/{version_info}"
def _azure_openai_client_from_config(config: Mapping[str, Any]) -> AsyncAzureOpenAI:
# Take a copy
copied_config = dict(config).copy()
# Shave down the config to just the AzureOpenAIChatCompletionClient kwargs
azure_config = {k: v for k, v in copied_config.items() if k in aopenai_init_kwargs}
DEFAULT_HEADERS_KEY = "default_headers"
if DEFAULT_HEADERS_KEY not in azure_config:
azure_config[DEFAULT_HEADERS_KEY] = {}
azure_config[DEFAULT_HEADERS_KEY][USER_AGENT_HEADER_NAME] = (
f"{AZURE_OPENAI_USER_AGENT} {azure_config[DEFAULT_HEADERS_KEY][USER_AGENT_HEADER_NAME]}"
if USER_AGENT_HEADER_NAME in azure_config[DEFAULT_HEADERS_KEY]
else AZURE_OPENAI_USER_AGENT
)
return AsyncAzureOpenAI(**azure_config)
@ -1548,6 +1569,10 @@ class AzureOpenAIChatCompletionClient(
Right now only `DefaultAzureCredential` is supported with no additional args passed to it.
.. note::
The Azure OpenAI client by default sets the User-Agent header to `autogen-python/{version}`. To override this, you can set the variable `autogen_ext.models.openai.AZURE_OPENAI_USER_AGENT` environment variable to an empty string.
See `here <https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/managed-identity#chat-completions>`_ for how to use the Azure client directly or for more info.
"""